From fd6983fcb450b4277488e0185cc01258f016d79f Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 3 Jul 2023 04:54:17 +0800 Subject: [PATCH] checker: fix autocast in complex if condtions 4 (#18744) --- vlib/v/checker/infix.v | 21 +++++----- vlib/v/tests/autocast_in_if_conds_5_test.v | 45 ++++++++++++++++++++++ 2 files changed, 55 insertions(+), 11 deletions(-) create mode 100644 vlib/v/tests/autocast_in_if_conds_5_test.v diff --git a/vlib/v/checker/infix.v b/vlib/v/checker/infix.v index ff041408c3..1f1e914f5a 100644 --- a/vlib/v/checker/infix.v +++ b/vlib/v/checker/infix.v @@ -830,18 +830,17 @@ fn (mut c Checker) invalid_operator_error(op token.Kind, left_type ast.Type, rig } // `if node is ast.Ident && node.is_mut { ... }` -> `if node is ast.Ident && (node as ast.Ident).is_mut { ... }` -fn (mut c Checker) autocast_in_if_conds(mut right_ ast.Expr, from_expr ast.Expr, from_type ast.Type, to_type ast.Type) { - mut right := right_ - match mut right { - ast.Ident { - if right.name == from_expr.str() { - right_ = ast.AsCast{ - typ: to_type - expr: from_expr - expr_type: from_type - } - } +fn (mut c Checker) autocast_in_if_conds(mut right ast.Expr, from_expr ast.Expr, from_type ast.Type, to_type ast.Type) { + if '${right}' == from_expr.str() { + right = ast.AsCast{ + typ: to_type + expr: from_expr + expr_type: from_type } + return + } + + match mut right { ast.SelectorExpr { if right.expr.str() == from_expr.str() { right.expr = ast.ParExpr{ diff --git a/vlib/v/tests/autocast_in_if_conds_5_test.v b/vlib/v/tests/autocast_in_if_conds_5_test.v new file mode 100644 index 0000000000..e5a9533bc1 --- /dev/null +++ b/vlib/v/tests/autocast_in_if_conds_5_test.v @@ -0,0 +1,45 @@ +type MySumType = S1 | S2 + +struct Info { + name string +} + +struct Node { + left MySumType +} + +struct S1 { + is_info bool + info Info +} + +fn (s1 S1) is_info() bool { + return s1.is_info +} + +struct S2 { + field2 string +} + +fn get_name(s1 S1) string { + return s1.info.name +} + +fn test_autocast_in_if_conds() { + node := Node{ + left: MySumType(S1{ + is_info: false + info: Info{'foo'} + }) + } + + a := 22 + + if a > 0 && node.left is S1 && !node.left.is_info && get_name(node.left) == 'foo' + && !node.left.is_info() { + println('ok') + assert true + } else { + assert false + } +}