Skip to content

Commit

Permalink
feat(turbopack): Evaluate simple numeric addition (#70273)
Browse files Browse the repository at this point in the history
### What?

Add evaluation logic for cases where we are sure that the result is a
number and not a string.

### Why?

It's required for DCE.
  • Loading branch information
kdy1 authored Sep 26, 2024
1 parent eefa9d7 commit 9b62028
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
13 changes: 13 additions & 0 deletions turbopack/crates/turbopack-ecmascript/src/analyzer/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,19 @@ pub fn early_replace_builtin(value: &mut JsValue) -> bool {
/// processed.
pub fn replace_builtin(value: &mut JsValue) -> bool {
match value {
JsValue::Add(_, list) => {
// numeric addition
let mut sum = 0f64;
for arg in list {
let JsValue::Constant(ConstantValue::Num(num)) = arg else {
return false;
};
sum += num.0;
}
*value = JsValue::Constant(ConstantValue::Num(ConstantNumber(sum)));
true
}

// matching property access like `obj.prop`
// Accessing a property on something can be handled in some cases
JsValue::Member(_, box ref mut obj, ref mut prop) => match obj {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ v1 = (???*0* + 2)
⚠️ function calls are not analysed yet

v2 = (undefined | 2 | (???*0* + 1))
- *0* (...) => (undefined | a | (r((a + 1)) + 1))((2 + 1))
- *0* (...) => (undefined | a | (r((a + 1)) + 1))(3)
⚠️ recursive function call
⚠️ This value might have side effects

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,9 @@ it("should keep side-effects in if statements", () => {
expect(ok).toBe(2);
}
});

it('should analyze numeric additions',()=>{
if (1 +2 !==3) {
require("fail");
}
})

0 comments on commit 9b62028

Please sign in to comment.