/
parser.rs
42 lines (35 loc) · 1.34 KB
/
parser.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use std::{env, path::Path};
use oxc_allocator::Allocator;
use oxc_parser::Parser;
use oxc_span::SourceType;
// Instruction:
// create a `test.js`,
// run `cargo run -p oxc_parser --example parser`
// or `cargo watch -x "run -p oxc_parser --example parser"`
fn main() -> Result<(), String> {
let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string());
let path = Path::new(&name);
let source_text = std::fs::read_to_string(path).map_err(|_| format!("Missing '{name}'"))?;
let allocator = Allocator::default();
let source_type = SourceType::from_path(path).unwrap();
let now = std::time::Instant::now();
let ret = Parser::new(&allocator, &source_text, source_type).parse();
let elapsed_time = now.elapsed();
println!("{}ms.", elapsed_time.as_millis());
println!("AST:");
println!("{}", serde_json::to_string_pretty(&ret.program).unwrap());
println!("Comments:");
let comments =
ret.trivias.comments().map(|(_, span)| span.source_text(&source_text)).collect::<Vec<_>>();
println!("{comments:?}");
if ret.errors.is_empty() {
println!("Parsed Successfully.");
} else {
for error in ret.errors {
let error = error.with_source_code(source_text.clone());
println!("{error:?}");
println!("Parsed with Errors.");
}
}
Ok(())
}