fix(es/compat): Fix the position for temp var injection (#7171)

This commit is contained in:
magic-akari 2023-03-30 16:41:55 +08:00 committed by GitHub
parent 6a015550ba
commit 23fb8c5563
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 4 deletions

View File

@ -1,3 +1,5 @@
use std::mem;
use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::perf::Parallel;
@ -173,17 +175,25 @@ impl VisitMut for Operators {
}
}
/// [swc_ecma_ast::ModuleItem] is the top level Item in the current
/// implementation of JavaScript until the proposal for
/// [module-declarations] and [module-expressions] are officially added.
///
/// [module declarations]: https://github.com/tc39/proposal-module-declarations.
/// [module-expressions]: https://github.com/tc39/proposal-module-expressions
fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) {
let vars = self.vars.take();
n.visit_mut_children_with(self);
if !self.vars.is_empty() {
let vars = mem::replace(&mut self.vars, vars);
if !vars.is_empty() {
prepend_stmt(
n,
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
declare: false,
decls: self.vars.take(),
decls: vars,
}
.into(),
)
@ -191,16 +201,18 @@ impl VisitMut for Operators {
}
fn visit_mut_stmts(&mut self, n: &mut Vec<Stmt>) {
let vars = self.vars.take();
n.visit_mut_children_with(self);
if !self.vars.is_empty() {
let vars = mem::replace(&mut self.vars, vars);
if !vars.is_empty() {
prepend_stmt(
n,
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
declare: false,
decls: self.vars.take(),
decls: vars,
}
.into(),
)

View File

@ -79,6 +79,23 @@ test!(
"
);
test!(
syntax(),
|_| tr(),
issue_7169,
"function myFunc(options) {
options.context ||= {}
const closure = function() {}
}",
"
function myFunc(options) {
var _options;
(_options = options).context || (_options.context = {});
const closure = function() {};
}
"
);
test_exec!(
syntax(),
|_| tr(),