Skip to content

Commit f6f15f3

Browse files
authored
fix(es/minifier): Check exported when optimize last expr (#10939)
**Related issue:** - Closes #10935
1 parent 4808875 commit f6f15f3

File tree

13 files changed

+74
-57
lines changed

13 files changed

+74
-57
lines changed

.changeset/honest-geese-rest.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
swc_core: patch
3+
swc_ecma_minifier: patch
4+
---
5+
6+
fix(es/minifier): Check exported when optimize last expr

crates/swc_ecma_minifier/src/compress/optimize/dead_code.rs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use swc_common::util::take::Take;
22
use swc_ecma_ast::*;
33

44
use super::{BitCtx, Optimizer};
5-
use crate::program_data::VarUsageInfoFlags;
5+
use crate::program_data::{ScopeData, VarUsageInfoFlags};
66

77
/// Methods related to option `dead_code`.
88
impl Optimizer<'_> {
@@ -48,14 +48,23 @@ impl Optimizer<'_> {
4848

4949
// We only handle identifiers on lhs for now.
5050
if let Some(lhs) = assign.left.as_ident() {
51+
let used_arguments = self
52+
.data
53+
.scopes
54+
.get(&self.ctx.scope)
55+
.map(|s| s.contains(ScopeData::USED_ARGUMENTS))
56+
.unwrap_or(false);
57+
5158
if self
5259
.data
5360
.vars
5461
.get(&lhs.to_id())
5562
.map(|var| {
5663
var.flags.contains(
5764
VarUsageInfoFlags::DECLARED.union(VarUsageInfoFlags::IS_FN_LOCAL),
58-
) && !var.flags.contains(VarUsageInfoFlags::DECLARED_AS_FN_PARAM)
65+
) && !(used_arguments
66+
&& var.flags.contains(VarUsageInfoFlags::DECLARED_AS_FN_PARAM))
67+
&& !var.flags.intersects(VarUsageInfoFlags::EXPORTED)
5968
})
6069
.unwrap_or(false)
6170
{
@@ -78,15 +87,23 @@ impl Optimizer<'_> {
7887
}
7988

8089
if let Some(lhs) = assign.left.as_ident() {
81-
//
90+
let used_arguments = self
91+
.data
92+
.scopes
93+
.get(&self.ctx.scope)
94+
.map(|s| s.contains(ScopeData::USED_ARGUMENTS))
95+
.unwrap_or(false);
96+
8297
if self
8398
.data
8499
.vars
85100
.get(&lhs.to_id())
86101
.map(|var| {
87102
var.flags.contains(
88103
VarUsageInfoFlags::DECLARED.union(VarUsageInfoFlags::IS_FN_LOCAL),
89-
)
104+
) && !(used_arguments
105+
&& var.flags.contains(VarUsageInfoFlags::DECLARED_AS_FN_PARAM))
106+
&& !var.flags.contains(VarUsageInfoFlags::EXPORTED)
90107
})
91108
.unwrap_or(false)
92109
{

crates/swc_ecma_minifier/tests/benches-full/echarts.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11474,7 +11474,7 @@
1147411474
// check: category-no-encode-has-axis-data in dataset.html
1147511475
var data = series.getData(), isValueMultipleLine = reduce(value, function(isValueMultipleLine, val, idx) {
1147611476
var dimItem = data.getDimensionInfo(idx);
11477-
return isValueMultipleLine = isValueMultipleLine || dimItem && !1 !== dimItem.tooltip && null != dimItem.displayName;
11477+
return isValueMultipleLine || dimItem && !1 !== dimItem.tooltip && null != dimItem.displayName;
1147811478
}, !1), inlineValues = [], inlineValueTypes = [], blocks = [];
1147911479
function setEachItem(val, dim) {
1148011480
var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
@@ -18950,7 +18950,7 @@
1895018950
*/ function(tpl, value, isUTC) {
1895118951
deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format'), ('week' === tpl || 'month' === tpl || 'quarter' === tpl || 'half-year' === tpl || 'year' === tpl) && (tpl = 'MM-dd\nyyyy');
1895218952
var date = parseDate(value), utc = isUTC ? 'UTC' : '', y = date['get' + utc + 'FullYear'](), M = date['get' + utc + 'Month']() + 1, d = date['get' + utc + 'Date'](), h = date['get' + utc + 'Hours'](), m = date['get' + utc + 'Minutes'](), s = date['get' + utc + 'Seconds'](), S = date['get' + utc + 'Milliseconds']();
18953-
return tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', y % 100 + '').replace('dd', pad(d, 2)).replace('d', d).replace('hh', pad(h, 2)).replace('h', h).replace('mm', pad(m, 2)).replace('m', m).replace('ss', pad(s, 2)).replace('s', s).replace('SSS', pad(S, 3));
18953+
return tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', y % 100 + '').replace('dd', pad(d, 2)).replace('d', d).replace('hh', pad(h, 2)).replace('h', h).replace('mm', pad(m, 2)).replace('m', m).replace('ss', pad(s, 2)).replace('s', s).replace('SSS', pad(S, 3));
1895418954
},
1895518955
capitalFirst: /**
1895618956
* Capital first

crates/swc_ecma_minifier/tests/benches-full/terser.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19779,7 +19779,7 @@
1977919779
mangle_options: options.mangle
1978019780
}).compress(toplevel)), timings && (timings.scope = Date.now()), options.mangle && toplevel.figure_out_scope(options.mangle), timings && (timings.mangle = Date.now()), options.mangle && (toplevel.compute_char_frequency(options.mangle), toplevel.mangle_names(options.mangle), toplevel = function(ast, options) {
1978119781
var cprivate = -1, private_cache = new Map(), nth_identifier = options.nth_identifier || base54;
19782-
return ast = ast.transform(new TreeTransformer(function(node) {
19782+
return ast.transform(new TreeTransformer(function(node) {
1978319783
node instanceof AST_ClassPrivateProperty || node instanceof AST_PrivateMethod || node instanceof AST_PrivateGetter || node instanceof AST_PrivateSetter || node instanceof AST_PrivateIn ? node.key.name = mangle_private(node.key.name) : node instanceof AST_DotHash && (node.property = mangle_private(node.property));
1978419784
}));
1978519785
function mangle_private(name) {

crates/swc_ecma_minifier/tests/benches-full/victory.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14507,7 +14507,7 @@
1450714507
"left",
1450814508
"right"
1450914509
].reduce(function(memo, opt) {
14510-
return memo = handles[opt] && _this.withinBounds(point, handles[opt]) ? memo.concat(opt) : memo;
14510+
return handles[opt] && _this.withinBounds(point, handles[opt]) ? memo.concat(opt) : memo;
1451114511
}, []);
1451214512
return activeHandles.length && activeHandles;
1451314513
},
@@ -14909,7 +14909,7 @@
1490914909
"left",
1491014910
"right"
1491114911
].reduce(function(memo, curr) {
14912-
return memo = handleProps[curr] ? memo.concat(react__WEBPACK_IMPORTED_MODULE_3___default.a.cloneElement(handleComponent, lodash_assign__WEBPACK_IMPORTED_MODULE_1___default()({
14912+
return handleProps[curr] ? memo.concat(react__WEBPACK_IMPORTED_MODULE_3___default.a.cloneElement(handleComponent, lodash_assign__WEBPACK_IMPORTED_MODULE_1___default()({
1491314913
key: "".concat(name, "-handle-").concat(curr)
1491414914
}, handleProps[curr]))) : memo;
1491514915
}, []);
@@ -17898,16 +17898,16 @@
1789817898
switch(textAnchor){
1789917899
case "start":
1790017900
return widths.reduce(function(memo, width, i) {
17901-
return memo = i < index ? memo + width : memo;
17901+
return i < index ? memo + width : memo;
1790217902
}, 0);
1790317903
case "end":
1790417904
return widths.reduce(function(memo, width, i) {
17905-
return memo = i > index ? memo - width : memo;
17905+
return i > index ? memo - width : memo;
1790617906
}, 0);
1790717907
default:
1790817908
// middle
1790917909
return widths.reduce(function(memo, width, i) {
17910-
return memo = i === index ? memo + width / 2 : memo + (i < index ? width : 0);
17910+
return i === index ? memo + width / 2 : memo + (i < index ? width : 0);
1791117911
}, -totalWidth / 2);
1791217912
}
1791317913
}, getChildBackgrounds = function(calculatedProps, tspanValues) {
@@ -19937,7 +19937,7 @@
1993719937
value: function(props, externalMutations) {
1993819938
if (!lodash_isEmpty__WEBPACK_IMPORTED_MODULE_2___default()(externalMutations)) {
1993919939
var callbacks = props.externalEventMutations.reduce(function(memo, mutation) {
19940-
return memo = lodash_isFunction__WEBPACK_IMPORTED_MODULE_5___default()(mutation.callback) ? memo.concat(mutation.callback) : memo;
19940+
return lodash_isFunction__WEBPACK_IMPORTED_MODULE_5___default()(mutation.callback) ? memo.concat(mutation.callback) : memo;
1994119941
}, []), compiledCallbacks = callbacks.length ? function() {
1994219942
callbacks.forEach(function(c) {
1994319943
return c();
@@ -21385,7 +21385,7 @@
2138521385
if (!lodash_isEmpty__WEBPACK_IMPORTED_MODULE_7___default()(eventReturn)) {
2138621386
var callbacks = compileCallbacks(eventReturn);
2138721387
_this2.setState(Array.isArray(eventReturn) ? eventReturn.reduce(function(memo, props) {
21388-
return memo = lodash_assign__WEBPACK_IMPORTED_MODULE_8___default()({}, memo, parseEvent(props, eventKey));
21388+
return lodash_assign__WEBPACK_IMPORTED_MODULE_8___default()({}, memo, parseEvent(props, eventKey));
2138921389
}, {}) : parseEvent(eventReturn, eventKey), callbacks);
2139021390
}
2139121391
}; // Returns the state object with the mutation caused by a given eventReturn
@@ -21509,8 +21509,8 @@
2150921509
* i.e. any static `defaultEvents` on `labelComponent` will be returned
2151021510
*/ getComponentEvents: function(props, components) {
2151121511
var events = Array.isArray(components) && components.reduce(function(memo, componentName) {
21512-
var _memo, component = props[componentName], defaultEvents = component && component.type && component.type.defaultEvents, componentEvents = lodash_isFunction__WEBPACK_IMPORTED_MODULE_6___default()(defaultEvents) ? defaultEvents(component.props) : defaultEvents;
21513-
return memo = Array.isArray(componentEvents) ? (_memo = memo).concat.apply(_memo, _toConsumableArray(componentEvents)) : memo;
21512+
var component = props[componentName], defaultEvents = component && component.type && component.type.defaultEvents, componentEvents = lodash_isFunction__WEBPACK_IMPORTED_MODULE_6___default()(defaultEvents) ? defaultEvents(component.props) : defaultEvents;
21513+
return Array.isArray(componentEvents) ? memo.concat.apply(memo, _toConsumableArray(componentEvents)) : memo;
2151421514
}, []);
2151521515
return events && events.length ? events : void 0;
2151621516
},
@@ -31426,7 +31426,7 @@
3142631426
filterDatasets: function(props, datasets, bounds) {
3142731427
var _this = this, filtered = datasets.reduce(function(memo, dataset) {
3142831428
var selectedData = _this.getSelectedData(props, dataset.data, bounds);
31429-
return memo = selectedData ? memo.concat({
31429+
return selectedData ? memo.concat({
3143031430
childName: dataset.childName,
3143131431
eventKey: selectedData.eventKey,
3143231432
data: selectedData.data
@@ -31850,7 +31850,7 @@
3185031850
value: function(props, externalMutations) {
3185131851
if (!lodash_isEmpty__WEBPACK_IMPORTED_MODULE_3___default()(externalMutations)) {
3185231852
var callbacks = props.externalEventMutations.reduce(function(memo, mutation) {
31853-
return memo = lodash_isFunction__WEBPACK_IMPORTED_MODULE_5___default()(mutation.callback) ? memo.concat(mutation.callback) : memo;
31853+
return lodash_isFunction__WEBPACK_IMPORTED_MODULE_5___default()(mutation.callback) ? memo.concat(mutation.callback) : memo;
3185431854
}, []), compiledCallbacks = callbacks.length ? function() {
3185531855
callbacks.forEach(function(c) {
3185631856
return c();
@@ -33246,7 +33246,7 @@
3324633246
}) : [
3324733247
style
3324833248
];
33249-
return memo = memo.concat(styleArray);
33249+
return memo.concat(styleArray);
3325033250
}, []);
3325133251
}
3325233252
},
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export let foo;
2+
foo = 1;
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export let foo;
2+
foo = 1;

crates/swc_ecma_minifier/tests/fixture/issues/2257/full/output.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15065,7 +15065,7 @@
1506515065
}, R.updateQueue = b, b.lastEffect = a.next = a) : null === (c = b.lastEffect) ? b.lastEffect = a.next = a : (d = c.next, c.next = a, a.next = d, b.lastEffect = a), a;
1506615066
}
1506715067
function Sh(a) {
15068-
return Hh().memoizedState = a = {
15068+
return Hh().memoizedState = {
1506915069
current: a
1507015070
};
1507115071
}
@@ -15555,13 +15555,13 @@
1555515555
case 0:
1555615556
case 2:
1555715557
case 15:
15558-
return a = Pa(a.type, !1);
15558+
return Pa(a.type, !1);
1555915559
case 11:
15560-
return a = Pa(a.type.render, !1);
15560+
return Pa(a.type.render, !1);
1556115561
case 22:
15562-
return a = Pa(a.type._render, !1);
15562+
return Pa(a.type._render, !1);
1556315563
case 1:
15564-
return a = Pa(a.type, !0);
15564+
return Pa(a.type, !0);
1556515565
default:
1556615566
return "";
1556715567
}
@@ -17293,7 +17293,7 @@
1729317293
if ("function" == typeof a.render) throw Error(y(188));
1729417294
throw Error(y(268, Object.keys(a)));
1729517295
}
17296-
return a = null === (a = cc(b)) ? null : a.stateNode;
17296+
return null === (a = cc(b)) ? null : a.stateNode;
1729717297
}, exports.flushSync = function(a, b) {
1729817298
var c = X;
1729917299
if (0 != (48 & c)) return a(b);

crates/swc_ecma_minifier/tests/fixture/issues/typescript/1/output.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -686,7 +686,7 @@ var ts, ts1, dynamicImportUMDHelper;
686686
* @param allowComments Whether to allow comments on the export.
687687
*/ function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
688688
var statement;
689-
return statements = ts1.append(statements, (statement = ts1.setTextRange(factory.createExpressionStatement(createExportExpression(exportName, expression, /* location */ void 0, liveBinding)), location), ts1.startOnNewLine(statement), allowComments || ts1.setEmitFlags(statement, 1536 /* NoComments */ ), statement));
689+
return ts1.append(statements, (statement = ts1.setTextRange(factory.createExpressionStatement(createExportExpression(exportName, expression, /* location */ void 0, liveBinding)), location), ts1.startOnNewLine(statement), allowComments || ts1.setEmitFlags(statement, 1536 /* NoComments */ ), statement));
690690
}
691691
function createUnderscoreUnderscoreESModule() {
692692
var statement;

crates/swc_ecma_minifier/tests/fixture/next/react-pdf-renderer/output.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25724,7 +25724,7 @@
2572425724
];
2572525725
},
2572625726
useRef: function(e) {
25727-
return rD().memoizedState = e = {
25727+
return rD().memoizedState = {
2572825728
current: e
2572925729
};
2573025730
},

0 commit comments

Comments
 (0)