From b2538e83da4b7ab9c39c8726a60ebcca307612ef Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 4 Jan 2022 22:04:15 +0800 Subject: [PATCH] checker: fix generic fn using generic type in if expr (#13027) --- vlib/v/checker/comptime.v | 2 +- vlib/v/checker/if.v | 2 +- .../generic_fn_using_generic_type_in_if_test.v | 16 ++++++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/generic_fn_using_generic_type_in_if_test.v diff --git a/vlib/v/checker/comptime.v b/vlib/v/checker/comptime.v index 180909c0f1..dac55459a8 100644 --- a/vlib/v/checker/comptime.v +++ b/vlib/v/checker/comptime.v @@ -547,7 +547,7 @@ fn (mut c Checker) comptime_if_branch(cond ast.Expr, pos token.Position) bool { return false } // `$if some_var {}`, or `[if user_defined_tag] fn abc(){}` - typ := c.expr(cond) + typ := c.unwrap_generic(c.expr(cond)) if cond.obj !is ast.Var && cond.obj !is ast.ConstField && cond.obj !is ast.GlobalField { if !c.inside_ct_attr { diff --git a/vlib/v/checker/if.v b/vlib/v/checker/if.v index a22f72380d..02ef3e4195 100644 --- a/vlib/v/checker/if.v +++ b/vlib/v/checker/if.v @@ -39,7 +39,7 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type { } else { // check condition type is boolean c.expected_type = ast.bool_type - cond_typ := c.expr(branch.cond) + cond_typ := c.unwrap_generic(c.expr(branch.cond)) if (cond_typ.idx() != ast.bool_type_idx || cond_typ.has_flag(.optional)) && !c.pref.translated { c.error('non-bool type `${c.table.type_to_str(cond_typ)}` used as if condition', diff --git a/vlib/v/tests/generic_fn_using_generic_type_in_if_test.v b/vlib/v/tests/generic_fn_using_generic_type_in_if_test.v new file mode 100644 index 0000000000..bd316fa934 --- /dev/null +++ b/vlib/v/tests/generic_fn_using_generic_type_in_if_test.v @@ -0,0 +1,16 @@ +fn test_generic_fn_using_generic_type_in_if() { + ret := generic_bool(true) + assert ret == 'true' +} + +fn generic_bool(val T) string { + $if T is bool { + if val { + println('is true') + return 'true' + } else { + println('is false') + return 'false' + } + } +}