checker: suggest using `:=` when assigning to undefined variable (#5911)

pull/5922/head
spaceface777 2020-07-21 18:49:53 +02:00 committed by GitHub
parent 8b930b4888
commit f4251dded0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 16 additions and 1 deletions

View File

@ -2524,8 +2524,13 @@ pub fn (mut c Checker) ident(mut ident ast.Ident) table.Type {
} }
ident.mod = saved_mod ident.mod = saved_mod
} }
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) c.error('undefined ident: `$ident.name`', ident.pos)
} }
}
if c.table.known_type(ident.name) { if c.table.known_type(ident.name) {
// e.g. `User` in `json.decode(User, '...')` // e.g. `User` in `json.decode(User, '...')`
return table.void_type return table.void_type

View File

@ -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 | }

View File

@ -0,0 +1,3 @@
fn main() {
x = 'hello v'
}

View File

@ -850,6 +850,7 @@ pub fn (mut p Parser) parse_ident(language table.Language) ast.Ident {
mut name := p.check_name() mut name := p.check_name()
if name == '_' { if name == '_' {
return ast.Ident{ return ast.Ident{
tok_kind: p.tok.kind
name: '_' name: '_'
kind: .blank_ident kind: .blank_ident
pos: pos pos: pos
@ -866,6 +867,7 @@ pub fn (mut p Parser) parse_ident(language table.Language) ast.Ident {
name = '${p.expr_mod}.$name' name = '${p.expr_mod}.$name'
} }
return ast.Ident{ return ast.Ident{
tok_kind: p.tok.kind
kind: .unresolved kind: .unresolved
name: name name: name
language: language language: language