diff --git a/crates/oxc_codegen/examples/codegen.rs b/crates/oxc_codegen/examples/codegen.rs index 5755d891ba311d..e941dfcbe34bd9 100644 --- a/crates/oxc_codegen/examples/codegen.rs +++ b/crates/oxc_codegen/examples/codegen.rs @@ -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; @@ -52,7 +52,12 @@ fn parse<'a>( source_text: &'a str, source_type: SourceType, ) -> Option> { - 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())); diff --git a/crates/oxc_codegen/src/gen.rs b/crates/oxc_codegen/src/gen.rs index f5cee102b14d31..5a9d864f549f22 100644 --- a/crates/oxc_codegen/src/gen.rs +++ b/crates/oxc_codegen/src/gen.rs @@ -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(); diff --git a/crates/oxc_codegen/tests/integration/unit.rs b/crates/oxc_codegen/tests/integration/unit.rs index 36d66059d2d89e..a05ef1f408bf49 100644 --- a/crates/oxc_codegen/tests/integration/unit.rs +++ b/crates/oxc_codegen/tests/integration/unit.rs @@ -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");