1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: check error for array of sumtype appendding (#13593)

This commit is contained in:
yuyi 2022-02-24 17:07:03 +08:00 committed by GitHub
parent f6891c405a
commit d30ad344e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 51 additions and 1 deletions

View File

@ -845,6 +845,22 @@ pub fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type {
right_pos) right_pos)
} }
return ast.void_type 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 // []T << T or []T << []T
unwrapped_right_type := c.unwrap_generic(right_type) unwrapped_right_type := c.unwrap_generic(right_type)

View File

@ -110,7 +110,17 @@ pub fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type {
continue continue
} else if expecting_sumtype_array { } else if expecting_sumtype_array {
if i == 0 { if i == 0 {
if expected_value_type.idx() == typ.idx()
|| c.table.sumtype_has_variant(expected_value_type, typ, false) {
elem_type = expected_value_type 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 continue
} }

View File

@ -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 | }

View File

@ -0,0 +1,11 @@
type Bar = BarA | BarB
struct BarA {}
struct BarB {}
fn main() {
mut bar := []Bar{}
bar << ['hey']
bar << 'hey'
}