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

Disable scope hoisting when 'this' points to an export #9291

Merged
merged 24 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
exports.foo = function() {
exports.bar()
}

exports.bar = function() {
this.baz()
}

exports.baz = function() {
return 2
}
17 changes: 17 additions & 0 deletions packages/core/integration-tests/test/scope-hoisting.js
Original file line number Diff line number Diff line change
Expand Up @@ -3574,6 +3574,23 @@ describe('scope hoisting', function () {
});

describe('commonjs', function () {
it('should wrap when this could refer to an export', async function () {
adelchan07 marked this conversation as resolved.
Show resolved Hide resolved
let b = await bundle(
path.join(
__dirname,
'/integration/scope-hoisting/commonjs/exports-this/a.js',
),
);

let contents = await outputFS.readFile(
b.getBundles()[0].filePath,
'utf8',
);

let wrapped = contents.includes('exports.bar()');
assert.equal(wrapped, true);
});

it('supports require of commonjs modules', async function () {
let b = await bundle(
path.join(
Expand Down
33 changes: 32 additions & 1 deletion packages/transformers/js/core/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ pub struct Collect {
pub should_wrap: bool,
/// local variable binding -> descriptor
pub imports: HashMap<Id, Import>,
pub this_exprs: HashMap<Id, (Ident, Span)>,
/// exported name -> descriptor
pub exports: HashMap<JsWord, Export>,
/// local variable binding -> exported name
Expand All @@ -76,6 +77,7 @@ pub struct Collect {
in_export_decl: bool,
in_function: bool,
in_assign: bool,
in_class: bool,
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -129,6 +131,7 @@ impl Collect {
is_esm: false,
should_wrap: false,
imports: HashMap::new(),
this_exprs: HashMap::new(),
exports: HashMap::new(),
exports_locals: HashMap::new(),
exports_all: HashMap::new(),
Expand All @@ -142,6 +145,7 @@ impl Collect {
in_export_decl: false,
in_function: false,
in_assign: false,
in_class: false,
bailouts: if trace_bailouts { Some(vec![]) } else { None },
}
}
Expand Down Expand Up @@ -241,6 +245,15 @@ impl Visit for Collect {
}
self.in_module_this = false;

let this_exprs = std::mem::take(&mut self.this_exprs);
for (_key, (ident, span)) in this_exprs {
// for (_key, (ident, span)) in self.this_exprs.clone() {
mischnic marked this conversation as resolved.
Show resolved Hide resolved
if self.exports.contains_key(&ident.sym) {
self.should_wrap = true;
self.add_bailout(span, BailoutReason::ThisInExport);
}
}

if let Some(bailouts) = &mut self.bailouts {
for (key, Import { specifier, .. }) in &self.imports {
if specifier == "*" {
Expand All @@ -260,7 +273,6 @@ impl Visit for Collect {
}

collect_visit_fn!(visit_function, Function);
collect_visit_fn!(visit_class, Class);
collect_visit_fn!(visit_getter_prop, GetterProp);
collect_visit_fn!(visit_setter_prop, SetterProp);

Expand Down Expand Up @@ -681,6 +693,10 @@ impl Visit for Collect {
Expr::This(_this) => {
if self.in_module_this {
handle_export!();
} else if !self.in_class {
if let MemberProp::Ident(prop) = &node.prop {
self.this_exprs.insert(id!(prop), (prop.clone(), node.span));
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we only want to handle this in exported functions? If you have a non-exported function that uses this we shouldn't need to wrap. You could track which functions use this instead of each property access, and then later check if any of the exported functions used this. Might be more accurate than just looking for property names?

Copy link
Contributor Author

@adelchan07 adelchan07 Oct 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we are tracking functions that use this, there would have to be some sort of struct that maps the Ident for the original exported function to every re-assignment of the function to another variable. Discussed this with @imbrian and we were thinking that the overhead from wrapping every time a this is encountered seems better than having to keep a (possibly very large) struct of every possible alias referring back to a function that calls this.

}
return;
}
Expand Down Expand Up @@ -769,6 +785,21 @@ impl Visit for Collect {
}
}

fn visit_class(&mut self, class: &Class) {
let in_module_this = self.in_module_this;
let in_function = self.in_function;
let in_class = self.in_class;

self.in_module_this = false;
self.in_function = true;
self.in_class = true;

class.visit_children_with(self);
self.in_module_this = in_module_this;
self.in_function = in_function;
self.in_class = in_class;
}

fn visit_this_expr(&mut self, node: &ThisExpr) {
if self.in_module_this {
self.has_cjs_exports = true;
Expand Down
62 changes: 62 additions & 0 deletions packages/transformers/js/core/src/hoist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3407,4 +3407,66 @@ mod tests {
}
);
}

#[test]
fn collect_this_exports() {
// module is wrapped when `this` accessor matches an export
let (collect, _code, _hoist) = parse(
r#"
exports.foo = function() {
exports.bar()
}

exports.bar = function() {
this.baz()
}

exports.baz = function() {
return 2
}
"#,
);
assert_eq!(
collect
.bailouts
.unwrap()
.iter()
.map(|b| &b.reason)
.collect::<Vec<_>>(),
vec![&BailoutReason::ThisInExport]
);
assert_eq!(collect.should_wrap, true);

// module is not wrapped when `this` inside a class collides with an export
let (collect, _code, _hoist) = parse(
r#"
class Foo {
constructor() {
this.a = 4
}

bar() {
return this.baz()
}

baz() {
return this.a
}
}

exports.baz = new Foo()
exports.a = 2
"#,
);
assert_eq!(
collect
.bailouts
.unwrap()
.iter()
.map(|b| &b.reason)
.collect::<Vec<_>>(),
Vec::<&BailoutReason>::new()
);
assert_eq!(collect.should_wrap, false);
}
}
5 changes: 5 additions & 0 deletions packages/transformers/js/core/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ pub enum BailoutReason {
ModuleReassignment,
NonStaticDynamicImport,
NonStaticAccess,
ThisInExport,
}

impl BailoutReason {
Expand Down Expand Up @@ -355,6 +356,10 @@ impl BailoutReason {
"Non-static access of an `import` or `require`. This causes tree shaking to be disabled for the resolved module.",
"https://parceljs.org/features/scope-hoisting/#dynamic-member-accesses"
),
BailoutReason::ThisInExport => (
"Module contains `this` access of an exported value. This causes the module to be wrapped and tree-shaking to be disabled.",
"https://parceljs.org/features/scope-hoisting/#avoiding-bail-outs"
),
}
}
}
Expand Down
Loading