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

**Related issue:**

  - Closes: #7977
This commit is contained in:
magic-akari 2023-09-21 13:16:43 +08:00 committed by GitHub
parent 95285e8a4a
commit 5050f5820a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 61 additions and 1 deletions

View File

@ -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
}

View File

@ -0,0 +1 @@
const foo = () => baz() ?? qux;

View File

@ -0,0 +1,4 @@
const foo = ()=>{
var _baz;
return (_baz = baz()) !== null && _baz !== void 0 ? _baz : qux;
};

View File

@ -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};
@ -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)]