1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: fix comptime if in const declaration (fix #15160) (#15169)

This commit is contained in:
yuyi 2022-07-22 21:03:45 +08:00 committed by GitHub
parent 9ec8a99243
commit 092f5f0bf8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 1 deletions

View File

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

View File

@ -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)
}

View File

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