diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 9e2a0f4e40..2de288ce04 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -845,6 +845,22 @@ pub fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type { right_pos) } return ast.void_type + } else if left_value_sym.kind == .sum_type { + if right_final.kind != .array { + if left_value_type.idx() != right_type.idx() + && !c.table.sumtype_has_variant(left_value_type, right_type, false) { + c.error('cannot append `$right_sym.name` to `$left_sym.name`', + right_pos) + } + } else { + right_value_type := c.table.value_type(right_type) + if left_value_type.idx() != right_value_type.idx() + && !c.table.sumtype_has_variant(left_value_type, right_value_type, false) { + c.error('cannot append `$right_sym.name` to `$left_sym.name`', + right_pos) + } + } + return ast.void_type } // []T << T or []T << []T unwrapped_right_type := c.unwrap_generic(right_type) diff --git a/vlib/v/checker/containers.v b/vlib/v/checker/containers.v index 143e76a0bf..05da835206 100644 --- a/vlib/v/checker/containers.v +++ b/vlib/v/checker/containers.v @@ -110,7 +110,17 @@ pub fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type { continue } else if expecting_sumtype_array { if i == 0 { - elem_type = expected_value_type + if expected_value_type.idx() == typ.idx() + || c.table.sumtype_has_variant(expected_value_type, typ, false) { + elem_type = expected_value_type + } else { + if expr.is_auto_deref_var() { + elem_type = ast.mktyp(typ.deref()) + } else { + elem_type = ast.mktyp(typ) + } + } + c.expected_type = elem_type } continue } diff --git a/vlib/v/checker/tests/array_of_sumtype_append_err.out b/vlib/v/checker/tests/array_of_sumtype_append_err.out new file mode 100644 index 0000000000..db60a7772b --- /dev/null +++ b/vlib/v/checker/tests/array_of_sumtype_append_err.out @@ -0,0 +1,13 @@ +vlib/v/checker/tests/array_of_sumtype_append_err.vv:9:9: error: cannot append `[]string` to `[]Bar` + 7 | fn main() { + 8 | mut bar := []Bar{} + 9 | bar << ['hey'] + | ~~~~~~~ + 10 | bar << 'hey' + 11 | } +vlib/v/checker/tests/array_of_sumtype_append_err.vv:10:9: error: cannot append `string` to `[]Bar` + 8 | mut bar := []Bar{} + 9 | bar << ['hey'] + 10 | bar << 'hey' + | ~~~~~ + 11 | } diff --git a/vlib/v/checker/tests/array_of_sumtype_append_err.vv b/vlib/v/checker/tests/array_of_sumtype_append_err.vv new file mode 100644 index 0000000000..5239a1ab78 --- /dev/null +++ b/vlib/v/checker/tests/array_of_sumtype_append_err.vv @@ -0,0 +1,11 @@ +type Bar = BarA | BarB + +struct BarA {} + +struct BarB {} + +fn main() { + mut bar := []Bar{} + bar << ['hey'] + bar << 'hey' +}