Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(es/compat): Handle nullish in fn expr scope #7980

Merged
merged 3 commits into from
Sep 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions crates/swc/tests/fixture/issues-7xxx/7977/input/.swcrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"$schema": "https://json.schemastore.org/swcrc",
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": false,
"dynamicImport": true
},
"transform": {
"react": {
"runtime": "automatic"
}
},
"baseUrl": "./",
"target": "es2019",
"keepClassNames": true,
"minify": {
"compress": false
}
},
"isModule": true,
"module": {
"type": "es6"
},
"minify": false
}
1 change: 1 addition & 0 deletions crates/swc/tests/fixture/issues-7xxx/7977/input/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const foo = () => baz() ?? qux;
4 changes: 4 additions & 0 deletions crates/swc/tests/fixture/issues-7xxx/7977/output/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const foo = ()=>{
var _baz;
return (_baz = baz()) !== null && _baz !== void 0 ? _baz : qux;
};
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::mem::take;

use serde::Deserialize;
use swc_common::{util::take::Take, Span, DUMMY_SP};
use swc_common::{util::take::Take, Span, Spanned, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::{alias_if_required, undefined, StmtLike};
use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith};
Expand Down Expand Up @@ -192,6 +192,35 @@ impl VisitMut for NullishCoalescing {
_ => {}
}
}

fn visit_mut_block_stmt_or_expr(&mut self, n: &mut BlockStmtOrExpr) {
let vars = self.vars.take();
n.visit_mut_children_with(self);

if !self.vars.is_empty() {
if let BlockStmtOrExpr::Expr(expr) = n {
// expr
// { var decl = init; return expr; }
let span = expr.span();
let stmts = vec![
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls: self.vars.take(),
declare: false,
}
.into(),
Stmt::Return(ReturnStmt {
span: DUMMY_SP,
arg: Some(expr.take()),
}),
];
*n = BlockStmtOrExpr::BlockStmt(BlockStmt { span, stmts });
}
}

self.vars = vars;
}
}

#[tracing::instrument(level = "info", skip_all)]
Expand Down
Loading