use super::common::*;
#[test]
fn test_native_proto_basic() {
let js = r#"
/**
* @returns {number}
*/
function add(a, b) {
return a + b;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_basic");
assert!(zig.contains("pub fn add(a: anytype, b: anytype) f64 {"));
assert!(zig.contains("return (a + b);"));
}
#[test]
fn test_native_proto_if_else() {
let js = r#"
function abs(x) {
if (x >= 0) {
return x;
} else {
return -x;
}
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_if_else");
assert!(zig.contains("fn abs(x: anytype) @TypeOf("));
assert!(
zig.contains("if ((x") && zig.contains(">= 0"),
"missing if: {}",
zig
);
assert!(zig.contains("return x;"));
assert!(zig.contains("} else {"));
assert!(zig.contains("return -x;"));
}
#[test]
fn test_native_proto_elseif() {
let js = r#"
function grade(score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else {
return "C";
}
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_elseif");
assert!(
zig.contains("else") && zig.contains("if ((score"),
"missing else if: {}",
zig
);
assert!(zig.contains("\"A\""));
assert!(zig.contains("\"B\""));
assert!(zig.contains("\"C\""));
}
#[test]
fn test_native_proto_while() {
let js = r#"
function countdown(n) {
while (n >0) {
n = n - 1;
}
return n;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_while");
assert!(zig.contains("while"), "missing while");
assert!(zig.contains("n > 0"), "missing n > 0: {}", zig);
assert!(zig.contains("n = (n - 1);"));
}
#[test]
fn test_native_proto_function_call() {
let js = r#"
function greet(name) {
return "Hello, " + name;
}
function main() {
var msg = greet("World");
return msg;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_function_call");
assert!(zig.contains("greet(")); assert!(zig.contains("std.fmt.allocPrint")); assert!(zig.contains("const msg = greet")); }
#[test]
fn test_native_proto_var_decl() {
let js = r#"
function sum(arr) {
var total = 0;
total = total + 1;
return total;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_var_decl");
assert!(zig.contains("var total: i64 = 0;"));
assert!(zig.contains("total = (total + 1);"));
}
#[test]
fn test_native_proto_operators() {
let js = r#"
function ops(a, b) {
var x = a + b;
var y = a - b;
var z = a * b;
var w = a / b;
var eq = a == b;
var ne = a != b;
var lt = a < b;
var gt = a > b;
return x;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_operators");
assert!(
zig.contains("+") && zig.contains("-") && zig.contains("*") && zig.contains("floatFromInt")
);
assert!(zig.contains("==") && zig.contains("!=") && zig.contains("<") && zig.contains(">"));
}
#[test]
fn test_native_proto_logical() {
let js = r#"
function check(a, b) {
if (a > 0 && b > 0) {
return true;
}
if (a < 0 || b < 0) {
return false;
}
return true;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_logical");
assert!(zig.contains("isTruthy(_lv_"));
assert!(zig.contains("break :blk_"));
}
#[test]
fn test_native_proto_toplevel_var_error() {
let js = r#"
let y = 10;
y = 20;
"#;
let zig = transpile_and_assert(js, "test_native_proto_toplevel_var_error");
assert!(zig.contains("// error: toplevel only allows 'const'"));
}
#[test]
fn test_native_proto_unary() {
let js = r#"
function negate(x) {
return -x;
}
function truthy(x) {
return !x;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_unary");
assert!(zig.contains("-x"));
assert!(zig.contains("!js_runtime.isTruthy(x)"));
}
#[test]
fn test_native_proto_typeof() {
let js = r#"
/**
* @param {number} x
* @param {boolean} b
* @param {string} s
*/
export function typeof_test(x, b, s) {
var t1 = typeof x;
var t2 = typeof b;
var t3 = typeof s;
return t1;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_typeof");
assert!(
zig.contains("\"number\""),
"typeof number should emit \"number\" string: {}",
zig
);
assert!(
zig.contains("\"boolean\""),
"typeof bool should emit \"boolean\" string: {}",
zig
);
assert!(
zig.contains("\"string\""),
"typeof string should emit \"string\" string: {}",
zig
);
assert!(
!zig.contains("@typeName"),
"typeof should NOT emit @typeName (old behavior): {}",
zig
);
}
#[test]
fn test_native_proto_typeof_literal() {
let js = r#"
function main() {
var n = typeof 42;
var s = typeof "hello";
var b = typeof true;
return n;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_typeof_literal");
assert!(
zig.contains("\"number\""),
"typeof 42 should emit \"number\": {}",
zig
);
assert!(
zig.contains("\"string\""),
r#"typeof "hello" should emit "string": {}"#,
zig
);
assert!(
zig.contains("\"boolean\""),
"typeof true should emit \"boolean\": {}",
zig
);
assert!(
!zig.contains("@typeName"),
"typeof should NOT emit @typeName: {}",
zig
);
}
#[test]
fn test_native_proto_typeof_object() {
let js = r#"
/**
* @typedef {Object} User
* @property {string} name
*/
/**
* @param {User} o
* @param {Array} a
*/
export function typeof_obj(o, a) {
var t1 = typeof o;
var t2 = typeof a;
return t1;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_typeof_object");
assert!(
zig.contains("\"object\""),
"typeof object should emit \"object\" string: {}",
zig
);
assert!(
zig.contains("js_runtime.jsTypeof"),
"typeof Array (JsAny) should use js_runtime.jsTypeof(): {}",
zig
);
}
#[test]
fn test_native_proto_typeof_dynamic() {
let js = r#"
function check(x) {
return typeof x;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_typeof_dynamic");
assert!(
zig.contains("js_runtime.jsTypeof"),
"typeof untyped param should use js_runtime.jsTypeof(): {}",
zig
);
}
#[test]
fn test_native_proto_void_operator() {
let js = r#"
function void_zero() {
return void 0;
}
function void_call() {
var x = 0;
void (x = 1);
return x;
}
function void_expr(a, b) {
void (a + b);
return void (a * b);
}
function void_comp_to_string() {
// void 2 === "2" should NOT use std.mem.eql(u8, ...)
// void returns JsAny, must use .strictEq() (=== is strict equality).
return void 2 === "2";
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_void_operator");
assert!(
zig.contains("JsAny.fromUndefined()"),
"void operator should generate JsAny.fromUndefined(): {}",
zig
);
assert!(
zig.contains("_ = "),
"void should use _ = to discard: {}",
zig
);
assert!(
!zig.contains("std.mem.eql(u8, blk_") && !zig.contains("std.mem.eql(u8, _ = blk_"),
"void === string must not use std.mem.eql with blk label: {}",
zig
);
assert!(
zig.contains(".strictEq("),
"void === string should use .strictEq() JsAny comparison: {}",
zig
);
}
#[test]
fn test_native_proto_delete_operator() {
let js = r#"
function delete_prop(obj) {
delete obj.name;
return obj;
}
function delete_computed(obj, key) {
delete obj[key];
return obj;
}
function delete_returns_bool(obj) {
return delete obj.x;
}
function delete_chain(obj) {
delete obj.a.b;
return obj;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_delete_operator");
assert!(
zig.contains(".deleteKey(\"name\")"),
"delete obj.prop should use deleteKey: {}",
zig
);
assert!(
zig.contains(".delete(js_allocator.allocator(), JsAny.from(_dk))"),
"delete obj[expr] should use .delete(alloc, JsAny.from(key)): {}",
zig
);
assert!(
zig.contains("_ = ") && zig.contains("deleteKey"),
"delete should use _ = to discard: {}",
zig
);
assert!(
zig.contains("deleteKey(\"b\")"),
"delete obj.a.b should still emit deleteKey for the outer property: {}",
zig
);
assert!(
!zig.contains("_ = .deleteKey"),
"delete obj.a.b must NOT discard the receiver (no bare `_ = .deleteKey`): {}",
zig
);
}
#[test]
fn test_native_proto_compound_assignment() {
let js = r#"
function exp_assign(a, b) {
a **= b;
return a;
}
function and_assign(a, b) {
a &&= b;
return a;
}
function or_assign(a, b) {
a ||= b;
return a;
}
function nullish_assign(a, b) {
a ??= b;
return a;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_compound_assignment");
assert!(
zig.contains("std.math.pow(f64,"),
"**= should use std.math.pow: {}",
zig
);
assert!(
zig.contains("js_runtime.isTruthy"),
"&&= should use js_runtime.isTruthy: {}",
zig
);
assert!(
zig.contains("js_runtime.isTruthy"),
"||= should use js_runtime.isTruthy: {}",
zig
);
assert!(
!zig.contains(".isNullish()"),
"??= on anytype should be no-op (no isNullish): {}",
zig
);
}
#[test]
fn test_nullish_assign_jsany() {
let js = r#"
function nullish_jsany() {
let x = null;
x ??= 42;
return x;
}
"#;
let zig = transpile_and_assert(js, "test_nullish_assign_jsany");
assert!(
zig.contains(".isNullish()"),
"??= on JsAny should use isNullish: {}",
zig
);
}
#[test]
fn test_compound_assign_member_side_effect() {
let js = r#"
/**
* @typedef {Object} Box
* @property {number} value
*/
/**
* @type {Box}
*/
var box = { value: 5 };
function getBox() {
return box;
}
/**
* @returns {number}
*/
export function testPowAssignSideEffect() {
getBox().value **= 3;
return box.value;
}
/**
* @returns {number}
*/
export function testRemAssignSideEffect() {
getBox().value %= 4;
return box.value;
}
/**
* @returns {number}
*/
export function testUrShrAssignSideEffect() {
getBox().value >>>= 1;
return box.value;
}
"#;
let zig = transpile_and_assert(js, "test_compound_assign_member_side_effect");
println!("=== Compound assign on side-effecting member ===\n{}", zig);
let co_count = zig.matches("__co_").count();
assert!(
co_count >= 3,
"Expected at least 3 __co_ temp bindings (one per compound op), got {}: {}",
co_count,
zig
);
assert!(
!zig.contains("__target"),
"Should not use __target placeholder:\n{}",
zig
);
assert!(
zig.contains("_co_blk"),
"Should use _co_blk labeled block for temp binding:\n{}",
zig
);
}
#[test]
fn test_p1_11_return_inside_for_loop() {
let js = r#"
export function firstMatch(arr) {
for (let i = 0; i < arr.length; i = i + 1) {
if (i === 2) return "found";
}
return "not-found";
}
"#;
let zig = transpile_and_assert(js, "test_p1_11_return_inside_for_loop");
assert!(
zig.contains("[]const u8"),
"Expected return type []const u8 (return inside for loop was dropped before P1-11):\n{}",
zig
);
}
#[test]
fn test_p1_11_return_inside_switch() {
let js = r#"
/** @param {number} code */
export function classify(code) {
switch (code) {
case 1: return "one";
case 2: return "two";
default: return "other";
}
}
"#;
let zig = transpile_and_assert(js, "test_p1_11_return_inside_switch");
assert!(
zig.contains("[]const u8"),
"Expected return type []const u8 (return inside switch was dropped before P1-11):\n{}",
zig
);
}
#[test]
fn test_p1_11_return_inside_labeled_for() {
let js = r#"
export function findTarget(target, items) {
search: for (let i = 0; i < items.length; i = i + 1) {
if (i === target) return i;
}
return -1;
}
"#;
let zig = transpile_and_assert(js, "test_p1_11_return_inside_labeled_for");
assert!(
zig.contains("return i;") || zig.contains("return _i;"),
"Expected return statement inside for-loop body in:\n{}",
zig
);
}
#[test]
fn test_native_proto_f64_inference() {
let js = r#"
function pi() {
return 3.14159;
}
function divide(a, b) {
return a / b;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_f64_inference");
assert!(zig.contains("3.14159"));
}
#[test]
fn test_native_proto_complex() {
let js = r#"
const PI = 3.14;
function circleArea(radius) {
var r2 = radius * radius;
return PI * r2;
}
function factorial(n) {
if (n <= 1) {
return 1;
}
var rest = factorial(n - 1);
return n * rest;
}
"#;
let zig = parse_and_transpile(js, None).unwrap().zig_code;
println!("=== Complex Test ===\n{}", zig);
assert!(zig.contains("const PI = 3.14;"));
assert!(zig.contains("fn circleArea(radius: anytype)"));
assert!(zig.contains("const r2 = (radius * radius);"));
assert!(zig.contains("factorial(")); assert!(
zig.contains("if ((n") && zig.contains("<="),
"missing if: {}",
zig
);
}
#[test]
fn test_native_proto_no_return_void() {
let js = r#"
function log(msg) {
// no explicit return →void
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_no_return_void");
assert!(zig.contains(") void {"));
}
#[test]
fn test_native_proto_do_while() {
let js = r#"
function count_down(n) {
var x = n;
do {
x = x - 1;
} while (x > 0);
return x;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_do_while");
assert!(
zig.contains("__dw_first"),
"missing do-while first-iteration flag: {}",
zig
);
assert!(
zig.contains("__dw_first_0"),
"missing do-while first-iteration flag (__dw_first_0): {}",
zig
);
assert!(
zig.contains("while (__dw_first_0 or ((x > 0)))"),
"missing do-while while condition: {}",
zig
);
assert!(
zig.contains(": (__dw_first_0 = false)"),
"missing do-while continuation: {}",
zig
);
assert!(
zig.contains("JsAny.from(x)"),
"expected JsAny.from(x) coercion for JsAny-returning function: {}",
zig
);
}
#[test]
fn test_native_proto_nested_do_while() {
let js = r#"
/** @param {number} n */
export function nestedDoWhile(n) {
let result = 0;
let i = 0;
do {
i = i + 1;
let j = 0;
do {
j = j + 1;
result = result + j;
} while (j < 3);
} while (i < n);
return result;
}
"#;
let zig = transpile_and_check(js, "test_native_proto_nested_do_while");
assert!(
zig.contains("__dw_first_0"),
"Expected outer do-while flag __dw_first_0 in:\n{}",
zig
);
assert!(
zig.contains("__dw_first_1"),
"Expected inner do-while flag __dw_first_1 in:\n{}",
zig
);
}
#[test]
fn test_native_proto_for_of() {
let js = r#"
function sum(arr) {
var total = 0;
for (const x of arr) {
total = total + x;
}
return total;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_for_of");
println!("=== Generated Zig (test_native_proto_for_of) ===\n{}", zig);
assert!(zig.contains("for ("), "missing for: {}", zig);
assert!(zig.contains("return total;"));
assert!(
zig.contains("var total: i64 = 0;"),
"Expected 'var total: i64 = 0;':\n{}",
zig
);
assert_zig_ast_check(&zig, "test_native_proto_for_of");
}
#[test]
fn test_native_proto_for_in() {
let js = r#"
function iterateKeys(obj) {
var keys = "";
for (var key in obj) {
keys = keys + key;
}
return keys;
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_for_in");
assert!(
zig.contains("__it") || zig.contains("for-in:") || zig.contains("compileError"),
"Expected for-in handler in:\n{}",
zig
);
}
#[test]
fn test_native_proto_for_in_static() {
let js = r#"
function gatherKeys(obj) {
var keys = "";
for (var k in obj) {
keys = keys + k;
}
return keys;
}
function useStaticObj() {
const obj = { a: 1, b: 2, name: "test" };
return gatherKeys(obj);
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_for_in_static");
assert!(
zig.contains("const k = \"a\""),
"Expected unrolled field 'a':\n{}",
zig
);
assert!(
zig.contains("const k = \"b\""),
"Expected unrolled field 'b':\n{}",
zig
);
assert!(
zig.contains("const k = \"name\""),
"Expected unrolled field 'name':\n{}",
zig
);
assert!(
!zig.contains("__it"),
"Should not have HashMap iterator:\n{}",
zig
);
}
#[test]
fn test_p2_for_in_static_codegen() {
let js = r#"
function gatherKeys(obj) {
var keys = "";
for (var k in obj) {
keys = keys + k + ";";
}
return keys;
}
function demo() {
const obj = { a: 1, b: 2, name: "test" };
return gatherKeys(obj);
}
"#;
let zig = transpile_and_assert(js, "test_p2_for_in_static_codegen");
assert!(
zig.contains("const k = \"a\""),
"Expected unrolled field 'a'"
);
assert!(
zig.contains("const k = \"b\""),
"Expected unrolled field 'b'"
);
assert!(
zig.contains("const k = \"name\""),
"Expected unrolled field 'name'"
);
assert!(!zig.contains("__it"), "Should not have HashMap iterator");
assert!(
zig.contains("allocPrint"),
"Expected allocPrint for string concat"
);
}
#[test]
fn test_p2_nested_function_no_capture() {
let js = r#"
function outer(x) {
function inner(y) {
return y * 2;
}
return inner(x);
}
"#;
let result = parse_and_transpile(js, None).unwrap();
let zig = result.zig_code;
eprintln!("=== DEBUG: outer() return type ===");
eprintln!("{}", zig);
assert!(
result.errors.is_empty(),
"Unexpected errors: {:?}",
result.errors
);
println!("=== Nested function (no capture) Zig code ===\n{}", zig);
assert!(
zig.contains("const inner = struct {"),
"Expected inner to be a struct"
);
assert!(zig.contains("pub fn call("), "Expected call() method");
assert!(
zig.contains("inner.call(x)"),
"Expected call to be rewritten"
);
}
#[test]
fn test_p2_nested_function_with_capture() {
let js = r#"
function outer(x) {
function inner(y) {
return x + y; // x is captured from outer scope
}
return inner(3);
}
"#;
let zig = parse_and_transpile(js, None).unwrap().zig_code;
println!("=== Nested function (with capture) Zig code ===\n{}", zig);
assert!(
zig.contains("_inner_type = struct {"),
"Expected _inner_type struct declaration"
);
assert!(zig.contains("x:"), "Expected capture field x");
assert!(
zig.contains("inner = _inner_type"),
"Expected inner = _inner_type instantiation"
);
assert!(zig.contains("inner.call("), "Expected call to be rewritten");
assert!(
zig.contains("pub fn call(self:"),
"Expected call method with self parameter"
);
}
#[test]
fn test_native_proto_switch() {
let js = r#"
function grade(score) {
switch (score) {
case 10:
return "perfect";
case 5:
return "good";
default:
return "bad";
}
}
"#;
let zig = transpile_and_assert(js, "test_native_proto_switch");
assert!(zig.contains("switch (score) {"), "missing switch: {}", zig);
assert!(zig.contains("10 => {"), "missing case 10: {}", zig);
assert!(zig.contains("5 => {"), "missing case 5: {}", zig);
assert!(zig.contains("else => {"), "missing else: {}", zig);
assert!(zig.contains("return \"perfect\";"));
assert!(zig.contains("return \"good\";"));
assert!(zig.contains("return \"bad\";"));
}
#[test]
fn test_native_proto_e2e_compile_and_run() {
let js = r#"
const PI = 3.14159;
function add(a, b) {
return a + b;
}
function abs(x) {
if (x >= 0) {
return x;
}
return -x;
}
function main() {
const x = add(10, 20);
const y = abs(-42);
}
"#;
let zig_gen = parse_and_transpile(js, None).unwrap().zig_code;
println!("=== Generated Zig code ===\n{}", zig_gen);
let tmp_dir = std::env::temp_dir();
let zig_path = tmp_dir.join("e2e_native_gen.zig");
std::fs::write(&zig_path, &zig_gen).unwrap();
let check_output = std::process::Command::new(zig_binary())
.args(["ast-check", zig_path.to_str().unwrap()])
.output();
match check_output {
Ok(o) => {
if !o.status.success() {
eprintln!("=== zig ast-check failed ===");
eprintln!("Generated code:\n{}", zig_gen);
eprintln!("stderr: {}", String::from_utf8_lossy(&o.stderr));
} else {
println!("=== zig ast-check passed ===");
}
}
Err(e) => {
eprintln!("Failed to run zig ast-check: {}", e);
return; }
}
let zig_full = r#"const std = @import("std");
const PI: f64 = 3.14159;
fn add(a: anytype, b: anytype) !@TypeOf(a + b) {
return a + b;
}
fn abs(x: anytype) !@TypeOf(x) {
if (x >= 0) {
return x;
}
return -x;
}
pub fn main() !void {
const x = try add(10, 20);
const y = try abs(-42);
std.debug.print("add(10,20)={} abs(-42)={}\n", .{x, y});
}
"#
.to_string();
let zig_path_full = tmp_dir.join("e2e_native_full.zig");
let exe_path = tmp_dir.join("e2e_native_full.exe");
std::fs::write(&zig_path_full, &zig_full).unwrap();
let build_output = std::process::Command::new(zig_binary())
.args([
"build-exe",
zig_path_full.to_str().unwrap(),
"-O",
"Debug",
&format!("-femit-bin={}", exe_path.to_str().unwrap()),
])
.output();
let build_output = match build_output {
Ok(o) => o,
Err(e) => {
eprintln!("Failed to run zig build-exe: {}", e);
return;
}
};
if !build_output.status.success() {
eprintln!("=== Zig compilation failed ===");
eprintln!("Generated code:\n{}", zig_full);
eprintln!("stderr: {}", String::from_utf8_lossy(&build_output.stderr));
panic!("Zig compilation failed - prototype needs fixing");
}
println!("=== Compilation succeeded ===");
let run_output = std::process::Command::new(&exe_path)
.output()
.expect("Failed to run executable");
let stdout = String::from_utf8_lossy(&run_output.stdout);
let stderr = String::from_utf8_lossy(&run_output.stderr);
println!("Program stdout: {}", stdout);
println!("Program stderr: {}", stderr);
assert!(
stderr.contains("add(10,20)=30"),
"expected 'add(10,20)=30' in stderr, got: stdout='{}' stderr='{}'",
stdout,
stderr
);
assert!(
stderr.contains("abs(-42)=42"),
"expected 'abs(-42)=42' in stderr, got: stdout='{}' stderr='{}'",
stdout,
stderr
);
println!("=== E2E test passed! Generated Zig code compiles and runs correctly ===");
}
#[test]
fn test_p2_1_neg_zero_preserves_f64() {
let js = r#"
export function negZero() {
var x = -0.0;
return x;
}
"#;
let zig = transpile_and_assert(js, "test_p2_1_neg_zero_preserves_f64");
assert!(
zig.contains("-0.0"),
"Expected '-0.0' in generated Zig to preserve signed zero:\n{}",
zig
);
}
#[test]
fn test_p2_2_bitwise_not_type_inference() {
let js = r#"
/** @param {number} x */
export function bitnot(x) {
var y = ~x;
return y;
}
"#;
let zig = transpile_and_check(js, "test_p2_2_bitwise_not_type_inference");
assert!(
zig.contains("~"),
"Expected bitwise not (~) in generated Zig:\n{}",
zig
);
}
#[test]
fn test_p2_2_bitwise_not_bigint() {
let js = r#"
/** @param {bigint} x */
export function bitnotBig(x) {
return ~x;
}
"#;
let zig = transpile_and_check(js, "test_p2_2_bitwise_not_bigint");
assert!(
zig.contains("bitwiseNot"),
"Expected bitwiseNot for ~BigInt:\n{}",
zig
);
}
#[test]
fn test_p2_6_negation_folding_still_works() {
let js = r#"
export function neg42() {
return -42;
}
"#;
let zig = transpile_and_assert(js, "test_p2_6_negation_folding_still_works");
assert!(
zig.contains("-42"),
"Expected '-42' (folded negation) in:\n{}",
zig
);
}
#[test]
fn test_p2_5_labeled_for_in_struct_unroll() {
let js = r#"
function gatherKeys(obj) {
var keys = "";
outer: for (var k in obj) {
if (k == "b") {
break outer;
}
keys = keys + k;
}
return keys;
}
function demo() {
const obj = { a: 1, b: 2, name: "test" };
return gatherKeys(obj);
}
"#;
let zig = transpile_and_assert(js, "test_p2_5_labeled_for_in_struct_unroll");
assert!(
zig.contains("\"a\""),
"Expected unrolled field 'a' in:\n{}",
zig
);
assert!(
zig.contains("\"b\""),
"Expected unrolled field 'b' in:\n{}",
zig
);
let after_label = zig.split("outer: {").nth(1);
assert!(
after_label.is_some(),
"Expected label 'outer: {{' in:\n{}",
zig
);
let rest = after_label.unwrap();
assert!(
rest.trim_start().starts_with('{'),
"Expected wrapper block after label (outer: {{ {{ ...), not direct iteration content:\n{}",
zig
);
}
#[test]
fn test_r4_1_div_int_baseline() {
let js = r#"
function safeDivide(a, b) {
return a / b;
}
"#;
let zig = transpile_and_check(js, "test_r4_1_div_int_baseline");
assert!(
zig.contains("@floatFromInt"),
"Integer / division should use @floatFromInt (anytype-safe): {}",
zig
);
assert!(
!zig.contains(".asF64()"),
"Integer / should NOT use .asF64() (no JsAny): {}",
zig
);
}
#[test]
fn test_r4_1_div_jsany_operand() {
let js = r#"
function divMapVal() {
const m = new Map();
m.set("a", 10);
const v = m.get("a");
return v / 2;
}
"#;
let zig = transpile_and_check(js, "test_r4_1_div_jsany_operand");
println!("=== R4-1 DivExpr with JsAny ===\n{}", zig);
assert!(
zig.contains(".asF64()"),
"DivExpr with JsAny operand should call .asF64(): {}",
zig
);
}
#[test]
fn test_r4_2_jsany_arith_f64_operand() {
let js = r#"
function addF64ToMapVal() {
const m = new Map();
m.set("a", 10);
const v = m.get("a");
return v + 1.5;
}
"#;
let zig = transpile_and_check(js, "test_r4_2_jsany_arith_f64_operand");
println!("=== R4-2 JsAny + F64 ===\n{}", zig);
assert!(
zig.contains(".asF64()"),
"JsAny + F64 should use .asF64() (not .asI64()): {}",
zig
);
assert!(
!zig.contains(".asI64()"),
"JsAny + F64 should NOT use .asI64() (would truncate the F64): {}",
zig
);
}
#[test]
fn test_r4_2_jsany_arith_i64_operand() {
let js = r#"
function addI64ToMapVal() {
const m = new Map();
m.set("a", 10);
const v = m.get("a");
return v + 5;
}
"#;
let zig = transpile_and_check(js, "test_r4_2_jsany_arith_i64_operand");
println!("=== R4-2 JsAny + i64 ===\n{}", zig);
assert!(
zig.contains(".asI64()"),
"JsAny + i64 should use .asI64(): {}",
zig
);
}
#[test]
fn test_r4_3_jsany_cmp_f64_preserves_float() {
let js = r#"
function cmpMapVal() {
const m = new Map();
m.set("a", 5.5);
const v = m.get("a");
if (v < 5.6) return 1;
return 0;
}
"#;
let zig = transpile_and_check(js, "test_r4_3_jsany_cmp_f64_preserves_float");
println!("=== R4-3 JsAny < F64 ordering ===\n{}", zig);
assert!(
zig.contains(".lt("),
"JsAny ordering should emit .lt() runtime method: {}",
zig
);
assert!(
!zig.contains(".asI64()"),
"JsAny ordering should NOT use .asI64() (truncates floats): {}",
zig
);
}
#[test]
fn test_r4_4_array_spread_wraps_via_jsany_from() {
let js = r#"
function spreadIntArr() {
const arr = [1, 2, 3];
return [...arr];
}
"#;
let zig = transpile_and_check(js, "test_r4_4_array_spread_wraps_via_jsany_from");
println!("=== R4-4 array spread with i64 source ===\n{}", zig);
assert!(
zig.contains("for (") && zig.contains(".items) |__spread_item|"),
"Spread should iterate .items via a for-loop with __spread_item: {}",
zig
);
assert!(
zig.contains("JsAny.from(__spread_item)"),
"Spread should wrap each item via JsAny.from(): {}",
zig
);
assert!(
!zig.contains("appendSlice"),
"Spread should NOT use appendSlice (breaks for non-JsAny element types): {}",
zig
);
}
#[test]
fn test_r4_5_index_compound_logical_uses_is_truthy() {
let js = r#"
function indexCompound() {
const arr = [1, 2, 3];
arr[0] &&= 2;
arr[1] ||= 3;
return arr[0];
}
"#;
let zig = transpile_and_check(js, "test_r4_5_index_compound_logical_uses_is_truthy");
println!("=== R4-5 Index compound &&= / ||= ===\n{}", zig);
assert!(
zig.contains("js_runtime.isTruthy"),
"Index-target compound &&= / ||= should use js_runtime.isTruthy (not .toBool()): {}",
zig
);
assert!(
!zig.contains(".toBool()"),
"Index-target compound should NOT use .toBool() (only valid on JsAny): {}",
zig
);
}
#[test]
fn test_r5_2_array_literal_non_literal_fallback_is_jsany() {
let js = r#"
function buildArr(x) {
const arr = [x];
return arr;
}
"#;
let zig = transpile_and_check(js, "test_r5_2_array_literal_non_literal_fallback_is_jsany");
println!(
"=== R5-2 array literal with non-literal element ===\n{}",
zig
);
assert!(
zig.contains("std.ArrayList(JsAny)"),
"Non-literal element array must use ArrayList(JsAny) fallback (post-fix): {}",
zig
);
assert!(
!zig.contains("std.ArrayList(i64)"),
"Non-literal element array must NOT use ArrayList(i64) (pre-fix fallback breaks f64 elements): {}",
zig
);
}
#[test]
fn test_r5_3_emit_bigint_string_concat_documented_unreachable() {
let src = include_str!("../zigir/emit/expr/binary.rs");
assert!(
!src.contains("\"blk:\""),
"emit_bigint_string_concat must not reintroduce the hardcoded \"blk:\" label"
);
assert!(
src.contains("next_label()"),
"emit_bigint_string_concat should use next_label() for unique labels"
);
}
#[test]
fn test_r5_4_bigint_postfix_returns_old_value() {
let js = r#"
/**
* @param {bigint} x
* @returns {bigint}
*/
export function test(x) {
const y = x++;
return y;
}
"#;
let zig = transpile_and_check(js, "test_r5_4_bigint_postfix_returns_old_value");
println!(
"=== R5-4 BigInt postfix `x++` (old value capture) ===\n{}",
zig
);
assert!(
zig.contains("__bi_post"),
"BigInt postfix must capture old value in a __bi_post temp var (BlockExpr): {}",
zig
);
assert!(
zig.contains("break :") && zig.contains("__bi_post"),
"BigInt postfix BlockExpr must break with the __bi_post temp var (old value): {}",
zig
);
}
#[test]
fn test_r5_5_return_type_unify_i64_f64_promotion() {
let js = r#"
function mixedReturn(x) {
if (x) return 1;
return 1.5;
}
"#;
let zig = transpile_and_check(js, "test_r5_5_return_type_unify_i64_f64_promotion");
println!("=== R5-5 mixed int/float return unification ===\n{}", zig);
assert!(
zig.contains(") f64 {") || zig.contains(") f64\n"),
"Mixed I64/F64 returns must unify to f64 (not default to i64): {}",
zig
);
assert!(
!zig.contains("Return type mismatch"),
"Should NOT report a return type mismatch for I64+F64 (should promote to F64): {}",
zig
);
}
#[test]
fn test_r5_6_str_plus_str_inferred_as_str() {
let js = r#"
function concatStr() {
return "a" + "b";
}
"#;
let zig = transpile_and_check(js, "test_r5_6_str_plus_str_inferred_as_str");
println!("=== R5-6 Str + Str inferred as Str ===\n{}", zig);
assert!(
zig.contains(") []const u8 {") || zig.contains(") []const u8\n"),
"Str + Str must infer as Str (return type []const u8), not i64: {}",
zig
);
assert!(
!zig.contains(") i64 {"),
"Str + Str must NOT infer as i64 (pre-fix bug — checked BigInt before Str): {}",
zig
);
}
#[test]
fn test_r5_7_top_level_unused_const_preserves_compileerror() {
let js = r#"
function tag(parts) { return parts[0]; }
const X = tag`hello`;
"#;
let zig = transpile_and_assert(
js,
"test_r5_7_top_level_unused_const_preserves_compileerror",
);
println!(
"=== R5-7 top-level unused const with @compileError ===\n{}",
zig
);
assert!(
zig.contains("@compileError"),
"Top-level unused const with unsupported init must preserve @compileError (was silently stripped by DCE pre-fix): {}",
zig
);
}
#[test]
fn test_r5_8_remexpr_jsany_uses_rem_asf64() {
let js = r#"
function modJsAny() {
const x = JSON.parse("5.7");
return x % 2;
}
"#;
let zig = transpile_and_check(js, "test_r5_8_remexpr_jsany_uses_rem_asf64");
println!("=== R5-8 RemExpr with JsAny operand ===\n{}", zig);
assert!(
zig.contains("@rem("),
"RemExpr with JsAny operand must use @rem (not jsRem): {}",
zig
);
assert!(
zig.contains(".asF64()"),
"RemExpr with JsAny must use .asF64() to preserve float payload: {}",
zig
);
assert!(
!zig.contains("js_runtime.jsRem"),
"RemExpr with JsAny must NOT use jsRem (truncates floats via .asI64): {}",
zig
);
}
#[test]
fn test_r5_11_array_type_walks_all_elements() {
let js = r#"
function mixedArray() {
const arr = [1, 2.5];
return arr;
}
"#;
let zig = transpile_and_check(js, "test_r5_11_array_type_walks_all_elements");
println!(
"=== R5-11 mixed int/float array walking elements ===\n{}",
zig
);
assert!(
zig.contains("std.ArrayList(JsAny)"),
"Mixed int/float array must infer ArrayList(JsAny) (any mismatch degrades from first elem type): {}",
zig
);
assert!(
!zig.contains("std.ArrayList(i64)"),
"Mixed int/float array must NOT infer ArrayList(I64) (pre-fix bug — used only first elem type): {}",
zig
);
}
#[test]
fn test_r5_12_conditional_expr_str_f64_not_promoted() {
let js = r#"
function condStr(flag) {
const x = flag ? "a" : 1.5;
return x;
}
"#;
let zig = transpile_and_check(js, "test_r5_12_conditional_expr_str_f64_not_promoted");
println!("=== R5-12 conditional Str+F64 not promoted ===\n{}", zig);
assert!(
!zig.contains(": f64 ="),
"Conditional Str+F64 variable must NOT be annotated :f64 (Str branch cannot coerce to f64): {}",
zig
);
}
#[test]
fn test_r6_1_try_finally_no_catch_propagates_throw() {
let js = r#"
function tryThrowFinally() {
try {
throw 1;
} finally {
}
}
"#;
let zig = transpile_and_check(js, "test_r6_1_try_finally_no_catch_propagates_throw");
println!(
"=== R6-1 try-finally-no-catch propagates throw ===\n{}",
zig
);
assert!(
zig.contains("else |_| return error.JsThrow;"),
"try{{throw}}finally{{}} (no catch) must propagate the throw via `else |_| return error.JsThrow;` (was silently swallowed pre-fix because the propagate guard was `if needs_catch`): {}",
zig
);
}
#[test]
fn test_r6_2_string_switch_uses_mem_eql() {
let js = r#"
function strSwitch(x) {
switch (x) {
case "a": return 1;
case "b": return 2;
default: return 0;
}
}
"#;
let zig = transpile_and_check(js, "test_r6_2_string_switch_uses_mem_eql");
println!("=== R6-2 string switch uses std.mem.eql ===\n{}", zig);
assert!(
zig.contains("std.mem.eql(u8,"),
"String switch must generate `std.mem.eql(u8, ...)` comparison (pre-fix emitted invalid `switch` on []const u8): {}",
zig
);
assert!(
!zig.contains("switch (x)"),
"String switch must NOT use Zig `switch` on the string variable (pre-fix bug): {}",
zig
);
}
#[test]
fn test_r6_3_template_literal_uses_cooked_not_raw() {
let js = r#"
function templateNewline() {
return `hello\nworld`;
}
"#;
let zig = transpile_and_check(js, "test_r6_3_template_literal_uses_cooked_not_raw");
println!("=== R6-3 template literal cooked vs raw ===\n{}", zig);
assert!(
zig.contains("hello\\nworld"),
"Template literal with \\n must use cooked value (Zig source: \"hello\\nworld\", 1 backslash + n): {}",
zig
);
assert!(
!zig.contains("hello\\\\nworld"),
"Template literal with \\n must NOT use raw value (Zig source: \"hello\\\\nworld\", 2 backslashes + n — runtime string would be `hello\\nworld` literally): {}",
zig
);
}
#[test]
fn test_r6_4_str_plus_bigint_no_n_suffix() {
let js = r#"
function strPlusBigInt() {
return "1" + 2n;
}
"#;
let zig = transpile_and_check(js, "test_r6_4_str_plus_bigint_no_n_suffix");
println!("=== R6-4 str + bigint no n suffix ===\n{}", zig);
assert!(
zig.contains(".toString("),
"String + BigInt must wrap the BigInt operand in a .toString(allocator) call (pre-fix used {{any}} format which invokes JsBigInt.format appending \"n\" suffix): {}",
zig
);
assert!(
!zig.contains("{any}"),
"String + BigInt must NOT use {{any}} format specifier for the BigInt operand (appends \"n\" suffix at runtime): {}",
zig
);
}
#[test]
fn test_r8_e6_math_max_min_empty_and_float() {
let js = r#"
/** @returns {number} */
export function maxEmpty() { return Math.max(); }
/** @returns {number} */
export function minEmpty() { return Math.min(); }
"#;
let zig = transpile_and_check(js, "test_r8_e6_math_max_min_empty_and_float");
assert!(
zig.contains("std.math.inf(f64)"),
"Math.max()/Math.min() with no args must return Infinity (R8-E6): {}",
zig
);
assert!(
zig.contains("-std.math.inf(f64)"),
"Math.max() with no args must return -Infinity (R8-E6): {}",
zig
);
let js2 = r#"
/** @returns {number} */
export function maxf(a, b) { return Math.max(1.5, 2.5); }
"#;
let zig2 = transpile_and_check(js2, "test_r8_e6_math_max_min_float_args");
assert!(
!zig2.contains("@as(i64, 1.5)"),
"Math.max with float args must not emit @as(i64, ...) (R8-E6): {}",
zig2
);
}
#[test]
fn test_r8_e1_unary_plus_to_number() {
let js = r#"
/** @returns {number} */
export function plusTrue() { return +true; }
"#;
let zig = transpile_and_check(js, "test_r8_e1_unary_plus_true");
assert!(
!zig.contains("+true"),
"+true must be constant-folded to 1, not emitted as +true (R8-E1): {}",
zig
);
let js2 = r#"
/** @param {boolean} flag @returns {number} */
export function plusBool(flag) { return +flag; }
"#;
let zig2 = transpile_and_check(js2, "test_r8_e1_unary_plus_bool");
println!("=== R8-E1 +bool ===\n{}", zig2);
assert!(
zig2.contains("if (") || zig2.contains("@intFromBool"),
"+boolVar must be coerced to number, not passed through as bool (R8-E1): {}",
zig2
);
let js3 = r#"
/** @param {string} s @returns {number} */
export function plusStr(s) { return +s; }
"#;
let zig3 = transpile_and_check(js3, "test_r8_e1_unary_plus_str");
println!("=== R8-E1 +str ===\n{}", zig3);
assert!(
zig3.contains("js_number.constructor"),
"+strVar must call js_number.constructor for ToNumber (R8-E1): {}",
zig3
);
}
#[test]
fn test_r8_p1_7_jsany_uses_f_specifier() {
let js = r#"
/** @returns {string} */
export function tmplJson() { return `val: ${JSON.parse("42")}`; }
"#;
let zig = transpile_and_check(js, "test_r8_p1_7_jsany_template_f");
println!("=== R8-P1-7 template ===\n{}", zig);
assert!(
zig.contains("{f}"),
"Template literal with JsAny must use {{f}} specifier (R8-P1-7): {}",
zig
);
assert!(
!zig.contains("{any}"),
"Template literal with JsAny must NOT use {{any}} specifier (R8-P1-7): {}",
zig
);
let js2 = r#"
/** @returns {string} */
export function concatJson() { return "val: " + JSON.parse("42"); }
"#;
let zig2 = transpile_and_check(js2, "test_r8_p1_7_jsany_concat_f");
println!("=== R8-P1-7 concat ===\n{}", zig2);
assert!(
zig2.contains("{f}"),
"String concat with JsAny must use {{f}} specifier (R8-P1-7): {}",
zig2
);
assert!(
!zig2.contains("{any}"),
"String concat with JsAny must NOT use {{any}} specifier (R8-P1-7): {}",
zig2
);
}
#[test]
fn test_r8_e2_f64_uses_default_specifier_not_d15() {
let js = r#"
/** @returns {string} */
export function tmplFloat() { return `v=${1.5}`; }
"#;
let zig = transpile_and_check(js, "test_r8_e2_f64_template");
println!("=== R8-E2 template ===\n{}", zig);
assert!(
!zig.contains("{d:.15}"),
"Template literal with F64 must NOT use {{d:.15}} (R8-E2): {}",
zig
);
let js2 = r#"
/** @returns {string} */
export function concatFloat() { return "v=" + 1.5; }
"#;
let zig2 = transpile_and_check(js2, "test_r8_e2_f64_concat");
println!("=== R8-E2 concat ===\n{}", zig2);
assert!(
!zig2.contains("{d:.15}"),
"String concat with F64 must NOT use {{d:.15}} (R8-E2): {}",
zig2
);
}
#[test]
fn test_r8_c7_this_field_in_loop_switch_try() {
let js = r#"
class Acc {
constructor(n) {
this.count = 0;
for (let i = 0; i < n; i++) {
this.count = this.count + 1;
}
switch (n) {
case 0: this.flag = "zero"; break;
default: this.flag = "nonzero"; break;
}
try {
this.computed = n * 2;
} catch (e) {
this.computed = -1;
}
}
}
"#;
let zig = transpile_and_check(js, "test_r8_c7_this_field_nested");
println!("=== R8-C7 nested this-field ===\n{}", zig);
assert!(
zig.contains("var count:") && zig.contains("var flag:") && zig.contains("var computed:"),
"Expected pre-declared `var count/flag/computed` at the top of init (R8-C7): {}",
zig
);
assert!(
!zig.contains("self.count"),
"this.count read/write must be rewritten to `count`, not `self.count` (R8-C7): {}",
zig
);
assert!(
!zig.contains("self.flag = "),
"Switch-body `this.flag = ...` must be rewritten (R8-C7): {}",
zig
);
assert!(
!zig.contains("self.computed = "),
"Try-body `this.computed = ...` must be rewritten (R8-C7): {}",
zig
);
assert!(
zig.contains("return .{ .count = count"),
"Expected `return .{{ .count = count, ... }}` referencing the pre-declared var (R8-C7): {}",
zig
);
}
#[test]
fn test_r8_c7_this_field_in_if_else() {
let js = r#"
class C {
constructor(f) {
if (f) { this.a = 1; } else { this.a = 2; }
}
}
"#;
let zig = transpile_and_check(js, "test_r8_c7_if_else");
println!("=== R8-C7 if/else ===\n{}", zig);
assert!(
zig.contains("var a:"),
"Expected `var a:` pre-declaration (R8-C7): {}",
zig
);
assert!(
zig.contains("a = 1;") && zig.contains("a = 2;"),
"Expected both if/else branches to assign to the local `a` (R8-C7): {}",
zig
);
assert!(
!zig.contains("self.a"),
"this.a must be rewritten to `a` (R8-C7): {}",
zig
);
assert!(
zig.contains("return .{ .a = a };"),
"Expected `return .{{ .a = a }};` (R8-C7): {}",
zig
);
}
#[test]
fn test_r8_c7_this_field_in_loop_only() {
let js = r#"
class C {
constructor(n) {
for (let i = 0; i < n; i++) { this.a = i; }
}
}
"#;
let zig = transpile_and_check(js, "test_r8_c7_loop_only");
println!("=== R8-C7 loop-only ===\n{}", zig);
assert!(
zig.contains("var a:"),
"Expected `var a:` pre-declaration (R8-C7): {}",
zig
);
assert!(
zig.contains("a = i;") && !zig.contains("self.a"),
"Expected loop body to assign `a = i`, never `self.a` (R8-C7): {}",
zig
);
assert!(
zig.contains("return .{ .a = a };"),
"Expected `return .{{ .a = a }};` (R8-C7): {}",
zig
);
}
#[test]
fn test_r8_c2_ctor_explicit_return_no_unreachable() {
let js = r#"
class C {
constructor(n) {
this.x = n;
return;
}
}
"#;
let zig = transpile_and_check(js, "test_r8_c2_ctor_return");
println!("=== R8-C2 ctor return ===\n{}", zig);
let init_section = zig
.split("pub fn init(")
.nth(1)
.expect("init function must exist");
let return_count = init_section.matches("return").count();
assert_eq!(
return_count, 1,
"Expected exactly one `return` in init body (R8-C2): {}",
zig
);
assert!(
!zig.contains("return .{ .x = x };"),
"Appended struct return must be suppressed when body ends in `return;` (R8-C2): {}",
zig
);
}
#[test]
fn test_r8_e4_c6_field_default_used_when_ctor_present() {
let js = r#"
class C {
x = 5;
constructor(n) {
this.y = n;
}
}
"#;
let zig = transpile_and_check(js, "test_r8_e4_c6_defaults_with_ctor");
println!("=== R8-E4/C6 defaults with ctor ===\n{}", zig);
assert!(
zig.contains("const x: i64 = 5;"),
"Expected `const x: i64 = 5;` seeding the field default in the ctor (R8-E4/C6): {}",
zig
);
assert!(
zig.contains("var y: JsAny = undefined;"),
"Expected `var y: JsAny = undefined;` for the reassigned field (R8-E4/C6): {}",
zig
);
assert!(
zig.contains("y = n;"),
"Expected `y = n;` rewrite (R8-E4/C6): {}",
zig
);
assert!(
zig.contains("return .{ .x = x, .y = y };") || zig.contains("return .{ .y = y, .x = x };"),
"Expected `return .{{ .x = x, .y = y }};` (order-independent) (R8-E4/C6): {}",
zig
);
}
#[test]
fn test_r8_c3_new_spread_rest_param() {
let js = r#"
class Collector {
count = 0;
constructor(...items) {
this.count = items.length;
}
}
export function makeCollector(...vals) {
const c = new Collector(...vals);
return c.count;
}
"#;
let zig = transpile_and_check(js, "test_r8_c3_new_spread_rest_param");
println!("=== R8-C3 new spread rest param ===\n{}", zig);
assert!(
zig.contains("Collector.init(vals)"),
"Expected `Collector.init(vals)` for rest-param spread in new (R8-C3): {}",
zig
);
assert!(
zig.contains("init(items: []const JsAny)"),
"Expected `init(items: []const JsAny)` rest param in constructor (R8-C3): {}",
zig
);
}
#[test]
fn test_r8_c3_new_spread_arraylist() {
let js = r#"
class Collector {
count = 0;
constructor(...items) {
this.count = items.length;
}
}
export function testSpread() {
const arr = [10, 20, 30];
const c = new Collector(...arr);
return c.count;
}
"#;
let zig = transpile_and_assert(js, "test_r8_c3_new_spread_arraylist");
println!("=== R8-C3 new spread arraylist ===\n{}", zig);
assert!(
zig.contains("Collector.init(arr.items)"),
"Expected `Collector.init(arr.items)` for ArrayList spread in new (R8-C3): {}",
zig
);
}
#[test]
fn test_r8_e5_c1_method_mutates_self() {
let js = r#"
class Counter {
count = 0;
increment() {
this.count = this.count + 1;
}
get() {
return this.count;
}
}
export function testMutate() {
const c = new Counter();
c.increment();
return c.get();
}
"#;
let zig = transpile_and_check(js, "test_r8_e5_c1_method_mutates_self");
println!("=== R8-E5/C1 method mutates self ===\n{}", zig);
assert!(
zig.contains("pub fn increment(self: *@This()"),
"Expected `self: *@This()` for mutating method (R8-E5/C1): {}",
zig
);
assert!(
zig.contains("pub fn get(self: @This()"),
"Expected `self: @This()` for read-only method (R8-E5/C1): {}",
zig
);
assert!(
zig.contains("var c = Counter.init()"),
"Expected `var c = Counter.init()` for class instance (R8-E5/C1): {}",
zig
);
}
#[test]
fn test_p0_5_operator_precedence_mul_over_add() {
let js = r#"
/**
* @param {number} a
* @param {number} b
* @param {number} c
* @returns {number}
*/
export function testParens(a, b, c) {
return (a + b) * c;
}
"#;
let zig = transpile_and_check(js, "test_p0_5_operator_precedence_mul_over_add");
println!("=== P0-5 operator precedence (mul over add) ===\n{}", zig);
assert!(
zig.contains("(a + b)"),
"Expected (a + b) to be parenthesized in: {}",
zig
);
}
#[test]
fn test_p0_5_shift_precedence_mismatch() {
let js = r#"
/**
* @param {number} a
* @param {number} b
* @param {number} c
* @returns {number}
*/
export function testShiftPrec(a, b, c) {
return (a + b) << c;
}
"#;
let zig = transpile_and_check(js, "test_p0_5_shift_precedence_mismatch");
println!("=== P0-5 shift precedence mismatch ===\n{}", zig);
assert!(
zig.contains("(a + b)"),
"Expected (a + b) to be parenthesized before << in: {}",
zig
);
}
#[test]
fn test_p0_5_implicit_shift_precedence() {
let js = r#"
/**
* @param {number} a
* @param {number} b
* @param {number} c
* @returns {number}
*/
export function testImplicitShift(a, b, c) {
return a + b << c;
}
"#;
let zig = transpile_and_check(js, "test_p0_5_implicit_shift_precedence");
println!("=== P0-5 implicit shift precedence ===\n{}", zig);
assert!(
zig.contains("(a + b)"),
"Expected (a + b) to be parenthesized for JS implicit precedence: {}",
zig
);
}
#[test]
fn test_p0_5_subtraction_in_multiplication() {
let js = r#"
/**
* @param {number} a
* @param {number} b
* @param {number} c
* @returns {number}
*/
export function testSubMul(a, b, c) {
return (a - b) * c;
}
"#;
let zig = transpile_and_check(js, "test_p0_5_subtraction_in_multiplication");
println!("=== P0-5 subtraction in multiplication ===\n{}", zig);
assert!(
zig.contains("(a - b)"),
"Expected (a - b) to be parenthesized in: {}",
zig
);
}