prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
ingMemoizationGuarantees:false
/**
* Repro from https://github.com/facebook/react/issues/34262
*
* The compiler memoizes more precisely than the original code, with two reactive scopes:
* - One for `transform(input)` with `input` as dep
* - One for `{value}` with `value` as dep
*
* When we validate preserving m... | ail validation. This confirms that even though we allow the dependency to diverge,
* we still check that the output value is memoized.
*/
function useInputValue(input) {
const object = React.useMemo(() => {
const {value} = transform(input);
ret | al mutation, which extends the scope and should
* f | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.repro-preserve-memoization-inner-destructured-value-mistaken-as-dependency-later-mutation.js",
"language": "javascript",
"file_size": 955,
"cut_index": 582,
"middle_length": 52
} |
import {Stringify, useIdentity} from 'shared-runtime';
function Component() {
const data = useIdentity(
new Map([
[0, 'value0'],
[1, 'value1'],
])
);
const items = [];
// NOTE: `i` is a context variable because it's reassigned and also referenced
// within a closure, the `onClick` handler... | {
items.push(
<Stringify key={i} onClick={() => data.get(i)} shouldInvokeFns={true} />
);
}
return <>{items}</>;
}
const MIN = 0;
const MAX = 3;
const INCREMENT = 1;
export const FIXTURE_ENTRYPOINT = {
params: [],
fn: Component,
}; | ly const within the body and the "update" acts more like
// a re-initialization than a reassignment.
// Until we model this "new environment" semantic, we allow this case to error
for (let i = MIN; i <= MAX; i += INCREMENT) | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-for-loop-with-context-variable-iterator.js",
"language": "javascript",
"file_size": 998,
"cut_index": 512,
"middle_length": 229
} |
eserveExistingMemoizationGuarantees @validatePreserveExistingMemoizationGuarantees @enableOptionalDependencies
import {useMemo} from 'react';
import {identity, ValidateMemoization} from 'shared-runtime';
function Component({x}) {
const object = useMemo(() => {
return identity({
callback: () => {
/... | e]);
const result = useMemo(() => {
return [object.callback()];
}, [object]);
return <Inner x={x} result={result} />;
}
function Inner({x, result}) {
'use no memo';
return <ValidateMemoization inputs={[x.y.z]} output={result} />;
}
export c | n we can access `.c.d?.e`. Thus we should take the
// full property chain, exactly as-is with optionals/non-optionals, as a
// dependency
return identity(x.a.b?.c.d?.e);
},
});
}, [x.a.b?.c.d?. | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-preserve-memo-deps-mixed-optional-nonoptional-property-chain.js",
"language": "javascript",
"file_size": 1258,
"cut_index": 524,
"middle_length": 229
} |
eExistingMemoizationGuarantees:false
import {useMemo} from 'react';
import {logValue, useFragment, useHook, typedLog} from 'shared-runtime';
component Component() {
const data = useFragment();
const getIsEnabled = () => {
if (data != null) {
return true;
} else {
return {};
}
};
// We... | is function are then inferred as extending
// the mutable range of isEnabled
const getLoggingData = () => {
return {
isEnabled,
};
};
// The call here is then inferred as an indirect mutation of isEnabled
useHook(getLoggingData()); | apturing that mutable value,
// so any calls to th | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-repro-missed-memoization-from-capture-in-invoked-function-inferred-as-mutation.js",
"language": "javascript",
"file_size": 955,
"cut_index": 582,
"middle_length": 52
} |
ot mutated later
// but a is a dependnecy of b, which is a dependency of c.
// we have to memoize a to avoid breaking memoization of b,
// to avoid breaking memoization of c.
const a = [props.a];
// a can be independently memoized, is not mutated later,
// but is a dependency of d which is part of c's scop... | zed or else b will invalidate
// on every render since a is a dependency. we also need to
// ensure that a is memoized, since it's a dependency of b.
const c = [];
const d = {};
d.b = b;
c.push(props.b);
return c;
}
export const FIXTURE_ENT | t escape, but
// we need to ensure that b is memoi | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-non-escaping-interleaved-allocating-nested-dependency.js",
"language": "javascript",
"file_size": 971,
"cut_index": 582,
"middle_length": 52
} |
ionMode:"infer" @enableResetCacheOnSourceFileChanges @validateExhaustiveMemoizationDependencies:false
import {useEffect, useMemo, useState} from 'react';
import {ValidateMemoization} from 'shared-runtime';
let pretendConst = 0;
function unsafeResetConst() {
pretendConst = 0;
}
function unsafeUpdateConst() {
pret... | should
// reset on changes to globals that impact the component/hook, effectively memoizing
// as if value was reactive. However, we don't want to actually treat globals as
// reactive (though that would be trivial) since it could change compilation | iable that is read by a component is normally
// unsafe, but in this case we're simulating a fast refresh between each render
unsafeUpdateConst();
// TODO: In fast refresh mode (@enableResetCacheOnSourceFileChanges) Forget | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fast-refresh-refresh-on-const-changes-dev.js",
"language": "javascript",
"file_size": 1349,
"cut_index": 524,
"middle_length": 229
} |
f function expressions,
* regardless of control flow. This is simply because we wrote support for
* function expressions before doing a lot of work in PropagateScopeDeps
* to handle conditionally accessed dependencies.
*
* Current evaluator error:
* Found differences in evaluator results
* Non-forget (expected... | ) => {
if (!isObjNull) {
return obj.prop;
} else {
return null;
}
};
return <Stringify shouldInvokeFns={true} callback={callback} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{obj: null, isObjNull: true | n Component({obj, isObjNull}) {
const callback = ( | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisting-functionexpr-conditional-dep.tsx",
"language": "tsx",
"file_size": 921,
"cut_index": 606,
"middle_length": 52
} |
@loggerTestOnly
import {createContext, use, useState} from 'react';
import {
Stringify,
identity,
makeObject_Primitives,
useHook,
} from 'shared-runtime';
function Component() {
const w = use(Context);
// The scopes for x and x2 are interleaved, so this is one scope with two values
const x = makeObject_... | s();
z.push(obj);
}
// Overall we expect two pruned scopes (for x+x2, and obj), with 3 pruned scope values.
return <Stringify items={[w, x, x2, y, z]} />;
}
const Context = createContext();
function Wrapper() {
return (
<Context value={4 | his case it's _just_ a hook call, so we don't count this as pruned
const y = useHook();
const z = [];
for (let i = 0; i < 10; i++) {
// The scope for obj is pruned bc it's in a loop
const obj = makeObject_Primitive | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/log-pruned-memoization.js",
"language": "javascript",
"file_size": 1117,
"cut_index": 515,
"middle_length": 229
} |
dentity,
makeArray,
Stringify,
useFragment,
} from 'shared-runtime';
/**
* Bug repro showing why it's invalid for function references to be annotated
* with a `Read` effect when that reference might lead to the function being
* invoked.
*
* Note that currently, `Array.map` is annotated to have `Read` effect... | ected): (kind: ok)
* <div>{"x":[2,2,2],"count":3}</div><div>{"item":1}</div>
* <div>{"x":[2,2,2],"count":4}</div><div>{"item":1}</div>
* Forget:
* (kind: ok)
* <div>{"x":[2,2,2],"count":3}</div><div>{"item":1}</div>
* <div>{"x":[2,2,2,2,2,2 | sing data dependency
* - ConditionallyMutate: maybe-aliasing data dependency; maybe-write / invoke
* but only if the value is mutable
*
* Invalid evaluator result: Found differences in evaluator results Non-forget
* (exp | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mixedreadonly-mutating-map.js",
"language": "javascript",
"file_size": 1809,
"cut_index": 537,
"middle_length": 229
} |
eserveExistingMemoizationGuarantees:false
import {Stringify, identity} from 'shared-runtime';
function foo() {
try {
identity(`${Symbol('0')}`); // Uncaught TypeError: Cannot convert a Symbol value to a string (leave as is)
} catch {}
return (
<Stringify
value={[
`` === '',
`\n` ==... | `${Number.MIN_VALUE}`,
`${-0}`,
`
`,
`${{}}`,
`${[1, 2, 3]}`,
`${true}`,
`${false}`,
`${null}`,
`${undefined}`,
`123456789${0}`,
`${0}123456789`,
`${0}1234 | {'d' + `e${2 + 4}f`}`,
`1${2}${Math.sin(0)}`,
`${NaN}`,
`${Infinity}`,
`${-Infinity}`,
`${Number.MAX_SAFE_INTEGER}`,
`${Number.MIN_SAFE_INTEGER}`,
`${Number.MAX_VALUE}`,
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagation-template-literal.js",
"language": "javascript",
"file_size": 1402,
"cut_index": 524,
"middle_length": 229
} |
untime';
function Component(props) {
const post = useFragment(
graphql`
fragment F on T {
id
}
`,
props.post
);
const allUrls = [];
// `media` and `urls` are exported from the scope that will wrap this code,
// but `comments` is not (it doesn't need to be memoized, bc the call... | this means we try to
// reassign `comments` when there's no declaration for it.
const {media, comments, urls} = post;
const onClick = e => {
if (!comments.length) {
return;
}
console.log(comments.length);
};
allUrls.push(...url | // a reassignment, instead of a const declaration. | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-mixed-scope-declarations-and-locals.js",
"language": "javascript",
"file_size": 913,
"cut_index": 547,
"middle_length": 52
} |
ffect} from 'react';
function Component() {
let local;
const mk_reassignlocal = () => {
// Create the reassignment function inside another function, then return it
const reassignLocal = newValue => {
local = newValue;
};
return reassignLocal;
};
const reassignLocal = mk_reassignlocal();
... | !');
} else {
// With React Compiler enabled, `reassignLocal` is only created
// once, capturing a binding to `local` in that render pass.
// Therefore, calling `reassignLocal` will reassign the wrong
// version of `local`, and | binding to the latest `local`,
// such that invoking reassignLocal will reassign the same
// binding that we are observing in the if condition, and
// we reach this branch
console.log('`local` was updated | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-nested-function-reassign-local-variable-in-effect.js",
"language": "javascript",
"file_size": 1315,
"cut_index": 524,
"middle_length": 229
} |
onAliasingModel @enablePreserveExistingMemoizationGuarantees:false
/**
* This hook returns a function that when called with an input object,
* will return the result of mapping that input with the supplied map
* function. Results are cached, so if the same input is passed again,
* the same output object will be ret... | eturnedFunction(someInput)`
* strictly depends on `returnedFunction` and `someInput`, and cannot
* otherwise change over time.
*/
hook useMemoMap<TInput: interface {}, TOutput>(
map: TInput => TOutput
): TInput => TOutput {
return useMemo(() => {
| called is inherently not pure.
*
* However, in this case it is technically safe _if_ the mapping function
* is pure *and* the resulting objects are never modified. This is because
* the function only caches: the result of `r | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-uncalled-function-capturing-mutable-values-memoizes-with-captures-values.js",
"language": "javascript",
"file_size": 1695,
"cut_index": 537,
"middle_length": 229
} |
ction foo([a, b], {c, d, e = 'e'}, f = 'f', ...args) {
let i = 0;
var x = [];
class Bar {
#secretSauce = 42;
constructor() {
console.log(this.#secretSauce);
}
}
const g = {b() {}, c: () => {}};
const {z, aa = 'aa'} = useCustom();
<Button haha={1}></Button>;
<Button>{/** empty */}</B... | eIdentifier.y++;
updateIdentifier.y--;
switch (i) {
case 1 + 1: {
}
case foo(): {
}
case x.y: {
}
default: {
}
}
function component(a) {
// Add support for function declarations once we support `var` hoisting.
| ;
graphql`\\t\n`;
for (c of [1, 2]) {
}
for ([v] of [[1], [2]]) {
}
for ({v} of [{v: 1}, {v: 2}]) {
}
for (let x in {a: 1}) {
}
let updateIdentifier = 0;
--updateIdentifier;
++updateIdentifier;
updat | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-kitchensink.js",
"language": "javascript",
"file_size": 1061,
"cut_index": 515,
"middle_length": 229
} |
@flow @validatePreserveExistingMemoizationGuarantees @enablePreserveExistingMemoizationGuarantees:false @validateExhaustiveMemoizationDependencies:false
import {useFragment} from 'react-relay';
import LogEvent from 'LogEvent';
import {useCallback, useMemo} from 'react';
component Component(id) {
const items = useFra... | ogData` may be mutated.
LogEvent.log(() => object);
setIndex(index);
},
[index, logData, items]
);
if (prevId !== id) {
setCurrentIndex(0);
}
return (
<Foo
index={index}
items={items}
current={mediaLi | CurrentIndex = useCallback(
(index: number) => {
const object = {
tracking: logData.key,
};
// We infer that this may mutate `object`, which in turn aliases
// data from `logData`, such that `l | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-repro-missed-memoization-from-inferred-mutation-in-logger.js",
"language": "javascript",
"file_size": 1065,
"cut_index": 515,
"middle_length": 229
} |
const TOTAL = 10;
function Component(props) {
const items = [];
for (let i = props.start ?? 0; i < props.items.length; i++) {
const item = props.items[i];
items.push(<div key={item.id}>{item.value}</div>);
}
return <div>{items}</div>;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [
... | {id: 0, value: 'zero'},
{id: 1, value: 'one'},
{id: 2, value: 'two'},
],
},
{
start: 1,
items: [
{id: 0, value: 'zero'},
{id: 1, value: 'one'},
{id: 2, value: 'two'},
],
},
],
| id: 0, value: 'zero'},
{id: 1, value: 'one'},
],
},
{
start: 2,
items: [
{id: 0, value: 'zero'},
{id: 1, value: 'one'},
],
},
{
start: 0,
items: [
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-loop-with-value-block-initializer.js",
"language": "javascript",
"file_size": 1000,
"cut_index": 512,
"middle_length": 229
} |
{Throw} from 'shared-runtime';
/**
* Note: this is disabled in the evaluator due to different devmode errors.
* Found differences in evaluator results
* Non-forget (expected):
* (kind: ok) <invalidtag val="[object Object]"></invalidtag>
* logs: ['Warning: <%s /> is using incorrect casing. Use PascalCase for R... | rcase letter.%s','invalidTag',
* ]
*/
function useFoo() {
const invalidTag = Throw;
/**
* Need to be careful to not parse `invalidTag` as a localVar (i.e. render
* Throw). Note that the jsx transform turns this into a string tag:
* `jsx("in | rect casing. Use PascalCase for React components, or lowercase for HTML elements.%s','invalidTag',
* 'Warning: The tag <%s> is unrecognized in this browser. If you meant to render a React component, start its name with an uppe | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/invalid-jsx-lowercase-localvar.jsx",
"language": "jsx",
"file_size": 1131,
"cut_index": 518,
"middle_length": 229
} |
Array} from 'shared-runtime';
/**
* This fixture tests what happens when a reactive has no declarations (other than an early return),
* no reassignments, and no dependencies. In this case the only thing we can use to decide if we
* should take the if or else branch is the early return declaration. But if that uses ... | that the scope for `x` only executes once, on the first render of the component.
*/
let ENABLE_FEATURE = false;
function Component(props) {
let x = [];
if (ENABLE_FEATURE) {
x.push(42);
return x;
} else {
console.log('fallthrough');
} | instead of skipping
* to the else branch.
*
* We have to use a distinct sentinel for the early return value.
*
* Here the fixture will always take the "else" branch and never early return. Logging (not included)
* confirms | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/early-return-no-declarations-reassignments-dependencies.js",
"language": "javascript",
"file_size": 1252,
"cut_index": 524,
"middle_length": 229
} |
lidatePreserveExistingMemoizationGuarantees @enablePreserveExistingMemoizationGuarantees:false
import {identity, Stringify, useHook} from 'shared-runtime';
/**
* Repro from https://github.com/facebook/react/issues/34262
*
* The compiler memoizes more precisely than the original code, with two reactive scopes:
* -... | ization of `value`. This gets correctly flagged since
// the dependency is being mutated
let x = {};
useHook();
const object = React.useMemo(() => {
const {value} = identity(input, x);
return {value};
}, [input, x]);
return object;
}
f | nal memoization had `object` depending on `input` but our scope depends on
* `value`.
*/
function useInputValue(input) {
// Conflate the `identity(input, x)` call with something outside the useMemo,
// to try and break memo | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.repro-preserve-memoization-inner-destructured-value-mistaken-as-dependency-mutated-dep.js",
"language": "javascript",
"file_size": 1165,
"cut_index": 518,
"middle_length": 229
} |
teMemoization} from 'shared-runtime';
let pretendConst = 0;
function unsafeResetConst() {
pretendConst = 0;
}
function unsafeUpdateConst() {
pretendConst += 1;
}
function Component() {
useState(() => {
// unsafe: reset the constant when first rendering the instance
unsafeResetConst();
});
// UNSAF... | mo caches are not
// reset unless the deps change
const value = useMemo(() => [{pretendConst}], []);
return <ValidateMemoization inputs={[]} output={value} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{}],
sequentialRende | on mode (no @enableResetCacheOnSourceFileChanges) me | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fast-refresh-dont-refresh-const-changes-prod.js",
"language": "javascript",
"file_size": 931,
"cut_index": 606,
"middle_length": 52
} |
@flow @enableTransitivelyFreezeFunctionExpressions:false @enableNewMutationAliasingModel
import {setPropertyByKey, Stringify} from 'shared-runtime';
/**
* Variation of bug in `bug-aliased-capture-aliased-mutate`.
* Fixed in the new inference model.
*
* Found differences in evaluator results
* Non-forget (expected... | ];
const obj = {value: a};
setPropertyByKey(obj, 'arr', arr);
const obj_alias = obj;
const cb = () => obj_alias.arr.length;
for (let i = 0; i < a; i++) {
arr.push(i);
}
return <Stringify cb={cb} shouldInvokeFns={true} />;
}
export const | nd: ok)
* <div>{"cb":{"kind":"Function","result":2},"shouldInvokeFns":true}</div>
* <div>{"cb":{"kind":"Function","result":2},"shouldInvokeFns":true}</div>
*/
function useFoo({a}: {a: number, b: number}) {
const arr = [ | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-aliased-capture-mutate.js",
"language": "javascript",
"file_size": 1100,
"cut_index": 515,
"middle_length": 229
} |
react';
import {invoke, Stringify} from 'shared-runtime';
function Content() {
const [announcement, setAnnouncement] = useState('');
const [users, setUsers] = useState([{name: 'John Doe'}, {name: 'Jane Doe'}]);
// This was originally passed down as an onClick, but React Compiler's test
// evaluator doesn't ye... | ewUsers.pop();
return newUsers;
});
setAnnouncement(`Removed user (${removedUserName})`);
}
}, [users]);
return <Stringify users={users} announcement={announcement} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Content,
p | removedUserName = newUsers.at(-1).name;
n | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-context-var-reassign-no-scope.js",
"language": "javascript",
"file_size": 902,
"cut_index": 547,
"middle_length": 52
} |
ow @compilationMode:"infer"
'use strict';
function getWeekendDays(user) {
return [0, 6];
}
function getConfig(weekendDays) {
return [1, 5];
}
component Calendar(user, defaultFirstDay, currentDate, view) {
const weekendDays = getWeekendDays(user);
let firstDay = defaultFirstDay;
let daysToDisplay = 7;
if ... | r: {},
defaultFirstDay: 1,
currentDate: {getDayOfWeek: () => 3},
view: 'week',
},
],
sequentialRenders: [
{
user: {},
defaultFirstDay: 1,
currentDate: {getDayOfWeek: () => 3},
view: 'week',
},
{ | else if (view === 'day') {
firstDay = currentDate.getDayOfWeek();
daysToDisplay = 1;
}
return [currentDate, firstDay, daysToDisplay];
}
export const FIXTURE_ENTRYPOINT = {
fn: Calendar,
params: [
{
use | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-invalid-destructuring-reassignment-undefined-variable.js",
"language": "javascript",
"file_size": 1124,
"cut_index": 518,
"middle_length": 229
} |
@enableNewMutationAliasingModel
import {CONST_TRUE, Stringify, mutate, useIdentity} from 'shared-runtime';
/**
* Fixture showing an edge case for ReactiveScope variable propagation.
* Fixed in the new inference model
*
* Found differences in evaluator results
* Non-forget (expected):
* <div>{"obj":{"inner":{... | ll;
const boxedInner = [obj?.inner];
useIdentity(null);
mutate(obj);
if (boxedInner[0] !== obj?.inner) {
throw new Error('invariant broken');
}
return <Stringify obj={obj} inner={boxedInner} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: | obj":{"inner":{"value":"hello"},"wat0":"joe"},"inner":["[[ cyclic ref *2 ]]"]}</div>
* [[ (exception in render) Error: invariant broken ]]
*
*/
function Component() {
const obj = CONST_TRUE ? {inner: {value: 'hello'}} : nu | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-invalid-phi-as-dependency.tsx",
"language": "tsx",
"file_size": 1079,
"cut_index": 515,
"middle_length": 229
} |
/ @flow @enableAssumeHooksFollowRulesOfReact
function Component({label, highlightedItem}) {
const serverTime = useServerTime();
const highlight = new Highlight(highlightedItem);
const time = serverTime.get();
// subtle bit here: the binary expression infers the result of the call
// as a primitive and not ne... | be a constant value from the server
},
};
}
class Highlight {
constructor(value) {
this.value = value;
}
render() {
return this.value;
}
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{label: '<unused>', highligh | const timestampLabel = time / 1000 || label;
return (
<>
{highlight.render()}
{timestampLabel}
</>
);
}
function useServerTime() {
'use no forget';
return {
get() {
return 42000; // would | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-independently-memoized-property-load-for-method-call.js",
"language": "javascript",
"file_size": 1032,
"cut_index": 513,
"middle_length": 229
} |
mport TestCase from '../../TestCase';
import HitBox from './hit-box';
const React = window.React;
class MouseMove extends React.Component {
state = {
events: [],
};
checkEvent = event => {
let {events} = this.state;
if (event.type === 'mousemove' && events.indexOf(event) === -1) {
this.setSt... | <HitBox onMouseMove={this.checkEvent} />
<p>
Was the event pooled?{' '}
<b>
{events.length ? (events.length <= 1 ? 'Yes' : 'No') : 'Unsure'} (
{events.length} events)
</b>
</p>
| <li>Mouse over the box below</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
Mousemove should share the same instance of the event between
dispatches.
</TestCase.ExpectedResult>
| {
"filepath": "fixtures/dom/src/components/fixtures/event-pooling/mouse-move.js",
"language": "javascript",
"file_size": 1055,
"cut_index": 513,
"middle_length": 229
} |
import {useMemo} from 'react';
import {ValidateMemoization} from 'shared-runtime';
function Component({a, b, c}) {
const map = new WeakMap();
const mapAlias = map.set(a, 0);
mapAlias.set(c, 0);
const hasB = map.has(b);
return (
<>
<ValidateMemoization
inputs={[a, c]}
output={map}
... | : [{a: v1, b: v1, c: v1}],
sequentialRenders: [
{a: v1, b: v1, c: v1},
{a: v2, b: v1, c: v1},
{a: v1, b: v1, c: v1},
{a: v1, b: v2, c: v1},
{a: v1, b: v1, c: v1},
{a: v3, b: v3, c: v1},
{a: v3, b: v3, c: v1},
{a: v1, b: v1 | inputs={[b]}
output={[hasB]}
onlyCheckCompiled={true}
/>
</>
);
}
const v1 = {value: 1};
const v2 = {value: 2};
const v3 = {value: 3};
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/weakmap-constructor.js",
"language": "javascript",
"file_size": 1015,
"cut_index": 512,
"middle_length": 229
} |
import {useMemo} from 'react';
import {ValidateMemoization} from 'shared-runtime';
function Component({a, b, c}) {
const set = new WeakSet();
const setAlias = set.add(a);
setAlias.add(c);
const hasB = set.has(b);
return (
<>
<ValidateMemoization
inputs={[a, c]}
output={set}
... | v1, b: v1, c: v1}],
sequentialRenders: [
{a: v1, b: v1, c: v1},
{a: v2, b: v1, c: v1},
{a: v1, b: v1, c: v1},
{a: v1, b: v2, c: v1},
{a: v1, b: v1, c: v1},
{a: v3, b: v3, c: v1},
{a: v3, b: v3, c: v1},
{a: v1, b: v1, c: v | puts={[b]}
output={[hasB]}
onlyCheckCompiled={true}
/>
</>
);
}
const v1 = {value: 1};
const v2 = {value: 2};
const v3 = {value: 3};
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/weakset-constructor.js",
"language": "javascript",
"file_size": 1009,
"cut_index": 512,
"middle_length": 229
} |
but hard to compute by brute-forcing
function MyComponent() {
// 40 conditions
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if ... |
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if ( | else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) {
} else {
}
if (c) { | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/rules-of-hooks-c1e8c7f4c191.js",
"language": "javascript",
"file_size": 1280,
"cut_index": 524,
"middle_length": 229
} |
neither the conditions before or after the hook affect the hook call
// Failed prior to implementing BigInt because pathsFromStartToEnd and allPathsFromStartToEnd were too big and had rounding errors
const useSomeHook = () => {};
const SomeName = () => {
const filler = FILLER ?? FILLER ?? FILLER;
const filler2 = ... | ILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
| ? FILLER ?? FILLER;
const filler7 = FILLER ?? FILLER ?? FILLER;
const filler8 = FILLER ?? FILLER ?? FILLER;
useSomeHook();
if (anyConditionCanEvenBeFalse) {
return null;
}
return (
<React.Fragment>
{F | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/todo.bail.rules-of-hooks-6949b255e7eb.js",
"language": "javascript",
"file_size": 2200,
"cut_index": 563,
"middle_length": 229
} |
@validateExhaustiveMemoizationDependencies
import {useMemo} from 'react';
import {Stringify} from 'shared-runtime';
function Component({x, y, z}) {
const a = useMemo(() => {
return x?.y.z?.a;
// error: too precise
}, [x?.y.z?.a.b]);
const b = useMemo(() => {
return x.y.z?.a;
// ok, not our job to... | .z, z?.y?.a, UNUSED_GLOBAL]);
const ref1 = useRef(null);
const ref2 = useRef(null);
const ref = z ? ref1 : ref2;
const cb = useMemo(() => {
return () => {
return ref.current;
};
// error: ref is a stable type but reactive
}, []) | sole.log(y), z?.b)];
// ok
}, [x?.y, y, z?.b]);
const e = useMemo(() => {
const e = [];
e.push(x);
return e;
// ok
}, [x]);
const f = useMemo(() => {
return [];
// error: unnecessary
}, [x, y | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/exhaustive-deps/error.invalid-exhaustive-deps.js",
"language": "javascript",
"file_size": 1061,
"cut_index": 515,
"middle_length": 229
} |
ExhaustiveMemoizationDependencies @validateExhaustiveEffectDependencies:"all"
import {
useCallback,
useTransition,
useState,
useOptimistic,
useActionState,
useRef,
useReducer,
useEffect,
} from 'react';
function useFoo() {
const [s, setState] = useState();
const ref = useRef(null);
const [t, star... | stable values
// to check that they're allowed
dispatch,
startTransition,
addOptimistic,
setState,
dispatchAction,
ref,
]);
return useCallback(() => {
dispatch();
startTransition(() => {});
addOptimistic();
| null);
useEffect(() => {
dispatch();
startTransition(() => {});
addOptimistic();
setState(null);
dispatchAction();
ref.current = true;
}, [
// intentionally adding unnecessary deps on nonreactive | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/exhaustive-deps/exhaustive-deps-allow-nonreactive-stable-types-as-extra-deps.js",
"language": "javascript",
"file_size": 1363,
"cut_index": 524,
"middle_length": 229
} |
ExhaustiveMemoizationDependencies
import {useCallback, useMemo} from 'react';
import {makeObject_Primitives, Stringify} from 'shared-runtime';
function useHook1(x) {
return useMemo(() => {
return x?.y.z?.a;
}, [x?.y.z?.a]);
}
function useHook2(x) {
useMemo(() => {
return x.y.z?.a;
}, [x.y.z?.a]);
}
fun... | useHook6(x) {
return useMemo(() => {
const f = [];
f.push(x.y.z);
f.push(x.y);
f.push(x);
return f;
}, [x]);
}
function useHook7(x) {
const [state, setState] = useState(true);
const f = () => {
setState(x => !x);
};
ret | , [x?.y, y, z?.b]);
}
function useHook5(x) {
return useMemo(() => {
const e = [];
const local = makeObject_Primitives(x);
const fn = () => {
e.push(local);
};
fn();
return e;
}, [x]);
}
function | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/exhaustive-deps/exhaustive-deps.js",
"language": "javascript",
"file_size": 1327,
"cut_index": 524,
"middle_length": 229
} |
{mutateAndReturn, Stringify, useIdentity} from 'shared-runtime';
/**
* Repro for bug with `mutableOnlyIfOperandsAreMutable` flag
* Found differences in evaluator results
* Non-forget (expected):
* (kind: ok)
* <div>{"children":[{"value":"foo","wat0":"joe"},{"value":5,"wat0":"joe"}]}</div>
* <div>{"children"... | "value":6,"wat0":"joe"}]}</div>
*/
function Component({value}) {
const arr = [{value: 'foo'}, {value: 'bar'}, {value}];
useIdentity(null);
const derived = arr.filter(mutateAndReturn);
return (
<Stringify>
{derived.at(0)}
{derived. | en":[{"value":"foo","wat0":"joe"},{"value":5,"wat0":"joe"}]}</div>
* <div>{"children":[{"value":"foo","wat0":"joe","wat1":"joe"},{"value":6,"wat0":"joe"}]}</div>
* <div>{"children":[{"value":"foo","wat0":"joe","wat1":"joe"},{ | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/global-types/repro-array-filter-capture-mutate-bug.tsx",
"language": "tsx",
"file_size": 1175,
"cut_index": 518,
"middle_length": 229
} |
.todo-multiple-fbt-plural, but note that we must
* count fbt plurals across both <fbt:plural /> namespaced jsx tags
* and fbt.plural(...) call expressions.
*
* Evaluator error:
* Found differences in evaluator results
* Non-forget (expected):
* (kind: ok) <div>1 apple and 2 bananas</div>
* Forget:
* ... | and
{' '}
<fbt:plural name={'number of bananas'} count={bananas} showCount="yes">
banana
</fbt:plural>
</fbt>
</div>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: useFoo,
params: [{apples: 1, bananas: 2}], | {' '}
{fbt.plural('apple', apples)} | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/bug-fbt-plural-multiple-mixed-call-tag.tsx",
"language": "tsx",
"file_size": 871,
"cut_index": 559,
"middle_length": 52
} |
* Note that the fbt transform looks for callsites with a `fbt`-named callee.
* This is incompatible with react-compiler as we rename local variables in
* HIRBuilder + RenameVariables.
*
* See evaluator error:
* Found differences in evaluator results
* Non-forget (expected):
* (kind: ok) <div>Hello, Sathya!... | ng'
);
const getText2 = fbt =>
fbt(
`Goodbye, ${fbt.param('(key) name', identity(props.name))}!`,
'(description) Greeting2'
);
return (
<div>
{getText1(fbt)}
{getText2(fbt)}
</div>
);
}
export const FIXT | dentity(props.name))}!`,
'(description) Greeti | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/error.todo-fbt-as-local.js",
"language": "javascript",
"file_size": 953,
"cut_index": 582,
"middle_length": 52
} |
**
* Forget + fbt inconsistency. Evaluator errors with the following
* Found differences in evaluator results
* Non-forget (expected):
* (kind: ok) 1 rewrite to Rust · 2 months traveling
* Forget:
* (kind: ok) 1 rewrites to Rust · 2 months traveling
*
* The root issue here is that fbt:plural/enum/pron... | /FbtUtil.js#L666-L673)
* simply returns the whole source code string. As a result, all fbt nodes dedupe together
* and _getStringVariationCombinations ends up early exiting (before adding valid candidate values).
*
*
*
* For fbt:plural tags specifica | packages/babel-plugin-fbt/src/JSFbtBuilder.js#L297))
*
*
* Since Forget does not add `.start` and `.end` for babel nodes it synthesizes,
* [getRawSource](https://github.com/facebook/fbt/blob/main/packages/babel-plugin-fbt/src | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/error.todo-multiple-fbt-plural.tsx",
"language": "tsx",
"file_size": 1666,
"cut_index": 537,
"middle_length": 229
} |
ort fbt from 'fbt';
import {Stringify, identity} from 'shared-runtime';
/**
* MemoizeFbtAndMacroOperands needs to account for nested fbt calls.
* Expected fixture `fbt-param-call-arguments` to succeed but it failed with error:
* /fbt-param-call-arguments.ts: Line 19 Column 11: fbt: unsupported babel node: Identif... | e={lastname} />),
'Inner fbt value'
)
)
),
],
'Name'
)}
</div>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{firstname: 'first', lastname: 'last'}],
| ingify key={0} name={firstname} />),
', ',
fbt.param(
'lastname',
identity(
fbt(
'(inner)' +
fbt.param('lastname', <Stringify key={1} nam | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/repro-fbt-param-nested-fbt-jsx.js",
"language": "javascript",
"file_size": 1064,
"cut_index": 515,
"middle_length": 229
} |
import fbt from 'fbt';
import {identity} from 'shared-runtime';
/**
* MemoizeFbtAndMacroOperands needs to account for nested fbt calls.
* Expected fixture `fbt-param-call-arguments` to succeed but it failed with error:
* /fbt-param-call-arguments.ts: Line 19 Column 11: fbt: unsupported babel node: Identifier
* ... | )
)
),
],
'Name'
)}
</div>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{firstname: 'first', lastname: 'last'}],
sequentialRenders: [{firstname: 'first', lastname: 'last'}],
};
| stname)),
', ',
fbt.param(
'lastname',
identity(
fbt(
'(inner)' + fbt.param('lastname', identity(lastname)),
'Inner fbt value'
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/repro-fbt-param-nested-fbt.js",
"language": "javascript",
"file_size": 997,
"cut_index": 512,
"middle_length": 229
} |
{throwErrorWithMessage, ValidateMemoization} from 'shared-runtime';
/**
* Context variables are local variables that (1) have at least one reassignment
* and (2) are captured into a function expression. These have a known mutable
* range: from first declaration / assignment to the last direct or aliased,
* mutabl... | specify input to avoid adding a `PropertyLoad` from contextVar,
* which might affect hoistable-objects analysis.
*/
return (
<ValidateMemoization
inputs={[cond ? a : undefined]}
output={cb}
onlyCheckCompiled={true}
/>
) | .
*/
function Component({cond, a}) {
let contextVar;
if (cond) {
contextVar = {val: a};
} else {
contextVar = {};
throwErrorWithMessage('');
}
const cb = {cb: () => contextVar.val * 4};
/**
* manually | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/context-var-granular-dep.js",
"language": "javascript",
"file_size": 1181,
"cut_index": 518,
"middle_length": 229
} |
ngify, useIdentity} from 'shared-runtime';
type HasA = {kind: 'hasA'; a: {value: number}};
type HasC = {kind: 'hasC'; c: {value: number}};
function Foo({cond}: {cond: boolean}) {
let x: HasA | HasC = shallowCopy({kind: 'hasA', a: {value: 2}});
/**
* This read of x.a.value is outside of x's identifier mutable
... | (x_@0, x_@1)) is a different ssa instance,
* we cannot safely hoist a read of `x.a.value`
*/
return <Stringify val={!cond && [(x as HasA).a.value + 2]} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [{cond: false}],
sequentialRend | alue: 3}});
}
/**
* Since this x (x_@2 = phi | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/hoist-deps-diff-ssa-instance1.tsx",
"language": "tsx",
"file_size": 894,
"cut_index": 547,
"middle_length": 52
} |
encies of an inner scope up to its parent,
// we prefer to retain granularity.
//
// In this test, we check that Forget propagates the inner scope's conditional
// dependencies (e.g. props.a.b) instead of only its derived minimal
// unconditional dependencies (e.g. props).
// ```javascript
// scope @0 (deps=[???] decl... | eJoinCondDepsInUncondScopes(props) {
let y = {};
let x = {};
if (CONST_TRUE) {
setProperty(x, props.a.b);
}
setProperty(y, props.a.b);
return [x, y];
}
export const FIXTURE_ENTRYPOINT = {
fn: useJoinCondDepsInUncondScopes,
params: [{a: | UE, setProperty} from 'shared-runtime';
function us | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/join-uncond-scopes-cond-deps.js",
"language": "javascript",
"file_size": 928,
"cut_index": 606,
"middle_length": 52
} |
unconditional dependency `props.a` is the subpath of a conditional
// dependency `props.a.b`, we can safely overestimate and only track `props.a`
// as a dependency
import {identity} from 'shared-runtime';
// ordering of accesses should not matter
function useConditionalSuperpath1({props, cond}) {
const x = {};
... | nders: [
{props: {a: null}, cond: false},
{props: {a: {}}, cond: true},
{props: {a: {b: 3}}, cond: true},
{props: {}, cond: false},
// test that we preserve nullthrows
{props: {a: {b: undefined}}, cond: true},
{props: {a: undefi | sequentialRe | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/superpath-order1.js",
"language": "javascript",
"file_size": 819,
"cut_index": 522,
"middle_length": 14
} |
unconditional dependency `props.a` is the subpath of a conditional
// dependency `props.a.b`, we can safely overestimate and only track `props.a`
// as a dependency
import {identity} from 'shared-runtime';
// ordering of accesses should not matter
function useConditionalSuperpath2({props, cond}) {
const x = {};
... | nders: [
{props: {a: null}, cond: false},
{props: {a: {}}, cond: true},
{props: {a: {b: 3}}, cond: true},
{props: {}, cond: false},
// test that we preserve nullthrows
{props: {a: {b: undefined}}, cond: true},
{props: {a: undefi | sequentialRe | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/superpath-order2.js",
"language": "javascript",
"file_size": 819,
"cut_index": 522,
"middle_length": 14
} |
pertyByKey,
} from 'shared-runtime';
/**
* This fixture is similar to `bug-aliased-capture-aliased-mutate` and
* `nonmutating-capture-in-unsplittable-memo-block`, but with a focus on
* dependency extraction.
*
* NOTE: this fixture is currently valid, but will break with optimizations:
* - Scope and mutable-range... | ptured into the array.
*
* Before scope block creation, HIR looks like this:
* //
* // $1 is unscoped as obj's mutable range will be
* // extended in a later pass
* //
* $1 = LoadLocal obj@0[0:12]
* $2 = PropertyLoad $1.id
* //
* // | ty optimizations may produce invalid
* output -- it may compare the array's contents / dependencies too early.
* - Runtime validation for immutable values will break if `mutate` does
* interior mutation of the value ca | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/new-mutability/aliased-nested-scope-truncated-dep.tsx",
"language": "tsx",
"file_size": 3434,
"cut_index": 614,
"middle_length": 229
} |
// @enableNewMutationAliasingModel
import {Stringify} from 'shared-runtime';
/**
* Forked from array-map-simple.js
*
* Named lambdas (e.g. cb1) may be defined in the top scope of a function and
* used in a different lambda (getArrMap1).
*
* Here, we should try to determine if cb1 is actually called. In this case... | {getArrMap2}
shouldInvokeFns={true}
/>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: useFoo,
params: [{arr1: [], arr2: []}],
sequentialRenders: [
{arr1: [], arr2: []},
{arr1: [], arr2: null},
{arr1: [{value: 1}, {value: 2}], a | => arr1[0].value + e.value;
const getArrMap1 = () => arr1.map(cb1);
const cb2 = e => arr2[0].value + e.value;
const getArrMap2 = () => arr1.map(cb2);
return (
<Stringify
getArrMap1={getArrMap1}
getArrMap2= | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/new-mutability/array-map-named-callback-cross-context.js",
"language": "javascript",
"file_size": 1026,
"cut_index": 512,
"middle_length": 229
} |
wMutationAliasingModel
import {arrayPush, Stringify} from 'shared-runtime';
function Component({prop1, prop2}) {
'use memo';
let x = [{value: prop1}];
let z;
while (x.length < 2) {
// there's a phi here for x (value before the loop and the reassignment later)
// this mutation occurs before the reassi... | rt const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{prop1: 0, prop2: 'a'}],
sequentialRenders: [
{prop1: 0, prop2: 'a'},
{prop1: 1, prop2: 'a'},
{prop1: 1, prop2: 'b'},
{prop1: 0, prop2: 'b'},
{prop1: 0, prop2: 'a'},
],
};
| z} />;
}
expo | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/new-mutability/capture-backedge-phi-with-later-mutation.js",
"language": "javascript",
"file_size": 794,
"cut_index": 524,
"middle_length": 14
} |
@enableNewMutationAliasingModel
function Component() {
let local;
const reassignLocal = newValue => {
local = newValue;
};
const onClick = newValue => {
reassignLocal('hello');
if (local === newValue) {
// Without React Compiler, `reassignLocal` is freshly created
// on each render, c... | `reassignLocal` will reassign the wrong
// version of `local`, and not update the binding we are checking
// in the if condition.
//
// To protect against this, we disallow reassigning locals from
// functions that escape
| s branch
console.log('`local` was updated!');
} else {
// With React Compiler enabled, `reassignLocal` is only created
// once, capturing a binding to `local` in that render pass.
// Therefore, calling | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/new-mutability/error.invalid-reassign-local-variable-in-jsx-callback.js",
"language": "javascript",
"file_size": 1110,
"cut_index": 515,
"middle_length": 229
} |
nt Component(
onAsyncSubmit?: (() => void) => void,
onClose: (isConfirmed: boolean) => void
) {
// When running inferReactiveScopeVariables,
// onAsyncSubmit and onClose update to share
// a mutableRange instance.
const onSubmit = useCallback(() => {
if (onAsyncSubmit) {
onAsyncSubmit(() => {
... | different mutable range instance, which is the
// one reset after AnalyzeFunctions.
// The fix is to fully reset mutable ranges *instances*
// after AnalyzeFunctions visit a function expression
return <Dialog onSubmit={onSubmit} onClose={() => onC | onAsyncSubmit) and then onClose gets assigned a
// | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/new-mutability/repro-internal-compiler-shared-mutablerange-bug.js",
"language": "javascript",
"file_size": 933,
"cut_index": 606,
"middle_length": 52
} |
@enablePreserveExistingMemoizationGuarantees:false @validateExhaustiveMemoizationDependencies:false
import {useMemo} from 'react';
import {
mutate,
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b, c}: {a: number; b: number; c: number}) {
co... | ion inputs={[a, b, c]} output={x[0]} />;
</>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0, c: 0}],
sequentialRenders: [
{a: 0, b: 0, c: 0},
{a: 0, b: 1, c: 0},
{a: 1, b: 1, c: 0},
{a: 1, b: 1, c: | // This mutation shouldn't affect the object in the consequent
mutate(x);
}
return (
<>
<ValidateMemoization inputs={[a, b, c]} output={x} />;
{/* TODO: should only depend on c */}
<ValidateMemoizat | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/new-mutability/todo-control-flow-sensitive-mutation.tsx",
"language": "tsx",
"file_size": 1085,
"cut_index": 515,
"middle_length": 229
} |
import {useMemo} from 'react';
import {
identity,
makeObject_Primitives,
typedIdentity,
useIdentity,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}) {
// create a mutable value with input `a`
const x = useMemo(() => makeObject_Primitives(a), [a]);
// freeze the value
useIde... | ency
identity(x2, b);
return <ValidateMemoization inputs={[a]} output={x} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 1, b: 0},
{a: 1, b: 1},
{a: 0, b: | es to a read.
// x should *not* take b as a depend | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/new-mutability/typed-identity-function-frozen-input.js",
"language": "javascript",
"file_size": 885,
"cut_index": 547,
"middle_length": 52
} |
rops) {
const a_DEBUG = [];
a_DEBUG.push(props.a);
if (props.b) {
return null;
}
a_DEBUG.push(props.d);
return a_DEBUG;
}
/**
* props.b *does* influence `a`
*/
function ComponentB(props) {
const a = [];
a.push(props.a);
if (props.b) {
a.push(props.c);
}
a.push(props.d);
return a;
}
/... | * props.b *does* influence `a`
*/
function ComponentD(props) {
const a = [];
a.push(props.a);
if (props.b) {
a.push(props.c);
return a;
}
a.push(props.d);
return a;
}
export const FIXTURE_ENTRYPOINT = {
fn: ComponentA,
params: [{ | urn null;
}
a.push(props.d);
return a;
}
/**
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/propagate-scope-deps-hir-fork/conditional-early-return.js",
"language": "javascript",
"file_size": 941,
"cut_index": 606,
"middle_length": 52
} |
mport {ValidateMemoization} from 'shared-runtime';
import {use, useMemo} from 'react';
const FooContext = React.createContext(null);
function Component(props) {
return (
<FooContext.Provider value={props.value}>
<Inner cond={props.cond} />
</FooContext.Provider>
);
}
function Inner(props) {
let in... | alse, value: null},
{cond: false, value: 42},
// change cond false->true
{cond: true, value: 42},
// change cond true->false, change unobserved value, change cond false->true
{cond: false, value: 42},
{cond: false, value: null},
| const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{cond: true, value: 42}],
sequentialRenders: [
// change cond true->false
{cond: true, value: 42},
{cond: false, value: 42},
// change value
{cond: f | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-operator-conditional.js",
"language": "javascript",
"file_size": 1034,
"cut_index": 513,
"middle_length": 229
} |
ableAllowSetStateFromRefsInEffects @loggerTestOnly @compilationMode:"infer" @outputMode:"lint"
import {useState, useRef, useEffect} from 'react';
function Component({x, y}) {
const previousXRef = useRef(null);
const previousYRef = useRef(null);
const [data, setData] = useState(null);
useEffect(() => {
co... | etData(data);
}
}, [x, y]);
return data;
}
function areEqual(a, b) {
return a === b;
}
function load({x, y}) {
return x * y;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{x: 0, y: 0}],
sequentialRenders: [
{x: 0, | eviousY)) {
const data = load({x, y});
s | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/valid-setState-in-useEffect-controlled-by-ref-value.js",
"language": "javascript",
"file_size": 906,
"cut_index": 547,
"middle_length": 52
} |
{useEffect} from 'react';
import {useIdentity} from 'shared-runtime';
function Component() {
let local;
const reassignLocal = newValue => {
local = newValue;
};
const callback = newValue => {
reassignLocal('hello');
if (local === newValue) {
// Without React Compiler, `reassignLocal` is f... | render pass.
// Therefore, calling `reassignLocal` will reassign the wrong
// version of `local`, and not update the binding we are checking
// in the if condition.
//
// To protect against this, we disallow reassigning local | e if condition, and
// we reach this branch
console.log('`local` was updated!');
} else {
// With React Compiler enabled, `reassignLocal` is only created
// once, capturing a binding to `local` in that | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-hook-argument.js",
"language": "javascript",
"file_size": 1162,
"cut_index": 518,
"middle_length": 229
} |
useRef();
function updateStyles() {
const foo = fooRef.current;
// The access of `barRef` here before its declaration causes it be hoisted...
if (barRef.current == null || foo == null) {
return;
}
foo.style.height = '100px';
}
// ...which previously meant that we didn't infer a type..... | to fail with "can't freeze a mutable function"
);
useLayoutEffect(() => {
const observer = new ResizeObserver(_ => {
updateStyles();
});
return () => {
observer.disconnect();
};
}, []);
return <div ref={resizeRef} /> | arRef.current = width;
} // ...which caused this | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-mutate-ref-in-function-passed-to-hook.js",
"language": "javascript",
"file_size": 871,
"cut_index": 559,
"middle_length": 52
} |
rveExistingMemoizationGuarantees
import {useMemo} from 'react';
import {Stringify} from 'shared-runtime';
// derived from https://github.com/facebook/react/issues/32261
function Component({items}) {
const record = useMemo(
() =>
Object.fromEntries(
items.map(item => [item.id, ref => <Stringify ref=... | ).map(([id, render]) => (
<Stringify key={id} render={render} />
))}
</div>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [
{
items: [
{id: '0', name: 'Hello'},
{id: '1', name: 'World!'}, | ed
return (
<div>
{Object.entries(record | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-object-fromEntries-entries.js",
"language": "javascript",
"file_size": 862,
"cut_index": 529,
"middle_length": 52
} |
1?: V3}>): V2b.V2a {
const v4 = v5(V6.v7({v8: V9.va}));
const vb = (
<ComponentC cd="TxqUy" ce="oh`]uc" cf="Bdbo" c10={!V9.va && v11.v12}>
gmhubcw
{v1 === V3.V13 ? (
<c14 c15="L^]w\\T\\qrGmqrlQyrvBgf\\inuRdkEqwVPwixiriYGSZmKJf]E]RdT{N[WyVPiEJIbdFzvDohJV[BV`H[[K^xoy[HOGKDqVzUJ^h">
i... | mmjhfserfuqyluxcewpyjihektogc
</c14>
) : (
<c14 c15="H\\\\GAcTc\\lfGMW[yHriCpvW`w]niSIKj\\kdgFI">
yejarlvudihqdrdgpvahovggdnmgnueedxpbwbkdvvkdhqwrtoiual
</c14>
)}
hflmn
</ComponentC>
);
return vb; | Qe{SUpoN[\\gL[`bLMOhvFqDVVMNOdY">
goprinbj | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-propagate-type-of-ternary-nested.js",
"language": "javascript",
"file_size": 846,
"cut_index": 535,
"middle_length": 52
} |
expressions should not be
* typed with `freeze` effects.
*/
function Foo({a, b}) {
'use memo';
const obj = {};
const updaterFactory = () => {
/**
* This returned function expression *is* a local value. But it might (1)
* capture and mutate its context environment and (2) be called during
* r... | j.a = a;
};
};
const updater = updaterFactory();
updater(b);
return <Stringify cb={obj} shouldInvokeFns={true} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [{a: 1, b: 2}],
sequentialRenders: [
{a: 1, b: 2},
{a: 1, | n newValue => {
obj.value = newValue;
ob | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-returned-inner-fn-mutates-context.js",
"language": "javascript",
"file_size": 929,
"cut_index": 606,
"middle_length": 52
} |
*
* Repro for https://github.com/facebook/react/issues/35122
*
* InferReactiveScopeVariables was excluding primitive operands
* when considering operands for merging. We previously did not
* infer types for context variables (StoreContext etc), but later
* started inferring types in cases of `const` context varia... | State(5);
const onClick = () => {
// Reference to isExpired prior to declaration
console.log('isExpired', isExpired);
};
const isExpired = expire === 0;
return <div onClick={onClick}>{expire}</div>;
}
export const FIXTURE_ENTRYPOINT = { | function Test1() {
const [expire, setExpire] = use | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-stale-closure-forward-reference.js",
"language": "javascript",
"file_size": 888,
"cut_index": 547,
"middle_length": 52
} |
aticText1, Stringify, Text} from 'shared-runtime';
function Component(props) {
const {buttons} = props;
const [primaryButton, ...nonPrimaryButtons] = buttons;
const renderedNonPrimaryButtons = nonPrimaryButtons.map((buttonProps, i) => (
<Stringify
{...buttonProps}
key={`button-${i}`}
style... | tton: {left: true},
rightSecondaryButton: {right: true},
};
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [
{
buttons: [
{},
{type: 'submit', children: ['Submit!']},
{type: 'button', children: ['Reset'] | eftSecondaryBu | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-undefined-expression-of-jsxexpressioncontainer.js",
"language": "javascript",
"file_size": 819,
"cut_index": 522,
"middle_length": 14
} |
t(props) {
const data = useFreeze(); // assume this returns {items: Array<{...}>}
// In this call `data` and `data.items` have a read effect *and* the lambda itself
// is readonly (it doesn't capture ony mutable references). Further, we ca
// theoretically determine that the lambda doesn't need to be memoized, ... | vascript object, then we can infer that any `.map()`
// calls *must* be Array.prototype.map (or else they are a runtime error), since no
// other builtin has a .map() function.
const items = data.items.map(item => <Item item={item} />);
return <div | ta`, if we know
// that it is a plain, readonly ja | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/todo.unnecessary-lambda-memoization.js",
"language": "javascript",
"file_size": 855,
"cut_index": 529,
"middle_length": 52
} |
ion Component({cond, obj, items}) {
try {
// items.length is accessed WITHIN the && expression
const result = cond && obj?.value && items.length;
return <div>{String(result)}</div>;
} catch {
return <div>error</div>;
}
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{cond: true,... | : false, obj: {value: 'hello'}, items: [1]},
{cond: true, obj: null, items: [1]},
{cond: true, obj: {value: 'test'}, items: null}, // errors because items.length throws WITHIN the && chain
{cond: null, obj: {value: 'test'}, items: [1]},
],
}; | obj: {value: 'world'}, items: [1, 2, 3]},
{cond | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-logical-and-optional.js",
"language": "javascript",
"file_size": 826,
"cut_index": 517,
"middle_length": 52
} |
Component({a, b, fallback}) {
try {
// fallback.value is accessed WITHIN the ?? chain
const result = a ?? b ?? fallback.value;
return <span>{result}</span>;
} catch {
return <span>error</span>;
}
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 'first', b: 'second', fallback... | null, fallback: {value: 'fallback'}},
{a: undefined, b: undefined, fallback: {value: 'fallback'}},
{a: 0, b: 'not zero', fallback: {value: 'default'}},
{a: null, b: null, fallback: null}, // errors because fallback.value throws WITHIN the ?? ch | d', fallback: {value: 'default'}},
{a: null, b: | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-nullish-coalescing.js",
"language": "javascript",
"file_size": 840,
"cut_index": 520,
"middle_length": 52
} |
WITHIN the optional call expression as an argument
// When obj is non-null but arg is null, arg.value throws inside the optional chain
const result = obj?.method?.(arg.value);
return <span>{result ?? 'no result'}</span>;
} catch {
return <span>error</span>;
}
}
export const FIXTURE_ENTRYPOINT = {
... | 'different:' + x}, arg: {value: 2}},
{obj: {method: null}, arg: {value: 3}},
{obj: {notMethod: true}, arg: {value: 4}},
{obj: null, arg: {value: 5}}, // obj is null, short-circuits so arg.value is NOT evaluated
{obj: {method: x => 'test:' | ed:' + x}, arg: {value: 1}},
{obj: {method: x => | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-optional-call.js",
"language": "javascript",
"file_size": 976,
"cut_index": 582,
"middle_length": 52
} |
rt * as SharedRuntime from 'shared-runtime';
export function Component({a, b}) {
const item1 = useMemo(() => ({a}), [a]);
const item2 = useMemo(() => ({b}), [b]);
const items = useMemo(() => {
const items = [];
SharedRuntime.typedArrayPush(items, item1);
SharedRuntime.typedArrayPush(items, item2);
... | ion inputs={[a, b]} output={items} />
</>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 1, b: 0},
{a: 1, b: 1},
{a: 1, b: 2},
{a: 2, b: 2},
{a: 3, | ={items[1]} />
<SharedRuntime.ValidateMemoizat | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-provider-store-capture-namespace-import.tsx",
"language": "tsx",
"file_size": 889,
"cut_index": 547,
"middle_length": 52
} |
:false @validateExhaustiveMemoizationDependencies:false
import {useMemo} from 'react';
import {identity, makeObject_Primitives, mutate, useHook} from 'shared-runtime';
function Component(props) {
// With the feature disabled these variables are inferred as being mutated inside the useMemo block
const free = makeOb... |
const x = makeObject_Primitives();
x.value = props.value;
mutate(x, free, part);
return x;
}, [props.value]);
identity(free);
identity(part);
return object;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{value | pruned
useHook();
const object = useMemo(() => { | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-mabye-modified-free-variable-dont-preserve-memoization-guarantees.js",
"language": "javascript",
"file_size": 878,
"cut_index": 559,
"middle_length": 52
} |
NoSetStateInEffects @enableAllowSetStateFromRefsInEffects @loggerTestOnly @compilationMode:"infer"
import {useState, useRef, useEffect, useEffectEvent} from 'react';
function Component({x, y}) {
const previousXRef = useRef(null);
const previousYRef = useRef(null);
const [data, setData] = useState(null);
cons... | const previousX = previousXRef.current;
previousXRef.current = xx;
const previousY = previousYRef.current;
previousYRef.current = yy;
if (!areEqual(xx, previousX) || !areEqual(yy, previousY)) {
const data = load({x: xx, y: yy});
| const previousY = previousYRef.current;
previousYRef.current = y;
if (!areEqual(x, previousX) || !areEqual(y, previousY)) {
effectEvent();
}
}, [x, y]);
const effectEvent2 = useEffectEvent((xx, yy) => {
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/valid-setState-in-useEffect-via-useEffectEvent-with-ref.js",
"language": "javascript",
"file_size": 1372,
"cut_index": 524,
"middle_length": 229
} |
ksFollowRulesOfReact
function Component(props) {
const logEvent = useLogging(props.appId);
const [currentStep, setCurrentStep] = useState(0);
// onSubmit gets the same mutable range as `logEvent`, since that is called
// later. however, our validation uses direct aliasing to track function
// expressions whi... | ={{foo: 'bar'}} />;
case 1:
return <OtherComponent data={{foo: 'joe'}} onSubmit={onSubmit} />;
default:
// 1. logEvent's mutable range is extended to this instruction
logEvent('Invalid step');
return <OtherComponent data={nu | tep) {
case 0:
return <OtherComponent data | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/validate-no-set-state-in-render-uncalled-function-with-mutable-range-is-valid.js",
"language": "javascript",
"file_size": 881,
"cut_index": 559,
"middle_length": 52
} |
from 'react';
function Component(props) {
const items = props.items ? props.items.slice() : [];
const [state] = useState('');
return props.cond ? (
<div>{state}</div>
) : (
<div>
{items.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}
export const FIXTURE_E... | {id: 1, name: 'Bob'},
],
},
{
cond: true,
items: [
{id: 0, name: 'Alice'},
{id: 1, name: 'Bob'},
],
},
{
cond: false,
items: [
{id: 1, name: 'Bob'},
{id: 2, name: 'Claire | items: [
{id: 0, name: 'Alice'},
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-mutable-range-extending-into-ternary.js",
"language": "javascript",
"file_size": 865,
"cut_index": 529,
"middle_length": 52
} |
import {makeArray, Stringify, useIdentity} from 'shared-runtime';
/**
* Example showing that returned inner function expressions should not be
* typed with `freeze` effects.
* Also see repro-returned-inner-fn-mutates-context
*/
function Foo({b}) {
'use memo';
const fnFactory = () => {
/**
* This retu... | ole.log('b');
useIdentity();
const fn = fnFactory();
const arr = makeArray(b);
fn(arr);
return <Stringify cb={myVar} value={arr} shouldInvokeFns={true} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [{b: 1}],
sequentialRenders | ould be incorrect as it would mean
* inferring that calls to updaterFactory()() do not mutate its captured
* context.
*/
return () => {
myVar = () => console.log('a');
};
};
let myVar = () => cons | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-returned-inner-fn-reassigns-context.js",
"language": "javascript",
"file_size": 1020,
"cut_index": 512,
"middle_length": 229
} |
ableNewMutationAliasingModel
import {ValidateMemoization} from 'shared-runtime';
const Codes = {
en: {name: 'English'},
ja: {name: 'Japanese'},
ko: {name: 'Korean'},
zh: {name: 'Chinese'},
};
function Component(a) {
let keys;
if (a) {
keys = Object.keys(Codes);
} else {
return null;
}
const ... | <>
<ValidateMemoization inputs={[]} output={keys} onlyCheckCompiled={true} />
<ValidateMemoization
inputs={[]}
output={options}
onlyCheckCompiled={true}
/>
</>
);
}
export const FIXTURE_ENTRYPOINT = {
f | a mutation since it's a function expression. The new
// model understands that `code` is captured but not mutated.
const country = Codes[code];
return {
name: country.name,
code,
};
});
return (
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-separate-memoization-due-to-callback-capturing.js",
"language": "javascript",
"file_size": 1165,
"cut_index": 518,
"middle_length": 229
} |
lidateMemoization} from 'shared-runtime';
/**
* Fixture for granular iterator semantics:
* 1. ConditionallyMutate the iterator itself, depending on whether the iterator
* is a mutable iterator.
* 2. Capture effect on elements within the iterator.
*/
function Validate({x, input}) {
'use no memo';
return (
... | 'use memo';
/**
* We should be able to memoize {} separately from `x`.
*/
const x = Array.from([{}]);
useIdentity();
x.push([input]);
return <Validate x={x} input={input} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: useFoo,
params: [ | }
/>
</>
);
}
function useFoo(input) {
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/todo-granular-iterator-semantics.js",
"language": "javascript",
"file_size": 850,
"cut_index": 535,
"middle_length": 52
} |
ponent({a, b, cond, items}) {
try {
const x = a?.value;
// items.length is accessed WITHIN the ternary expression - throws if items is null
const y = cond ? b?.first : items.length;
const z = x && y;
return (
<div>
{String(x)}-{String(y)}-{String(z)}
</div>
);
} catch {
... | B2'},
cond: true,
items: [1, 2, 3],
},
{
a: {value: 'A'},
b: {first: 'B1', second: 'B2'},
cond: false,
items: [1, 2],
},
{a: null, b: {first: 'B1', second: 'B2'}, cond: true, items: [1, 2, 3]},
{a: {v | tems: [1, 2, 3],
},
],
sequentialRenders: [
{
a: {value: 'A'},
b: {first: 'B1', second: 'B2'},
cond: true,
items: [1, 2, 3],
},
{
a: {value: 'A'},
b: {first: 'B1', second: ' | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-multiple-value-blocks.js",
"language": "javascript",
"file_size": 1362,
"cut_index": 524,
"middle_length": 229
} |
useMemo} from 'react';
import {typedArrayPush, ValidateMemoization} from 'shared-runtime';
export function Component({a, b}) {
const item1 = useMemo(() => ({a}), [a]);
const item2 = useMemo(() => ({b}), [b]);
const items = useMemo(() => {
const items = [];
typedArrayPush(items, item1);
typedArrayPush... | ut={items} />
</>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 1, b: 0},
{a: 1, b: 1},
{a: 1, b: 2},
{a: 2, b: 2},
{a: 3, b: 2},
{a: 0, b: 0} | } />
<ValidateMemoization inputs={[a, b]} outp | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-provider-store-capture.tsx",
"language": "tsx",
"file_size": 838,
"cut_index": 520,
"middle_length": 52
} |
y, makeObject_Primitives, mutate, useHook} from 'shared-runtime';
function Component(props) {
// With the feature enabled these variables are inferred as frozen as of
// the useMemo call
const free = makeObject_Primitives();
const free2 = makeObject_Primitives();
const part = free2.part;
// Thus their mut... | ree, part);
return x;
}, [props.value, free, part]);
// These calls should be inferred as non-mutating due to the above freeze inference
identity(free);
identity(part);
return object;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
| itives();
x.value = props.value;
mutate(x, f | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-mabye-modified-free-variable-preserve-memoization-guarantees.js",
"language": "javascript",
"file_size": 942,
"cut_index": 606,
"middle_length": 52
} |
tringify} from 'shared-runtime';
/**
* Repro from https://github.com/facebook/react/issues/34262
*
* The compiler memoizes more precisely than the original code, with two reactive scopes:
* - One for `transform(input)` with `input` as dep
* - One for `{value}` with `value` as dep
*
* Previously ValidatePreserve... | function useInputValue(input) {
const object = React.useMemo(() => {
const {value} = identity(input);
return {value};
}, [input]);
return object;
}
function Component() {
return <Stringify value={useInputValue({value: 42}).value} />;
}
ex | on is the second scope which depends on `value`
*/
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-preserve-memoization-inner-destructured-value-mistaken-as-dependency.js",
"language": "javascript",
"file_size": 960,
"cut_index": 582,
"middle_length": 52
} |
r the ideal scopes, not what is currently
// emitted
function foo(props) {
// scope 0: deps=[props.a] decl=[x] reassign=none
let x = [];
x.push(props.a);
// scope 1: deps=[x] decl=[header] reassign=none
const header = props.showHeader ? <div>{x}</div> : null;
// scope 2:
// deps=[x, props.b, props.c]
... | pe 3 ...
const content = (
<div>
{x}
{y}
</div>
);
// scope 4 ...
return (
<>
{header}
{content}
</>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: foo,
params: ['TodoAdd'],
isComponent: 'TodoAdd',
}; | tion
// sco | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/same-variable-as-dep-and-redeclare-maybe-frozen.js",
"language": "javascript",
"file_size": 807,
"cut_index": 536,
"middle_length": 14
} |
function Component({data, fallback}) {
try {
// fallback.default is accessed WITHIN the optional chain via nullish coalescing
const value = data?.nested?.deeply?.value ?? fallback.default;
return <div>{value}</div>;
} catch {
return <div>error</div>;
}
}
export const FIXTURE_ENTRYPOINT = {
fn: ... | ult: 'none'}}, // uses fallback.default
{data: {nested: null}, fallback: {default: 'none'}}, // uses fallback.default
{data: null, fallback: null}, // errors because fallback.default throws
{data: {nested: {deeply: {value: 42}}}, fallback: {def | fault: 'none'}},
{data: {nested: {deeply: {value: 'found'}}}, fallback: {default: 'none'}},
{data: {nested: {deeply: {value: 'changed'}}}, fallback: {default: 'none'}},
{data: {nested: {deeply: null}}, fallback: {defa | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-nested-optional-chaining.js",
"language": "javascript",
"file_size": 1021,
"cut_index": 512,
"middle_length": 229
} |
import {useEffect, useState} from 'react';
/**
* Example of a function expression whose return value shouldn't have
* a "freeze" effect on all operands.
*
* This is because the function expression is passed to `useEffect` and
* thus is not a render function. `cleanedUp` is also created within
* the effect and is... | eanedUp = true;
setCleanupCount(c => c + 1);
}
};
}, [prop]);
return <div>{cleanupCount}</div>;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{prop: 5}],
sequentialRenders: [{prop: 5}, {prop: 5}, {prop: 6}],
};
| (!cleanedUp) {
cleanedUp = true;
setCleanupCount(c => c + 1);
}
}, 0);
// This return value should not have freeze effects
// on its operands
return () => {
if (!cleanedUp) {
cl | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-effect-cleanup-reassigns.js",
"language": "javascript",
"file_size": 997,
"cut_index": 512,
"middle_length": 229
} |
@enableNewMutationAliasingModel
import {identity, mutate} from 'shared-runtime';
/**
* Fixed in the new inference model.
*
* Bug: copy of error.todo-object-expression-computed-key-modified-during-after-construction-sequence-expr
* with the mutation hoisted to a named variable instead of being directly
* inlined i... | key = {};
const tmp = (mutate(key), key);
const context = {
// Here, `tmp` is frozen (as it's inferred to be a primitive/string)
[tmp]: identity([props.value]),
};
mutate(key);
return [context, key];
}
export const FIXTURE_ENTRYPOINT = { | ]},{"wat0":"joe","wat1":"joe"}]
* Forget:
* (kind: ok) [{"[object Object]":[42]},{"wat0":"joe","wat1":"joe"}]
* [{"[object Object]":[42]},{"wat0":"joe","wat1":"joe","wat2":"joe"}]
*/
function Component(props) {
const | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-object-expression-computed-key-modified-during-after-construction-hoisted-sequence-expr.js",
"language": "javascript",
"file_size": 1095,
"cut_index": 515,
"middle_length": 229
} |
ps) {
const x = {};
let y;
if (props.cond) {
if (props.cond2) {
y = [props.value];
} else {
y = [props.value2];
}
} else {
y = [];
}
// This should be inferred as `<store> y` s.t. `x` can still
// be independently memoized. *But* this also must properly
// extend the mutable ... | e, value: 3.14},
{cond: true, cond2: true, value: 42},
{cond: true, cond2: true, value: 3.14},
{cond: true, cond2: false, value2: 3.14},
{cond: true, cond2: false, value2: 42},
{cond: true, cond2: false, value2: 3.14},
{cond: false} | ,
sequentialRenders: [
{cond: true, cond2: tru | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/propagate-scope-deps-hir-fork/phi-type-inference-array-push-consecutive-phis.js",
"language": "javascript",
"file_size": 943,
"cut_index": 606,
"middle_length": 52
} |
**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {memo} from 'react';
export const IconGitHub = memo<JSX.IntrinsicElements['svg']>(
function IconGitHub(props) {
ret... | 11-4.55-4.94 0-1.1.39-1.99 1.03-2.69a3.6 3.6 0 0 1 .1-2.64s.84-.27 2.75 1.02a9.58 9.58 0 0 1 5 0c1.91-1.3 2.75-1.02 2.75-1.02.55 1.37.2 2.4.1 2.64.64.7 1.03 1.6 1.03 2.69 0 3.84-2.34 4.68-4.57 4.93.36.31.68.92.68 1.85l-.01 2.75c0 .26.18.58.69.48A10 10 0 0 | ath d="M10 0a10 10 0 0 0-3.16 19.49c.5.1.68-.22.68-.48l-.01-1.7c-2.78.6-3.37-1.34-3.37-1.34-.46-1.16-1.11-1.47-1.11-1.47-.9-.62.07-.6.07-.6 1 .07 1.53 1.03 1.53 1.03.9 1.52 2.34 1.08 2.91.83.1-.65.35-1.09.63-1.34-2.22-.25-4.55-1. | {
"filepath": "compiler/apps/playground/components/Icons/IconGitHub.tsx",
"language": "tsx",
"file_size": 1042,
"cut_index": 513,
"middle_length": 229
} |
ight (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import '../styles/globals.css';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}): JSX.Element {
'use... | <link rel="manifest" href="/site.webmanifest" />
<link
rel="preload"
href="/fonts/Source-Code-Pro-Regular.woff2"
as="font"
type="font/woff2"
crossOrigin="anonymous"
/>
<link
| ompiler Playground'}
</title>
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"></meta>
<link rel="icon" href="/favicon.ico" />
| {
"filepath": "compiler/apps/playground/app/layout.tsx",
"language": "tsx",
"file_size": 1287,
"cut_index": 524,
"middle_length": 229
} |
'shared-runtime';
/**
* Fixture to assert that we can infer the type and effects of an array created
* with `Array.from`.
*/
function Validate({x, val1, val2}) {
'use no memo';
return (
<>
<ValidateMemoization
inputs={[val1]}
output={x[0]}
onlyCheckCompiled={true}
/>
... | [val2]);
return <Validate x={x} val1={val1} val2={val2} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: useFoo,
params: [{val1: 1, val2: 2}],
params: [
{val1: 1, val2: 2},
{val1: 1, val2: 2},
{val1: 1, val2: 3},
{val1: 4, val2: 2},
| om([]);
useIdentity();
x.push([val1]);
x.push( | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-inference-array-from.js",
"language": "javascript",
"file_size": 874,
"cut_index": 559,
"middle_length": 52
} |
llowRulesOfReact @enableTransitivelyFreezeFunctionExpressions @validateExhaustiveMemoizationDependencies:false
import {useCallback} from 'react';
function Component({entity, children}) {
const showMessage = useCallback(() => entity != null);
// We currently model functions as if they could escape intor their retu... | in this instance.
const shouldShowMessage = showMessage();
return (
<div>
<div>{shouldShowMessage}</div>
<div>{children}</div>
</div>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [
{
entity: {nam | doesn't need to be memoized since it doesn't escape | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-nonescaping-invoked-callback-escaping-return.js",
"language": "javascript",
"file_size": 974,
"cut_index": 582,
"middle_length": 52
} |
ight (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as React from 'react';
import {render} from '@testing-library/react';
import {expectLogsAndClear, log} from './expectLogs';
functi... | World
</b>
<div>
Item 1
</div>
<div>
Item 2
</div>
<div>
Item 3
</div>
</div>
</DocumentFragment>
`);
expectLogsAndClear(['recomputing 1', 'recomput | {items}
</div>
);
}
test('hello', () => {
const {asFragment, rerender} = render(<Hello name="World" />);
expect(asFragment()).toMatchInlineSnapshot(`
<DocumentFragment>
<div>
Hello
<b>
| {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/e2e/hello.e2e.js",
"language": "javascript",
"file_size": 1504,
"cut_index": 524,
"middle_length": 229
} |
ight (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {render, screen, fireEvent} from '@testing-library/react';
import * as React from 'react';
import {expectLogsAndClear, log} from './e... | ue;
expect(f).toBe(props.value);
expect(value).toBe(props.value);
return <span>{value}</span>;
}
test('use-state', async () => {
const {asFragment, rerender} = render(<Counter value={0} />);
expect(asFragment()).toMatchInlineSnapshot(`
<Docu | ); // previous postfix operation + prefix operation
let c = ++value;
expect(c).toBe(props.value + 3);
let d = value--;
expect(d).toBe(props.value + 3);
let e = --value;
expect(e).toBe(props.value + 1);
let f = --val | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/e2e/update-expressions.e2e.js",
"language": "javascript",
"file_size": 1267,
"cut_index": 524,
"middle_length": 229
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Sync from <https://github.com/reactjs/reactjs.org/blob/main/beta/colors.js>.
*/
module.exports = {
// Text colors
primary: '#23272F', // gray-90
'primary-dark': '#F... | ay-10
'border-dark': '#343A46', // gray-80
'secondary-button': '#EBECF0', // gray-10
'secondary-button-dark': '#404756', // gray-70
// Gray
'gray-95': '#16181D',
'gray-90': '#23272F',
'gray-80': '#343A46',
'gray-70': '#404756',
'gray-60' | 0
wash: '#FFFFFF',
'wash-dark': '#23272F', // gray-90
card: '#F6F7F9', // gray-05
'card-dark': '#343A46', // gray-80
highlight: '#E6F7FF', // blue-10
'highlight-dark': 'rgba(88,175,223,.1)',
border: '#EBECF0', // gr | {
"filepath": "compiler/apps/playground/colors.js",
"language": "javascript",
"file_size": 2456,
"cut_index": 563,
"middle_length": 229
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {defineConfig, devices} from '@playwright/test';
import path from 'path';
// Use process.env.PORT by default and fallback to port 3000
const PORT = process.env.PORT || 300... | a test fails, retry it additional 2 times
retries: 3,
// Artifacts folder where screenshots, videos, and traces are stored.
outputDir: 'test-results/',
// Note: we only use text snapshots, so its safe to omit the host environment name
snapshotPat | cs/test-configuration
export default defineConfig({
// Timeout per test
timeout: 30 * 1000,
// Run all tests in parallel.
fullyParallel: true,
// Test directory
testDir: path.join(__dirname, '__tests__/e2e'),
// If | {
"filepath": "compiler/apps/playground/playwright.config.js",
"language": "javascript",
"file_size": 2842,
"cut_index": 563,
"middle_length": 229
} |
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const {execSync} = require('child_process');
// So that we don't need to check them into the repo.
// See https://github.com/re... | 'curl https://conf.reactjs.org/fonts/Optimistic_Display_W_Md.woff2 --output public/fonts/Optimistic_Display_W_Md.woff2'
);
execSync(
'curl https://conf.reactjs.org/fonts/Optimistic_Display_W_Bd.woff2 --output public/fonts/Optimistic_Display_W_Bd.woff2'
) | ;
execSync(
| {
"filepath": "compiler/apps/playground/scripts/downloadFonts.js",
"language": "javascript",
"file_size": 784,
"cut_index": 512,
"middle_length": 14
} |
MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {RefreshIcon, ShareIcon} from '@heroicons/react/outline';
import {CheckIcon} from '@heroicons/react/solid';
import clsx from 'clsx';
import Link from 'next/link';
import {useSnackbar} from 'notistack';
import {
useState,
... | useState(false);
const store = useStore();
const dispatchStore = useStoreDispatch();
const {enqueueSnackbar, closeSnackbar} = useSnackbar();
const handleReset: () => void = () => {
if (confirm('Are you sure you want to reset the playground?') | go from './Logo';
import {useStore, useStoreDispatch} from './StoreContext';
import {TOGGLE_INTERNALS_TRANSITION} from '../lib/transitionTypes';
export default function Header(): JSX.Element {
const [showCheck, setShowCheck] = | {
"filepath": "compiler/apps/playground/components/Header.tsx",
"language": "tsx",
"file_size": 4897,
"cut_index": 614,
"middle_length": 229
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {
BanIcon,
ExclamationIcon,
InformationCircleIcon,
XIcon,
} from '@heroicons/react/solid';
import {CustomContentProps, SnackbarContent, useSnackbar} from 'notistack... | tring;
level: MessageLevel;
source: MessageSource;
codeframe: string | undefined;
}
const Message = forwardRef<HTMLDivElement, MessageProps>(
({id, title, level, source, codeframe}, ref) => {
const {closeSnackbar} = useSnackbar();
const is | module 'notistack' {
interface VariantOverrides {
message: {
title: string;
level: MessageLevel;
codeframe: string | undefined;
};
}
}
interface MessageProps extends CustomContentProps {
title: s | {
"filepath": "compiler/apps/playground/components/Message.tsx",
"language": "tsx",
"file_size": 2867,
"cut_index": 563,
"middle_length": 229
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {Dispatch, ReactNode} from 'react';
import {useState, useEffect, useReducer} from 'react';
import createContext from '../lib/createContext';
import {emptyStore, defaul... | = StoreDispatchContext.useContext;
/**
* Make Store and dispatch function available to all sub-components in children.
*/
export function StoreProvider({children}: {children: ReactNode}): JSX.Element {
const [store, dispatch] = useReducer(storeReducer | access the store.
*/
export const useStore = StoreContext.useContext;
const StoreDispatchContext = createContext<Dispatch<ReducerAction>>();
/**
* Hook to access the store dispatch function.
*/
export const useStoreDispatch | {
"filepath": "compiler/apps/playground/components/StoreContext.tsx",
"language": "tsx",
"file_size": 2818,
"cut_index": 563,
"middle_length": 229
} |
oEditor, {loader, type Monaco} from '@monaco-editor/react';
import {
CompilerErrorDetail,
CompilerDiagnostic,
} from 'babel-plugin-react-compiler';
import invariant from 'invariant';
import type {editor} from 'monaco-editor';
import * as monaco from 'monaco-editor';
import {
useEffect,
useState,
unstable_View... | loading them with webpack.
import React$Types from '../../node_modules/@types/react/index.d.ts';
loader.config({monaco});
type Props = {
errors: Array<CompilerErrorDetail | CompilerDiagnostic>;
language: 'flow' | 'typescript';
};
export default fun | mport TabbedWindow from '../TabbedWindow';
import {monacoOptions} from './monacoOptions';
import {CONFIG_PANEL_TRANSITION} from '../../lib/transitionTypes';
// @ts-expect-error TODO: Make TS recognize .d.ts files, in addition to | {
"filepath": "compiler/apps/playground/components/Editor/Input.tsx",
"language": "tsx",
"file_size": 5433,
"cut_index": 716,
"middle_length": 229
} |
type CompilerError,
} from 'babel-plugin-react-compiler';
import parserBabel from 'prettier/plugins/babel';
import * as prettierPluginEstree from 'prettier/plugins/estree';
import * as prettier from 'prettier/standalone';
import {type Store} from '../../lib/stores';
import {
memo,
ReactNode,
use,
useState,
... | ON,
} from '../../lib/transitionTypes';
import {LRUCache} from 'lru-cache';
const MemoizedOutput = memo(Output);
export default MemoizedOutput;
export const BASIC_OUTPUT_TAB_NAMES = ['Output', 'SourceMap'];
const tabifyCache = new LRUCache<Store, Promi | mport TabbedWindow from '../TabbedWindow';
import {monacoOptions} from './monacoOptions';
import {BabelFileResult} from '@babel/core';
import {
CONFIG_PANEL_TRANSITION,
TOGGLE_INTERNALS_TRANSITION,
EXPAND_ACCORDION_TRANSITI | {
"filepath": "compiler/apps/playground/components/Editor/Output.tsx",
"language": "tsx",
"file_size": 11968,
"cut_index": 921,
"middle_length": 229
} |
ectness property.
// When propagating reactive dependencies of an inner scope up to its parent,
// we prefer to retain granularity.
//
// In this test, we check that Forget propagates the inner scope's conditional
// dependencies (e.g. props.a.b) instead of only its derived minimal
// unconditional dependencies (e.g. p... | RUE, setProperty} from 'shared-runtime';
function useJoinCondDepsInUncondScopes(props) {
let y = {};
let x = {};
if (CONST_TRUE) {
setProperty(x, props.a.b);
}
setProperty(y, props.a.b);
return [x, y];
}
export const FIXTURE_ENTRYPOINT = |
// mutate2(y, props.a.b);
// }
import {CONST_T | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/propagate-scope-deps-hir-fork/reduce-reactive-deps/join-uncond-scopes-cond-deps.js",
"language": "javascript",
"file_size": 957,
"cut_index": 582,
"middle_length": 52
} |
// @validateNoDerivedComputationsInEffects_exp @loggerTestOnly @outputMode:"lint"
function Component() {
const [foo, setFoo] = useState({});
const [bar, setBar] = useState(new Set());
/*
* isChanged is considered context of the effect's function expression,
* if we don't bail out of effect mutation deriva... | > {
let isChanged = false;
const newData = foo.map(val => {
bar.someMethod(val);
isChanged = true;
});
if (isChanged) {
setFoo(newData);
}
}, [foo, bar]);
return (
<div>
{foo}, {bar}
</div>
);
}
| useEffect(() = | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/effect-derived-computations/function-expression-mutation-edge-case.js",
"language": "javascript",
"file_size": 782,
"cut_index": 512,
"middle_length": 14
} |
from 'react';
import {Stringify} from 'shared-runtime';
/**
* TODO: we're currently bailing out because `contextVar` is a context variable
* and not recorded into the PropagateScopeDeps LoadLocal / PropertyLoad
* sidemap. Previously, we were able to avoid this as `BuildHIR` hoisted
* `LoadContext` and `PropertyLo... | mutable range.
*/
function Foo(props) {
let contextVar;
if (props.cond) {
contextVar = {val: 2};
} else {
contextVar = {};
}
const cb = useCallback(() => [contextVar.val], [contextVar.val]);
return <Stringify cb={cb} shouldInvokeFns= | nstruction occurs *after* the context
* variable's | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-captures-reassigned-context-property.tsx",
"language": "tsx",
"file_size": 980,
"cut_index": 582,
"middle_length": 52
} |
iates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as React from 'react';
import {render} from '@testing-library/react';
globalThis.constantValue = 'global test value';
test('literal-constant-propagation', () => {
fun... | st value 1
</div>
</DocumentFragment>
`);
});
test('global-constant-propagation', () => {
function Component() {
'use memo';
const x = constantValue;
return <div>{x}</div>;
}
const {asFragment, rerender} = render(<Component | apshot(`
<DocumentFragment>
<div>
test value 1
</div>
</DocumentFragment>
`);
rerender(<Component />);
expect(asFragment()).toMatchInlineSnapshot(`
<DocumentFragment>
<div>
te | {
"filepath": "compiler/packages/babel-plugin-react-compiler/src/__tests__/e2e/constant-prop.e2e.js",
"language": "javascript",
"file_size": 2781,
"cut_index": 563,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.