From f4251dded07e2fafc5a609241173504071e1d9e0 Mon Sep 17 00:00:00 2001 From: spaceface777 Date: Tue, 21 Jul 2020 18:49:53 +0200 Subject: [PATCH] checker: suggest using `:=` when assigning to undefined variable (#5911) --- vlib/v/checker/checker.v | 7 ++++++- vlib/v/checker/tests/unknown_var_assign.out | 5 +++++ vlib/v/checker/tests/unknown_var_assign.vv | 3 +++ vlib/v/parser/parser.v | 2 ++ 4 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 vlib/v/checker/tests/unknown_var_assign.out create mode 100644 vlib/v/checker/tests/unknown_var_assign.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 1e0307c252..72816185a5 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -2524,7 +2524,12 @@ pub fn (mut c Checker) ident(mut ident ast.Ident) table.Type { } ident.mod = saved_mod } - c.error('undefined ident: `$ident.name`', ident.pos) + if ident.tok_kind == .assign { + c.error('undefined ident: `$ident.name` (use `:=` to assign a variable)', + ident.pos) + } else { + c.error('undefined ident: `$ident.name`', ident.pos) + } } if c.table.known_type(ident.name) { // e.g. `User` in `json.decode(User, '...')` diff --git a/vlib/v/checker/tests/unknown_var_assign.out b/vlib/v/checker/tests/unknown_var_assign.out new file mode 100644 index 0000000000..c129fa4780 --- /dev/null +++ b/vlib/v/checker/tests/unknown_var_assign.out @@ -0,0 +1,5 @@ +vlib/v/checker/tests/unknown_var_assign.v:2:5: error: undefined ident: `x` (use `:=` to assign a variable) + 1 | fn main() { + 2 | x = 'hello v' + | ^ + 3 | } diff --git a/vlib/v/checker/tests/unknown_var_assign.vv b/vlib/v/checker/tests/unknown_var_assign.vv new file mode 100644 index 0000000000..d7ed5306d5 --- /dev/null +++ b/vlib/v/checker/tests/unknown_var_assign.vv @@ -0,0 +1,3 @@ +fn main() { + x = 'hello v' +} diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index 10b2af49f3..a13bb93c32 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -850,6 +850,7 @@ pub fn (mut p Parser) parse_ident(language table.Language) ast.Ident { mut name := p.check_name() if name == '_' { return ast.Ident{ + tok_kind: p.tok.kind name: '_' kind: .blank_ident pos: pos @@ -866,6 +867,7 @@ pub fn (mut p Parser) parse_ident(language table.Language) ast.Ident { name = '${p.expr_mod}.$name' } return ast.Ident{ + tok_kind: p.tok.kind kind: .unresolved name: name language: language