From 11e25bc9ea30ffde14bcd51d79ced465e3dcb4e2 Mon Sep 17 00:00:00 2001 From: Gonzalo Chumillas Date: Fri, 18 Apr 2025 10:52:07 +0100 Subject: [PATCH] jsgen: fix array type checking in sum type match expressions (fix #24237 ) (#24259) --- vlib/v/gen/js/js.v | 8 +++++++- vlib/v/gen/js/tests/testdata/match.out | 6 +++++- vlib/v/gen/js/tests/testdata/match.v | 22 ++++++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/vlib/v/gen/js/js.v b/vlib/v/gen/js/js.v index 3aa1cc3967..7bc7fdb28f 100644 --- a/vlib/v/gen/js/js.v +++ b/vlib/v/gen/js/js.v @@ -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]) diff --git a/vlib/v/gen/js/tests/testdata/match.out b/vlib/v/gen/js/tests/testdata/match.out index 19adfb61b7..02034c9446 100644 --- a/vlib/v/gen/js/tests/testdata/match.out +++ b/vlib/v/gen/js/tests/testdata/match.out @@ -2,4 +2,8 @@ Vec2d(42,43) Vec2d(46,74,21) life V is running on JS -c: \ No newline at end of file +c: +sum is int +sum is string +sum is Vec2d +sum is []Vec2d \ No newline at end of file diff --git a/vlib/v/gen/js/tests/testdata/match.v b/vlib/v/gen/js/tests/testdata/match.v index a43419fcc5..61796f1b1b 100644 --- a/vlib/v/gen/js/tests/testdata/match.v +++ b/vlib/v/gen/js/tests/testdata/match.v @@ -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}]) }