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!(
157 "test \"{}\" {{\n",
158 sanitize_name(test_name)
159 ));
160 out.push_str(" var arena = std.heap.ArenaAllocator.init(std.testing.allocator);\n");
161 out.push_str(" defer arena.deinit();\n");
162 out.push_str(" const allocator = arena.allocator();\n");
163 out.push_str(" init_js2rust(allocator);\n");
164 out.push_str(" defer deinit_js2rust();\n");
165
166 if let Some(ref expected) = tc.expected {
167 if expected.starts_with('"') {
168 out.push_str(&format!(
170 " try std.testing.expectEqualSlices(u8, {}, {});\n",
171 expected, call_expr
172 ));
173 } else {
174 out.push_str(&format!(
175 " try std.testing.expectEqual({}, {});\n",
176 expected, call_expr
177 ));
178 }
179 } else {
180 out.push_str(&format!(" _ = {};\n", call_expr));
181 }
182
183 out.push_str("}\n\n");
184 }
185
186 out
187}
188
189fn sanitize_name(name: &str) -> String {
191 let mut s = String::new();
192 for ch in name.chars() {
193 if ch.is_ascii_alphanumeric() || ch == '_' {
194 s.push(ch);
195 } else {
196 s.push('_');
197 }
198 }
199 s
200}
201
202fn expr_to_string(expr: &Expression) -> String {
206 match expr {
207 Expression::ArrowFunctionExpression(arrow) => {
208 if let Statement::ExpressionStatement(es) = &arrow.body.statements[0] {
210 expr_to_string(&es.expression)
211 } else {
212 "<expr>".to_string()
213 }
214 }
215 Expression::CallExpression(call) => {
216 let callee_str = expr_to_string(&call.callee);
217 let args_str: Vec<String> = call
218 .arguments
219 .iter()
220 .map(|arg| match arg {
221 Argument::SpreadElement(spread) => {
222 format!("...{}", expr_to_string(&spread.argument))
223 }
224 _ => arg
225 .as_expression()
226 .map(|e| expr_to_string(e))
227 .unwrap_or_else(|| "_".to_string()),
228 })
229 .collect();
230 format!("{}({})", callee_str, args_str.join(", "))
231 }
232 Expression::Identifier(id) => id.name.to_string(),
233 Expression::NumericLiteral(lit) => {
234 if let Some(raw) = &lit.raw {
235 raw.to_string()
236 } else if lit.value.fract() == 0.0 {
237 format!("{}", lit.value as i64)
238 } else {
239 format!("{}", lit.value)
240 }
241 }
242 Expression::StringLiteral(lit) => {
243 format!("\"{}\"", lit.value)
244 }
245 Expression::BooleanLiteral(lit) => lit.value.to_string(),
246 Expression::NullLiteral(_) => "null".to_string(),
247 Expression::ArrayExpression(arr) => {
248 let elements: Vec<String> = arr
249 .elements
250 .iter()
251 .filter_map(|elem| {
252 elem.as_expression().map(|e| expr_to_string(e))
253 })
254 .collect();
255 format!("&[_]i64{{ {} }}", elements.join(", "))
256 }
257 Expression::UnaryExpression(unary) => {
258 let arg = expr_to_string(&unary.argument);
259 match unary.operator {
260 UnaryOperator::UnaryNegation => format!("-{}", arg),
261 UnaryOperator::LogicalNot => format!("!{}", arg),
262 UnaryOperator::BitwiseNot => format!("~{}", arg),
263 _ => arg,
264 }
265 }
266 Expression::BinaryExpression(bin) => {
267 let left = expr_to_string(&bin.left);
268 let right = expr_to_string(&bin.right);
269 let op = match bin.operator {
270 BinaryOperator::Addition => "+",
271 BinaryOperator::Subtraction => "-",
272 BinaryOperator::Multiplication => "*",
273 BinaryOperator::Division => "/",
274 BinaryOperator::Remainder => "%",
275 BinaryOperator::Equality => "==",
276 BinaryOperator::Inequality => "!=",
277 BinaryOperator::StrictEquality => "===",
278 BinaryOperator::StrictInequality => "!==",
279 BinaryOperator::LessThan => "<",
280 BinaryOperator::LessEqualThan => "<=",
281 BinaryOperator::GreaterThan => ">",
282 BinaryOperator::GreaterEqualThan => ">=",
283 BinaryOperator::ShiftLeft => "<<",
284 BinaryOperator::ShiftRight => ">>",
285 BinaryOperator::ShiftRightZeroFill => ">>>",
286 BinaryOperator::BitwiseAnd => "&",
287 BinaryOperator::BitwiseOR => "|",
288 BinaryOperator::BitwiseXOR => "^",
289 _ => "??",
290 };
291 format!("({} {} {})", left, op, right)
292 }
293 Expression::ConditionalExpression(cond) => {
294 format!("({} ? {} : {})",
295 expr_to_string(&cond.test),
296 expr_to_string(&cond.consequent),
297 expr_to_string(&cond.alternate))
298 }
299 Expression::LogicalExpression(logic) => {
300 let left = expr_to_string(&logic.left);
301 let right = expr_to_string(&logic.right);
302 let op = match logic.operator {
303 LogicalOperator::And => "&&",
304 LogicalOperator::Or => "||",
305 LogicalOperator::Coalesce => "??",
306 };
307 format!("({} {} {})", left, op, right)
308 }
309 Expression::ObjectExpression(obj) => {
310 let props: Vec<String> = obj.properties.iter().filter_map(|prop| {
311 match prop {
312 ObjectPropertyKind::ObjectProperty(p) => {
313 let key = match &p.key {
314 PropertyKey::StaticIdentifier(id) => id.name.to_string(),
315 _ => "?".to_string(),
316 };
317 let val = expr_to_string(&p.value);
318 Some(format!(".{} = {}", key, val))
319 }
320 _ => None,
321 }
322 }).collect();
323 format!(".{{ {} }}", props.join(", "))
324 }
325 Expression::ParenthesizedExpression(parens) => {
326 format!("({})", expr_to_string(&parens.expression))
327 }
328 Expression::TemplateLiteral(tl) => {
329 if tl.expressions.is_empty() && 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!("({} = {})", expr_to_string_simple(&assign.left), expr_to_string(&assign.right))
350 }
351 _ => "<expr>".to_string(),
352 }
353}
354
355fn expr_to_string_simple(target: &AssignmentTarget) -> String {
357 match target {
358 AssignmentTarget::AssignmentTargetIdentifier(id) => id.name.to_string(),
359 _ => "_".to_string(),
360 }
361}
362
363fn rewrite_closure_calls(expr: &str, closure_fns: &HashSet<&str>) -> String {
366 let first_paren = match expr.find('(') {
368 Some(pos) => pos,
369 None => return expr.to_string(),
370 };
371 let fn_name = &expr[..first_paren];
372 if !closure_fns.contains(fn_name) {
373 return expr.to_string();
374 }
375
376 if let Some(close_pos) = find_matching_paren(expr, first_paren) {
378 let after_first_call = &expr[close_pos + 1..];
379 if after_first_call.starts_with('(') {
380 let prefix = &expr[..=close_pos];
382 let rest = after_first_call.replacen('(', ".call(", 1);
383 return format!("{}{}", prefix, rest);
384 }
385 }
386
387 expr.to_string()
388}
389
390fn extract_callee_name(expr: &str) -> Option<String> {
393 let first_paren = expr.find('(')?;
394 let fn_name = &expr[..first_paren];
395 if fn_name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$') {
397 Some(fn_name.to_string())
398 } else {
399 None
400 }
401}
402
403fn find_matching_paren(s: &str, open_pos: usize) -> Option<usize> {
405 let bytes = s.as_bytes();
406 if open_pos >= bytes.len() || bytes[open_pos] != b'(' {
407 return None;
408 }
409 let mut depth = 0;
410 for (i, &ch) in bytes.iter().enumerate().skip(open_pos) {
411 match ch {
412 b'(' => depth += 1,
413 b')' => {
414 depth -= 1;
415 if depth == 0 {
416 return Some(i);
417 }
418 }
419 _ => {}
420 }
421 }
422 None
423}
424
425#[cfg(test)]
426mod tests {
427 use super::*;
428
429 #[test]
430 fn test_sanitize_name() {
431 assert_eq!(sanitize_name("add_main"), "add_main");
432 assert_eq!(sanitize_name("add-main"), "add_main");
433 assert_eq!(sanitize_name("数学运算"), "____");
434 }
435
436 #[test]
437 fn test_find_matching_paren() {
438 assert_eq!(find_matching_paren("add(3, 5)", 3), Some(8));
439 assert_eq!(find_matching_paren("add(3, max(1, 2))", 3), Some(16));
440 assert_eq!(find_matching_paren("no_paren", 0), None);
441 }
442
443 #[test]
444 fn test_rewrite_closure_calls() {
445 let mut fns = HashSet::new();
446 fns.insert("makeAdder");
447 assert_eq!(
448 rewrite_closure_calls("makeAdder(10)(5)", &fns),
449 "makeAdder(10).call(5)"
450 );
451 let empty: HashSet<&str> = HashSet::new();
453 assert_eq!(
454 rewrite_closure_calls("add(1, 2)", &empty),
455 "add(1, 2)"
456 );
457 }
458}