Skip to content

Commit

Permalink
cgen: fix smartcast for struct fields in the match branches(fix #20167)…
Browse files Browse the repository at this point in the history
… (#20171)
  • Loading branch information
shove70 committed Dec 14, 2023
1 parent 0b12d64 commit f303679
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
6 changes: 4 additions & 2 deletions vlib/v/gen/c/cgen.v
Expand Up @@ -2479,8 +2479,10 @@ fn (mut g Gen) expr_with_cast(expr ast.Expr, got_type_raw ast.Type, expected_typ
}
}
} else if expr is ast.SelectorExpr {
if _ := scope.find_struct_field(expr.expr.str(), expr.expr_type, expr.field_name) {
is_already_sum_type = true
if v := scope.find_struct_field(expr.expr.str(), expr.expr_type, expr.field_name) {
if v.smartcasts.len > 0 && unwrapped_expected_type == v.orig_type {
is_already_sum_type = true
}
}
}
if is_already_sum_type && !g.inside_return {
Expand Down
20 changes: 20 additions & 0 deletions vlib/v/tests/match_smartcast_test.v
Expand Up @@ -97,3 +97,23 @@ fn test_match_mut_selector() {
}
}
}

// for issue 20167
type Any_1 = f64 | int | string
type Any_2 = int | string

struct Struct {
field Any_2
}

fn test_branches_return_struct_field() {
any_2 := Struct{Any_2(42)}
m := {
'item1': Any_1('')
'item2': match any_2.field {
string { any_2.field }
int { any_2.field }
}
}
assert m['item2']! == Any_1(42)
}

0 comments on commit f303679

Please sign in to comment.