Skip to content

Commit 51aaf3c

Browse files
authored
checker: fix incorrect checks when struct fields are ref and option type(fix #19555) (#20195)
1 parent 136193a commit 51aaf3c

File tree

4 files changed

+25
-3
lines changed

4 files changed

+25
-3
lines changed

vlib/json/json_encode_recursive_ptr_test.v

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ struct PostTag {
99
}
1010

1111
fn test_main() {
12-
new_post_tag := PostTag{}
12+
new_post_tag := &PostTag{}
1313
assert json.encode(new_post_tag) == '{"id":"","visibility":"","createdAt":"","metadata":""}'
1414

1515
new_post_tag2 := PostTag{

vlib/v/checker/struct.v

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -704,8 +704,9 @@ or use an explicit `unsafe{ a[..] }`, if you do not want a copy of the slice.',
704704
c.error('reference field must be initialized with reference',
705705
init_field.pos)
706706
}
707-
} else if exp_type.is_pointer() && !got_type.is_any_kind_of_pointer()
708-
&& !got_type.is_int() {
707+
} else if exp_type.is_any_kind_of_pointer()
708+
&& !got_type.is_any_kind_of_pointer() && !got_type.is_int()
709+
&& (!exp_type.has_flag(.option) || got_type.idx() != ast.none_type_idx) {
709710
got_typ_str := c.table.type_to_str(got_type)
710711
exp_typ_str := c.table.type_to_str(exp_type)
711712
c.error('cannot assign to field `${field_info.name}`: expected a pointer `${exp_typ_str}`, but got `${got_typ_str}`',
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
vlib/v/checker/tests/struct_field_init_option_ref_err.vv:12:3: error: cannot assign to field `field`: expected a pointer `?&Foo`, but got `?Foo`
2+
10 | foo := ?Foo{}
3+
11 | _ := Bar{
4+
12 | field: foo
5+
| ~~~~~~~~~~
6+
13 | }
7+
14 | }
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
module main
2+
3+
struct Foo {}
4+
5+
struct Bar {
6+
field ?&Foo
7+
}
8+
9+
fn main() {
10+
foo := ?Foo{}
11+
_ := Bar{
12+
field: foo
13+
}
14+
}

0 commit comments

Comments
 (0)