gen: fix generation of comptime if T is (#7971)

pull/7972/head
Daniel Däschle 2021-01-08 18:39:58 +01:00 committed by GitHub
parent 78376a0250
commit 687b152318
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 1 deletions

View File

@ -146,6 +146,7 @@ fn (mut g Gen) comp_if(node ast.IfExpr) {
} else {
''
}
mut comp_if_stmts_skip := false
for i, branch in node.branches {
start_pos := g.out.len
if i == node.branches.len - 1 && node.has_else {
@ -188,7 +189,22 @@ fn (mut g Gen) comp_if(node ast.IfExpr) {
if should_create_scope {
g.writeln('{')
}
g.stmts(branch.stmts)
if branch.cond is ast.InfixExpr {
if branch.cond.op == .key_is {
left := branch.cond.left
got_type := (branch.cond.right as ast.Type).typ
if left is ast.Type {
left_type := g.unwrap_generic(left.typ)
if left_type != got_type {
comp_if_stmts_skip = true
}
}
}
}
is_else := node.has_else && i == node.branches.len - 1
if !comp_if_stmts_skip || (comp_if_stmts_skip && is_else) {
g.stmts(branch.stmts)
}
if should_create_scope {
g.writeln('}')
}

View File

@ -65,3 +65,18 @@ fn test_generic_t_is2() {
assert res == 'It\'s a string!'
assert res2 == GenericTIsTest{}
}
fn generic_t_is3<T>(raw_data string) ?T {
$if T is string {
return ''
}
return T{}
}
fn test_generic_t_is3() {
res := generic_t_is3<GenericTIsTest>('') or {
assert false
GenericTIsTest{}
}
assert res == GenericTIsTest{}
}