Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions crates/oxc_formatter/examples/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use pico_args::Arguments;
fn main() -> Result<(), String> {
let mut args = Arguments::from_env();
let no_semi = args.contains("--no-semi");
let show_ir = args.contains("--ir");
let name = args.free_from_str().unwrap_or_else(|_| "test.js".to_string());

// Read source file
Expand Down Expand Up @@ -57,9 +58,19 @@ fn main() -> Result<(), String> {
semicolons,
..Default::default()
};
let code = Formatter::new(&allocator, options).build(&ret.program);

println!("{code}");
let formatter = Formatter::new(&allocator, options);
if show_ir {
let doc = formatter.doc(&ret.program);
println!("[");
for el in doc.iter() {
println!(" {el:?},");
}
println!("]");
} else {
let code = formatter.build(&ret.program);
println!("{code}");
}

Ok(())
}
19 changes: 15 additions & 4 deletions crates/oxc_formatter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use write::FormatWrite;
pub use crate::options::*;
pub use crate::service::source_type::get_supported_source_type;
use crate::{
formatter::FormatContext,
formatter::{FormatContext, Formatted, format_element::document::Document},
generated::ast_nodes::{AstNode, AstNodes},
};

Expand All @@ -53,20 +53,31 @@ impl<'a> Formatter<'a> {
Self { allocator, source_text: "", options }
}

/// Formats the given AST `Program` and returns the IR before printing.
pub fn doc(mut self, program: &'a Program<'a>) -> Document<'a> {
let formatted = self.format(program);
formatted.into_document()
}

/// Formats the given AST `Program` and returns the formatted string.
pub fn build(mut self, program: &Program<'a>) -> String {
let formatted = self.format(program);
formatted.print().unwrap().into_code()
}

fn format(mut self, program: &'a Program<'a>) -> Formatted<'a> {
let parent = self.allocator.alloc(AstNodes::Dummy());
let program_node = AstNode::new(program, parent, self.allocator);

let source_text = program.source_text;
self.source_text = source_text;
let context = FormatContext::new(program, self.allocator, self.options);
let formatted = formatter::format(
formatter::format(
program,
context,
formatter::Arguments::new(&[formatter::Argument::new(&program_node)]),
)
.unwrap();
formatted.print().unwrap().into_code()
.unwrap()
}
}

Expand Down
Loading