From 9d77fd90bf8e3fda49ea5c8e956428e95ca772bf Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Thu, 22 Jun 2023 16:48:15 -0300 Subject: [PATCH] checker: fix missing check for diff type on map value declaration (#18522) --- vlib/v/checker/containers.v | 6 ++++-- vlib/v/checker/tests/diff_type_map_value_err.out | 7 +++++++ vlib/v/checker/tests/diff_type_map_value_err.vv | 16 ++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 vlib/v/checker/tests/diff_type_map_value_err.out create mode 100644 vlib/v/checker/tests/diff_type_map_value_err.vv diff --git a/vlib/v/checker/containers.v b/vlib/v/checker/containers.v index 4a45e4607f..dfea54e9d9 100644 --- a/vlib/v/checker/containers.v +++ b/vlib/v/checker/containers.v @@ -440,8 +440,10 @@ fn (mut c Checker) map_init(mut node ast.MapInit) ast.Type { c.error('invalid map value: ${msg}', val.pos()) } } - if !c.check_types(val_type, val0_type) || (i == 0 && val_type.is_number() - && val0_type.is_number() && val0_type != ast.mktyp(val_type)) { + if !c.check_types(val_type, val0_type) + || val0_type.has_flag(.option) != val_type.has_flag(.option) + || (i == 0 && val_type.is_number() && val0_type.is_number() + && val0_type != ast.mktyp(val_type)) { msg := c.expected_msg(val_type, val0_type) c.error('invalid map value: ${msg}', val.pos()) } diff --git a/vlib/v/checker/tests/diff_type_map_value_err.out b/vlib/v/checker/tests/diff_type_map_value_err.out new file mode 100644 index 0000000000..bf1e04206b --- /dev/null +++ b/vlib/v/checker/tests/diff_type_map_value_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/diff_type_map_value_err.vv:10:44: error: invalid map value: expected `?MyStruct`, not `MyStruct` + 8 | + 9 | fn empty() map[string]?MyStruct { + 10 | return {'key1': ?MyStruct(none), 'key2': MyStruct{field: 10}} + | ~~~~~~~~~~~~~~~~~~~ + 11 | } + 12 | diff --git a/vlib/v/checker/tests/diff_type_map_value_err.vv b/vlib/v/checker/tests/diff_type_map_value_err.vv new file mode 100644 index 0000000000..c22ea58c7d --- /dev/null +++ b/vlib/v/checker/tests/diff_type_map_value_err.vv @@ -0,0 +1,16 @@ +struct MyStruct { + field int +} + +struct MyStruct2 { + field int +} + +fn empty() map[string]?MyStruct { + return {'key1': ?MyStruct(none), 'key2': MyStruct{field: 10}} +} + +fn test_empty() { + expected := {'key': ?MyStruct(none)} + assert empty() == expected +} \ No newline at end of file