checker: disallow taking the address of consts with int literal values (#19160)

This commit is contained in:
Turiiya 2023-08-17 21:00:14 +02:00 committed by GitHub
parent 757d26cd89
commit 4908ec57e2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 39 additions and 1 deletions

View File

@ -264,7 +264,17 @@ fn (mut c Checker) assign_stmt(mut node ast.AssignStmt) {
node.left_types << left_type node.left_types << left_type
match mut left { match mut left {
ast.Ident { ast.Ident {
if left.kind == .blank_ident { if (is_decl || left.kind == .blank_ident) && left_type.is_ptr()
&& mut right is ast.PrefixExpr && right.right_type == ast.int_literal_type_idx {
if mut right.right is ast.Ident && right.right.obj is ast.ConstField {
const_name := right.right.name.all_after_last('.')
const_val := (right.right.obj as ast.ConstField).expr
c.add_error_detail('Specify the type for the constant value. Example:')
c.add_error_detail(' `const ${const_name} = int(${const_val})`')
c.error('cannot assign a pointer to a constant with an integer literal value',
right.right.pos)
}
} else if left.kind == .blank_ident {
left_type = right_type left_type = right_type
node.left_types[i] = right_type node.left_types[i] = right_type
if node.op !in [.assign, .decl_assign] { if node.op !in [.assign, .decl_assign] {

View File

@ -0,0 +1,9 @@
vlib/v/checker/tests/assign_const_ptr_int_literal_err.vv:4:8: error: cannot assign a pointer to a constant with an integer literal value
2 |
3 | fn main() {
4 | b := &a
| ^
5 | dump(b)
6 | }
Details: Specify the type for the constant value. Example:
`const a = int(3)`

View File

@ -0,0 +1,6 @@
const a = 3
fn main() {
b := &a
dump(b)
}

View File

@ -0,0 +1,8 @@
vlib/v/checker/tests/blank_ident_const_ptr_int_literal_err.vv:4:8: error: cannot assign a pointer to a constant with an integer literal value
2 |
3 | fn main() {
4 | _ := &a
| ^
5 | }
Details: Specify the type for the constant value. Example:
`const a = int(3)`

View File

@ -0,0 +1,5 @@
const a = 3
fn main() {
_ := &a
}