checker: fix generic fn using generic type in if expr (#13027)

pull/13028/head
yuyi 2022-01-04 22:04:15 +08:00 committed by GitHub
parent b94c5c2a9c
commit b2538e83da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 2 deletions

View File

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

View File

@ -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',

View File

@ -0,0 +1,16 @@
fn test_generic_fn_using_generic_type_in_if() {
ret := generic_bool(true)
assert ret == 'true'
}
fn generic_bool<T>(val T) string {
$if T is bool {
if val {
println('is true')
return 'true'
} else {
println('is false')
return 'false'
}
}
}