fix(codegen): print if else without block with proper indentation (#8135)

This commit is contained in:
Boshen 2024-12-27 00:39:52 +00:00
parent 6b51e6dff1
commit ad61e70186
3 changed files with 25 additions and 3 deletions

View file

@ -3,7 +3,7 @@ use std::path::Path;
use oxc_allocator::Allocator; use oxc_allocator::Allocator;
use oxc_codegen::{CodeGenerator, CodegenOptions}; use oxc_codegen::{CodeGenerator, CodegenOptions};
use oxc_parser::{Parser, ParserReturn}; use oxc_parser::{ParseOptions, Parser, ParserReturn};
use oxc_span::SourceType; use oxc_span::SourceType;
use pico_args::Arguments; use pico_args::Arguments;
@ -52,7 +52,12 @@ fn parse<'a>(
source_text: &'a str, source_text: &'a str,
source_type: SourceType, source_type: SourceType,
) -> Option<ParserReturn<'a>> { ) -> 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() { if !ret.errors.is_empty() {
for error in ret.errors { for error in ret.errors {
println!("{:?}", error.with_source_code(source_text.to_string())); println!("{:?}", error.with_source_code(source_text.to_string()));

View file

@ -301,7 +301,12 @@ fn print_if(if_stmt: &IfStatement<'_>, p: &mut Codegen, ctx: Context) {
p.print_soft_newline(); 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() { if let Some(alternate) = if_stmt.alternate.as_ref() {
p.print_semicolon_if_needed(); p.print_semicolon_if_needed();

View file

@ -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] #[test]
fn shorthand() { fn shorthand() {
test("let _ = { x }", "let _ = { x };\n"); test("let _ = { x }", "let _ = { x };\n");