Skip to main content

js2zig_core/
testgen.rs

1use oxc_ast::ast::*;
2use std::collections::{HashMap, HashSet};
3
4/// A single test case extracted from a test_* variable
5#[derive(Debug, Clone)]
6pub struct TestCase {
7    /// The test_ variable name (e.g. "test_add")
8    pub var_name: String,
9    /// The expression text reconstructed from AST (e.g. "add(3, 5)")
10    pub expr_text: String,
11    /// Optional expected value as a Zig literal (e.g. "@as(i64, 8)")
12    /// parsed from a trailing `// => value` comment.
13    pub expected: Option<String>,
14}
15
16/// Parse a `// => value` comment into a Zig literal.
17/// Supports: integers → @as(i64, N), floats → @as(f64, N), strings → "s", bool/null.
18fn parse_expected_value(raw: &str) -> Option<String> {
19    let raw = raw.trim();
20    if raw.is_empty() {
21        return None;
22    }
23    // Boolean
24    if raw == "true" || raw == "false" {
25        return Some(raw.to_string());
26    }
27    // Null
28    if raw == "null" {
29        return Some("null".to_string());
30    }
31    // String literal
32    if raw.starts_with('"') && raw.ends_with('"') {
33        return Some(raw.to_string());
34    }
35    if raw.starts_with('\'') && raw.ends_with('\'') {
36        // Convert single-quoted JS string to double-quoted Zig string
37        let inner = &raw[1..raw.len() - 1];
38        return Some(format!("\"{}\"", inner));
39    }
40    // Float
41    if raw.contains('.') {
42        return Some(format!("@as(f64, {})", raw));
43    }
44    // Negative integer
45    if let Some(num) = raw.strip_prefix('-')
46        && num.chars().all(|c| c.is_ascii_digit())
47    {
48        return Some(format!("@as(i64, -{})", num));
49    }
50    // Positive integer
51    if raw.chars().all(|c| c.is_ascii_digit()) {
52        return Some(format!("@as(i64, {})", raw));
53    }
54    // Fallback: treat as raw identifier/expression
55    Some(raw.to_string())
56}
57
58/// Scan source text after `end_pos` for a `// => value` trailing comment.
59/// Only searches within the current line (up to the first newline).
60fn scan_expected_comment(source: &str, end_pos: usize) -> Option<String> {
61    let rest = &source[end_pos..];
62    // Only look on the current line
63    let line = rest.split('\n').next()?;
64    let comment_pos = line.find("// =>")?;
65    // Extract everything after `// =>` until end of line
66    let after_marker = &line[comment_pos + 5..]; // skip "// =>"
67    let trimmed = after_marker.trim();
68    if trimmed.is_empty() {
69        return None;
70    }
71    parse_expected_value(trimmed)
72}
73
74/// Extract test_* variable definitions from the AST.
75/// Scans source text for `// => expected` trailing comments.
76pub fn extract_test_cases(program: &Program, source: &str) -> Vec<TestCase> {
77    let mut cases = Vec::new();
78
79    for stmt in &program.body {
80        let Statement::VariableDeclaration(decl) = stmt else {
81            continue;
82        };
83        for declarator in &decl.declarations {
84            let name = match &declarator.id {
85                BindingPattern::BindingIdentifier(id) => id.name.as_str().to_string(),
86                _ => continue,
87            };
88            if !name.starts_with("test_") {
89                continue;
90            }
91            let Some(ref init) = declarator.init else {
92                continue;
93            };
94            let expr_text = expr_to_string(init);
95
96            // Try to find `// => value` comment after this statement
97            let expected = scan_expected_comment(source, decl.span.end as usize);
98
99            cases.push(TestCase {
100                var_name: name,
101                expr_text,
102                expected,
103            });
104        }
105    }
106
107    cases
108}
109
110/// Generate Zig test code from test cases.
111/// If a test case has an expected value (from `// => value` comment),
112/// generates an assertion; otherwise generates a smoke test (call + discard).
113///
114/// `closure_fns`: names of functions that return closure structs (needs .call() syntax)
115/// `fn_return_types`: map from function name to its Zig return type string (e.g. "i64", "JsValue")
116pub fn generate_test_code(
117    test_cases: &[TestCase],
118    closure_fns: &HashSet<&str>,
119    fn_return_types: &HashMap<String, String>,
120) -> String {
121    if test_cases.is_empty() {
122        return String::new();
123    }
124
125    let mut out = String::new();
126    out.push_str("// Auto-generated tests from test_* variables\n\n");
127
128    for tc in test_cases {
129        let test_name = tc.var_name.strip_prefix("test_").unwrap_or(&tc.var_name);
130
131        // Transform closure calls: makeAdder(10)(5) → makeAdder(10).call(5)
132        let mut call_expr = rewrite_closure_calls(&tc.expr_text, closure_fns);
133
134        // If the function returns JsValue/JsAny, extract the appropriate field
135        if let Some(fn_name) = extract_callee_name(&tc.expr_text)
136            && let Some(ret_type) = fn_return_types.get(&fn_name)
137            && let Some(ref expected) = tc.expected
138        {
139            if !expected.starts_with('"') {
140                // Numeric comparison: extract .int
141                if ret_type == "JsValue" {
142                    call_expr = format!("{}.int", call_expr);
143                } else if ret_type == "JsAny" {
144                    call_expr = format!("{}.value.int", call_expr);
145                }
146            } else {
147                // String comparison: extract .string / .value.string
148                if ret_type == "JsValue" {
149                    call_expr = format!("{}.string", call_expr);
150                } else if ret_type == "JsAny" {
151                    call_expr = format!("{}.value.string", call_expr);
152                }
153            }
154        }
155
156        out.push_str(&format!("test \"{}\" {{\n", sanitize_name(test_name)));
157        out.push_str("    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);\n");
158        out.push_str("    defer arena.deinit();\n");
159        out.push_str("    const allocator = arena.allocator();\n");
160        out.push_str("    init_js2rust();\n");
161        out.push_str("    defer deinit_js2rust();\n");
162
163        if let Some(ref expected) = tc.expected {
164            if expected.starts_with('"') {
165                // String comparison — use expectEqualSlices to compare content, not pointers
166                out.push_str(&format!(
167                    "    try std.testing.expectEqualSlices(u8, {}, {});\n",
168                    expected, call_expr
169                ));
170            } else {
171                out.push_str(&format!(
172                    "    try std.testing.expectEqual({}, {});\n",
173                    expected, call_expr
174                ));
175            }
176        } else {
177            out.push_str(&format!("    _ = {};\n", call_expr));
178        }
179
180        out.push_str("}\n\n");
181    }
182
183    out
184}
185
186/// Sanitize a name for use in Zig test strings
187fn sanitize_name(name: &str) -> String {
188    let mut s = String::new();
189    for ch in name.chars() {
190        if ch.is_ascii_alphanumeric() || ch == '_' {
191            s.push(ch);
192        } else {
193            s.push('_');
194        }
195    }
196    s
197}
198
199/// Reconstruct a JS expression as a string from its AST node.
200/// Handles the expression types that appear in test_ variable initializers
201/// (function calls, numeric/string/boolean literals, identifiers).
202fn expr_to_string(expr: &Expression) -> String {
203    match expr {
204        Expression::ArrowFunctionExpression(arrow) => {
205            // () => expr → extract the expression from the body statement
206            if let Statement::ExpressionStatement(es) = &arrow.body.statements[0] {
207                expr_to_string(&es.expression)
208            } else {
209                "<expr>".to_string()
210            }
211        }
212        Expression::CallExpression(call) => {
213            let callee_str = expr_to_string(&call.callee);
214            let args_str: Vec<String> = call
215                .arguments
216                .iter()
217                .map(|arg| match arg {
218                    Argument::SpreadElement(spread) => {
219                        format!("...{}", expr_to_string(&spread.argument))
220                    }
221                    _ => arg
222                        .as_expression()
223                        .map(|e| expr_to_string(e))
224                        .unwrap_or_else(|| "_".to_string()),
225                })
226                .collect();
227            format!("{}({})", callee_str, args_str.join(", "))
228        }
229        Expression::Identifier(id) => id.name.to_string(),
230        Expression::NumericLiteral(lit) => {
231            if let Some(raw) = &lit.raw {
232                raw.to_string()
233            } else if lit.value.fract() == 0.0 {
234                format!("{}", lit.value as i64)
235            } else {
236                format!("{}", lit.value)
237            }
238        }
239        Expression::StringLiteral(lit) => {
240            format!("\"{}\"", lit.value)
241        }
242        Expression::BooleanLiteral(lit) => lit.value.to_string(),
243        Expression::NullLiteral(_) => "null".to_string(),
244        Expression::ArrayExpression(arr) => {
245            let elements: Vec<String> = arr
246                .elements
247                .iter()
248                .filter_map(|elem| elem.as_expression().map(|e| expr_to_string(e)))
249                .collect();
250            format!("&[_]i64{{ {} }}", elements.join(", "))
251        }
252        Expression::UnaryExpression(unary) => {
253            let arg = expr_to_string(&unary.argument);
254            match unary.operator {
255                UnaryOperator::UnaryNegation => format!("-{}", arg),
256                UnaryOperator::LogicalNot => format!("!{}", arg),
257                UnaryOperator::BitwiseNot => format!("~{}", arg),
258                _ => arg,
259            }
260        }
261        Expression::BinaryExpression(bin) => {
262            let left = expr_to_string(&bin.left);
263            let right = expr_to_string(&bin.right);
264            let op = match bin.operator {
265                BinaryOperator::Addition => "+",
266                BinaryOperator::Subtraction => "-",
267                BinaryOperator::Multiplication => "*",
268                BinaryOperator::Division => "/",
269                BinaryOperator::Remainder => "%",
270                BinaryOperator::Equality => "==",
271                BinaryOperator::Inequality => "!=",
272                BinaryOperator::StrictEquality => "===",
273                BinaryOperator::StrictInequality => "!==",
274                BinaryOperator::LessThan => "<",
275                BinaryOperator::LessEqualThan => "<=",
276                BinaryOperator::GreaterThan => ">",
277                BinaryOperator::GreaterEqualThan => ">=",
278                BinaryOperator::ShiftLeft => "<<",
279                BinaryOperator::ShiftRight => ">>",
280                BinaryOperator::ShiftRightZeroFill => ">>>",
281                BinaryOperator::BitwiseAnd => "&",
282                BinaryOperator::BitwiseOR => "|",
283                BinaryOperator::BitwiseXOR => "^",
284                _ => "??",
285            };
286            format!("({} {} {})", left, op, right)
287        }
288        Expression::ConditionalExpression(cond) => {
289            format!(
290                "({} ? {} : {})",
291                expr_to_string(&cond.test),
292                expr_to_string(&cond.consequent),
293                expr_to_string(&cond.alternate)
294            )
295        }
296        Expression::LogicalExpression(logic) => {
297            let left = expr_to_string(&logic.left);
298            let right = expr_to_string(&logic.right);
299            let op = match logic.operator {
300                LogicalOperator::And => "&&",
301                LogicalOperator::Or => "||",
302                LogicalOperator::Coalesce => "??",
303            };
304            format!("({} {} {})", left, op, right)
305        }
306        Expression::ObjectExpression(obj) => {
307            let props: Vec<String> = obj
308                .properties
309                .iter()
310                .filter_map(|prop| match prop {
311                    ObjectPropertyKind::ObjectProperty(p) => {
312                        let key = match &p.key {
313                            PropertyKey::StaticIdentifier(id) => id.name.to_string(),
314                            _ => "?".to_string(),
315                        };
316                        let val = expr_to_string(&p.value);
317                        Some(format!(".{} = {}", key, val))
318                    }
319                    _ => None,
320                })
321                .collect();
322            format!(".{{ {} }}", props.join(", "))
323        }
324        Expression::ParenthesizedExpression(parens) => {
325            format!("({})", expr_to_string(&parens.expression))
326        }
327        Expression::TemplateLiteral(tl) => {
328            if tl.expressions.is_empty()
329                && tl.quasis.len() == 1
330                && let Some(cooked) = &tl.quasis[0].value.cooked
331            {
332                return format!("\"{}\"", cooked);
333            }
334            // For template literals with expressions, just reconstruct the args
335            let mut parts = Vec::new();
336            for (i, quasi) in tl.quasis.iter().enumerate() {
337                if let Some(cooked) = &quasi.value.cooked
338                    && !cooked.is_empty()
339                {
340                    parts.push(format!("\"{}\"", cooked));
341                }
342                if i < tl.expressions.len() {
343                    parts.push(expr_to_string(&tl.expressions[i]));
344                }
345            }
346            parts.join(", ")
347        }
348        Expression::AssignmentExpression(assign) => {
349            format!(
350                "({} = {})",
351                expr_to_string_simple(&assign.left),
352                expr_to_string(&assign.right)
353            )
354        }
355        _ => "<expr>".to_string(),
356    }
357}
358
359/// Simplified expression to string for assignment targets
360fn expr_to_string_simple(target: &AssignmentTarget) -> String {
361    match target {
362        AssignmentTarget::AssignmentTargetIdentifier(id) => id.name.to_string(),
363        _ => "_".to_string(),
364    }
365}
366
367/// Rewrite closure function calls: `makeAdder(10)(5)` → `makeAdder(10).call(5)`.
368/// Only applies when the base function name is in `closure_fns`.
369fn rewrite_closure_calls(expr: &str, closure_fns: &HashSet<&str>) -> String {
370    // Check if the expression starts with a known closure function name followed by '('
371    let first_paren = match expr.find('(') {
372        Some(pos) => pos,
373        None => return expr.to_string(),
374    };
375    let fn_name = &expr[..first_paren];
376    if !closure_fns.contains(fn_name) {
377        return expr.to_string();
378    }
379
380    // Find the matching closing paren for the first call
381    if let Some(close_pos) = find_matching_paren(expr, first_paren) {
382        let after_first_call = &expr[close_pos + 1..];
383        if after_first_call.starts_with('(') {
384            // Replace subsequent calls with .call(...)
385            let prefix = &expr[..=close_pos];
386            let rest = after_first_call.replacen('(', ".call(", 1);
387            return format!("{}{}", prefix, rest);
388        }
389    }
390
391    expr.to_string()
392}
393
394/// Extract the callee function name from an expression like "forLoop(5)" or "add(1, 2)".
395/// Returns None if the expression doesn't start with a simple identifier call.
396fn extract_callee_name(expr: &str) -> Option<String> {
397    let first_paren = expr.find('(')?;
398    let fn_name = &expr[..first_paren];
399    // Verify it's a simple identifier (not a complex expression)
400    if fn_name
401        .chars()
402        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
403    {
404        Some(fn_name.to_string())
405    } else {
406        None
407    }
408}
409
410/// Find the position of the matching closing paren for an opening paren at `open_pos`
411fn find_matching_paren(s: &str, open_pos: usize) -> Option<usize> {
412    let bytes = s.as_bytes();
413    if open_pos >= bytes.len() || bytes[open_pos] != b'(' {
414        return None;
415    }
416    let mut depth = 0;
417    for (i, &ch) in bytes.iter().enumerate().skip(open_pos) {
418        match ch {
419            b'(' => depth += 1,
420            b')' => {
421                depth -= 1;
422                if depth == 0 {
423                    return Some(i);
424                }
425            }
426            _ => {}
427        }
428    }
429    None
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    #[test]
437    fn test_sanitize_name() {
438        assert_eq!(sanitize_name("add_main"), "add_main");
439        assert_eq!(sanitize_name("add-main"), "add_main");
440        assert_eq!(sanitize_name("数学运算"), "____");
441    }
442
443    #[test]
444    fn test_find_matching_paren() {
445        assert_eq!(find_matching_paren("add(3, 5)", 3), Some(8));
446        assert_eq!(find_matching_paren("add(3, max(1, 2))", 3), Some(16));
447        assert_eq!(find_matching_paren("no_paren", 0), None);
448    }
449
450    #[test]
451    fn test_rewrite_closure_calls() {
452        let mut fns = HashSet::new();
453        fns.insert("makeAdder");
454        assert_eq!(
455            rewrite_closure_calls("makeAdder(10)(5)", &fns),
456            "makeAdder(10).call(5)"
457        );
458        // Not a closure function — no rewrite
459        let empty: HashSet<&str> = HashSet::new();
460        assert_eq!(rewrite_closure_calls("add(1, 2)", &empty), "add(1, 2)");
461    }
462}