Skip to content

Commit

Permalink
feat(es/minifier): Allow expr_simplifier to do arithmetic with stri…
Browse files Browse the repository at this point in the history
…ng literals (#8683)

**Description:**
This PR implements the feature described for the issue in #8682.


**Related issue:**

 - Closes #8682.
  • Loading branch information
levi-nz authored Mar 4, 2024
1 parent eac6620 commit 7e05adf
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
//// [enumConstantMemberWithString.ts]
var T1, T2, T3, T4, T5, T11, T21, T31;
(T11 = T1 || (T1 = {})).a = "1", T11.b = "12", T11.c = "123", T11[T11.d = "a" - "a"] = "d", T11.e = "a1", (T21 = T2 || (T2 = {})).a = "1", T21.b = "12", (T31 = T3 || (T3 = {})).a = "1", T31.b = "12", T31[T31.c = 1] = "c", T31[T31.d = 3] = "d", (T4 || (T4 = {})).a = "1", (T5 || (T5 = {})).a = "12";
(T11 = T1 || (T1 = {})).a = "1", T11.b = "12", T11.c = "123", T11[T11.d = NaN] = "d", T11.e = "a1", (T21 = T2 || (T2 = {})).a = "1", T21.b = "12", (T31 = T3 || (T3 = {})).a = "1", T31.b = "12", T31[T31.c = 1] = "c", T31[T31.d = 3] = "d", (T4 || (T4 = {})).a = "1", (T5 || (T5 = {})).a = "12";

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -896,8 +896,9 @@ impl SimplifyExpr {
);

if (lv.is_unknown() && rv.is_unknown())
|| !left.get_type().casted_to_number_on_add()
|| !right.get_type().casted_to_number_on_add()
|| op == op!(bin, "+")
&& (!left.get_type().casted_to_number_on_add()
|| !right.get_type().casted_to_number_on_add())
{
return Unknown;
}
Expand Down
27 changes: 27 additions & 0 deletions crates/swc_ecma_transforms_optimization/src/simplify/expr/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1314,6 +1314,33 @@ fn test_fold_literals_as_numbers() {
fold("x/false", "x/0"); // should we add an error check? :)
}

#[test]
fn test_fold_arithmetic_with_strings() {
// Left side of expression is a string
fold("'10' - 5", "5");
fold("'4' / 2", "2");
fold("'11' % 2", "1");
fold("'10' ** 2", "100");
fold("'Infinity' * 2", "Infinity");
fold("'NaN' * 2", "NaN");

// Right side of expression is a string
fold("10 - '5'", "5");
fold("4 / '2'", "2");
fold("11 % '2'", "1");
fold("10 ** '2'", "100");
fold("2 * 'Infinity'", "Infinity");
fold("2 * 'NaN'", "NaN");

// Both sides are strings
fold("'10' - '5'", "5");
fold("'4' / '2'", "2");
fold("'11' % '2'", "1");
fold("'10' ** '2'", "100");
fold("'Infinity' * '2'", "Infinity");
fold("'NaN' * '2'", "NaN");
}

#[test]
fn test_not_fold_back_to_true_false() {
fold("!0", "!0");
Expand Down

0 comments on commit 7e05adf

Please sign in to comment.