Skip to content

Commit cdbddef

Browse files
committed
feat(formatter): support printing Formatter IR
1 parent f3b75c3 commit cdbddef

File tree

6 files changed

+471
-443
lines changed

6 files changed

+471
-443
lines changed

crates/oxc_formatter/examples/formatter.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -60,17 +60,16 @@ fn main() -> Result<(), String> {
6060
};
6161

6262
let formatter = Formatter::new(&allocator, options);
63+
let formatted = formatter.format(&ret.program);
6364
if show_ir {
64-
let doc = formatter.doc(&ret.program);
65-
println!("[");
66-
for el in doc.iter() {
67-
println!(" {el:?},");
68-
}
69-
println!("]");
70-
} else {
71-
let code = formatter.build(&ret.program);
72-
println!("{code}");
65+
println!("--- IR ---");
66+
println!("{}", &formatted.document().to_string());
67+
println!("--- End IR ---\n");
7368
}
7469

70+
println!("--- Formatted Code ---");
71+
let code = formatted.print().map_err(|e| e.to_string())?.into_code();
72+
println!("{code}");
73+
println!("--- End Formatted Code ---");
7574
Ok(())
7675
}

crates/oxc_formatter/src/formatter/context.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,18 @@ impl std::fmt::Debug for FormatContext<'_> {
4242

4343
impl<'ast> FormatContext<'ast> {
4444
pub fn new(
45-
program: &'ast Program<'ast>,
45+
source_text: &'ast str,
46+
source_type: SourceType,
47+
comments: &'ast [Comment],
4648
allocator: &'ast Allocator,
4749
options: FormatOptions,
4850
) -> Self {
49-
let source_text = SourceText::new(program.source_text);
51+
let source_text = SourceText::new(source_text);
5052
Self {
5153
options,
5254
source_text,
53-
source_type: program.source_type,
54-
comments: Comments::new(source_text, &program.comments),
55+
source_type,
56+
comments: Comments::new(source_text, comments),
5557
allocator,
5658
cached_elements: FxHashMap::default(),
5759
}

0 commit comments

Comments
 (0)