diff --git a/crates/oxc_formatter/examples/formatter.rs b/crates/oxc_formatter/examples/formatter.rs index ade1b9472c4a0..f6dc0de2984e7 100644 --- a/crates/oxc_formatter/examples/formatter.rs +++ b/crates/oxc_formatter/examples/formatter.rs @@ -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 @@ -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(()) } diff --git a/crates/oxc_formatter/src/lib.rs b/crates/oxc_formatter/src/lib.rs index 0c89180d8c7c2..dcaef4b2032e5 100644 --- a/crates/oxc_formatter/src/lib.rs +++ b/crates/oxc_formatter/src/lib.rs @@ -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}, }; @@ -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() } }