From 687b15231810a909cab00c1b49348afc4b131d39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20D=C3=A4schle?= Date: Fri, 8 Jan 2021 18:39:58 +0100 Subject: [PATCH] gen: fix generation of comptime if T is (#7971) --- vlib/v/gen/comptime.v | 18 +++++++++++++++++- vlib/v/tests/comptime_if_expr_test.v | 15 +++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/vlib/v/gen/comptime.v b/vlib/v/gen/comptime.v index 9786d3136d..c977cbfd96 100644 --- a/vlib/v/gen/comptime.v +++ b/vlib/v/gen/comptime.v @@ -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('}') } diff --git a/vlib/v/tests/comptime_if_expr_test.v b/vlib/v/tests/comptime_if_expr_test.v index c9fa4642ad..86c458f6f2 100644 --- a/vlib/v/tests/comptime_if_expr_test.v +++ b/vlib/v/tests/comptime_if_expr_test.v @@ -65,3 +65,18 @@ fn test_generic_t_is2() { assert res == 'It\'s a string!' assert res2 == GenericTIsTest{} } + +fn generic_t_is3(raw_data string) ?T { + $if T is string { + return '' + } + return T{} +} + +fn test_generic_t_is3() { + res := generic_t_is3('') or { + assert false + GenericTIsTest{} + } + assert res == GenericTIsTest{} +}