jsgen: fix array type checking in sum type match expressions (fix #24237 ) (#24259)

This commit is contained in:
Gonzalo Chumillas 2025-04-18 10:52:07 +01:00 committed by GitHub
parent dead5e69b4
commit 11e25bc9ea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 34 additions and 2 deletions

View File

@ -561,7 +561,7 @@ fn (mut g JsGen) js_name(name_ string) string {
name = name[3..]
return name
}
name = name_.replace('.', '__')
name = name_.replace('[]', '').replace('.', '__')
if name in js_reserved {
return '_v_${name}'
}
@ -2511,6 +2511,12 @@ fn (mut g JsGen) match_expr_sumtype(node ast.MatchExpr, is_expr bool, cond_var M
if tsym.language == .js && (tsym.name == 'JS.Number'
|| tsym.name == 'JS.Boolean' || tsym.name == 'JS.String') {
g.write(' === "${tsym.name[3..].to_lower_ascii()}"')
} else if tsym.kind == .array {
g.write(' && ')
g.match_cond(cond_var)
g.write('.arr.arr.every(x => x instanceof ')
g.expr(branch.exprs[sumtype_index])
g.write(')')
} else {
g.write(' instanceof ')
g.expr(branch.exprs[sumtype_index])

View File

@ -2,4 +2,8 @@ Vec2d(42,43)
Vec2d(46,74,21)
life
V is running on JS
c:
c:
sum is int
sum is string
sum is Vec2d
sum is []Vec2d

View File

@ -10,6 +10,7 @@ struct Vec3d {
}
type Vec = Vec2d | Vec3d
type SumType = int | string | Vec2d | []Vec2d
fn match_vec(v Vec) {
match v {
@ -63,10 +64,31 @@ fn match_bool_cond() {
})
}
fn match_sum_type(sum SumType) {
match sum {
int {
println('sum is int')
}
string {
println('sum is string')
}
Vec2d {
println('sum is Vec2d')
}
[]Vec2d {
println('sum is []Vec2d')
}
}
}
fn main() {
match_vec(Vec2d{42, 43})
match_vec(Vec3d{46, 74, 21})
match_classic_num()
match_classic_string()
match_bool_cond()
match_sum_type(42)
match_sum_type('everything')
match_sum_type(Vec2d{7, 11})
match_sum_type([Vec2d{7, 11}, Vec2d{13, 17}])
}