Skip to content

Commit

Permalink
checker: check struct init with pointer field (fix #18485) (#18501)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Jun 21, 2023
1 parent 5006ffb commit 76ae9db
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
6 changes: 6 additions & 0 deletions vlib/v/checker/struct.v
Expand Up @@ -544,6 +544,12 @@ fn (mut c Checker) struct_init(mut node ast.StructInit, is_field_zero_struct_ini
&& field.expr.str() != '0' && !exp_type.has_flag(.option) {
c.error('reference field must be initialized with reference',
field.pos)
} else if exp_type.is_pointer() && !got_type.is_any_kind_of_pointer()
&& !got_type.is_int() {
got_typ_str := c.table.type_to_str(got_type)
exp_typ_str := c.table.type_to_str(exp_type)
c.error('cannot assign to field `${field_info.name}`: expected a pointer `${exp_typ_str}`, but got `${got_typ_str}`',
field.pos)
}
}
node.fields[i].typ = got_type
Expand Down
7 changes: 7 additions & 0 deletions vlib/v/checker/tests/struct_voidptr_field_init_err.out
@@ -0,0 +1,7 @@
vlib/v/checker/tests/struct_voidptr_field_init_err.vv:7:3: error: cannot assign to field `example`: expected a pointer `voidptr`, but got `string`
5 | fn main() {
6 | println(Example{
7 | example: get()
| ~~~~~~~~~~~~~~
8 | })
9 | }
13 changes: 13 additions & 0 deletions vlib/v/checker/tests/struct_voidptr_field_init_err.vv
@@ -0,0 +1,13 @@
struct Example {
example voidptr
}

fn main() {
println(Example{
example: get()
})
}

fn get() string {
return 'hello'
}

0 comments on commit 76ae9db

Please sign in to comment.