From 092f5f0bf86e890f4acd3c7f3229afbfce6b1e70 Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 22 Jul 2022 21:03:45 +0800 Subject: [PATCH] checker: fix comptime if in const declaration (fix #15160) (#15169) --- vlib/v/checker/checker.v | 17 +++++++++++++++++ vlib/v/checker/if.v | 2 +- .../tests/comptime_if_expr_in_const_decl_test.v | 10 ++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/comptime_if_expr_in_const_decl_test.v diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 0388b75218..4f399dbfd9 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -1338,6 +1338,23 @@ pub fn (mut c Checker) const_decl(mut node ast.ConstDecl) { } } node.fields[i].typ = ast.mktyp(typ) + if mut field.expr is ast.IfExpr { + if field.expr.branches.len == 2 { + first_stmts := field.expr.branches[0].stmts + second_stmts := field.expr.branches[1].stmts + if first_stmts.len > 0 && first_stmts.last() is ast.ExprStmt + && (first_stmts.last() as ast.ExprStmt).typ != ast.void_type { + field.expr.is_expr = true + field.expr.typ = (first_stmts.last() as ast.ExprStmt).typ + field.typ = field.expr.typ + } else if second_stmts.len > 0 && second_stmts.last() is ast.ExprStmt + && (second_stmts.last() as ast.ExprStmt).typ != ast.void_type { + field.expr.is_expr = true + field.expr.typ = (second_stmts.last() as ast.ExprStmt).typ + field.typ = field.expr.typ + } + } + } c.const_deps = [] c.const_var = prev_const_var } diff --git a/vlib/v/checker/if.v b/vlib/v/checker/if.v index 8b4ecb0877..004fef3a83 100644 --- a/vlib/v/checker/if.v +++ b/vlib/v/checker/if.v @@ -227,7 +227,7 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type { c.error('mismatched types `${c.table.type_to_str(node.typ)}` and `${c.table.type_to_str(last_expr.typ)}`', node.pos) } - } else { + } else if !node.is_comptime { c.error('`$if_kind` expression requires an expression as the last statement of every branch', branch.pos) } diff --git a/vlib/v/tests/comptime_if_expr_in_const_decl_test.v b/vlib/v/tests/comptime_if_expr_in_const_decl_test.v new file mode 100644 index 0000000000..bbf1719dfe --- /dev/null +++ b/vlib/v/tests/comptime_if_expr_in_const_decl_test.v @@ -0,0 +1,10 @@ +const msg = $if windows { + 'windows, eh?' +} $else { + 'ok, then' +} + +fn test_comptime_if_in_const_decl() { + println(msg) + assert msg.len > 0 +}