parser: check error for struct field type using 'mut' (#13847)

pull/13855/head
yuyi 2022-03-28 23:13:38 +08:00 committed by GitHub
parent 62553dcc2e
commit dd1a8cbadc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 27 additions and 4 deletions

View File

@ -376,8 +376,12 @@ pub fn (mut p Parser) parse_type() ast.Type {
p.register_auto_import('sync') p.register_auto_import('sync')
} }
mut nr_muls := 0 mut nr_muls := 0
if p.inside_fn_return && p.tok.kind == .key_mut { if p.tok.kind == .key_mut {
p.error_with_pos('cannot use `mut` on fn return type', p.tok.pos()) if p.inside_fn_return {
p.error_with_pos('cannot use `mut` on fn return type', p.tok.pos())
} else if p.inside_struct_field_decl {
p.error_with_pos('cannot use `mut` on struct field type', p.tok.pos())
}
} }
if p.tok.kind == .key_mut || is_shared || is_atomic { if p.tok.kind == .key_mut || is_shared || is_atomic {
nr_muls++ nr_muls++

View File

@ -54,8 +54,9 @@ mut:
inside_asm_template bool inside_asm_template bool
inside_asm bool inside_asm bool
inside_defer bool inside_defer bool
inside_generic_params bool // indicates if parsing between `<` and `>` of a method/function inside_generic_params bool // indicates if parsing between `<` and `>` of a method/function
inside_receiver_param bool // indicates if parsing the receiver parameter inside the first `(` and `)` of a method inside_receiver_param bool // indicates if parsing the receiver parameter inside the first `(` and `)` of a method
inside_struct_field_decl bool
or_is_handled bool // ignore `or` in this expression or_is_handled bool // ignore `or` in this expression
builtin_mod bool // are we in the `builtin` module? builtin_mod bool // are we in the `builtin` module?
mod string // current module name mod string // current module name

View File

@ -223,7 +223,9 @@ fn (mut p Parser) struct_decl() ast.StructDecl {
break break
} }
} }
p.inside_struct_field_decl = true
typ = p.parse_type() typ = p.parse_type()
p.inside_struct_field_decl = false
if typ.idx() == 0 { if typ.idx() == 0 {
// error is set in parse_type // error is set in parse_type
return ast.StructDecl{} return ast.StructDecl{}

View File

@ -0,0 +1,7 @@
vlib/v/parser/tests/struct_field_mut_type_err.vv:3:6: error: cannot use `mut` on struct field type
1 | struct Foo {
2 | mut:
3 | foo mut string
| ~~~
4 | }
5 |

View File

@ -0,0 +1,9 @@
struct Foo {
mut:
foo mut string
}
fn main() {
f := Foo{}
println(f)
}