Skip to content

Commit 11e25bc

Browse files
authoredApr 18, 2025
jsgen: fix array type checking in sum type match expressions (fix #24237 ) (#24259)
1 parent dead5e6 commit 11e25bc

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed
 

‎vlib/v/gen/js/js.v

+7-1
Original file line numberDiff line numberDiff line change
@@ -561,7 +561,7 @@ fn (mut g JsGen) js_name(name_ string) string {
561561
name = name[3..]
562562
return name
563563
}
564-
name = name_.replace('.', '__')
564+
name = name_.replace('[]', '').replace('.', '__')
565565
if name in js_reserved {
566566
return '_v_${name}'
567567
}
@@ -2511,6 +2511,12 @@ fn (mut g JsGen) match_expr_sumtype(node ast.MatchExpr, is_expr bool, cond_var M
25112511
if tsym.language == .js && (tsym.name == 'JS.Number'
25122512
|| tsym.name == 'JS.Boolean' || tsym.name == 'JS.String') {
25132513
g.write(' === "${tsym.name[3..].to_lower_ascii()}"')
2514+
} else if tsym.kind == .array {
2515+
g.write(' && ')
2516+
g.match_cond(cond_var)
2517+
g.write('.arr.arr.every(x => x instanceof ')
2518+
g.expr(branch.exprs[sumtype_index])
2519+
g.write(')')
25142520
} else {
25152521
g.write(' instanceof ')
25162522
g.expr(branch.exprs[sumtype_index])

‎vlib/v/gen/js/tests/testdata/match.out

+5-1
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,8 @@ Vec2d(42,43)
22
Vec2d(46,74,21)
33
life
44
V is running on JS
5-
c:
5+
c:
6+
sum is int
7+
sum is string
8+
sum is Vec2d
9+
sum is []Vec2d

‎vlib/v/gen/js/tests/testdata/match.v

+22
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ struct Vec3d {
1010
}
1111

1212
type Vec = Vec2d | Vec3d
13+
type SumType = int | string | Vec2d | []Vec2d
1314

1415
fn match_vec(v Vec) {
1516
match v {
@@ -63,10 +64,31 @@ fn match_bool_cond() {
6364
})
6465
}
6566

67+
fn match_sum_type(sum SumType) {
68+
match sum {
69+
int {
70+
println('sum is int')
71+
}
72+
string {
73+
println('sum is string')
74+
}
75+
Vec2d {
76+
println('sum is Vec2d')
77+
}
78+
[]Vec2d {
79+
println('sum is []Vec2d')
80+
}
81+
}
82+
}
83+
6684
fn main() {
6785
match_vec(Vec2d{42, 43})
6886
match_vec(Vec3d{46, 74, 21})
6987
match_classic_num()
7088
match_classic_string()
7189
match_bool_cond()
90+
match_sum_type(42)
91+
match_sum_type('everything')
92+
match_sum_type(Vec2d{7, 11})
93+
match_sum_type([Vec2d{7, 11}, Vec2d{13, 17}])
7294
}

0 commit comments

Comments
 (0)
Please sign in to comment.