Skip to main content

js2zig_core/
parser.rs

1use oxc_allocator::Allocator;
2use oxc_ast::ast::Program;
3use oxc_parser::Parser;
4use oxc_span::SourceType;
5
6/// Parse JS source text.
7/// Always parses in module mode: oxc handles plain scripts (no import/export)
8/// correctly in module mode too — `program.body` simply contains no
9/// import/export statements. This lets codegen read import/export directly
10/// from the AST instead of pre-scanning the raw source text.
11pub fn parse<'a>(allocator: &'a Allocator, source: &'a str) -> Program<'a> {
12    let source_type = SourceType::default().with_module(true);
13    let ret = Parser::new(allocator, source, source_type).parse();
14
15    for err in &ret.errors {
16        eprintln!("Parse error: {:?}", err);
17    }
18
19    ret.program
20}
21
22#[cfg(test)]
23mod tests {
24    use super::*;
25
26    #[test]
27    fn parse_simple_expression() {
28        let alloc = Allocator::default();
29        let program = parse(&alloc, "1 + 2;");
30        assert!(!program.body.is_empty());
31    }
32
33    #[test]
34    fn parse_function_declaration() {
35        let alloc = Allocator::default();
36        let program = parse(&alloc, "function add(a, b) { return a + b; }");
37        assert!(!program.body.is_empty());
38    }
39
40    #[test]
41    fn parse_module_with_import_export() {
42        let alloc = Allocator::default();
43        let program = parse(
44            &alloc,
45            "import { x } from './m.js'; export function f() { return x; }",
46        );
47        assert!(!program.body.is_empty());
48    }
49
50    #[test]
51    fn parse_async_function() {
52        let alloc = Allocator::default();
53        let program = parse(&alloc, "async function fetch() { return 1; }");
54        assert!(!program.body.is_empty());
55    }
56
57    #[test]
58    fn parse_class_declaration() {
59        let alloc = Allocator::default();
60        let program = parse(
61            &alloc,
62            "class Point { constructor(x,y) { this.x=x; this.y=y; } }",
63        );
64        assert!(!program.body.is_empty());
65    }
66
67    #[test]
68    fn parse_arrow_function() {
69        let alloc = Allocator::default();
70        let program = parse(&alloc, "const add = (a, b) => a + b;");
71        assert!(!program.body.is_empty());
72    }
73
74    #[test]
75    fn parse_empty_program() {
76        let alloc = Allocator::default();
77        let program = parse(&alloc, "");
78        assert!(program.body.is_empty());
79    }
80}