Skip to content

feat(compiler): implement constant folding for unary minus #33140

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

Merged
merged 3 commits into from
May 7, 2025
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,23 @@ function evaluateInstruction(
}
return null;
}
case '-': {
const operand = read(constants, value.value);
if (
operand !== null &&
operand.kind === 'Primitive' &&
typeof operand.value === 'number'
) {
const result: Primitive = {
kind: 'Primitive',
value: operand.value * -1,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're only operating on numbers here. Part in the spec:
https://tc39.es/ecma262/2024/#sec-unary-minus-operator-runtime-semantics-evaluation

loc: value.loc,
};
instr.value = result;
return result;
}
return null;
}
default:
return null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@

## Input

```javascript
import {Stringify} from 'shared-runtime';

function foo() {
const a = -1;
return (
<Stringify
value={[
2 * a,
-0,
0 === -0,
-Infinity,
-NaN,
a * NaN,
a * Infinity,
a * -Infinity,
]}
/>
);
}

export const FIXTURE_ENTRYPOINT = {
fn: foo,
params: [],
isComponent: false,
};

```

## Code

```javascript
import { c as _c } from "react/compiler-runtime";
import { Stringify } from "shared-runtime";

function foo() {
const $ = _c(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = (
<Stringify
value={[
-2,
0,
true,
-Infinity,
-NaN,

-1 * NaN,
-1 * Infinity,
-1 * -Infinity,
]}
/>
);
$[0] = t0;
} else {
t0 = $[0];
}
return t0;
}

export const FIXTURE_ENTRYPOINT = {
fn: foo,
params: [],
isComponent: false,
};

```

### Eval output
(kind: ok) <div>{"value":[-2,0,true,null,null,null,null,null]}</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import {Stringify} from 'shared-runtime';

function foo() {
const a = -1;
return (
<Stringify
value={[
2 * a,
-0,
0 === -0,
-Infinity,
-NaN,
a * NaN,
a * Infinity,
a * -Infinity,
]}
/>
);
}

export const FIXTURE_ENTRYPOINT = {
fn: foo,
params: [],
isComponent: false,
};
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ function foo() {
n0: true,
n1: false,
n2: false,
n3: !-1,
n3: false,
s0: true,
s1: false,
s2: false,
Expand Down
Loading