oxc/crates/oxc_parser/examples/parser.rs
Luca Bruno 5731e3957f
refactor(ast)!: store span details inside comment struct (#4132)
This tweaks `Comment` definition in order to internally store the start
and end position of its span.

Closes: https://github.com/oxc-project/oxc/issues/4069
2024-07-09 23:23:43 +08:00

46 lines
1.4 KiB
Rust

#![allow(clippy::print_stdout)]
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(|comment| comment.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(())
}