From 7878bad95e711cdce08319188e7a199a5ada9c34 Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 11 Jun 2021 02:34:36 +0800 Subject: [PATCH] checker: check array type mismatch of array append (#10405) --- vlib/v/checker/check_types.v | 7 +++++++ vlib/v/checker/checker.v | 2 +- .../checker/tests/array_append_array_type_mismatch_err.out | 7 +++++++ .../checker/tests/array_append_array_type_mismatch_err.vv | 5 +++++ 4 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 vlib/v/checker/tests/array_append_array_type_mismatch_err.out create mode 100644 vlib/v/checker/tests/array_append_array_type_mismatch_err.vv diff --git a/vlib/v/checker/check_types.v b/vlib/v/checker/check_types.v index 1c8874f486..524cc1f375 100644 --- a/vlib/v/checker/check_types.v +++ b/vlib/v/checker/check_types.v @@ -331,6 +331,13 @@ pub fn (mut c Checker) check_types(got ast.Type, expected ast.Type) bool { return true } +fn (mut c Checker) check_array_value_types(got ast.Type, expected ast.Type) bool { + if expected.is_number() && got.is_number() && expected != c.table.mktyp(got) { + return false + } + return c.check_types(got, expected) +} + pub fn (mut c Checker) check_expected(got ast.Type, expected ast.Type) ? { if c.check_types(got, expected) { return diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index a6456c2322..56047d34f2 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -1242,7 +1242,7 @@ pub fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type { return ast.void_type } if right_final.kind == .array - && c.check_types(left_value_type, c.table.value_type(right_type)) { + && c.check_array_value_types(left_value_type, c.table.value_type(right_type)) { // []T << []T return ast.void_type } diff --git a/vlib/v/checker/tests/array_append_array_type_mismatch_err.out b/vlib/v/checker/tests/array_append_array_type_mismatch_err.out new file mode 100644 index 0000000000..0cd37f3d75 --- /dev/null +++ b/vlib/v/checker/tests/array_append_array_type_mismatch_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/array_append_array_type_mismatch_err.vv:3:8: error: cannot append `[]int` to `[]byte` + 1 | fn main() { + 2 | mut bc := []byte{} + 3 | bc << [0xCA, 0xFE, 0xBA, 0xBE] + | ~~~~~~~~~~~~~~~~~~~~~~~~ + 4 | println(bc) + 5 | } diff --git a/vlib/v/checker/tests/array_append_array_type_mismatch_err.vv b/vlib/v/checker/tests/array_append_array_type_mismatch_err.vv new file mode 100644 index 0000000000..45de913508 --- /dev/null +++ b/vlib/v/checker/tests/array_append_array_type_mismatch_err.vv @@ -0,0 +1,5 @@ +fn main() { + mut bc := []byte{} + bc << [0xCA, 0xFE, 0xBA, 0xBE] + println(bc) +}