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

checker, cgen: allow comptime ident is array of types (#18765)

This commit is contained in:
phoebe 2023-07-04 05:45:30 +02:00 committed by GitHub
parent 1db67f7505
commit 2fb561ba7f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 29 additions and 8 deletions

View File

@ -743,7 +743,11 @@ fn (mut c Checker) comptime_if_branch(cond ast.Expr, pos token.Pos) ComptimeBran
}
}
.key_in, .not_in {
if cond.left in [ast.SelectorExpr, ast.TypeNode] && cond.right is ast.ArrayInit {
if cond.left is ast.Ident {
c.expr(cond.left)
}
if cond.left in [ast.TypeNode, ast.SelectorExpr, ast.Ident]
&& cond.right is ast.ArrayInit {
for expr in cond.right.exprs {
if expr !in [ast.ComptimeType, ast.TypeNode] {
c.error('invalid `\$if` condition, only types are allowed',

View File

@ -0,0 +1,4 @@
str
this is an else block
32-bit number
32-bit number

View File

@ -0,0 +1,16 @@
fn test[T](val T) string {
$if val is string {
return val
} $else $if val in [i32, u32] {
return '32-bit number'
} $else {
return 'this is an else block'
}
}
fn main() {
println(test('str'))
println(test(7))
println(test(u32(7)))
println(test(i32(7)))
}

View File

@ -617,7 +617,8 @@ fn (mut g Gen) comptime_if_cond(cond ast.Expr, pkg_exist bool) (bool, bool) {
}
}
.key_in, .not_in {
if cond.left in [ast.TypeNode, ast.SelectorExpr] && cond.right is ast.ArrayInit {
if cond.left in [ast.TypeNode, ast.SelectorExpr, ast.Ident]
&& cond.right is ast.ArrayInit {
checked_type := g.get_expr_type(cond.left)
for expr in cond.right.exprs {
@ -632,9 +633,8 @@ fn (mut g Gen) comptime_if_cond(cond ast.Expr, pkg_exist bool) (bool, bool) {
}
} else if expr is ast.TypeNode {
got_type := g.unwrap_generic(expr.typ)
is_true := checked_type.idx() == got_type.idx()
&& checked_type.has_flag(.option) == got_type.has_flag(.option)
if is_true {
if checked_type.idx() == got_type.idx()
&& checked_type.has_flag(.option) == got_type.has_flag(.option) {
if cond.op == .key_in {
g.write('1')
} else {
@ -650,9 +650,6 @@ fn (mut g Gen) comptime_if_cond(cond ast.Expr, pkg_exist bool) (bool, bool) {
g.write('0')
}
return cond.op == .not_in, true
} else {
g.write('1')
return true, true
}
}
.gt, .lt, .ge, .le {