Skip to content

Commit c4a839b

Browse files
authored
feat(es/minifier): Make seq inliner inline into var without init (#10077)
1 parent 608bc69 commit c4a839b

File tree

10 files changed

+72
-56
lines changed

10 files changed

+72
-56
lines changed
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
//// [compoundExponentiationAssignmentLHSIsReference.ts]
2-
var value, x1, x3;
3-
x1 = Math.pow(x1, value), x3.a = Math.pow(x3.a, value), x3.a = Math.pow(x3.a, value), x1 = Math.pow(x1, value), x3.a = Math.pow(x3.a, value), x3.a = Math.pow(x3.a, value);
2+
var value, x3, x1 = Math.pow(x1, value);
3+
x3.a = Math.pow(x3.a, value), x3.a = Math.pow(x3.a, value), x1 = Math.pow(x1, value), x3.a = Math.pow(x3.a, value), x3.a = Math.pow(x3.a, value);
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
//// [invalidVoidAssignments.ts]
22
import "@swc/helpers/_/_class_call_check";
3-
(M || (M = {})).x = 1, M = x;
4-
var E, x, M, E1 = ((E = E1 || {})[E.A = 0] = "A", E);
3+
(M || (M = {})).x = 1;
4+
var E, M = void 0, E1 = ((E = E1 || {})[E.A = 0] = "A", E);

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

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::{iter::once, mem::take};
22

33
use rustc_hash::FxHashSet;
4-
use swc_common::{pass::Either, util::take::Take, Spanned, DUMMY_SP};
4+
use swc_common::{pass::Either, util::take::Take, EqIgnoreSpan, Spanned, DUMMY_SP};
55
use swc_ecma_ast::*;
66
use swc_ecma_usage_analyzer::{
77
alias::{try_collect_infects_from, AccessKind, AliasConfig},
@@ -946,7 +946,39 @@ impl Optimizer<'_> {
946946
break;
947947
}
948948
}
949-
None => continue,
949+
None => {
950+
if let Mergable::Expr(Expr::Assign(a_exp)) = a {
951+
if let (Some(a_id), Some(b_id)) =
952+
(a_exp.left.as_ident(), b.name.as_ident())
953+
{
954+
if a_id.id.eq_ignore_span(&b_id.id)
955+
&& a_exp.op == op!("=")
956+
&& self
957+
.data
958+
.vars
959+
.get(&a_id.id.to_id())
960+
.map(|u| {
961+
!u.inline_prevented && !u.declared_as_fn_expr
962+
})
963+
.unwrap_or(false)
964+
{
965+
changed = true;
966+
report_change!("merge assign and var decl");
967+
b.init = Some(a_exp.right.take());
968+
merge_seq_cache.invalidate(a_idx);
969+
merge_seq_cache.invalidate(b_idx);
970+
971+
if let Mergable::Expr(e) = a {
972+
e.take();
973+
}
974+
975+
break;
976+
}
977+
}
978+
}
979+
980+
continue;
981+
}
950982
},
951983
Mergable::Expr(b) => {
952984
if !merge_seq_cache.is_top_retain(self, a, a_idx)
@@ -2573,6 +2605,7 @@ impl Optimizer<'_> {
25732605
in_abort: false,
25742606
};
25752607
b.visit_with(&mut v);
2608+
println!("{:#?}", v.abort);
25762609
if v.expr_usage != 1 || v.pat_usage != 0 || v.abort {
25772610
log_abort!(
25782611
"sequences: Aborting because of usage counts ({}{:?}, ref = {}, pat = {})",

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

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17551,8 +17551,7 @@
1755117551
each(sysDims, function(sysDimItemRaw) {
1755217552
if (isString(sysDimItemRaw)) coordDim = sysDimItemRaw, sysDimItem = {};
1755317553
else {
17554-
coordDim = (sysDimItem = sysDimItemRaw).name;
17555-
var coordDim, sysDimItemDimsDef, sysDimItemOtherDims, sysDimItem, ordinalMeta = sysDimItem.ordinalMeta;
17554+
var sysDimItemDimsDef, sysDimItemOtherDims, sysDimItem, coordDim = (sysDimItem = sysDimItemRaw).name, ordinalMeta = sysDimItem.ordinalMeta;
1755617555
sysDimItem.ordinalMeta = null, (sysDimItem = clone(sysDimItem)).ordinalMeta = ordinalMeta, sysDimItemDimsDef = sysDimItem.dimsDef, sysDimItemOtherDims = sysDimItem.otherDims, sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
1755717556
}
1755817557
var dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping.
@@ -26551,8 +26550,8 @@
2655126550
}
2655226551
function getEdgeShape(layoutOpt, orient, curvature, sourceLayout, targetLayout) {
2655326552
if ('radial' === layoutOpt) {
26554-
x1 = sourceLayout.rawX, y1 = sourceLayout.rawY, x2 = targetLayout.rawX, y2 = targetLayout.rawY;
26555-
var cpx1, cpy1, cpx2, cpy2, x1, x2, y1, y2, radialCoor1 = radialCoordinate(x1, y1), radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * curvature), radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * curvature), radialCoor4 = radialCoordinate(x2, y2);
26553+
x1 = sourceLayout.rawX, y1 = sourceLayout.rawY, x2 = targetLayout.rawX;
26554+
var cpx1, cpy1, cpx2, cpy2, x1, x2, y1, y2 = targetLayout.rawY, radialCoor1 = radialCoordinate(x1, y1), radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * curvature), radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * curvature), radialCoor4 = radialCoordinate(x2, y2);
2655626555
return {
2655726556
x1: radialCoor1.x || 0,
2655826557
y1: radialCoor1.y || 0,

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

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11818,9 +11818,7 @@ function(global, factory) {
1181811818
},
1181911819
// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
1182011820
getUtoTmapping: function(u, distance) {
11821-
var arcLengths = this.getLengths(), i = 0, il = arcLengths.length;
11822-
targetArcLength = distance || u * arcLengths[il - 1]; // binary search for the index with largest value smaller than target u distance
11823-
for(var targetArcLength, comparison, low = 0, high = il - 1; low <= high;)if ((comparison = arcLengths[i = Math.floor(low + (high - low) / 2)] - targetArcLength) < 0) low = i + 1;
11821+
for(var comparison, arcLengths = this.getLengths(), i = 0, il = arcLengths.length, targetArcLength = distance || u * arcLengths[il - 1], low = 0, high = il - 1; low <= high;)if ((comparison = arcLengths[i = Math.floor(low + (high - low) / 2)] - targetArcLength) < 0) low = i + 1;
1182411822
else if (comparison > 0) high = i - 1;
1182511823
else {
1182611824
high = i;
@@ -13057,8 +13055,7 @@ function(global, factory) {
1305713055
object = new Mesh(geometry = getGeometry(data.geometry), material = getMaterial(data.material));
1305813056
break;
1305913057
case 'InstancedMesh':
13060-
geometry = getGeometry(data.geometry), material = getMaterial(data.material);
13061-
var object, geometry, material, count = data.count, instanceMatrix = data.instanceMatrix;
13058+
var object, geometry = getGeometry(data.geometry), material = getMaterial(data.material), count = data.count, instanceMatrix = data.instanceMatrix;
1306213059
(object = new InstancedMesh(geometry, material, count)).instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
1306313060
break;
1306413061
case 'LOD':

crates/swc_ecma_minifier/tests/fixture/next/33265/static/chunks/d6e1aeb5-38a8d7ae57119c23/output.js

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2037,8 +2037,7 @@
20372037
* `Component` will get created by this process.
20382038
*/ _proto.addChild = function(child, options, index) {
20392039
if (void 0 === options && (options = {}), void 0 === index && (index = this.children_.length), "string" == typeof child) {
2040-
componentName = toTitleCase$1(child);
2041-
var component, componentName, componentClassName = options.componentClass || componentName; // Set name through options
2040+
var component, componentName = toTitleCase$1(child), componentClassName = options.componentClass || componentName; // Set name through options
20422041
options.name = componentName; // Create a new object & element for this controls set
20432042
// If there's no .player_, this is a player
20442043
var ComponentClass = Component.getComponent(componentClassName);
@@ -3792,8 +3791,8 @@
37923791
*
37933792
* @abstract
37943793
*/ function Track(options) {
3795-
void 0 === options && (options = {}), _this = _EventTarget.call(this) || this;
3796-
var _this, trackProps = {
3794+
void 0 === options && (options = {});
3795+
var _this = _EventTarget.call(this) || this, trackProps = {
37973796
id: options.id || "vjs_track_" + _guid++,
37983797
kind: options.kind || "",
37993798
language: options.language || ""
@@ -4220,8 +4219,8 @@
42204219
* @param {boolean} [options.default]
42214220
* If this track should default to on or off.
42224221
*/ function HTMLTrackElement(options) {
4223-
void 0 === options && (options = {}), _this = _EventTarget.call(this) || this;
4224-
var _this, readyState, track = new TextTrack(options);
4222+
void 0 === options && (options = {});
4223+
var readyState, _this = _EventTarget.call(this) || this, track = new TextTrack(options);
42254224
return _this.kind = track.kind, _this.src = track.src, _this.srclang = track.language, _this.label = track.label, _this.default = track.default, Object.defineProperties((0, _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_17__ /* ["default"] */ .Z)(_this), {
42264225
/**
42274226
* @memberof HTMLTrackElement
@@ -5593,8 +5592,7 @@
55935592
* @param {Component~ReadyCallback} [ready]
55945593
* The function to call when `TextTrackDisplay` is ready.
55955594
*/ function TextTrackDisplay(player, options, ready) {
5596-
_this = _Component.call(this, player, options, ready) || this;
5597-
var _this, updateDisplayHandler = function(e) {
5595+
var _this = _Component.call(this, player, options, ready) || this, updateDisplayHandler = function(e) {
55985596
return _this.updateDisplay(e);
55995597
};
56005598
return player.on("loadstart", function(e) {
@@ -6259,8 +6257,7 @@
62596257
* @param {Object} [options]
62606258
* The key/value store of player options.
62616259
*/ function DurationDisplay(player, options) {
6262-
_this = _TimeDisplay.call(this, player, options) || this;
6263-
var _this, updateContent = function(e) {
6260+
var _this = _TimeDisplay.call(this, player, options) || this, updateContent = function(e) {
62646261
return _this.updateContent(e);
62656262
}; // we do not want to/need to throttle duration changes,
62666263
return(// as they should always display the changed duration as
@@ -8991,8 +8988,7 @@
89918988
* @param {Component~ReadyCallback} [ready]
89928989
* The function to call when this component is ready.
89938990
*/ function DescriptionsButton(player, options, ready) {
8994-
_this = _TextTrackButton.call(this, player, options, ready) || this;
8995-
var _this, tracks = player.textTracks(), changeHandler = bind((0, _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_17__ /* ["default"] */ .Z)(_this), _this.handleTracksChange);
8991+
var _this = _TextTrackButton.call(this, player, options, ready) || this, tracks = player.textTracks(), changeHandler = bind((0, _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_17__ /* ["default"] */ .Z)(_this), _this.handleTracksChange);
89968992
return tracks.addEventListener("change", changeHandler), _this.on("dispose", function() {
89978993
tracks.removeEventListener("change", changeHandler);
89988994
}), _this;
@@ -10612,8 +10608,7 @@
1061210608
* @param {Component~ReadyCallback} ready
1061310609
* Callback function to call when the `HTML5` Tech is ready.
1061410610
*/ function Html5(options, ready) {
10615-
_this = _Tech.call(this, options, ready) || this;
10616-
var _this, source = options.source, crossoriginTracks = !1;
10611+
var _this = _Tech.call(this, options, ready) || this, source = options.source, crossoriginTracks = !1;
1061710612
if (source && (_this.el_.currentSrc !== source.src || options.tag && 3 === options.tag.initNetworkState_) ? _this.setSource(source) : _this.handleLateInit_(_this.el_), options.enableSourceset && _this.setupSourcesetHandling_(), _this.isScrubbing_ = !1, _this.el_.hasChildNodes()) {
1061810613
for(var nodes = _this.el_.childNodes, nodesLength = nodes.length, removeNodes = []; nodesLength--;){
1061910614
var node = nodes[nodesLength];
@@ -25349,8 +25344,7 @@
2534925344
return log("not " + sharedLogLine + " as no switching criteria met"), !1;
2535025345
}, MasterPlaylistController = /*#__PURE__*/ function(_videojs$EventTarget) {
2535125346
function MasterPlaylistController(options) {
25352-
_this = _videojs$EventTarget.call(this) || this;
25353-
var _this, src = options.src, handleManifestRedirects = options.handleManifestRedirects, withCredentials = options.withCredentials, tech = options.tech, bandwidth = options.bandwidth, externVhs = options.externVhs, useCueTags = options.useCueTags, blacklistDuration = options.blacklistDuration, enableLowInitialPlaylist = options.enableLowInitialPlaylist, sourceType = options.sourceType, cacheEncryptionKeys = options.cacheEncryptionKeys, experimentalBufferBasedABR = options.experimentalBufferBasedABR, experimentalLeastPixelDiffSelector = options.experimentalLeastPixelDiffSelector, captionServices = options.captionServices;
25347+
var _this = _videojs$EventTarget.call(this) || this, src = options.src, handleManifestRedirects = options.handleManifestRedirects, withCredentials = options.withCredentials, tech = options.tech, bandwidth = options.bandwidth, externVhs = options.externVhs, useCueTags = options.useCueTags, blacklistDuration = options.blacklistDuration, enableLowInitialPlaylist = options.enableLowInitialPlaylist, sourceType = options.sourceType, cacheEncryptionKeys = options.cacheEncryptionKeys, experimentalBufferBasedABR = options.experimentalBufferBasedABR, experimentalLeastPixelDiffSelector = options.experimentalLeastPixelDiffSelector, captionServices = options.captionServices;
2535425348
if (!src) throw Error("A non-empty playlist URL or JSON manifest string is required");
2535525349
var maxPlaylistRetries = options.maxPlaylistRetries;
2535625350
null == maxPlaylistRetries && (maxPlaylistRetries = 1 / 0), Vhs$1 = externVhs, _this.experimentalBufferBasedABR = !!experimentalBufferBasedABR, _this.experimentalLeastPixelDiffSelector = !!experimentalLeastPixelDiffSelector, _this.withCredentials = withCredentials, _this.tech_ = tech, _this.vhs_ = tech.vhs, _this.sourceType_ = sourceType, _this.useCueTags_ = useCueTags, _this.blacklistDuration = blacklistDuration, _this.maxPlaylistRetries = maxPlaylistRetries, _this.enableLowInitialPlaylist = enableLowInitialPlaylist, _this.useCueTags_ && (_this.cueTagsTrack_ = _this.tech_.addTextTrack("metadata", "ad-cues"), _this.cueTagsTrack_.inBandMetadataTrackDispatchType = ""), _this.requestOptions_ = {

crates/swc_ecma_minifier/tests/fixture/next/33265/static/chunks/pages/index-cb36c1bf7f830e3c/output.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -948,9 +948,8 @@
948948
function loadFunc() {
949949
if (!aborted) {
950950
clearTimeout(timeoutTimer);
951-
var status, response = failureResponse, err = null;
952-
return 0 !== (//IE8 CORS GET successful response doesn't have a status field, but body is fine
953-
status = options.useXDR && void 0 === xhr.status ? 200 : 1223 === xhr.status ? 204 : xhr.status) ? (response = {
951+
var status = options.useXDR && void 0 === xhr.status ? 200 : 1223 === xhr.status ? 204 : xhr.status, response = failureResponse, err = null;
952+
return 0 !== status ? (response = {
954953
body: function() {
955954
// Chrome with requestType=blob throws errors arround when even testing access to responseText
956955
var body = void 0;
@@ -5791,7 +5790,7 @@
57915790
if ("INITIAL" === self1.state) {
57925791
// We can't start parsing until we have the first line.
57935792
if (!/\r\n|\n/.test(self1.buffer)) return this;
5794-
var input, line, m = (line = collectNextLine()).match(/^WEBVTT([ \t].*)?$/);
5793+
var input, line = collectNextLine(), m = line.match(/^WEBVTT([ \t].*)?$/);
57955794
if (!m || !m[0]) throw new ParsingError(ParsingError.Errors.BadSignature);
57965795
self1.state = "HEADER";
57975796
}

crates/swc_ecma_minifier/tests/fixture/next/react-ace/chunks/8a28b14e.d8fbda268ed281a1/output.js

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5299,7 +5299,7 @@
52995299
}, this), folds;
53005300
range = location;
53015301
}
5302-
for(var range, folds, outermostFolds = folds = this.getFoldsInRangeList(range); 1 == folds.length && 0 > Range.comparePoints(folds[0].start, range.start) && Range.comparePoints(folds[0].end, range.end) > 0;)this.expandFolds(folds), folds = this.getFoldsInRangeList(range);
5302+
for(var range, folds = this.getFoldsInRangeList(range), outermostFolds = folds; 1 == folds.length && 0 > Range.comparePoints(folds[0].start, range.start) && Range.comparePoints(folds[0].end, range.end) > 0;)this.expandFolds(folds), folds = this.getFoldsInRangeList(range);
53035303
if (!1 != expandInner ? this.removeFolds(folds) : this.expandFolds(folds), outermostFolds.length) return outermostFolds;
53045304
}, this.isRowFolded = function(docRow, startFoldRow) {
53055305
return !!this.getFoldLine(docRow, startFoldRow);
@@ -10798,11 +10798,10 @@ margin: 0 10px;\
1079810798
if (deltaY < 0 && this.session.getScrollTop() >= 1 - this.scrollMargin.top || deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight - this.layerConfig.maxHeight < -1 + this.scrollMargin.bottom || deltaX < 0 && this.session.getScrollLeft() >= 1 - this.scrollMargin.left || deltaX > 0 && this.session.getScrollLeft() + this.$size.scrollerWidth - this.layerConfig.width < -1 + this.scrollMargin.right) return !0;
1079910799
}, this.pixelToScreenCoordinates = function(x, y) {
1080010800
if (this.$hasCssTransforms) {
10801-
canvasPos = {
10801+
var canvasPos = {
1080210802
top: 0,
1080310803
left: 0
10804-
};
10805-
var canvasPos, p = this.$fontMetrics.transformCoordinates([
10804+
}, p = this.$fontMetrics.transformCoordinates([
1080610805
x,
1080710806
y
1080810807
]);
@@ -10817,11 +10816,10 @@ margin: 0 10px;\
1081710816
};
1081810817
}, this.screenToTextCoordinates = function(x, y) {
1081910818
if (this.$hasCssTransforms) {
10820-
canvasPos = {
10819+
var canvasPos = {
1082110820
top: 0,
1082210821
left: 0
10823-
};
10824-
var canvasPos, p = this.$fontMetrics.transformCoordinates([
10822+
}, p = this.$fontMetrics.transformCoordinates([
1082510823
x,
1082610824
y
1082710825
]);

0 commit comments

Comments
 (0)