refactor(parser): add --ast and --comments to example

This commit is contained in:
Boshen 2024-09-14 09:01:14 +08:00
parent 36e698b411
commit 4abfa7682a
No known key found for this signature in database
GPG key ID: 67715A371E534061
3 changed files with 23 additions and 13 deletions

1
Cargo.lock generated
View file

@ -1750,6 +1750,7 @@ dependencies = [
"oxc_regular_expression",
"oxc_span",
"oxc_syntax",
"pico-args",
"rustc-hash",
"seq-macro",
"serde_json",

View file

@ -38,6 +38,7 @@ memchr = { workspace = true }
[dev-dependencies]
oxc_ast = { workspace = true, features = ["serialize"] }
pico-args = { workspace = true }
serde_json = { workspace = true }
[features]

View file

@ -1,9 +1,10 @@
#![allow(clippy::print_stdout)]
use std::{env, path::Path};
use std::{fs, path::Path};
use oxc_allocator::Allocator;
use oxc_parser::{ParseOptions, Parser};
use oxc_span::SourceType;
use pico_args::Arguments;
// Instruction:
// create a `test.js`,
@ -11,25 +12,32 @@ use oxc_span::SourceType;
// 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 mut args = Arguments::from_env();
let name = args.subcommand().ok().flatten().unwrap_or_else(|| String::from("test.js"));
let show_ast = args.contains("--ast");
let show_comments = args.contains("--comments");
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_text = fs::read_to_string(path).map_err(|_| format!("Missing '{name}'"))?;
let source_type = SourceType::from_path(path).unwrap();
let now = std::time::Instant::now();
let allocator = Allocator::default();
let ret = Parser::new(&allocator, &source_text, source_type)
.with_options(ParseOptions { parse_regular_expression: true, ..ParseOptions::default() })
.parse();
let elapsed_time = now.elapsed();
println!("{}ms.", elapsed_time.as_millis());
println!("AST:");
println!("{}", serde_json::to_string_pretty(&ret.program).unwrap());
if show_ast {
println!("AST:");
println!("{}", serde_json::to_string_pretty(&ret.program).unwrap());
}
println!("Comments:");
for comment in ret.trivias.comments() {
let s = comment.real_span().source_text(&source_text);
println!("{s}");
if show_comments {
println!("Comments:");
for comment in ret.trivias.comments() {
let s = comment.real_span().source_text(&source_text);
println!("{s}");
}
}
if ret.errors.is_empty() {