From df3829c7efd3327059cd5ab606a038c845936506 Mon Sep 17 00:00:00 2001 From: IWANABETHATGUY <17974631+IWANABETHATGUY@users.noreply.github.com> Date: Thu, 14 Aug 2025 14:51:24 +0000 Subject: [PATCH] feat(oxc_codegen): support configure initial indent when using `oxc_codegen` (#13091) Here is an example in rolldown https://github.com/rolldown/rolldown/pull/5724/files#diff-8a1733ecebbc28acb7d0c6ccd52499d7d2c9611f046b0b4a30ee3e1f939cbf13R57-R74, when concate multiple module, rolldown uses the output of `oxc_codegen` for AST and adding head and tail of the concatenatedModules with string replace to make sure generates the correct sourcemap with minimum effort. In this scenario, rolldown needs `oxc_codegen` to start generating string with initial ident `1` --- crates/oxc_codegen/src/lib.rs | 1 + crates/oxc_codegen/src/options.rs | 7 +++++++ crates/oxc_codegen/tests/integration/js.rs | 7 +++++++ 3 files changed, 15 insertions(+) diff --git a/crates/oxc_codegen/src/lib.rs b/crates/oxc_codegen/src/lib.rs index 86830aa35137b..c1ec1bc36f019 100644 --- a/crates/oxc_codegen/src/lib.rs +++ b/crates/oxc_codegen/src/lib.rs @@ -197,6 +197,7 @@ impl<'a> Codegen<'a> { pub fn build(mut self, program: &Program<'a>) -> CodegenReturn { self.quote = if self.options.single_quote { Quote::Single } else { Quote::Double }; self.source_text = Some(program.source_text); + self.indent = self.options.initial_indent; self.code.reserve(program.source_text.len()); self.build_comments(&program.comments); if let Some(path) = &self.options.source_map_path { diff --git a/crates/oxc_codegen/src/options.rs b/crates/oxc_codegen/src/options.rs index 5fc98f49bf388..d4f7674c55038 100644 --- a/crates/oxc_codegen/src/options.rs +++ b/crates/oxc_codegen/src/options.rs @@ -38,6 +38,11 @@ pub struct CodegenOptions { /// /// Default is `1`. pub indent_width: usize, + + /// Initial indentation level for generated code. + /// + /// Default is `0`. + pub initial_indent: u32, } impl Default for CodegenOptions { @@ -49,6 +54,7 @@ impl Default for CodegenOptions { source_map_path: None, indent_char: IndentChar::default(), indent_width: DEFAULT_INDENT_WIDTH, + initial_indent: 0, } } } @@ -63,6 +69,7 @@ impl CodegenOptions { source_map_path: None, indent_char: IndentChar::default(), indent_width: DEFAULT_INDENT_WIDTH, + initial_indent: 0, } } diff --git a/crates/oxc_codegen/tests/integration/js.rs b/crates/oxc_codegen/tests/integration/js.rs index 302e057b4dfb5..cc55b3cc90119 100644 --- a/crates/oxc_codegen/tests/integration/js.rs +++ b/crates/oxc_codegen/tests/integration/js.rs @@ -647,4 +647,11 @@ fn indentation() { ..CodegenOptions::default() }, ); + + // Test initial indent with 1 + test_options( + "let foo = 1;", + "\tlet foo = 1;\n", + CodegenOptions { initial_indent: 1, ..CodegenOptions::default() }, + ); }