From fbcb1f3711d4c95ecfebc3306d598c5c1742a831 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Mon, 13 Feb 2023 09:24:11 -0300 Subject: [PATCH] checker: disallow &nil (#17283) --- vlib/v/checker/checker.v | 3 +++ vlib/v/checker/tests/invalid_nilref_err.out | 6 ++++++ vlib/v/checker/tests/invalid_nilref_err.vv | 4 ++++ 3 files changed, 13 insertions(+) create mode 100644 vlib/v/checker/tests/invalid_nilref_err.out create mode 100644 vlib/v/checker/tests/invalid_nilref_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index c8ae36bc63..9d17194f2a 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3643,6 +3643,9 @@ fn (mut c Checker) prefix_expr(mut node ast.PrefixExpr) ast.Type { c.inside_ref_lit = old_inside_ref_lit node.right_type = right_type if node.op == .amp { + if node.right is ast.Nil { + c.error('invalid operation: cannot take address of nil', node.right.pos()) + } if mut node.right is ast.PrefixExpr { if node.right.op == .amp { c.error('unexpected `&`, expecting expression', node.right.pos) diff --git a/vlib/v/checker/tests/invalid_nilref_err.out b/vlib/v/checker/tests/invalid_nilref_err.out new file mode 100644 index 0000000000..392fd12906 --- /dev/null +++ b/vlib/v/checker/tests/invalid_nilref_err.out @@ -0,0 +1,6 @@ +vlib/v/checker/tests/invalid_nilref_err.vv:2:19: error: invalid operation: cannot take address of nil + 1 | fn main() { + 2 | var := unsafe { &nil } + | ~~~ + 3 | println(var) + 4 | } diff --git a/vlib/v/checker/tests/invalid_nilref_err.vv b/vlib/v/checker/tests/invalid_nilref_err.vv new file mode 100644 index 0000000000..221ba04502 --- /dev/null +++ b/vlib/v/checker/tests/invalid_nilref_err.vv @@ -0,0 +1,4 @@ +fn main() { + var := unsafe { &nil } + println(var) +}