Skip to content

Commit

Permalink
checker: check error for array of sumtype appendding (#13593)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Feb 24, 2022
1 parent f6891c4 commit d30ad34
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 1 deletion.
16 changes: 16 additions & 0 deletions vlib/v/checker/checker.v
Expand Up @@ -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)
Expand Down
12 changes: 11 additions & 1 deletion vlib/v/checker/containers.v
Expand Up @@ -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
}
Expand Down
13 changes: 13 additions & 0 deletions 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 | }
11 changes: 11 additions & 0 deletions 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'
}

0 comments on commit d30ad34

Please sign in to comment.