Unverified Commit 8c875cb8 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

turbopack: handle no-side-effects edge cases

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 844ae05a
......@@ -171,7 +171,8 @@ pub enum Effect<'a> {
ImportedBinding {
esm_reference_index: usize,
export: Option<RcStr>,
/// A single member read from a named import (`z.member`), used only to narrow the part.
/// A statically known member accessed on the imported binding, used to narrow the part
/// and to query purity if the named import resolves to a namespace export.
member: Option<RcStr>,
ast_path: BumpBox<'a, [AstParentKind]>,
span: Span,
......
......@@ -2460,6 +2460,12 @@ impl VisitAstPath for Analyzer<'_, '_> {
// Attempt to add import effects.
if let Some((esm_reference_index, export)) = self.eval_context.imports.get_binding(&id) {
let static_member = member_access_parent(ast_path).and_then(|member| {
self.eval_context
.eval_member_prop(self.arena, &member.prop)
.and_then(|prop| prop.as_str().map(|prop| (member, RcStr::from(prop))))
});
// Optimization: Look for a MemberExpr to see if we only access a few members from the
// module, add those specific effects instead of depending on the entire module.
//
......@@ -2469,15 +2475,13 @@ impl VisitAstPath for Analyzer<'_, '_> {
.eval_context
.imports
.should_import_all(esm_reference_index)
&& let Some(member) = member_access_parent(ast_path)
&& let Some(prop) = self.eval_context.eval_member_prop(self.arena, &member.prop)
&& let Some(prop_str) = prop.as_str()
&& let Some((member, prop)) = &static_member
{
// a namespace member access like
// `import * as ns from "..."; ns.exportName`
self.add_effect(Effect::ImportedBinding {
esm_reference_index,
export: Some(prop_str.into()),
export: Some(prop.clone()),
member: None,
// point to the MemberExpression instead
ast_path: as_parent_path_skip_in(self.arena, ast_path, 1),
......
......@@ -595,14 +595,18 @@ impl<'a> SideEffectVisitor<'a> {
self.comments.has_flag(span.lo, "PURE")
}
fn is_no_side_effects_callee(&self, callee: &Callee) -> bool {
let Callee::Expr(callee) = callee else {
fn is_no_side_effects_expr(&self, expr: &Expr) -> bool {
let Expr::Ident(ident) = unparen(expr) else {
return false;
};
let Expr::Ident(ident) = unparen(callee) else {
self.no_side_effects.contains(&ident.to_id())
}
fn is_no_side_effects_callee(&self, callee: &Callee) -> bool {
let Callee::Expr(callee) = callee else {
return false;
};
self.no_side_effects.contains(&ident.to_id())
self.is_no_side_effects_expr(callee)
}
/// Check if a callee expression is a known pure built-in function.
......@@ -1109,13 +1113,15 @@ impl<'a> Visit for SideEffectVisitor<'a> {
e.arg.visit_with(self);
}
Expr::TaggedTpl(tagged_tpl)
// Tagged template literals are function calls
// But some are known to be pure, like String.raw
if self.is_known_pure_builtin_function(&tagged_tpl.tag) => {
for arg in &tagged_tpl.tpl.exprs {
arg.visit_with(self);
}
// Tagged template literals are function calls. Some are known to be pure, like
// String.raw, and NO_SIDE_EFFECTS applies to tags just like regular callees.
if self.is_known_pure_builtin_function(&tagged_tpl.tag)
|| self.is_no_side_effects_expr(&tagged_tpl.tag) =>
{
for arg in &tagged_tpl.tpl.exprs {
arg.visit_with(self);
}
}
Expr::OptChain(opt_chain) => {
// Optional chaining can be pure if it's just member access
// But if it's an optional call, it has side effects
......@@ -1622,6 +1628,21 @@ mod tests {
side_effects!(test_unannotated_binding_call, "const fn = other; fn();");
no_side_effects!(
test_no_side_effects_annotation_tagged_template,
"const tag = /*#__NO_SIDE_EFFECTS__*/ other; tag`value`;"
);
side_effects!(
test_no_side_effects_annotation_tagged_template_substitution,
"const tag = /*#__NO_SIDE_EFFECTS__*/ other; tag`${sideEffect()}`;"
);
side_effects!(
test_unannotated_tagged_template,
"const tag = other; tag`value`;"
);
no_side_effects!(
test_pure_annotation_in_variable,
"const x = /*#__PURE__*/ foo();"
......
......@@ -190,6 +190,69 @@ pub async fn is_export_no_side_effects(
}
}
/// Returns whether `member_name` is a no-side-effects export of a namespace exported as
/// `export_name`. Named re-export chains leading to that namespace are followed.
#[turbo_tasks::function]
pub async fn is_exported_namespace_member_no_side_effects(
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
export_name: RcStr,
member_name: RcStr,
) -> Result<Vc<bool>> {
let mut module = module;
let mut export_name = export_name;
let mut visited = FxHashSet::default();
loop {
if !visited.insert((module, export_name.clone())) {
return Ok(Vc::cell(false));
}
let exports = module.get_exports().await?;
let EcmascriptExports::EsmExports(exports) = &*exports else {
return Ok(Vc::cell(false));
};
let exports_vc = *exports;
let exports = exports_vc.await?;
let export = if let Some(export) = exports.exports.get(&export_name) {
export.clone()
} else {
let expanded = exports_vc
.expand_exports(ModuleExportUsageInfo::all())
.await?;
if !expanded.dynamic_exports.is_empty() {
return Ok(Vc::cell(false));
}
let Some(export) = expanded.exports.get(&export_name) else {
return Ok(Vc::cell(false));
};
export.clone()
};
match &export {
EsmExport::ImportedBinding(reference, imported_name, _) => {
let ReferencedAsset::Some(imported_module) =
ReferencedAsset::from_resolve_result(reference.resolve_reference()).await?
else {
return Ok(Vc::cell(false));
};
module = imported_module;
export_name = imported_name.clone();
}
EsmExport::ImportedNamespace(reference) => {
let ReferencedAsset::Some(imported_module) =
ReferencedAsset::from_resolve_result(reference.resolve_reference()).await?
else {
return Ok(Vc::cell(false));
};
return Ok(is_export_no_side_effects(*imported_module, member_name));
}
EsmExport::LocalBinding(..) | EsmExport::Error => {
return Ok(Vc::cell(false));
}
}
}
}
#[turbo_tasks::function]
pub async fn all_known_export_names(
module: Vc<Box<dyn EcmascriptChunkPlaceable>>,
......
......@@ -1514,9 +1514,10 @@ async fn analyze_ecmascript_module_internal(
.resolved_cell()
},
);
analysis.esm_bindings.add(
analysis.esm_bindings.add_with_namespace_member(
narrowed_reference,
export,
Some(member),
analysis.intern_path(&ast_path),
);
continue;
......@@ -1524,9 +1525,12 @@ async fn analyze_ecmascript_module_internal(
}
analysis.add_esm_reference(esm_reference_index);
analysis
.esm_bindings
.add(*r, export, analysis.intern_path(&ast_path));
analysis.esm_bindings.add_with_namespace_member(
*r,
export,
member,
analysis.intern_path(&ast_path),
);
}
}
Effect::TypeOf {
......
import annotatedDefault, {
annotated,
annotatedDeclaration,
exportedLater,
getState,
unannotated,
} from '../../pure/input/library'
import { reexported } from '../../pure/input/reexport'
import { annotated as starReexported } from '../../pure/input/star'
import * as directNamespace from '../../pure/input/library'
import { namespace } from '../../pure/input/namespace-reexport'
annotated()
annotatedDeclaration()
annotatedDefault()
exportedLater()
reexported()
starReexported()
directNamespace.annotated()
namespace.annotated()
annotated`tagged`
const alias = annotated
alias()
const parenthesizedAlias = annotated
parenthesizedAlias()
let argumentState = 0
annotated(argumentState++)
annotated`tagged${argumentState++}`
unannotated()
unannotated`tagged`
it('should propagate NO_SIDE_EFFECTS without scope hoisting', () => {
expect(getState()).toBe(2)
expect(argumentState).toBe(2)
})
......@@ -7,6 +7,8 @@ import annotatedDefault, {
} from './library'
import { reexported } from './reexport'
import { annotated as starReexported } from './star'
import * as directNamespace from './library'
import { namespace } from './namespace-reexport'
let state = 0
......@@ -20,20 +22,28 @@ annotatedDefault()
exportedLater()
reexported()
starReexported()
directNamespace.annotated()
namespace.annotated()
annotated`tagged`
const alias = annotated
alias()
const parenthesizedAlias = annotated
parenthesizedAlias()
let argumentState = 0
annotated(argumentState++)
annotated`tagged${argumentState++}`
unannotated()
unannotated`tagged`
it('should remove unused PURE statements', () => {
expect(state).toBe(0)
})
it('should propagate NO_SIDE_EFFECTS across imports and reexports', () => {
expect(getState()).toBe(1)
expect(argumentState).toBe(1)
expect(getState()).toBe(2)
expect(argumentState).toBe(2)
})
import { annotated, unannotated } from './library'
import { namespace } from './namespace-reexport'
annotated()
annotated`tagged`
namespace.annotated()
const alias = annotated
alias()
const parenthesizedAlias = annotated
parenthesizedAlias()
unannotated()
unannotated`tagged`
(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_basic_no-side-effects-import_input_0j6sxdtyjbhtp._.js",
(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_basic_no-side-effects-import_input_0hzc3c7_7upyo._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
__turbopack_context__.s([]);
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$no$2d$side$2d$effects$2d$import$2f$input$2f$library$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/library.js [test] (ecmascript)");
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$no$2d$side$2d$effects$2d$import$2f$input$2f$namespace$2d$reexport$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/namespace-reexport.js [test] (ecmascript)");
;
;
/*#__PURE__*/ (0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$no$2d$side$2d$effects$2d$import$2f$input$2f$library$2e$js__$5b$test$5d$__$28$ecmascript$29$__["annotated"])();
/*#__PURE__*/ (0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$no$2d$side$2d$effects$2d$import$2f$input$2f$library$2e$js__$5b$test$5d$__$28$ecmascript$29$__["annotated"])`tagged`;
/*#__PURE__*/ __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$no$2d$side$2d$effects$2d$import$2f$input$2f$namespace$2d$reexport$2e$js__$5b$test$5d$__$28$ecmascript$29$__["namespace"].annotated();
const alias = /*#__NO_SIDE_EFFECTS__*/ __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$no$2d$side$2d$effects$2d$import$2f$input$2f$library$2e$js__$5b$test$5d$__$28$ecmascript$29$__["annotated"];
alias();
const parenthesizedAlias = /*#__NO_SIDE_EFFECTS__*/ __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$no$2d$side$2d$effects$2d$import$2f$input$2f$library$2e$js__$5b$test$5d$__$28$ecmascript$29$__["annotated"];
parenthesizedAlias();
(0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$no$2d$side$2d$effects$2d$import$2f$input$2f$library$2e$js__$5b$test$5d$__$28$ecmascript$29$__["unannotated"])();
(0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$no$2d$side$2d$effects$2d$import$2f$input$2f$library$2e$js__$5b$test$5d$__$28$ecmascript$29$__["unannotated"])`tagged`;
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/library.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
......@@ -22,6 +29,16 @@ __turbopack_context__.s([
const annotated = /*#__NO_SIDE_EFFECTS__*/ function() {};
function unannotated() {}
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/namespace-reexport.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
__turbopack_context__.s([
"namespace",
()=>__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$no$2d$side$2d$effects$2d$import$2f$input$2f$library$2e$js__$5b$test$5d$__$28$ecmascript$29$__
]);
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$no$2d$side$2d$effects$2d$import$2f$input$2f$library$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/library.js [test] (ecmascript)");
;
}),
]);})()
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_basic_no-side-effects-import_input_0j6sxdtyjbhtp._.js.map
\ No newline at end of file
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_basic_no-side-effects-import_input_0hzc3c7_7upyo._.js.map
\ No newline at end of file
......@@ -2,6 +2,7 @@
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/index.js"],"sourcesContent":["import { annotated, unannotated } from './library'\n\nannotated()\n\nconst alias = annotated\nalias()\n\nunannotated()\n"],"names":["alias"],"mappings":";AAAA;;cAEA,IAAA,qOAAS;AAET,MAAMA,iCAAQ,qOAAS;AACvBA;AAEA,IAAA,uOAAW"}},
{"offset": {"line": 15, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/library.js"],"sourcesContent":["export const annotated = /*#__NO_SIDE_EFFECTS__*/ function () {}\nexport function unannotated() {}\n"],"names":["annotated","unannotated"],"mappings":";;;;;;AAAO,MAAMA,YAAY,sBAAsB,GAAG,YAAa;AACxD,SAASC,eAAe"}}]
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/index.js"],"sourcesContent":["import { annotated, unannotated } from './library'\nimport { namespace } from './namespace-reexport'\n\nannotated()\nannotated`tagged`\nnamespace.annotated()\n\nconst alias = annotated\nalias()\n\nconst parenthesizedAlias = (annotated)\nparenthesizedAlias()\n\nunannotated()\nunannotated`tagged`\n"],"names":["annotated","alias","parenthesizedAlias"],"mappings":";AAAA;AACA;;;cAEA,IAAA,qOAAS;cACT,IAAA,qOAAS,CAAA,CAAC,MAAM,CAAC;cACjB,mPAAS,CAACA,SAAS;AAEnB,MAAMC,iCAAQ,qOAAS;AACvBA;AAEA,MAAMC,8CAAsB,qOAAS;AACrCA;AAEA,IAAA,uOAAW;AACX,IAAA,uOAAW,CAAA,CAAC,MAAM,CAAC"}},
{"offset": {"line": 22, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/library.js"],"sourcesContent":["export const annotated = /*#__NO_SIDE_EFFECTS__*/ function () {}\nexport function unannotated() {}\n"],"names":["annotated","unannotated"],"mappings":";;;;;;AAAO,MAAMA,YAAY,sBAAsB,GAAG,YAAa;AACxD,SAASC,eAAe"}},
{"offset": {"line": 34, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/namespace-reexport.js"],"sourcesContent":["export * as namespace from './library'\n"],"names":[],"mappings":";;;;AAAA"}}]
}
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1ece_tests_snapshot_basic_no-side-effects-import_input_index_0gwnf7iwk9s7n.js",
{"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_basic_no-side-effects-import_input_0j6sxdtyjbhtp._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/index.js [test] (ecmascript)"]}
"output/1ece_tests_snapshot_basic_no-side-effects-import_input_index_1kng2gpdm_3v8.js",
{"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_basic_no-side-effects-import_input_0hzc3c7_7upyo._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/no-side-effects-import/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment