From febd54b77cf977bc121133b19344ba9baed31319 Mon Sep 17 00:00:00 2001 From: shove Date: Sat, 25 Nov 2023 02:26:02 +0800 Subject: [PATCH] checker: disallow directly indexing sumtype and interface, when using as parameters(fix #19811) (#19982) --- vlib/v/checker/checker.v | 3 ++- .../tests/index_sumtype_or_interface_params_err.out | 13 +++++++++++++ .../tests/index_sumtype_or_interface_params_err.vv | 8 ++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 vlib/v/checker/tests/index_sumtype_or_interface_params_err.out create mode 100644 vlib/v/checker/tests/index_sumtype_or_interface_params_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 73fce3405849be..7cdf77cee19ec0 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -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) diff --git a/vlib/v/checker/tests/index_sumtype_or_interface_params_err.out b/vlib/v/checker/tests/index_sumtype_or_interface_params_err.out new file mode 100644 index 00000000000000..714ffc811bcd06 --- /dev/null +++ b/vlib/v/checker/tests/index_sumtype_or_interface_params_err.out @@ -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 | } diff --git a/vlib/v/checker/tests/index_sumtype_or_interface_params_err.vv b/vlib/v/checker/tests/index_sumtype_or_interface_params_err.vv new file mode 100644 index 00000000000000..c686b777bfcbc7 --- /dev/null +++ b/vlib/v/checker/tests/index_sumtype_or_interface_params_err.vv @@ -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] +}