Skip to content

Commit 2fb561b

Browse files
author
phoebe
authored
checker, cgen: allow comptime ident is array of types (#18765)
1 parent 1db67f7 commit 2fb561b

File tree

4 files changed

+29
-8
lines changed

4 files changed

+29
-8
lines changed

vlib/v/checker/comptime.v

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -743,7 +743,11 @@ fn (mut c Checker) comptime_if_branch(cond ast.Expr, pos token.Pos) ComptimeBran
743743
}
744744
}
745745
.key_in, .not_in {
746-
if cond.left in [ast.SelectorExpr, ast.TypeNode] && cond.right is ast.ArrayInit {
746+
if cond.left is ast.Ident {
747+
c.expr(cond.left)
748+
}
749+
if cond.left in [ast.TypeNode, ast.SelectorExpr, ast.Ident]
750+
&& cond.right is ast.ArrayInit {
747751
for expr in cond.right.exprs {
748752
if expr !in [ast.ComptimeType, ast.TypeNode] {
749753
c.error('invalid `\$if` condition, only types are allowed',
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
str
2+
this is an else block
3+
32-bit number
4+
32-bit number
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
fn test[T](val T) string {
2+
$if val is string {
3+
return val
4+
} $else $if val in [i32, u32] {
5+
return '32-bit number'
6+
} $else {
7+
return 'this is an else block'
8+
}
9+
}
10+
11+
fn main() {
12+
println(test('str'))
13+
println(test(7))
14+
println(test(u32(7)))
15+
println(test(i32(7)))
16+
}

vlib/v/gen/c/comptime.v

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -617,7 +617,8 @@ fn (mut g Gen) comptime_if_cond(cond ast.Expr, pkg_exist bool) (bool, bool) {
617617
}
618618
}
619619
.key_in, .not_in {
620-
if cond.left in [ast.TypeNode, ast.SelectorExpr] && cond.right is ast.ArrayInit {
620+
if cond.left in [ast.TypeNode, ast.SelectorExpr, ast.Ident]
621+
&& cond.right is ast.ArrayInit {
621622
checked_type := g.get_expr_type(cond.left)
622623

623624
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) {
632633
}
633634
} else if expr is ast.TypeNode {
634635
got_type := g.unwrap_generic(expr.typ)
635-
is_true := checked_type.idx() == got_type.idx()
636-
&& checked_type.has_flag(.option) == got_type.has_flag(.option)
637-
if is_true {
636+
if checked_type.idx() == got_type.idx()
637+
&& checked_type.has_flag(.option) == got_type.has_flag(.option) {
638638
if cond.op == .key_in {
639639
g.write('1')
640640
} else {
@@ -650,9 +650,6 @@ fn (mut g Gen) comptime_if_cond(cond ast.Expr, pkg_exist bool) (bool, bool) {
650650
g.write('0')
651651
}
652652
return cond.op == .not_in, true
653-
} else {
654-
g.write('1')
655-
return true, true
656653
}
657654
}
658655
.gt, .lt, .ge, .le {

0 commit comments

Comments
 (0)