From f3036799888e637d66f76e14887325bb7d0973d4 Mon Sep 17 00:00:00 2001 From: shove Date: Thu, 14 Dec 2023 20:15:45 +0800 Subject: [PATCH] cgen: fix smartcast for struct fields in the match branches(fix #20167) (#20171) --- vlib/v/gen/c/cgen.v | 6 ++++-- vlib/v/tests/match_smartcast_test.v | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 5c5820db927eb1..3bca8a2f9814c7 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -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 { diff --git a/vlib/v/tests/match_smartcast_test.v b/vlib/v/tests/match_smartcast_test.v index 23d66334af1615..5e4ecdd711a0e2 100644 --- a/vlib/v/tests/match_smartcast_test.v +++ b/vlib/v/tests/match_smartcast_test.v @@ -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) +}