Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 6 additions & 0 deletions .changeset/honest-geese-rest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
swc_core: patch
swc_ecma_minifier: patch
---

fix(es/minifier): Check exported when optimize last expr
25 changes: 21 additions & 4 deletions crates/swc_ecma_minifier/src/compress/optimize/dead_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use swc_common::util::take::Take;
use swc_ecma_ast::*;

use super::{BitCtx, Optimizer};
use crate::program_data::VarUsageInfoFlags;
use crate::program_data::{ScopeData, VarUsageInfoFlags};

/// Methods related to option `dead_code`.
impl Optimizer<'_> {
Expand Down Expand Up @@ -48,14 +48,23 @@ impl Optimizer<'_> {

// We only handle identifiers on lhs for now.
if let Some(lhs) = assign.left.as_ident() {
let used_arguments = self
.data
.scopes
.get(&self.ctx.scope)
.map(|s| s.contains(ScopeData::USED_ARGUMENTS))
.unwrap_or(false);

if self
.data
.vars
.get(&lhs.to_id())
.map(|var| {
var.flags.contains(
VarUsageInfoFlags::DECLARED.union(VarUsageInfoFlags::IS_FN_LOCAL),
) && !var.flags.contains(VarUsageInfoFlags::DECLARED_AS_FN_PARAM)
) && !(used_arguments
&& var.flags.contains(VarUsageInfoFlags::DECLARED_AS_FN_PARAM))
&& !var.flags.intersects(VarUsageInfoFlags::EXPORTED)
})
.unwrap_or(false)
{
Expand All @@ -78,15 +87,23 @@ impl Optimizer<'_> {
}

if let Some(lhs) = assign.left.as_ident() {
//
let used_arguments = self
.data
.scopes
.get(&self.ctx.scope)
.map(|s| s.contains(ScopeData::USED_ARGUMENTS))
.unwrap_or(false);

if self
.data
.vars
.get(&lhs.to_id())
.map(|var| {
var.flags.contains(
VarUsageInfoFlags::DECLARED.union(VarUsageInfoFlags::IS_FN_LOCAL),
)
) && !(used_arguments
&& var.flags.contains(VarUsageInfoFlags::DECLARED_AS_FN_PARAM))
&& !var.flags.contains(VarUsageInfoFlags::EXPORTED)
})
.unwrap_or(false)
{
Expand Down
4 changes: 2 additions & 2 deletions crates/swc_ecma_minifier/tests/benches-full/echarts.js
Original file line number Diff line number Diff line change
Expand Up @@ -11474,7 +11474,7 @@
// check: category-no-encode-has-axis-data in dataset.html
var data = series.getData(), isValueMultipleLine = reduce(value, function(isValueMultipleLine, val, idx) {
var dimItem = data.getDimensionInfo(idx);
return isValueMultipleLine = isValueMultipleLine || dimItem && !1 !== dimItem.tooltip && null != dimItem.displayName;
return isValueMultipleLine || dimItem && !1 !== dimItem.tooltip && null != dimItem.displayName;
}, !1), inlineValues = [], inlineValueTypes = [], blocks = [];
function setEachItem(val, dim) {
var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
Expand Down Expand Up @@ -18950,7 +18950,7 @@
*/ function(tpl, value, isUTC) {
deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format'), ('week' === tpl || 'month' === tpl || 'quarter' === tpl || 'half-year' === tpl || 'year' === tpl) && (tpl = 'MM-dd\nyyyy');
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']();
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));
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));
},
capitalFirst: /**
* Capital first
Expand Down
2 changes: 1 addition & 1 deletion crates/swc_ecma_minifier/tests/benches-full/terser.js
Original file line number Diff line number Diff line change
Expand Up @@ -19779,7 +19779,7 @@
mangle_options: options.mangle
}).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) {
var cprivate = -1, private_cache = new Map(), nth_identifier = options.nth_identifier || base54;
return ast = ast.transform(new TreeTransformer(function(node) {
return ast.transform(new TreeTransformer(function(node) {
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));
}));
function mangle_private(name) {
Expand Down
24 changes: 12 additions & 12 deletions crates/swc_ecma_minifier/tests/benches-full/victory.js
Original file line number Diff line number Diff line change
Expand Up @@ -14507,7 +14507,7 @@
"left",
"right"
].reduce(function(memo, opt) {
return memo = handles[opt] && _this.withinBounds(point, handles[opt]) ? memo.concat(opt) : memo;
return handles[opt] && _this.withinBounds(point, handles[opt]) ? memo.concat(opt) : memo;
}, []);
return activeHandles.length && activeHandles;
},
Expand Down Expand Up @@ -14909,7 +14909,7 @@
"left",
"right"
].reduce(function(memo, curr) {
return memo = handleProps[curr] ? memo.concat(react__WEBPACK_IMPORTED_MODULE_3___default.a.cloneElement(handleComponent, lodash_assign__WEBPACK_IMPORTED_MODULE_1___default()({
return handleProps[curr] ? memo.concat(react__WEBPACK_IMPORTED_MODULE_3___default.a.cloneElement(handleComponent, lodash_assign__WEBPACK_IMPORTED_MODULE_1___default()({
key: "".concat(name, "-handle-").concat(curr)
}, handleProps[curr]))) : memo;
}, []);
Expand Down Expand Up @@ -17898,16 +17898,16 @@
switch(textAnchor){
case "start":
return widths.reduce(function(memo, width, i) {
return memo = i < index ? memo + width : memo;
return i < index ? memo + width : memo;
}, 0);
case "end":
return widths.reduce(function(memo, width, i) {
return memo = i > index ? memo - width : memo;
return i > index ? memo - width : memo;
}, 0);
default:
// middle
return widths.reduce(function(memo, width, i) {
return memo = i === index ? memo + width / 2 : memo + (i < index ? width : 0);
return i === index ? memo + width / 2 : memo + (i < index ? width : 0);
}, -totalWidth / 2);
}
}, getChildBackgrounds = function(calculatedProps, tspanValues) {
Expand Down Expand Up @@ -19937,7 +19937,7 @@
value: function(props, externalMutations) {
if (!lodash_isEmpty__WEBPACK_IMPORTED_MODULE_2___default()(externalMutations)) {
var callbacks = props.externalEventMutations.reduce(function(memo, mutation) {
return memo = lodash_isFunction__WEBPACK_IMPORTED_MODULE_5___default()(mutation.callback) ? memo.concat(mutation.callback) : memo;
return lodash_isFunction__WEBPACK_IMPORTED_MODULE_5___default()(mutation.callback) ? memo.concat(mutation.callback) : memo;
}, []), compiledCallbacks = callbacks.length ? function() {
callbacks.forEach(function(c) {
return c();
Expand Down Expand Up @@ -21385,7 +21385,7 @@
if (!lodash_isEmpty__WEBPACK_IMPORTED_MODULE_7___default()(eventReturn)) {
var callbacks = compileCallbacks(eventReturn);
_this2.setState(Array.isArray(eventReturn) ? eventReturn.reduce(function(memo, props) {
return memo = lodash_assign__WEBPACK_IMPORTED_MODULE_8___default()({}, memo, parseEvent(props, eventKey));
return lodash_assign__WEBPACK_IMPORTED_MODULE_8___default()({}, memo, parseEvent(props, eventKey));
}, {}) : parseEvent(eventReturn, eventKey), callbacks);
}
}; // Returns the state object with the mutation caused by a given eventReturn
Expand Down Expand Up @@ -21509,8 +21509,8 @@
* i.e. any static `defaultEvents` on `labelComponent` will be returned
*/ getComponentEvents: function(props, components) {
var events = Array.isArray(components) && components.reduce(function(memo, componentName) {
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;
return memo = Array.isArray(componentEvents) ? (_memo = memo).concat.apply(_memo, _toConsumableArray(componentEvents)) : memo;
var component = props[componentName], defaultEvents = component && component.type && component.type.defaultEvents, componentEvents = lodash_isFunction__WEBPACK_IMPORTED_MODULE_6___default()(defaultEvents) ? defaultEvents(component.props) : defaultEvents;
return Array.isArray(componentEvents) ? memo.concat.apply(memo, _toConsumableArray(componentEvents)) : memo;
}, []);
return events && events.length ? events : void 0;
},
Expand Down Expand Up @@ -31426,7 +31426,7 @@
filterDatasets: function(props, datasets, bounds) {
var _this = this, filtered = datasets.reduce(function(memo, dataset) {
var selectedData = _this.getSelectedData(props, dataset.data, bounds);
return memo = selectedData ? memo.concat({
return selectedData ? memo.concat({
childName: dataset.childName,
eventKey: selectedData.eventKey,
data: selectedData.data
Expand Down Expand Up @@ -31850,7 +31850,7 @@
value: function(props, externalMutations) {
if (!lodash_isEmpty__WEBPACK_IMPORTED_MODULE_3___default()(externalMutations)) {
var callbacks = props.externalEventMutations.reduce(function(memo, mutation) {
return memo = lodash_isFunction__WEBPACK_IMPORTED_MODULE_5___default()(mutation.callback) ? memo.concat(mutation.callback) : memo;
return lodash_isFunction__WEBPACK_IMPORTED_MODULE_5___default()(mutation.callback) ? memo.concat(mutation.callback) : memo;
}, []), compiledCallbacks = callbacks.length ? function() {
callbacks.forEach(function(c) {
return c();
Expand Down Expand Up @@ -33246,7 +33246,7 @@
}) : [
style
];
return memo = memo.concat(styleArray);
return memo.concat(styleArray);
}, []);
}
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export let foo;
foo = 1;
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export let foo;
foo = 1;
Original file line number Diff line number Diff line change
Expand Up @@ -15065,7 +15065,7 @@
}, 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;
}
function Sh(a) {
return Hh().memoizedState = a = {
return Hh().memoizedState = {
current: a
};
}
Expand Down Expand Up @@ -15555,13 +15555,13 @@
case 0:
case 2:
case 15:
return a = Pa(a.type, !1);
return Pa(a.type, !1);
case 11:
return a = Pa(a.type.render, !1);
return Pa(a.type.render, !1);
case 22:
return a = Pa(a.type._render, !1);
return Pa(a.type._render, !1);
case 1:
return a = Pa(a.type, !0);
return Pa(a.type, !0);
default:
return "";
}
Expand Down Expand Up @@ -17293,7 +17293,7 @@
if ("function" == typeof a.render) throw Error(y(188));
throw Error(y(268, Object.keys(a)));
}
return a = null === (a = cc(b)) ? null : a.stateNode;
return null === (a = cc(b)) ? null : a.stateNode;
}, exports.flushSync = function(a, b) {
var c = X;
if (0 != (48 & c)) return a(b);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@ var ts, ts1, dynamicImportUMDHelper;
* @param allowComments Whether to allow comments on the export.
*/ function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
var statement;
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));
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));
}
function createUnderscoreUnderscoreESModule() {
var statement;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25724,7 +25724,7 @@
];
},
useRef: function(e) {
return rD().memoizedState = e = {
return rD().memoizedState = {
current: e
};
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2992,7 +2992,7 @@
];
},
useRef: function(a) {
return $h().memoizedState = a = {
return $h().memoizedState = {
current: a
};
},
Expand Down Expand Up @@ -3110,11 +3110,11 @@
case 0:
case 2:
case 15:
return a = Na(a.type, !1);
return Na(a.type, !1);
case 11:
return a = Na(a.type.render, !1);
return Na(a.type.render, !1);
case 1:
return a = Na(a.type, !0);
return Na(a.type, !0);
default:
return "";
}
Expand Down Expand Up @@ -5552,7 +5552,7 @@
if ("function" == typeof a.render) throw Error(p(188));
throw Error(p(268, a = Object.keys(a).join(",")));
}
return a = null === (a = Yb(b)) ? null : a.stateNode;
return null === (a = Yb(b)) ? null : a.stateNode;
}, exports.flushSync = function(a) {
return Qk(a);
}, exports.hydrate = function(a, b, c) {
Expand Down
Loading
Loading