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> {
9 let is_module = source.contains("import ") || source.contains("export ");
10 let source_type = if is_module {
11 SourceType::default().with_module(true)
12 } else {
13 SourceType::default()
14 };
15 let ret = Parser::new(allocator, source, source_type).parse();
16
17 for err in &ret.errors {
18 eprintln!("Parse error: {:?}", err);
19 }
20
21 ret.program
22}
23
24#[cfg(test)]
25mod tests {
26 use super::*;
27
28 #[test]
29 fn parse_simple_expression() {
30 let alloc = Allocator::default();
31 let program = parse(&alloc, "1 + 2;");
32 assert!(!program.body.is_empty());
33 }
34
35 #[test]
36 fn parse_function_declaration() {
37 let alloc = Allocator::default();
38 let program = parse(&alloc, "function add(a, b) { return a + b; }");
39 assert!(!program.body.is_empty());
40 }
41
42 #[test]
43 fn parse_module_with_import_export() {
44 let alloc = Allocator::default();
45 let program = parse(
46 &alloc,
47 "import { x } from './m.js'; export function f() { return x; }",
48 );
49 assert!(!program.body.is_empty());
50 }
51
52 #[test]
53 fn parse_async_function() {
54 let alloc = Allocator::default();
55 let program = parse(&alloc, "async function fetch() { return 1; }");
56 assert!(!program.body.is_empty());
57 }
58
59 #[test]
60 fn parse_class_declaration() {
61 let alloc = Allocator::default();
62 let program = parse(&alloc, "class Point { constructor(x,y) { this.x=x; this.y=y; } }");
63 assert!(!program.body.is_empty());
64 }
65
66 #[test]
67 fn parse_arrow_function() {
68 let alloc = Allocator::default();
69 let program = parse(&alloc, "const add = (a, b) => a + b;");
70 assert!(!program.body.is_empty());
71 }
72
73 #[test]
74 fn parse_empty_program() {
75 let alloc = Allocator::default();
76 let program = parse(&alloc, "");
77 assert!(program.body.is_empty());
78 }
79}