Skip to content

Commit afa1a9a

Browse files
authored
jsgen: fix inconsistent output (u32) in JS backend (#20691)
1 parent 804a7bd commit afa1a9a

File tree

3 files changed

+25
-7
lines changed

3 files changed

+25
-7
lines changed

vlib/v/gen/js/builtin_types.v

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -348,15 +348,25 @@ fn (mut g JsGen) gen_builtin_type_defs() {
348348
to_jsval: '+this'
349349
)
350350
}
351-
// u16 / u32 requires special handling in JavaScript to correctly represent it as an unsigned 32-bit integer.
352-
// The '>>> 0' bit operation ensures it is treated as unsigned, covering the full 0 to 2^32-1 range.
353-
// For u16, '>>> 0' combined with a mask of 0xffff limits it to the 0 to 2^16-1 range, correctly handling values as unsigned 16-bit integers.
354-
'u16', 'u32' {
351+
// u16 and u32 requires special handling in JavaScript to correctly represent it.
352+
// u16, '>>> 0' combined with a mask of 0xffff limits it to the 0 to 2^16-1 range, correctly handling values as unsigned 16-bit integers.
353+
'u16' {
355354
g.gen_builtin_prototype(
356355
typ_name: typ_name
357356
default_value: 'new Number(0)'
358-
constructor: "this.val = Math.floor(Number(val) & ('" + typ_name +
359-
'\' === "u16" ? 0xffff : 0xffffffff)) >>> 0'
357+
constructor: 'this.val = Math.floor(Number(val) & 0xffff) >>> 0'
358+
value_of: 'Number(this.val)'
359+
to_string: 'this.valueOf().toString()'
360+
eq: 'new bool(self.valueOf() === other.valueOf())'
361+
to_jsval: '+this'
362+
)
363+
}
364+
// u32 '>>> 0' combined with a mask of 0xffffffff limits it to the 0 to 2^32-1 range, correctly handling values as unsigned 32-bit integers.
365+
'u32' {
366+
g.gen_builtin_prototype(
367+
typ_name: typ_name
368+
default_value: 'new Number(0)'
369+
constructor: 'this.val = Math.floor(Number(val) & 0xffffffff) >>> 0'
360370
value_of: 'Number(this.val)'
361371
to_string: 'this.valueOf().toString()'
362372
eq: 'new bool(self.valueOf() === other.valueOf())'

vlib/v/gen/js/str.v

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,11 +120,19 @@ fn (mut g JsGen) gen_expr_to_string(expr ast.Expr, etype ast.Type) {
120120
is_var_mut := expr.is_auto_deref_var()
121121
str_fn_name := g.get_str_fn(typ)
122122
g.write('${str_fn_name}(')
123+
123124
if str_method_expects_ptr && !is_ptr {
124125
g.write('new \$ref(')
125126
}
127+
if typ == ast.u32_type && expr is ast.CastExpr {
128+
g.write('new u32(')
129+
}
126130

127131
g.expr(expr)
132+
133+
if typ == ast.u32_type && expr is ast.CastExpr {
134+
g.write(')')
135+
}
128136
if (!str_method_expects_ptr && is_ptr && !is_shared) || is_var_mut {
129137
g.write('.val')
130138
}

vlib/v/gen/js/tests/testdata/u32.out

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
-1
1+
4294967295
22
0
33
true
44
25600000

0 commit comments

Comments
 (0)