Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(minifier): minify String::concat into template literal #8443

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
212 changes: 164 additions & 48 deletions crates/oxc_minifier/src/peephole/replace_known_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::borrow::Cow;

use cow_utils::CowUtils;

use oxc_allocator::IntoIn;
use oxc_ast::ast::*;
use oxc_ecmascript::{
constant_evaluation::ConstantEvaluation, StringCharAt, StringCharCodeAt, StringIndexOf,
Expand Down Expand Up @@ -50,7 +51,7 @@ impl<'a> PeepholeOptimizations {
"indexOf" | "lastIndexOf" => Self::try_fold_string_index_of(ce, name, object, ctx),
"charAt" => Self::try_fold_string_char_at(ce, object, ctx),
"charCodeAt" => Self::try_fold_string_char_code_at(ce, object, ctx),
"concat" => Self::try_fold_concat(ce, ctx),
"concat" => self.try_fold_concat(ce, ctx),
"replace" | "replaceAll" => Self::try_fold_string_replace(ce, name, object, ctx),
"fromCharCode" => Self::try_fold_string_from_char_code(ce, object, ctx),
"toString" => Self::try_fold_to_string(ce, object, ctx),
Expand Down Expand Up @@ -410,7 +411,12 @@ impl<'a> PeepholeOptimizations {
}

/// `[].concat(1, 2)` -> `[1, 2]`
fn try_fold_concat(ce: &mut CallExpression<'a>, ctx: Ctx<'a, '_>) -> Option<Expression<'a>> {
/// `"".concat(a, "b")` -> "`${a}b`"
fn try_fold_concat(
&self,
ce: &mut CallExpression<'a>,
ctx: Ctx<'a, '_>,
) -> Option<Expression<'a>> {
// let concat chaining reduction handle it first
if let Ancestor::StaticMemberExpressionObject(parent_member) = ctx.parent() {
if parent_member.property().name.as_str() == "concat" {
Expand All @@ -419,52 +425,138 @@ impl<'a> PeepholeOptimizations {
}

let Expression::StaticMemberExpression(member) = &mut ce.callee else { unreachable!() };
let Expression::ArrayExpression(array_expr) = &mut member.object else { return None };

let can_merge_until = ce
.arguments
.iter()
.enumerate()
.take_while(|(_, argument)| match argument {
Argument::SpreadElement(_) => false,
match_expression!(Argument) => {
let argument = argument.to_expression();
if argument.is_literal() {
true
} else {
matches!(argument, Expression::ArrayExpression(_))
match &mut member.object {
Expression::ArrayExpression(array_expr) => {
let can_merge_until = ce
.arguments
.iter()
.enumerate()
.take_while(|(_, argument)| match argument {
Argument::SpreadElement(_) => false,
match_expression!(Argument) => {
let argument = argument.to_expression();
if argument.is_literal() {
true
} else {
matches!(argument, Expression::ArrayExpression(_))
}
}
})
.map(|(i, _)| i)
.last();

if let Some(can_merge_until) = can_merge_until {
for argument in ce.arguments.drain(..=can_merge_until) {
let argument = argument.into_expression();
if argument.is_literal() {
array_expr.elements.push(ArrayExpressionElement::from(argument));
} else {
let Expression::ArrayExpression(mut argument_array) = argument else {
unreachable!()
};
array_expr.elements.append(&mut argument_array.elements);
}
}
}
})
.map(|(i, _)| i)
.last();

if let Some(can_merge_until) = can_merge_until {
for argument in ce.arguments.drain(..=can_merge_until) {
let argument = argument.into_expression();
if argument.is_literal() {
array_expr.elements.push(ArrayExpressionElement::from(argument));

if ce.arguments.is_empty() {
Some(ctx.ast.move_expression(&mut member.object))
} else if can_merge_until.is_some() {
Some(ctx.ast.expression_call(
ce.span,
ctx.ast.move_expression(&mut ce.callee),
Option::<TSTypeParameterInstantiation>::None,
ctx.ast.move_vec(&mut ce.arguments),
false,
))
} else {
let Expression::ArrayExpression(mut argument_array) = argument else {
unreachable!()
};
array_expr.elements.append(&mut argument_array.elements);
None
}
}
}
Expression::StringLiteral(base_str) => {
if self.target < ESTarget::ES2015
|| ce.arguments.is_empty()
|| !ce.arguments.iter().all(Argument::is_expression)
{
return None;
}

if ce.arguments.is_empty() {
Some(ctx.ast.move_expression(&mut member.object))
} else if can_merge_until.is_some() {
Some(ctx.ast.expression_call(
ce.span,
ctx.ast.move_expression(&mut ce.callee),
Option::<TSTypeParameterInstantiation>::None,
ctx.ast.move_vec(&mut ce.arguments),
false,
))
} else {
None
let expression_count = ce
.arguments
.iter()
.filter(|arg| !matches!(arg, Argument::StringLiteral(_)))
.count();
let string_count = ce.arguments.len() - expression_count;

// whether it is shorter to use `String::concat`
if ".concat()".len() + ce.arguments.len() + "''".len() * string_count
< "${}".len() * expression_count
{
return None;
}

let mut quasi_strs: Vec<Cow<'a, str>> =
vec![Cow::Borrowed(base_str.value.as_str())];
let mut expressions = ctx.ast.vec();
let mut pushed_quasi = true;
for argument in ce.arguments.drain(..) {
if let Argument::StringLiteral(str_lit) = argument {
if pushed_quasi {
let last_quasi = quasi_strs
.last_mut()
.expect("last element should exist because pushed_quasi is true");
last_quasi.to_mut().push_str(&str_lit.value);
} else {
quasi_strs.push(Cow::Borrowed(str_lit.value.as_str()));
}
pushed_quasi = true;
} else {
if !pushed_quasi {
// need a pair
quasi_strs.push(Cow::Borrowed(""));
}
// checked that all the arguments are expression above
expressions.push(argument.into_expression());
pushed_quasi = false;
}
}
if !pushed_quasi {
quasi_strs.push(Cow::Borrowed(""));
}

if expressions.is_empty() {
debug_assert_eq!(quasi_strs.len(), 1);
return Some(ctx.ast.expression_string_literal(
ce.span,
quasi_strs.pop().unwrap(),
None,
));
}

let mut quasis = ctx.ast.vec_from_iter(quasi_strs.into_iter().map(|s| {
let cooked = s.clone().into_in(ctx.ast.allocator);
ctx.ast.template_element(
SPAN,
false,
TemplateElementValue {
raw: s
.cow_replace("\\", "\\\\")
.cow_replace("`", "\\`")
.cow_replace("${", "\\${")
.cow_replace("\r\n", "\\r\n")
.into_in(ctx.ast.allocator),
cooked: Some(cooked),
},
)
}));
if let Some(last_quasi) = quasis.last_mut() {
last_quasi.tail = true;
}

debug_assert_eq!(quasis.len(), expressions.len() + 1);
Some(ctx.ast.expression_template_literal(ce.span, quasis, expressions))
}
_ => None,
}
}

Expand Down Expand Up @@ -1309,13 +1401,13 @@ mod test {
test("var x; [1].concat(x.a).concat(x)", "var x; [1].concat(x.a, x)"); // x.a might have a getter that updates x, but that side effect is preserved correctly

// string
test("'1'.concat(1).concat(2,['abc']).concat('abc')", "'1'.concat(1,2,['abc'],'abc')");
test("''.concat(['abc']).concat(1).concat([2,3])", "''.concat(['abc'],1,[2,3])");
test_same("''.concat(1)");
test("'1'.concat(1).concat(2,['abc']).concat('abc')", "`1${1}${2}${['abc']}abc`");
test("''.concat(['abc']).concat(1).concat([2,3])", "`${['abc']}${1}${[2, 3]}`");
test("''.concat(1)", "`${1}`");

test("var x, y; ''.concat(x).concat(y)", "var x, y; ''.concat(x, y)");
test("var y; ''.concat(x).concat(y)", "var y; ''.concat(x, y)"); // x might have a getter that updates y, but that side effect is preserved correctly
test("var x; ''.concat(x.a).concat(x)", "var x; ''.concat(x.a, x)"); // x.a might have a getter that updates x, but that side effect is preserved correctly
test("var x, y; ''.concat(x).concat(y)", "var x, y; `${x}${y}`");
test("var y; ''.concat(x).concat(y)", "var y; `${x}${y}`"); // x might have a getter that updates y, but that side effect is preserved correctly
test("var x; ''.concat(x.a).concat(x)", "var x; `${x.a}${x}`"); // x.a might have a getter that updates x, but that side effect is preserved correctly

// other
test_same("obj.concat([1,2]).concat(1)");
Expand Down Expand Up @@ -1451,6 +1543,30 @@ mod test {
test("/./.toString(b)", "/./.toString(b)");
}

#[test]
fn test_fold_string_concat() {
test_same("x = ''.concat()");
test("x = ''.concat(a, b)", "x = `${a}${b}`");
test("x = ''.concat(a, b, c)", "x = `${a}${b}${c}`");
test("x = ''.concat(a, b, c, d)", "x = `${a}${b}${c}${d}`");
test_same("x = ''.concat(a, b, c, d, e)");
test("x = ''.concat('a')", "x = 'a'");
test("x = ''.concat('a', 'b')", "x = 'ab'");
test("x = ''.concat('a', 'b', 'c')", "x = 'abc'");
test("x = ''.concat('a', 'b', 'c', 'd')", "x = 'abcd'");
test("x = ''.concat('a', 'b', 'c', 'd', 'e')", "x = 'abcde'");
test("x = ''.concat(a, 'b')", "x = `${a}b`");
test("x = ''.concat('a', b)", "x = `a${b}`");
test("x = ''.concat(a, 'b', c)", "x = `${a}b${c}`");
test("x = ''.concat('a', b, 'c')", "x = `a${b}c`");
test("x = ''.concat('a', b, 'c', d, 'e', f, 'g', h, 'i', j, 'k', l, 'm', n, 'o', p, 'q', r, 's', t)", "x = `a${b}c${d}e${f}g${h}i${j}k${l}m${n}o${p}q${r}s${t}`");
test("x = ''.concat(a, 1)", "x = `${a}${1}`"); // inlining 1 is not implemented yet

test("x = '\\\\s'.concat(a)", "x = `\\\\s${a}`");
test("x = '`'.concat(a)", "x = `\\`${a}`");
test("x = '${'.concat(a)", "x = `\\${${a}`");
}

#[test]
fn test_number_constants() {
test("v = Number.POSITIVE_INFINITY", "v = Infinity");
Expand Down
8 changes: 4 additions & 4 deletions tasks/minsize/minsize.snap
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Original | minified | minified | gzip | gzip | Fixture

173.90 kB | 59.69 kB | 59.82 kB | 19.26 kB | 19.33 kB | moment.js

287.63 kB | 89.58 kB | 90.07 kB | 31.08 kB | 31.95 kB | jquery.js
287.63 kB | 89.57 kB | 90.07 kB | 31.07 kB | 31.95 kB | jquery.js

342.15 kB | 117.76 kB | 118.14 kB | 43.67 kB | 44.37 kB | vue.js

Expand All @@ -17,11 +17,11 @@ Original | minified | minified | gzip | gzip | Fixture

1.25 MB | 650.82 kB | 646.76 kB | 161.51 kB | 163.73 kB | three.js

2.14 MB | 719.54 kB | 724.14 kB | 162.47 kB | 181.07 kB | victory.js
2.14 MB | 717.93 kB | 724.14 kB | 162.41 kB | 181.07 kB | victory.js

3.20 MB | 1.01 MB | 1.01 MB | 325.41 kB | 331.56 kB | echarts.js

6.69 MB | 2.30 MB | 2.31 MB | 470.00 kB | 488.28 kB | antd.js
6.69 MB | 2.29 MB | 2.31 MB | 469.69 kB | 488.28 kB | antd.js

10.95 MB | 3.37 MB | 3.49 MB | 866.65 kB | 915.50 kB | typescript.js
10.95 MB | 3.37 MB | 3.49 MB | 866.85 kB | 915.50 kB | typescript.js

Loading