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

turbopack: keep parens around PURE-annotated callees in fixer

Turbopack ran SWC's fixer without comments, so it dropped the parentheses in
(/* @__PURE__ */ f())(). After printing and re-parsing for minification, the
annotation applied to the outer call and the minifier removed side-effecting
IIFEs (#99897). Pass a read-only view of the parsed and codegen comments so
the fixer's PURE/NO_SIDE_EFFECTS guard works without mutating the stores.
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 207b08b6
......@@ -74,6 +74,8 @@ test/development/mcp-server/fixtures/compilation-errors-app/app/syntax-error/pag
/turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css
/test/development/app-dir/css-parse-error-recovery/app/css-error/style.css
/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/cjs/input/mod.cjs
# prettier removes the parentheses that scope the PURE annotation to the inner call
/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-*/input/index.js
/turbopack/crates/turbopack-tests/tests/snapshot/source_maps/*
/turbopack/crates/turbopack-tests/tests/**/output*
/turbopack/crates/turbopack-tests/tests/**/static
......
......@@ -130,7 +130,7 @@ use crate::{
exports::compute_ecmascript_module_exports,
},
side_effect_optimization::reference::EcmascriptModulePartReference,
swc_comments::{CowComments, ImmutableComments},
swc_comments::{CowComments, ImmutableComments, ReadOnlyComments},
transform::{remove_directives, remove_shebang},
};
pub use crate::{
......@@ -2152,7 +2152,21 @@ async fn process_parse_result(
),
);
}
program.visit_mut_with(&mut swc_core::ecma::transforms::base::fixer::fixer(None));
// The fixer needs to see the comments: without them it drops the parentheses in
// `(/* @__PURE__ */ f())()`, which moves the PURE annotation onto the outer call
// when the code is printed (and re-parsed by the minifier), so the whole call
// would be removed as side-effect free.
{
let parsed_comments: &ImmutableComments = match &comments {
Either::Left(c) => c,
Either::Right(c) => c,
};
let stores: [&dyn Comments; 2] = [parsed_comments, &extra_comments];
let fixer_comments = ReadOnlyComments::new(&stores);
program.visit_mut_with(&mut swc_core::ecma::transforms::base::fixer::fixer(
Some(&fixer_comments),
));
}
// we need to remove any shebang before bundling as it's only valid as the first
// line in a js file (not in a chunk item wrapped in the runtime)
......
......@@ -266,6 +266,78 @@ impl Comments for ImmutableComments {
}
}
/// A read-only [Comments] view over several comment stores.
///
/// Some SWC transforms (e.g. the fixer) need to *read* comments to make correct decisions -- the
/// fixer keeps the parentheses around a `/* @__PURE__ */`-annotated callee, which would otherwise
/// move the annotation onto the outer call -- but they also try to move comments around as they
/// rewrite the AST. The comment stores at that point are either immutable ([ImmutableComments]
/// panics on mutation) or must not be changed, so this adapter:
///
/// - answers `has_*` / `get_*` by looking at every store and concatenating the results,
/// - implements `take_*` as a non-destructive copy (like `get_*`), because SWC's default
/// [Comments::has_flag] uses `take_leading` followed by `add_leading_comments`,
/// - ignores every mutation (`add_*`, `move_*`, `add_pure_comment`).
pub struct ReadOnlyComments<'a> {
stores: &'a [&'a dyn Comments],
}
impl<'a> ReadOnlyComments<'a> {
pub fn new(stores: &'a [&'a dyn Comments]) -> Self {
Self { stores }
}
fn collect(&self, f: impl Fn(&dyn Comments) -> Option<Vec<Comment>>) -> Option<Vec<Comment>> {
let mut result: Option<Vec<Comment>> = None;
for store in self.stores {
if let Some(c) = f(*store) {
result.get_or_insert_with(Vec::new).extend(c);
}
}
result
}
}
impl Comments for ReadOnlyComments<'_> {
fn add_leading(&self, _pos: BytePos, _cmt: Comment) {}
fn add_leading_comments(&self, _pos: BytePos, _comments: Vec<Comment>) {}
fn has_leading(&self, pos: BytePos) -> bool {
self.stores.iter().any(|s| s.has_leading(pos))
}
fn move_leading(&self, _from: BytePos, _to: BytePos) {}
fn take_leading(&self, pos: BytePos) -> Option<Vec<Comment>> {
self.get_leading(pos)
}
fn get_leading(&self, pos: BytePos) -> Option<Vec<Comment>> {
self.collect(|s| s.get_leading(pos))
}
fn add_trailing(&self, _pos: BytePos, _cmt: Comment) {}
fn add_trailing_comments(&self, _pos: BytePos, _comments: Vec<Comment>) {}
fn has_trailing(&self, pos: BytePos) -> bool {
self.stores.iter().any(|s| s.has_trailing(pos))
}
fn move_trailing(&self, _from: BytePos, _to: BytePos) {}
fn take_trailing(&self, pos: BytePos) -> Option<Vec<Comment>> {
self.get_trailing(pos)
}
fn get_trailing(&self, pos: BytePos) -> Option<Vec<Comment>> {
self.collect(|s| s.get_trailing(pos))
}
fn add_pure_comment(&self, _pos: BytePos) {}
}
pub struct CowComments<'a> {
leading: RefCell<FxHashMap<BytePos, Cow<'a, [Comment]>>>,
trailing: RefCell<FxHashMap<BytePos, Cow<'a, [Comment]>>>,
......@@ -426,3 +498,135 @@ impl Comments for CowComments<'_> {
}
}
}
#[cfg(test)]
mod tests {
use swc_core::{
base::SwcComments,
common::{
BytePos, DUMMY_SP,
comments::{Comment, CommentKind, Comments},
},
};
use super::{ImmutableComments, ReadOnlyComments};
fn block(text: &str) -> Comment {
Comment {
kind: CommentKind::Block,
span: DUMMY_SP,
text: text.into(),
}
}
fn texts(comments: Option<Vec<Comment>>) -> Option<Vec<String>> {
comments.map(|c| c.into_iter().map(|c| c.text.to_string()).collect())
}
/// An [ImmutableComments] store with `a` leading and `b` trailing at position 1, plus a
/// [SwcComments] store with `@__PURE__` leading at position 1 and `c` leading at position 2.
fn stores() -> (ImmutableComments, SwcComments) {
let mut immutable = ImmutableComments::default();
immutable.leading.insert(BytePos(1), vec![block("a")]);
immutable.trailing.insert(BytePos(1), vec![block("b")]);
let extra = SwcComments::default();
extra.add_leading(BytePos(1), block(" @__PURE__ "));
extra.add_leading(BytePos(2), block("c"));
(immutable, extra)
}
#[test]
fn reads_and_concatenates_all_stores() {
let (immutable, extra) = stores();
let stores: [&dyn Comments; 2] = [&immutable, &extra];
let comments = ReadOnlyComments::new(&stores);
assert_eq!(
texts(comments.get_leading(BytePos(1))),
Some(vec!["a".to_string(), " @__PURE__ ".to_string()])
);
assert_eq!(
texts(comments.get_leading(BytePos(2))),
Some(vec!["c".to_string()])
);
assert_eq!(
texts(comments.get_trailing(BytePos(1))),
Some(vec!["b".to_string()])
);
assert_eq!(comments.get_leading(BytePos(3)), None);
assert_eq!(comments.get_trailing(BytePos(2)), None);
assert!(comments.has_leading(BytePos(1)));
assert!(comments.has_leading(BytePos(2)));
assert!(!comments.has_leading(BytePos(3)));
assert!(comments.has_trailing(BytePos(1)));
assert!(!comments.has_trailing(BytePos(2)));
}
#[test]
fn take_does_not_consume() {
let (immutable, extra) = stores();
let stores: [&dyn Comments; 2] = [&immutable, &extra];
let comments = ReadOnlyComments::new(&stores);
let first = texts(comments.take_leading(BytePos(1)));
assert_eq!(first, texts(comments.take_leading(BytePos(1))));
assert_eq!(first, texts(comments.get_leading(BytePos(1))));
assert_eq!(
texts(comments.take_trailing(BytePos(1))),
texts(comments.take_trailing(BytePos(1)))
);
assert!(comments.has_trailing(BytePos(1)));
// The underlying stores are untouched.
assert!(extra.has_leading(BytePos(1)));
assert_eq!(immutable.leading[&BytePos(1)].len(), 1);
}
#[test]
fn mutations_are_ignored() {
let (immutable, extra) = stores();
let stores: [&dyn Comments; 2] = [&immutable, &extra];
let comments = ReadOnlyComments::new(&stores);
// None of these may panic, even though `ImmutableComments` panics on mutation.
comments.add_leading(BytePos(5), block("x"));
comments.add_leading_comments(BytePos(5), vec![block("x")]);
comments.add_trailing(BytePos(5), block("x"));
comments.add_trailing_comments(BytePos(5), vec![block("x")]);
comments.add_pure_comment(BytePos(5));
comments.move_leading(BytePos(1), BytePos(6));
comments.move_trailing(BytePos(1), BytePos(6));
assert!(!comments.has_leading(BytePos(5)));
assert!(!comments.has_trailing(BytePos(5)));
assert!(!comments.has_leading(BytePos(6)));
assert!(!comments.has_trailing(BytePos(6)));
assert!(comments.has_leading(BytePos(1)));
assert!(comments.has_trailing(BytePos(1)));
assert_eq!(extra.get_leading(BytePos(1)).map(|c| c.len()), Some(1));
}
#[test]
fn has_flag_sees_every_store() {
let mut immutable = ImmutableComments::default();
immutable
.leading
.insert(BytePos(1), vec![block(" #__NO_SIDE_EFFECTS__ ")]);
let extra = SwcComments::default();
extra.add_leading(BytePos(2), block(" @__PURE__ "));
let stores: [&dyn Comments; 2] = [&immutable, &extra];
let comments = ReadOnlyComments::new(&stores);
// `has_flag` uses the default implementation (`take_leading` + `add_leading_comments`),
// so calling it repeatedly must keep returning the same answer.
for _ in 0..2 {
assert!(comments.has_flag(BytePos(1), "NO_SIDE_EFFECTS"));
assert!(!comments.has_flag(BytePos(1), "PURE"));
assert!(comments.has_flag(BytePos(2), "PURE"));
assert!(!comments.has_flag(BytePos(3), "PURE"));
}
}
}
import { __name } from './name.js'
// The PURE annotation applies to the inner `__name(...)` call only. The outer
// call (the IIFE) has side effects and must be kept.
;(/* @__PURE__ */ __name(function annotated() {
console.log('annotated IIFE ran')
}, 'annotated'))()
export const value = 1
var __defProp = Object.defineProperty
export var __name = (target, value) =>
__defProp(target, 'name', { value, configurable: true })
{
"minifyType": {
"Minify": {
"mangle": "optimal-size"
}
},
"scopeHoisting": true
}
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["output/0nf9_minification_pure-annotated-iife-scope-hoisted_input_index_10cuajmww7lap.js",{otherChunks:["output/154e_minification_pure-annotated-iife-scope-hoisted_input_index_0z5laqz7qel98.js"],runtimeModuleIds:["[project]/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-iife-scope-hoisted/input/index.js [test] (ecmascript)"]}]);
//# sourceMappingURL=154e_minification_pure-annotated-iife-scope-hoisted_input_index_10cuajmww7lap.js.map
\ No newline at end of file
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["output/154e_minification_pure-annotated-iife-scope-hoisted_input_index_0z5laqz7qel98.js","[project]/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-iife-scope-hoisted/input/index.js [test] (ecmascript)",t=>{"use strict";t.s(["value",()=>e],"[project]/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-iife-scope-hoisted/input/index.js [test] (ecmascript)"),(0,Object.defineProperty)(function(){console.log("annotated IIFE ran")},"name",{value:"annotated",configurable:!0})();let e=1}]);
//# sourceMappingURL=154e_minification_pure-annotated-iife-scope-hoisted_input_index_0z5laqz7qel98.js.map
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-iife-scope-hoisted/input/name.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-iife-scope-hoisted/input/index.js"],"sourcesContent":["var __defProp = Object.defineProperty\n\nexport var __name = (target, value) =>\n __defProp(target, 'name', { value, configurable: true })\n","import { __name } from './name.js'\n\n// The PURE annotation applies to the inner `__name(...)` call only. The outer\n// call (the IIFE) has side effects and must be kept.\n;(/* @__PURE__ */ __name(function annotated() {\n console.log('annotated IIFE ran')\n}, 'annotated'))()\n\nexport const value = 1\n"],"names":["__defProp","Object","defineProperty","__name","target","value","configurable"],"mappings":"odAGEA,ACCD,CAAC,EDJcC,OAAOC,AAGXE,ICCG,GAAG,ODJKF,AAAc,ECIZ,SAAS,EAChC,QAAQ,GAAG,CAAC,qBACd,EDHoB,OAAQ,CAAEG,MCG3B,YDHkCC,cAAc,CAAK,KCKjD,IAAM,EAAQ"}
\ No newline at end of file
var __defProp = Object.defineProperty
var __name = (target, value) =>
__defProp(target, 'name', { value, configurable: true })
// The PURE annotation applies to the inner `__name(...)` call only. The outer
// call (the IIFE) has side effects and must be kept.
;(/* @__PURE__ */ __name(function annotated() {
console.log('annotated IIFE ran')
}, 'annotated'))()
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["output/1ece_tests_snapshot_minification_pure-annotated-iife_input_index_0odiguvy7orvo.js",{otherChunks:["output/1jsg_tests_snapshot_minification_pure-annotated-iife_input_index_0esx4hyletpzn.js"],runtimeModuleIds:["[project]/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-iife/input/index.js [test] (ecmascript)"]}]);
//# sourceMappingURL=1jsg_tests_snapshot_minification_pure-annotated-iife_input_index_0odiguvy7orvo.js.map
\ No newline at end of file
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["output/1jsg_tests_snapshot_minification_pure-annotated-iife_input_index_0esx4hyletpzn.js","[project]/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-iife/input/index.js [test] (ecmascript)",(t,e,n)=>{(0,Object.defineProperty)(function(){console.log("annotated IIFE ran")},"name",{value:"annotated",configurable:!0})()}]);
//# sourceMappingURL=1jsg_tests_snapshot_minification_pure-annotated-iife_input_index_0esx4hyletpzn.js.map
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-iife/input/index.js"],"sourcesContent":["var __defProp = Object.defineProperty\nvar __name = (target, value) =>\n __defProp(target, 'name', { value, configurable: true })\n\n// The PURE annotation applies to the inner `__name(...)` call only. The outer\n// call (the IIFE) has side effects and must be kept.\n;(/* @__PURE__ */ __name(function annotated() {\n console.log('annotated IIFE ran')\n}, 'annotated'))()\n"],"names":["__defProp","Object","defineProperty","__name","target","value","configurable","annotated","console","log"],"mappings":"6RAEEA,AAID,CAAC,EANcC,OAAOC,AAEXE,IAIG,GAAGD,OANKD,AAAc,EAMZ,SAASK,EAChCC,QAAQC,GAAG,CAAC,qBACd,EANoB,OAAQ,CAAEJ,MAM3B,YANkCC,cAAc,CAAK"}
\ No newline at end of file
function make() {
return {
run() {
console.log('member call ran')
},
}
}
// The PURE annotation applies to the inner `make()` call only. The outer
// `.run()` call has side effects and must be kept.
;(/* @__PURE__ */ make()).run()
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["output/1ece_tests_snapshot_minification_pure-annotated-member_input_index_1k5u1-yl8rq5n.js",{otherChunks:["output/1jsg_tests_snapshot_minification_pure-annotated-member_input_index_06zc3vqhxqozy.js"],runtimeModuleIds:["[project]/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-member/input/index.js [test] (ecmascript)"]}]);
//# sourceMappingURL=1jsg_tests_snapshot_minification_pure-annotated-member_input_index_1k5u1-yl8rq5n.js.map
\ No newline at end of file
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["output/1jsg_tests_snapshot_minification_pure-annotated-member_input_index_06zc3vqhxqozy.js","[project]/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-member/input/index.js [test] (ecmascript)",(t,e,s)=>{({run(){console.log("member call ran")}}).run()}]);
//# sourceMappingURL=1jsg_tests_snapshot_minification_pure-annotated-member_input_index_06zc3vqhxqozy.js.map
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/minification/pure-annotated-member/input/index.js"],"sourcesContent":["function make() {\n return {\n run() {\n console.log('member call ran')\n },\n }\n}\n\n// The PURE annotation applies to the inner `make()` call only. The outer\n// `.run()` call has side effects and must be kept.\n;(/* @__PURE__ */ make()).run()\n"],"names":["make","run","console","log"],"mappings":"iSAUC,CATQ,AASP,CAREC,MACEC,MAOS,EAPDC,CAOIH,EAPD,CAAC,kBACd,EACF,EAKwBC,GAAG"}
\ 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