Skip to content

Commit 898f170

Browse files
authored
feat(es/minifier): Remove useless to number (#10308)
1 parent 7f76fa3 commit 898f170

File tree

22 files changed

+143
-89
lines changed

22 files changed

+143
-89
lines changed

.changeset/dull-steaks-happen.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
swc_core: minor
3+
swc_ecma_minifier: minor
4+
---
5+
6+
feat(es/minifier): Remove useless to number

crates/swc/tests/vercel/full/d3-time-format/1/output/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -464,5 +464,5 @@ function nF(n) {
464464
return +n;
465465
}
466466
function nZ(n) {
467-
return Math.floor(+n / 1000);
467+
return Math.floor(n / 1000);
468468
}

crates/swc_ecma_minifier/src/compress/pure/mod.rs

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,23 @@ impl VisitMut for Pure<'_> {
209209

210210
self.compress_bin_assignment_to_left(e);
211211
self.compress_bin_assignment_to_right(e);
212+
213+
if matches!(
214+
e.op,
215+
op!("-=")
216+
| op!("*=")
217+
| op!("/=")
218+
| op!("%=")
219+
| op!("**=")
220+
| op!("&=")
221+
| op!("|=")
222+
| op!("^=")
223+
| op!("<<=")
224+
| op!(">>=")
225+
| op!(">>>=")
226+
) {
227+
self.optimize_expr_in_num_ctx(&mut e.right);
228+
}
212229
}
213230

214231
fn visit_mut_bin_expr(&mut self, e: &mut BinExpr) {
@@ -220,6 +237,24 @@ impl VisitMut for Pure<'_> {
220237
if e.op == op!(bin, "+") {
221238
self.concat_tpl(&mut e.left, &mut e.right);
222239
}
240+
241+
if matches!(
242+
e.op,
243+
op!(bin, "-")
244+
| op!("*")
245+
| op!("/")
246+
| op!("%")
247+
| op!("**")
248+
| op!("&")
249+
| op!("|")
250+
| op!("^")
251+
| op!("<<")
252+
| op!(">>")
253+
| op!(">>>")
254+
) {
255+
self.optimize_expr_in_num_ctx(&mut e.left);
256+
self.optimize_expr_in_num_ctx(&mut e.right);
257+
}
223258
}
224259

225260
fn visit_mut_block_stmt_or_expr(&mut self, body: &mut BlockStmtOrExpr) {
@@ -1256,7 +1291,7 @@ impl VisitMut for Pure<'_> {
12561291
self.optimize_expr_in_bool_ctx(&mut e.arg, false);
12571292
}
12581293

1259-
op!(unary, "+") | op!(unary, "-") => {
1294+
op!(unary, "+") | op!(unary, "-") | op!("~") => {
12601295
self.optimize_expr_in_num_ctx(&mut e.arg);
12611296
}
12621297
_ => {}

crates/swc_ecma_minifier/src/compress/pure/numbers.rs

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,37 @@ use super::Pure;
66

77
impl Pure<'_> {
88
pub(super) fn optimize_expr_in_num_ctx(&mut self, e: &mut Expr) {
9-
if let Expr::Lit(Lit::Str(Str { span, value, .. })) = e {
10-
let value = if value.is_empty() {
11-
0f64
12-
} else {
13-
match num_from_str(value).into_result() {
14-
Ok(f) if f.is_finite() => f,
15-
_ => return,
16-
}
17-
};
18-
19-
self.changed = true;
20-
report_change!("numbers: Converting a string literal to {:?}", value);
21-
*e = Lit::Num(Number {
22-
span: *span,
23-
value,
24-
raw: None,
25-
})
26-
.into();
9+
match e {
10+
Expr::Lit(Lit::Str(Str { span, value, .. })) => {
11+
let value = if value.is_empty() {
12+
0f64
13+
} else {
14+
match num_from_str(value).into_result() {
15+
Ok(f) if f.is_finite() => f,
16+
_ => return,
17+
}
18+
};
19+
20+
self.changed = true;
21+
report_change!("numbers: Converting a string literal to {:?}", value);
22+
*e = Lit::Num(Number {
23+
span: *span,
24+
value,
25+
raw: None,
26+
})
27+
.into();
28+
}
29+
Expr::Unary(UnaryExpr {
30+
arg,
31+
op: op!(unary, "+"),
32+
..
33+
}) => {
34+
self.changed = true;
35+
report_change!("numbers: remove useless to number");
36+
let new_expr = *arg.take();
37+
*e = new_expr
38+
}
39+
_ => (),
2740
}
2841
}
2942

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ function(global, factory) {
268268
if ((p *= 1) <= 0 || n < 2) return +valueof(values[0], 0, values);
269269
if (p >= 1) return +valueof(values[n - 1], n - 1, values);
270270
var n, i = (n - 1) * p, i0 = Math.floor(i), value0 = +valueof(values[i0], i0, values);
271-
return value0 + (+valueof(values[i0 + 1], i0 + 1, values) - value0) * (i - i0);
271+
return value0 + (valueof(values[i0 + 1], i0 + 1, values) - value0) * (i - i0);
272272
}
273273
}
274274
function maxIndex(values, valueof) {
@@ -4285,7 +4285,7 @@ function(global, factory) {
42854285
var xm = (x1 + x2) / 2, ym = (y1 + y2) / 2;
42864286
quads.push(new Quad(node[3], xm, ym, x2, y2), new Quad(node[2], x1, ym, xm, y2), new Quad(node[1], xm, y1, x2, ym), new Quad(node[0], x1, y1, xm, ym)), (i = (y >= ym) << 1 | x >= xm) && (q = quads[quads.length - 1], quads[quads.length - 1] = quads[quads.length - 1 - i], quads[quads.length - 1 - i] = q);
42874287
} else {
4288-
var dx = x - +this._x.call(null, node.data), dy = y - +this._y.call(null, node.data), d2 = dx * dx + dy * dy;
4288+
var dx = x - this._x.call(null, node.data), dy = y - this._y.call(null, node.data), d2 = dx * dx + dy * dy;
42894289
if (d2 < radius) {
42904290
var d = Math.sqrt(radius = d2);
42914291
x0 = x - d, y0 = y - d, x3 = x + d, y3 = y + d, data = node.data;
@@ -7719,7 +7719,7 @@ function(global, factory) {
77197719
return +d;
77207720
}
77217721
function formatUnixTimestampSeconds(d) {
7722-
return Math.floor(+d / 1000);
7722+
return Math.floor(d / 1000);
77237723
}
77247724
function defaultLocale$1(definition) {
77257725
return exports1.timeFormat = (locale$1 = formatLocale$1(definition)).format, exports1.timeParse = locale$1.parse, exports1.utcFormat = locale$1.utcFormat, exports1.utcParse = locale$1.utcParse, locale$1;
@@ -9581,7 +9581,7 @@ function(global, factory) {
95819581
}, exports1.easeCubicInOut = cubicInOut, exports1.easeCubicOut = function(t) {
95829582
return --t * t * t + 1;
95839583
}, exports1.easeElastic = elasticOut, exports1.easeElasticIn = elasticIn, exports1.easeElasticInOut = elasticInOut, exports1.easeElasticOut = elasticOut, exports1.easeExp = expInOut, exports1.easeExpIn = function(t) {
9584-
return tpmt(1 - +t);
9584+
return tpmt(1 - t);
95859585
}, exports1.easeExpInOut = expInOut, exports1.easeExpOut = function(t) {
95869586
return 1 - tpmt(t);
95879587
}, exports1.easeLinear = (t)=>+t, exports1.easePoly = polyInOut, exports1.easePolyIn = polyIn, exports1.easePolyInOut = polyInOut, exports1.easePolyOut = polyOut, exports1.easeQuad = quadInOut, exports1.easeQuadIn = function(t) {

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

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3654,7 +3654,7 @@
36543654
markTouch(event = normalizeEvent(this.dom, event)), this.handler.processGesture(event, 'change'), localDOMHandlers.mousemove.call(this, event);
36553655
},
36563656
touchend: function(event) {
3657-
markTouch(event = normalizeEvent(this.dom, event)), this.handler.processGesture(event, 'end'), localDOMHandlers.mouseup.call(this, event), +new Date() - +this.__lastTouchMoment < 300 && localDOMHandlers.click.call(this, event);
3657+
markTouch(event = normalizeEvent(this.dom, event)), this.handler.processGesture(event, 'end'), localDOMHandlers.mouseup.call(this, event), new Date() - this.__lastTouchMoment < 300 && localDOMHandlers.click.call(this, event);
36583658
},
36593659
pointerdown: function(event) {
36603660
localDOMHandlers.mousedown.call(this, event);
@@ -3727,7 +3727,7 @@
37273727
}, HandlerDomProxy.prototype.setCursor = function(cursorStyle) {
37283728
this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
37293729
}, HandlerDomProxy.prototype.__togglePointerCapture = function(isPointerCapturing) {
3730-
if (this.__mayPointerCapture = null, globalEventSupported && +this.__pointerCapturing ^ +isPointerCapturing) {
3730+
if (this.__mayPointerCapture = null, globalEventSupported && this.__pointerCapturing ^ isPointerCapturing) {
37313731
this.__pointerCapturing = isPointerCapturing;
37323732
var globalHandlerScope = this._globalHandlerScope;
37333733
isPointerCapturing ? function(instance, scope) {
@@ -4099,9 +4099,9 @@
40994099
// Use local time when no timezone offset specifed.
41004100
if (!match[8]) // match[n] can only be string or undefined.
41014101
// But take care of '12' + 1 => '121'.
4102-
return new Date(+match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, +match[7] || 0);
4102+
return new Date(+match[1], (match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, +match[7] || 0);
41034103
var hour = +match[4] || 0;
4104-
return 'Z' !== match[8].toUpperCase() && (hour -= +match[8].slice(0, 3)), new Date(Date.UTC(+match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, +match[7] || 0));
4104+
return 'Z' !== match[8].toUpperCase() && (hour -= match[8].slice(0, 3)), new Date(Date.UTC(+match[1], (match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, +match[7] || 0));
41054105
}
41064106
return new Date(null == value ? NaN : Math.round(value));
41074107
}
@@ -13570,7 +13570,7 @@
1357013570
el.beforeBrush && el.beforeBrush(), el.innerBeforeBrush();
1357113571
var prevEl = scope.prevEl;
1357213572
prevEl || (forceSetStyle = forceSetTransform = !0);
13573-
var canBatchPath = el instanceof Path && el.autoBatch && (hasFill = styleHasFill(style = el.style), hasStroke = styleHasStroke(style), !(style.lineDash || !(+hasFill ^ +hasStroke) || hasFill && 'string' != typeof style.fill || hasStroke && 'string' != typeof style.stroke || style.strokePercent < 1 || style.strokeOpacity < 1 || style.fillOpacity < 1));
13573+
var canBatchPath = el instanceof Path && el.autoBatch && (hasFill = styleHasFill(style = el.style), hasStroke = styleHasStroke(style), !(style.lineDash || !(hasFill ^ hasStroke) || hasFill && 'string' != typeof style.fill || hasStroke && 'string' != typeof style.stroke || style.strokePercent < 1 || style.strokeOpacity < 1 || style.fillOpacity < 1));
1357413574
!forceSetTransform && (m1 = prevEl.transform, m && m1 ? m[0] === m1[0] && m[1] === m1[1] && m[2] === m1[2] && m[3] === m1[3] && m[4] === m1[4] && m[5] === m1[5] : +(!m && !m1)) ? canBatchPath || flushPathDrawn(ctx, scope) : (flushPathDrawn(ctx, scope), setContextTransform(ctx, el));
1357513575
var style1 = getStyle(el, scope.inHover);
1357613576
el instanceof Path ? (1 !== scope.lastDrawType && (forceSetStyle = !0, scope.lastDrawType = 1), bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope), canBatchPath && (scope.batchFill || scope.batchStroke) || ctx.beginPath(), function(ctx, el, style, inBatch) {
@@ -15145,7 +15145,7 @@
1514515145
// frame is executed immedietely after task reset.
1514615146
// this._coordSysMgr.update(ecModel, api);
1514715147
// console.log('--- ec frame visual ---', remainTime);
15148-
scheduler.performVisualTasks(ecModel), renderSeries(this, this._model, api, 'remain'), remainTime -= +new Date() - startTime;
15148+
scheduler.performVisualTasks(ecModel), renderSeries(this, this._model, api, 'remain'), remainTime -= new Date() - startTime;
1514915149
}while (remainTime > 0 && scheduler.unfinished) // Call flush explicitly for trigger finished event.
1515015150
scheduler.unfinished || this._zr.flush(); // Else, zr flushing be ensue within the same frame,
1515115151
// because zr flushing is after onframe event.
@@ -15970,7 +15970,7 @@
1597015970
function disposedWarning(id) {
1597115971
console.warn('Instance ' + id + ' has been disposed');
1597215972
}
15973-
var actions = {}, eventActionMap = {}, dataProcessorFuncs = [], optionPreprocessorFuncs = [], postInitFuncs = [], postUpdateFuncs = [], visualFuncs = [], themeStorage = {}, loadingEffects = {}, instances$1 = {}, connectedGroups = {}, idBase = +new Date() - 0, groupIdBase = +new Date() - 0, DOM_ATTRIBUTE_KEY = '_echarts_instance_';
15973+
var actions = {}, eventActionMap = {}, dataProcessorFuncs = [], optionPreprocessorFuncs = [], postInitFuncs = [], postUpdateFuncs = [], visualFuncs = [], themeStorage = {}, loadingEffects = {}, instances$1 = {}, connectedGroups = {}, idBase = new Date() - 0, groupIdBase = new Date() - 0, DOM_ATTRIBUTE_KEY = '_echarts_instance_';
1597415974
/**
1597515975
* @deprecated
1597615976
*/ function disConnect(groupId) {
@@ -23335,7 +23335,7 @@
2333523335
layout.position = [
2333623336
'y' === axisDim ? posBound[idx[axisPosition]] : rectBound[0],
2333723337
'x' === axisDim ? posBound[idx[axisPosition]] : rectBound[3]
23338-
], layout.rotation = Math.PI / 2 * +('x' !== axisDim), layout.labelDirection = layout.tickDirection = layout.nameDirection = ({
23338+
], layout.rotation = Math.PI / 2 * ('x' !== axisDim), layout.labelDirection = layout.tickDirection = layout.nameDirection = ({
2333923339
top: -1,
2334023340
bottom: 1,
2334123341
left: -1,
@@ -29080,7 +29080,7 @@
2908029080
];
2908129081
symbolOffsetArr[0] = parsePercent$1(symbolOffsetArr[0], symbolSizeArr[0]), symbolOffsetArr[1] = parsePercent$1(retrieve2(symbolOffsetArr[1], symbolOffsetArr[0]), symbolSizeArr[1]);
2908229082
var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2 + symbolOffsetArr[0], -symbolSizeArr[1] / 2 + symbolOffsetArr[1], symbolSizeArr[0], symbolSizeArr[1], null, symbolKeepAspect);
29083-
return symbolPath.__specifiedRotation = null == symbolRotate || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0, symbolPath.name = name, symbolPath;
29083+
return symbolPath.__specifiedRotation = null == symbolRotate || isNaN(symbolRotate) ? void 0 : symbolRotate * Math.PI / 180 || 0, symbolPath.name = name, symbolPath;
2908429084
}
2908529085
}
2908629086
function setLinePoints(targetShape, points) {
@@ -32503,7 +32503,7 @@
3250332503
}, !0));
3250432504
});
3250532505
}), each(edges, function(edge) {
32506-
var edgeDy = +edge.getValue() * minKy;
32506+
var edgeDy = edge.getValue() * minKy;
3250732507
edge.setLayout({
3250832508
dy: edgeDy
3250932509
}, !0);
@@ -34347,7 +34347,7 @@
3434734347
],
3434834348
isHorizontal: isHorizontal,
3434934349
valueDim: LAYOUT_ATTRS[+isHorizontal],
34350-
categoryDim: LAYOUT_ATTRS[1 - +isHorizontal]
34350+
categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
3435134351
};
3435234352
return data.diff(oldData).add(function(dataIndex) {
3435334353
if (data.hasValue(dataIndex)) {
@@ -34393,7 +34393,7 @@
3439334393
z2: itemModel.getShallow('z', !0) || 0
3439434394
};
3439534395
(function(itemModel, symbolRepeat, layout, opt, outputSymbolMeta) {
34396-
var boundingLength, valueDim = opt.valueDim, symbolBoundingData = itemModel.get('symbolBoundingData'), valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis()), zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0)), pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
34396+
var boundingLength, valueDim = opt.valueDim, symbolBoundingData = itemModel.get('symbolBoundingData'), valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis()), zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0)), pxSignIdx = 1 - (layout[valueDim.wh] <= 0);
3439734397
if (isArray(symbolBoundingData)) {
3439834398
var symbolBoundingExtent = [
3439934399
convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
@@ -39339,7 +39339,7 @@
3933939339
var firstDayPoints = this._firstDayPoints[i];
3934039340
tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
3934139341
}
39342-
var formatter = monthLabel.get('formatter'), name_1 = nameMap[+firstDay.m - 1], params = {
39342+
var formatter = monthLabel.get('formatter'), name_1 = nameMap[firstDay.m - 1], params = {
3934339343
yyyy: firstDay.y,
3934439344
yy: (firstDay.y + '').slice(2),
3934539345
MM: firstDay.m,
@@ -46007,7 +46007,7 @@
4600746007
if (this._brushing = !1, brushRect) {
4600846008
brushRect.attr('ignore', !0);
4600946009
var brushShape = brushRect.shape;
46010-
if (!(+new Date() - this._brushStartTime < 200 && 5 > Math.abs(brushShape.width))) {
46010+
if (!(new Date() - this._brushStartTime < 200 && 5 > Math.abs(brushShape.width))) {
4601146011
var viewExtend = this._getViewExtent(), percentExtent = [
4601246012
0,
4601346013
100

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1420,7 +1420,7 @@
14201420
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
14211421
*/ function(key) {
14221422
var result = this.has(key) && delete this.__data__[key];
1423-
return this.size -= +!!result, result;
1423+
return this.size -= !!result, result;
14241424
}, Hash.prototype.get = /**
14251425
* Gets the hash value for `key`.
14261426
*
@@ -1538,7 +1538,7 @@
15381538
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
15391539
*/ function(key) {
15401540
var result = getMapData(this, key).delete(key);
1541-
return this.size -= +!!result, result;
1541+
return this.size -= !!result, result;
15421542
}, MapCache.prototype.get = /**
15431543
* Gets the map value for `key`.
15441544
*
@@ -3130,7 +3130,7 @@
31303130
// Shift with exponential notation to avoid floating-point issues.
31313131
// See [MDN](https://mdn.io/round#Examples) for more details.
31323132
var pair = (toString(number) + 'e').split('e');
3133-
return +((pair = (toString(func(pair[0] + 'e' + (+pair[1] + precision))) + 'e').split('e'))[0] + 'e' + (+pair[1] - precision));
3133+
return +((pair = (toString(func(pair[0] + 'e' + (+pair[1] + precision))) + 'e').split('e'))[0] + 'e' + (pair[1] - precision));
31343134
}
31353135
return func(number);
31363136
};

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1106,7 +1106,7 @@
11061106
}
11071107
function positiveMomentsDifference(base, other) {
11081108
var res = {};
1109-
return res.months = other.month() - base.month() + (other.year() - base.year()) * 12, base.clone().add(res.months, 'M').isAfter(other) && --res.months, res.milliseconds = +other - +base.clone().add(res.months, 'M'), res;
1109+
return res.months = other.month() - base.month() + (other.year() - base.year()) * 12, base.clone().add(res.months, 'M').isAfter(other) && --res.months, res.milliseconds = other - base.clone().add(res.months, 'M'), res;
11101110
}
11111111
// TODO: remove 'name' arg after deprecation is removed
11121112
function createAdder(direction, name) {

0 commit comments

Comments
 (0)