Skip to content

Commit

Permalink
fix(codegen): print if else without block wither proper indentation
Browse files Browse the repository at this point in the history
  • Loading branch information
Boshen committed Dec 27, 2024
1 parent 6b51e6d commit 28e14d4
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
9 changes: 7 additions & 2 deletions crates/oxc_codegen/examples/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::path::Path;

use oxc_allocator::Allocator;
use oxc_codegen::{CodeGenerator, CodegenOptions};
use oxc_parser::{Parser, ParserReturn};
use oxc_parser::{ParseOptions, Parser, ParserReturn};
use oxc_span::SourceType;
use pico_args::Arguments;

Expand Down Expand Up @@ -52,7 +52,12 @@ fn parse<'a>(
source_text: &'a str,
source_type: SourceType,
) -> Option<ParserReturn<'a>> {
let ret = Parser::new(allocator, source_text, source_type).parse();
let ret = Parser::new(allocator, source_text, source_type)
.with_options(ParseOptions {
allow_return_outside_function: true,
..ParseOptions::default()
})
.parse();
if !ret.errors.is_empty() {
for error in ret.errors {
println!("{:?}", error.with_source_code(source_text.to_string()));
Expand Down
7 changes: 6 additions & 1 deletion crates/oxc_codegen/src/gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,12 @@ fn print_if(if_stmt: &IfStatement<'_>, p: &mut Codegen, ctx: Context) {
p.print_soft_newline();
}
}
stmt => p.print_body(stmt, false, ctx),
stmt => {
p.print_body(stmt, false, ctx);
if if_stmt.alternate.is_some() {
p.print_indent();
}
}
}
if let Some(alternate) = if_stmt.alternate.as_ref() {
p.print_semicolon_if_needed();
Expand Down
12 changes: 12 additions & 0 deletions crates/oxc_codegen/tests/integration/unit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,18 @@ fn for_stmt() {
);
}

#[test]
fn if_stmt() {
test(
"function f() { if (foo) return foo; else if (bar) return foo; }",
"function f() {\n\tif (foo) return foo;\n\telse if (bar) return foo;\n}\n",
);
test_minify(
"function f() { if (foo) return foo; else if (bar) return foo; }",
"function f(){if(foo)return foo;else if(bar)return foo}",
);
}

#[test]
fn shorthand() {
test("let _ = { x }", "let _ = { x };\n");
Expand Down

0 comments on commit 28e14d4

Please sign in to comment.