1use oxc_ast::ast::*;
2use std::collections::{HashMap, HashSet};
3
4#[derive(Debug, Clone)]
6pub struct TestCase {
7 pub var_name: String,
9 pub expr_text: String,
11 pub expected: Option<String>,
14}
15
16fn parse_expected_value(raw: &str) -> Option<String> {
19 let raw = raw.trim();
20 if raw.is_empty() {
21 return None;
22 }
23 if raw == "true" || raw == "false" {
25 return Some(raw.to_string());
26 }
27 if raw == "null" {
29 return Some("null".to_string());
30 }
31 if raw.starts_with('"') && raw.ends_with('"') {
33 return Some(raw.to_string());
34 }
35 if raw.starts_with('\'') && raw.ends_with('\'') {
36 let inner = &raw[1..raw.len() - 1];
38 return Some(format!("\"{}\"", inner));
39 }
40 if raw.contains('.') {
42 return Some(format!("@as(f64, {})", raw));
43 }
44 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 if raw.chars().all(|c| c.is_ascii_digit()) {
52 return Some(format!("@as(i64, {})", raw));
53 }
54 Some(raw.to_string())
56}
57
58fn scan_expected_comment(source: &str, end_pos: usize) -> Option<String> {
61 let rest = &source[end_pos..];
62 let line = rest.split('\n').next()?;
64 let comment_pos = line.find("// =>")?;
65 let after_marker = &line[comment_pos + 5..]; let trimmed = after_marker.trim();
68 if trimmed.is_empty() {
69 return None;
70 }
71 parse_expected_value(trimmed)
72}
73
74pub 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 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
110pub 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 let mut call_expr = rewrite_closure_calls(&tc.expr_text, closure_fns);
133
134 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 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 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 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
186fn 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
199fn expr_to_string(expr: &Expression) -> String {
203 match expr {
204 Expression::ArrowFunctionExpression(arrow) => {
205 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 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
359fn expr_to_string_simple(target: &AssignmentTarget) -> String {
361 match target {
362 AssignmentTarget::AssignmentTargetIdentifier(id) => id.name.to_string(),
363 _ => "_".to_string(),
364 }
365}
366
367fn rewrite_closure_calls(expr: &str, closure_fns: &HashSet<&str>) -> String {
370 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 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 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
394fn extract_callee_name(expr: &str) -> Option<String> {
397 let first_paren = expr.find('(')?;
398 let fn_name = &expr[..first_paren];
399 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
410fn 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 let empty: HashSet<&str> = HashSet::new();
460 assert_eq!(rewrite_closure_calls("add(1, 2)", &empty), "add(1, 2)");
461 }
462}