Skip to content

Commit

Permalink
checker: disallow directly indexing sumtype and interface, when using…
Browse files Browse the repository at this point in the history
… as parameters(fix #19811) (#19982)
  • Loading branch information
shove70 authored Nov 24, 2023
1 parent 90d3523 commit febd54b
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
3 changes: 2 additions & 1 deletion vlib/v/checker/checker.v
Original file line number Diff line number Diff line change
Expand Up @@ -4319,7 +4319,8 @@ fn (mut c Checker) index_expr(mut node ast.IndexExpr) ast.Type {
}
is_aggregate_arr := typ_sym.kind == .aggregate
&& (typ_sym.info as ast.Aggregate).types.filter(c.table.type_kind(it) !in [.array, .array_fixed, .string, .map]).len == 0
if typ_sym.kind !in [.array, .array_fixed, .string, .map] && !typ.is_ptr()
if typ_sym.kind !in [.array, .array_fixed, .string, .map]
&& (!typ.is_ptr() || typ_sym.kind in [.sum_type, .interface_])
&& typ !in [ast.byteptr_type, ast.charptr_type] && !typ.has_flag(.variadic)
&& !is_aggregate_arr {
c.error('type `${typ_sym.name}` does not support indexing', node.pos)
Expand Down
13 changes: 13 additions & 0 deletions vlib/v/checker/tests/index_sumtype_or_interface_params_err.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
vlib/v/checker/tests/index_sumtype_or_interface_params_err.vv:6:9: error: type `Foo` does not support indexing
4 |
5 | fn sum_type_or_interface_as_parameters(mut foo Foo, mut bar Bar) {
6 | _ = foo[0]
| ~~~
7 | _ = bar[0]
8 | }
vlib/v/checker/tests/index_sumtype_or_interface_params_err.vv:7:9: error: type `Bar` does not support indexing
5 | fn sum_type_or_interface_as_parameters(mut foo Foo, mut bar Bar) {
6 | _ = foo[0]
7 | _ = bar[0]
| ~~~
8 | }
8 changes: 8 additions & 0 deletions vlib/v/checker/tests/index_sumtype_or_interface_params_err.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
type Foo = int | map[int]int

interface Bar {}

fn sum_type_or_interface_as_parameters(mut foo Foo, mut bar Bar) {
_ = foo[0]
_ = bar[0]
}

0 comments on commit febd54b

Please sign in to comment.