Skip to content

Commit 84152cc

Browse files
authored
checker: prevent array.insert for array of references when non-reference is passed (fix #25511) (#25557)
1 parent 3dfd06b commit 84152cc

3 files changed

Lines changed: 40 additions & 2 deletions

File tree

‎vlib/v/checker/fn.v‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3321,8 +3321,15 @@ fn (mut c Checker) array_builtin_method_call(mut node ast.CallExpr, left_type as
33213321
node.args[i].typ = c.expr(mut arg.expr)
33223322
if i == val_arg_n {
33233323
arg_sym := c.table.sym(node.args[i].typ)
3324-
if !c.check_types(node.args[i].typ, info.elem_type)
3325-
&& !c.check_types(left_type, node.args[i].typ) {
3324+
base_arg_type := c.unwrap_generic(node.args[i].typ)
3325+
if c.check_types(base_arg_type, info.elem_type) {
3326+
if !base_arg_type.is_ptr() && info.elem_type.is_ptr()
3327+
&& info.elem_type.share() == .mut_t {
3328+
c.error('cannot ${method_name} `${arg_sym.name}` to `${left_sym.name}`',
3329+
arg.expr.pos())
3330+
continue
3331+
}
3332+
} else if !c.check_types(base_arg_type, c.unwrap_generic(left_type)) {
33263333
c.error('cannot ${method_name} `${arg_sym.name}` to `${left_sym.name}`',
33273334
arg.expr.pos())
33283335
continue
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
vlib/v/checker/tests/array_of_refs_insert_non_ref.vv:16:12: error: cannot append `Dummy` to `[]&Dummy`
2+
14 | v: 1
3+
15 | }
4+
16 | c.vals << d
5+
| ^
6+
17 | c.vals.insert(0, d)
7+
18 | }
8+
vlib/v/checker/tests/array_of_refs_insert_non_ref.vv:17:19: error: cannot insert `Dummy` to `[]&Dummy`
9+
15 | }
10+
16 | c.vals << d
11+
17 | c.vals.insert(0, d)
12+
| ^
13+
18 | }
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
struct Dummy {
2+
v int
3+
}
4+
5+
@[heap]
6+
struct Container {
7+
mut:
8+
vals []&Dummy
9+
}
10+
11+
fn main() {
12+
mut c := &Container{}
13+
d := Dummy{
14+
v: 1
15+
}
16+
c.vals << d
17+
c.vals.insert(0, d)
18+
}

0 commit comments

Comments
 (0)