1use oxc_allocator::Allocator;
2use oxc_ast::ast::Program;
3use oxc_parser::Parser;
4use oxc_span::SourceType;
5
6pub fn parse<'a>(allocator: &'a Allocator, source: &'a str) -> Program<'a> {
12 parse_with_name(allocator, source, "<unknown>")
13}
14
15pub fn parse_with_name<'a>(
17 allocator: &'a Allocator,
18 source: &'a str,
19 debug_name: &str,
20) -> Program<'a> {
21 let source_type = SourceType::default().with_module(true);
22 let ret = Parser::new(allocator, source, source_type).parse();
23
24 for err in &ret.diagnostics {
25 eprintln!("Parse error [{}]: {:?}", debug_name, err);
26 }
27
28 ret.program
29}
30
31#[cfg(test)]
32mod tests {
33 use super::*;
34
35 #[test]
36 fn parse_simple_expression() {
37 let alloc = Allocator::default();
38 let program = parse(&alloc, "1 + 2;");
39 assert!(!program.body.is_empty());
40 }
41
42 #[test]
43 fn parse_function_declaration() {
44 let alloc = Allocator::default();
45 let program = parse(&alloc, "function add(a, b) { return a + b; }");
46 assert!(!program.body.is_empty());
47 }
48
49 #[test]
50 fn parse_module_with_import_export() {
51 let alloc = Allocator::default();
52 let program = parse(
53 &alloc,
54 "import { x } from './m.js'; export function f() { return x; }",
55 );
56 assert!(!program.body.is_empty());
57 }
58
59 #[test]
60 fn parse_async_function() {
61 let alloc = Allocator::default();
62 let program = parse(&alloc, "async function fetch() { return 1; }");
63 assert!(!program.body.is_empty());
64 }
65
66 #[test]
67 fn parse_class_declaration() {
68 let alloc = Allocator::default();
69 let program = parse(
70 &alloc,
71 "class Point { constructor(x,y) { this.x=x; this.y=y; } }",
72 );
73 assert!(!program.body.is_empty());
74 }
75
76 #[test]
77 fn parse_arrow_function() {
78 let alloc = Allocator::default();
79 let program = parse(&alloc, "const add = (a, b) => a + b;");
80 assert!(!program.body.is_empty());
81 }
82
83 #[test]
84 fn parse_empty_program() {
85 let alloc = Allocator::default();
86 let program = parse(&alloc, "");
87 assert!(program.body.is_empty());
88 }
89}