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

cgen: fix comptime if in struct field default (fix #15058) (#15152)

This commit is contained in:
yuyi 2022-07-21 21:59:18 +08:00 committed by GitHub
parent 7029e39088
commit be9f8cc777
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 6 deletions

View File

@ -234,6 +234,7 @@ fn (mut g Gen) comptime_if(node ast.IfExpr) {
} }
} }
} }
tmp_var := g.new_tmp_var()
line := if node.is_expr { line := if node.is_expr {
stmt_str := g.go_before_stmt(0) stmt_str := g.go_before_stmt(0)
g.write(util.tabs(g.indent)) g.write(util.tabs(g.indent))
@ -265,21 +266,23 @@ fn (mut g Gen) comptime_if(node ast.IfExpr) {
len := branch.stmts.len len := branch.stmts.len
if len > 0 { if len > 0 {
last := branch.stmts.last() as ast.ExprStmt last := branch.stmts.last() as ast.ExprStmt
styp := g.typ(node.typ)
if len > 1 { if len > 1 {
tmp := g.new_tmp_var()
styp := g.typ(last.typ)
g.indent++ g.indent++
g.writeln('$styp $tmp;') g.writeln('$styp $tmp_var;')
g.writeln('{') g.writeln('{')
g.stmts(branch.stmts[..len - 1]) g.stmts(branch.stmts[..len - 1])
g.write('\t$tmp = ') g.write('\t$tmp_var = ')
g.stmt(last) g.stmt(last)
g.writeln(';')
g.writeln('}') g.writeln('}')
g.indent-- g.indent--
g.writeln('$line $tmp;')
} else { } else {
g.write('$line ') g.indent++
g.write('$styp $tmp_var = ')
g.stmt(last) g.stmt(last)
g.writeln(';')
g.indent--
} }
} }
} else { } else {
@ -298,6 +301,9 @@ fn (mut g Gen) comptime_if(node ast.IfExpr) {
g.defer_ifdef = '' g.defer_ifdef = ''
} }
g.writeln('#endif') g.writeln('#endif')
if node.is_expr {
g.write('$line $tmp_var')
}
} }
// returns the value of the bool comptime expression // returns the value of the bool comptime expression

View File

@ -0,0 +1,14 @@
struct Foo {
text string = $if linux {
'linux'
} $else {
println('else')
'else'
}
}
fn test_comptime_if_expr_in_struct_field_default() {
f := Foo{}
println(f)
assert f.text.len > 0
}