From 1e416de627ccb9e5a85cbb9eb6c7c2cbbbf3a06c Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Tue, 7 Mar 2023 05:15:46 -0300 Subject: [PATCH] checker: fix const init with comptime (#17528) --- vlib/v/checker/comptime.v | 21 +++++++++++++++++++++ vlib/v/tests/comptime_const_def_test.v | 12 ++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 vlib/v/tests/comptime_const_def_test.v diff --git a/vlib/v/checker/comptime.v b/vlib/v/checker/comptime.v index f8709f1f15..e809ae7413 100644 --- a/vlib/v/checker/comptime.v +++ b/vlib/v/checker/comptime.v @@ -388,6 +388,27 @@ fn (mut c Checker) eval_comptime_const_expr(expr ast.Expr, nlevel int) ?ast.Comp } } } + ast.IfExpr { + if !expr.is_comptime { + return none + } + for i in 0 .. expr.branches.len { + branch := expr.branches[i] + if !expr.has_else || i < expr.branches.len - 1 { + if c.comptime_if_branch(branch.cond, branch.pos) == .eval { + last_stmt := branch.stmts.last() + if last_stmt is ast.ExprStmt { + return c.eval_comptime_const_expr(last_stmt.expr, nlevel + 1) + } + } + } else { + last_stmt := branch.stmts.last() + if last_stmt is ast.ExprStmt { + return c.eval_comptime_const_expr(last_stmt.expr, nlevel + 1) + } + } + } + } // ast.ArrayInit {} // ast.PrefixExpr { // c.note('prefixexpr: $expr', expr.pos) diff --git a/vlib/v/tests/comptime_const_def_test.v b/vlib/v/tests/comptime_const_def_test.v new file mode 100644 index 0000000000..d9bf9916d3 --- /dev/null +++ b/vlib/v/tests/comptime_const_def_test.v @@ -0,0 +1,12 @@ +const ( + buf_size = $if true { + 2 + } $else { + 1 + } +) + +fn test_main() { + mut buf := [buf_size]u8{} + assert buf.len == 2 +}