Skip to content

Commit

Permalink
checker: disallow &((&a)) and similar expressions, with innermost …
Browse files Browse the repository at this point in the history
…`ast.PrefixExpr` (enhance #23418) (#23419)
  • Loading branch information
Delta456 authored Jan 10, 2025
1 parent ba9d358 commit 3b31699
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
18 changes: 8 additions & 10 deletions vlib/v/checker/checker.v
Original file line number Diff line number Diff line change
Expand Up @@ -4671,6 +4671,11 @@ fn (mut c Checker) prefix_expr(mut node ast.PrefixExpr) ast.Type {
right_type := c.expr(mut node.right)
c.inside_ref_lit = old_inside_ref_lit
node.right_type = right_type
mut expr := node.right
// if ParExpr get the innermost expr
for mut expr is ast.ParExpr {
expr = expr.expr
}
if node.op == .amp {
if node.right is ast.Nil {
c.error('invalid operation: cannot take address of nil', node.right.pos())
Expand All @@ -4679,11 +4684,9 @@ fn (mut c Checker) prefix_expr(mut node ast.PrefixExpr) ast.Type {
if node.right.op == .amp {
c.error('unexpected `&`, expecting expression', node.right.pos)
}
} else if mut node.right is ast.ParExpr {
if mut node.right.expr is ast.PrefixExpr {
if node.right.expr.op == .amp {
c.error('cannot take the address of this expression', node.right.pos)
}
} else if mut expr is ast.PrefixExpr {
if expr.op == .amp {
c.error('cannot take the address of this expression', expr.pos)
}
} else if mut node.right is ast.SelectorExpr {
if node.right.expr.is_literal() {
Expand All @@ -4710,11 +4713,6 @@ fn (mut c Checker) prefix_expr(mut node ast.PrefixExpr) ast.Type {
// TODO: testing ref/deref strategy
right_is_ptr := right_type.is_ptr()
if node.op == .amp && (!right_is_ptr || (right_is_ptr && node.right is ast.CallExpr)) {
mut expr := node.right
// if ParExpr get the innermost expr
for mut expr is ast.ParExpr {
expr = expr.expr
}
if expr in [ast.BoolLiteral, ast.CallExpr, ast.CharLiteral, ast.FloatLiteral, ast.IntegerLiteral,
ast.InfixExpr, ast.StringLiteral, ast.StringInterLiteral] {
c.error('cannot take the address of ${expr}', node.pos)
Expand Down
4 changes: 2 additions & 2 deletions vlib/v/checker/tests/addr_of_invalid_expr.out
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
vlib/v/checker/tests/addr_of_invalid_expr.vv:3:8: error: cannot take the address of this expression
vlib/v/checker/tests/addr_of_invalid_expr.vv:3:9: error: cannot take the address of this expression
1 | fn main() {
2 | a := 1
3 | _ := &(&a)
| ~~~~
| ^
4 | }

0 comments on commit 3b31699

Please sign in to comment.