Compare commits

..

1 Commits

Author SHA1 Message Date
Joe Savona
cebe9dc9e2 [compiler] Update fixtures for new inference 2025-06-18 13:00:42 -07:00
79 changed files with 448 additions and 3625 deletions

View File

@@ -72,7 +72,7 @@ export function lower(
env: Environment,
// Bindings captured from the outer function, in case lower() is called recursively (for lambdas)
bindings: Bindings | null = null,
capturedRefs: Map<t.Identifier, SourceLocation> = new Map(),
capturedRefs: Array<t.Identifier> = [],
): Result<HIRFunction, CompilerError> {
const builder = new HIRBuilder(env, {
bindings,
@@ -80,13 +80,13 @@ export function lower(
});
const context: HIRFunction['context'] = [];
for (const [ref, loc] of capturedRefs ?? []) {
for (const ref of capturedRefs ?? []) {
context.push({
kind: 'Identifier',
identifier: builder.resolveBinding(ref),
effect: Effect.Unknown,
reactive: false,
loc,
loc: ref.loc ?? GeneratedSource,
});
}
@@ -3439,12 +3439,10 @@ function lowerFunction(
* This isn't a problem in practice because use Babel's scope analysis to
* identify the correct references.
*/
const lowering = lower(
expr,
builder.environment,
builder.bindings,
new Map([...builder.context, ...capturedContext]),
);
const lowering = lower(expr, builder.environment, builder.bindings, [
...builder.context,
...capturedContext,
]);
let loweredFunc: HIRFunction;
if (lowering.isErr()) {
lowering
@@ -4162,11 +4160,6 @@ function captureScopes({from, to}: {from: Scope; to: Scope}): Set<Scope> {
return scopes;
}
/**
* Returns a mapping of "context" identifiers — references to free variables that
* will become part of the function expression's `context` array — along with the
* source location of their first reference within the function.
*/
function gatherCapturedContext(
fn: NodePath<
| t.FunctionExpression
@@ -4175,8 +4168,8 @@ function gatherCapturedContext(
| t.ObjectMethod
>,
componentScope: Scope,
): Map<t.Identifier, SourceLocation> {
const capturedIds = new Map<t.Identifier, SourceLocation>();
): Array<t.Identifier> {
const capturedIds = new Set<t.Identifier>();
/*
* Capture all the scopes from the parent of this function up to and including
@@ -4219,15 +4212,8 @@ function gatherCapturedContext(
// Add the base identifier binding as a dependency.
const binding = baseIdentifier.scope.getBinding(baseIdentifier.node.name);
if (
binding !== undefined &&
pureScopes.has(binding.scope) &&
!capturedIds.has(binding.identifier)
) {
capturedIds.set(
binding.identifier,
path.node.loc ?? binding.identifier.loc ?? GeneratedSource,
);
if (binding !== undefined && pureScopes.has(binding.scope)) {
capturedIds.add(binding.identifier);
}
}
@@ -4264,7 +4250,7 @@ function gatherCapturedContext(
},
});
return capturedIds;
return [...capturedIds.keys()];
}
function notNull<T>(value: T | null): value is T {

View File

@@ -246,7 +246,7 @@ export const EnvironmentConfigSchema = z.object({
/**
* Enable a new model for mutability and aliasing inference
*/
enableNewMutationAliasingModel: z.boolean().default(true),
enableNewMutationAliasingModel: z.boolean().default(false),
/**
* Enables inference of optional dependency chains. Without this flag

View File

@@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {Effect, ValueKind, ValueReason} from './HIR';
import {Effect, makeIdentifierId, ValueKind, ValueReason} from './HIR';
import {
BUILTIN_SHAPES,
BuiltInArrayId,
@@ -34,6 +34,7 @@ import {
addFunction,
addHook,
addObject,
signatureArgument,
} from './ObjectShape';
import {BuiltInType, ObjectType, PolyType} from './Types';
import {TypeConfig} from './TypeSchema';
@@ -645,35 +646,35 @@ const REACT_APIS: Array<[string, BuiltInType]> = [
hookKind: 'useEffect',
returnValueKind: ValueKind.Frozen,
aliasing: {
receiver: '@receiver',
receiver: makeIdentifierId(0),
params: [],
rest: '@rest',
returns: '@returns',
temporaries: ['@effect'],
rest: makeIdentifierId(1),
returns: makeIdentifierId(2),
temporaries: [signatureArgument(3)],
effects: [
// Freezes the function and deps
{
kind: 'Freeze',
value: '@rest',
value: signatureArgument(1),
reason: ValueReason.Effect,
},
// Internally creates an effect object that captures the function and deps
{
kind: 'Create',
into: '@effect',
into: signatureArgument(3),
value: ValueKind.Frozen,
reason: ValueReason.KnownReturnSignature,
},
// The effect stores the function and dependencies
{
kind: 'Capture',
from: '@rest',
into: '@effect',
from: signatureArgument(1),
into: signatureArgument(3),
},
// Returns undefined
{
kind: 'Create',
into: '@returns',
into: signatureArgument(2),
value: ValueKind.Primitive,
reason: ValueReason.KnownReturnSignature,
},
@@ -905,7 +906,6 @@ export function installTypeConfig(
noAlias: typeConfig.noAlias === true,
mutableOnlyIfOperandsAreMutable:
typeConfig.mutableOnlyIfOperandsAreMutable === true,
aliasing: typeConfig.aliasing,
});
}
case 'hook': {
@@ -923,7 +923,6 @@ export function installTypeConfig(
),
returnValueKind: typeConfig.returnValueKind ?? ValueKind.Frozen,
noAlias: typeConfig.noAlias === true,
aliasing: typeConfig.aliasing,
});
}
case 'object': {

View File

@@ -1388,16 +1388,6 @@ export enum ValueReason {
*/
JsxCaptured = 'jsx-captured',
/**
* Argument to a hook
*/
HookCaptured = 'hook-captured',
/**
* Return value of a hook
*/
HookReturn = 'hook-return',
/**
* Passed to an effect
*/
@@ -1453,20 +1443,6 @@ export const ValueKindSchema = z.enum([
ValueKind.Context,
]);
export const ValueReasonSchema = z.enum([
ValueReason.Context,
ValueReason.Effect,
ValueReason.Global,
ValueReason.HookCaptured,
ValueReason.HookReturn,
ValueReason.JsxCaptured,
ValueReason.KnownReturnSignature,
ValueReason.Other,
ValueReason.ReactiveFunctionArgument,
ValueReason.ReducerState,
ValueReason.State,
]);
// The effect with which a value is modified.
export enum Effect {
// Default value: not allowed after lifetime inference

View File

@@ -106,7 +106,7 @@ export default class HIRBuilder {
#current: WipBlock;
#entry: BlockId;
#scopes: Array<Scope> = [];
#context: Map<t.Identifier, SourceLocation>;
#context: Array<t.Identifier>;
#bindings: Bindings;
#env: Environment;
#exceptionHandlerStack: Array<BlockId> = [];
@@ -121,7 +121,7 @@ export default class HIRBuilder {
return this.#env.nextIdentifierId;
}
get context(): Map<t.Identifier, SourceLocation> {
get context(): Array<t.Identifier> {
return this.#context;
}
@@ -137,13 +137,13 @@ export default class HIRBuilder {
env: Environment,
options?: {
bindings?: Bindings | null;
context?: Map<t.Identifier, SourceLocation>;
context?: Array<t.Identifier>;
entryBlockKind?: BlockKind;
},
) {
this.#env = env;
this.#bindings = options?.bindings ?? new Map();
this.#context = options?.context ?? new Map();
this.#context = options?.context ?? [];
this.#entry = makeBlockId(env.nextBlockId);
this.#current = newBlock(this.#entry, options?.entryBlockKind ?? 'block');
}

View File

@@ -6,18 +6,14 @@
*/
import {CompilerError} from '../CompilerError';
import {AliasingEffect, AliasingSignature} from '../Inference/AliasingEffects';
import {assertExhaustive} from '../Utils/utils';
import {AliasingSignature} from '../Inference/AliasingEffects';
import {
Effect,
GeneratedSource,
Hole,
makeDeclarationId,
makeIdentifierId,
makeInstructionId,
Place,
SourceLocation,
SpreadPattern,
ValueKind,
ValueReason,
} from './HIR';
@@ -29,7 +25,6 @@ import {
PolyType,
PrimitiveType,
} from './Types';
import {AliasingEffectConfig, AliasingSignatureConfig} from './TypeSchema';
/*
* This file exports types and defaults for JavaScript object shapes. These are
@@ -58,20 +53,13 @@ function createAnonId(): string {
export function addFunction(
registry: ShapeRegistry,
properties: Iterable<[string, BuiltInType | PolyType]>,
fn: Omit<FunctionSignature, 'hookKind' | 'aliasing'> & {
aliasing?: AliasingSignatureConfig | null | undefined;
},
fn: Omit<FunctionSignature, 'hookKind'>,
id: string | null = null,
isConstructor: boolean = false,
): FunctionType {
const shapeId = id ?? createAnonId();
const aliasing =
fn.aliasing != null
? parseAliasingSignatureConfig(fn.aliasing, '<builtin>', GeneratedSource)
: null;
addShape(registry, shapeId, properties, {
...fn,
aliasing,
hookKind: null,
});
return {
@@ -89,18 +77,11 @@ export function addFunction(
*/
export function addHook(
registry: ShapeRegistry,
fn: Omit<FunctionSignature, 'aliasing'> & {
hookKind: HookKind;
aliasing?: AliasingSignatureConfig | null | undefined;
},
fn: FunctionSignature & {hookKind: HookKind},
id: string | null = null,
): FunctionType {
const shapeId = id ?? createAnonId();
const aliasing =
fn.aliasing != null
? parseAliasingSignatureConfig(fn.aliasing, '<builtin>', GeneratedSource)
: null;
addShape(registry, shapeId, [], {...fn, aliasing});
addShape(registry, shapeId, [], fn);
return {
kind: 'Function',
return: fn.returnType,
@@ -109,129 +90,6 @@ export function addHook(
};
}
function parseAliasingSignatureConfig(
typeConfig: AliasingSignatureConfig,
moduleName: string,
loc: SourceLocation,
): AliasingSignature {
const lifetimes = new Map<string, Place>();
function define(temp: string): Place {
CompilerError.invariant(!lifetimes.has(temp), {
reason: `Invalid type configuration for module`,
description: `Expected aliasing signature to have unique names for receiver, params, rest, returns, and temporaries in module '${moduleName}'`,
loc,
});
const place = signatureArgument(lifetimes.size);
lifetimes.set(temp, place);
return place;
}
function lookup(temp: string): Place {
const place = lifetimes.get(temp);
CompilerError.invariant(place != null, {
reason: `Invalid type configuration for module`,
description: `Expected aliasing signature effects to reference known names from receiver/params/rest/returns/temporaries, but '${temp}' is not a known name in '${moduleName}'`,
loc,
});
return place;
}
const receiver = define(typeConfig.receiver);
const params = typeConfig.params.map(define);
const rest = typeConfig.rest != null ? define(typeConfig.rest) : null;
const returns = define(typeConfig.returns);
const temporaries = typeConfig.temporaries.map(define);
const effects = typeConfig.effects.map(
(effect: AliasingEffectConfig): AliasingEffect => {
switch (effect.kind) {
case 'CreateFrom':
case 'Capture':
case 'Alias':
case 'Assign': {
const from = lookup(effect.from);
const into = lookup(effect.into);
return {
kind: effect.kind,
from,
into,
};
}
case 'Mutate':
case 'MutateTransitiveConditionally': {
const value = lookup(effect.value);
return {kind: effect.kind, value};
}
case 'Create': {
const into = lookup(effect.into);
return {
kind: 'Create',
into,
reason: effect.reason,
value: effect.value,
};
}
case 'Freeze': {
const value = lookup(effect.value);
return {
kind: 'Freeze',
value,
reason: effect.reason,
};
}
case 'Impure': {
const place = lookup(effect.place);
return {
kind: 'Impure',
place,
error: CompilerError.throwTodo({
reason: 'Support impure effect declarations',
loc: GeneratedSource,
}),
};
}
case 'Apply': {
const receiver = lookup(effect.receiver);
const fn = lookup(effect.function);
const args: Array<Place | SpreadPattern | Hole> = effect.args.map(
arg => {
if (typeof arg === 'string') {
return lookup(arg);
} else if (arg.kind === 'Spread') {
return {kind: 'Spread', place: lookup(arg.place)};
} else {
return arg;
}
},
);
const into = lookup(effect.into);
return {
kind: 'Apply',
receiver,
function: fn,
mutatesFunction: effect.mutatesFunction,
args,
into,
loc,
signature: null,
};
}
default: {
assertExhaustive(
effect,
`Unexpected effect kind '${(effect as any).kind}'`,
);
}
}
},
);
return {
receiver: receiver.identifier.id,
params: params.map(p => p.identifier.id),
rest: rest != null ? rest.identifier.id : null,
returns: returns.identifier.id,
temporaries,
effects,
};
}
/*
* Add an object to an existing ShapeRegistry.
*
@@ -334,7 +192,8 @@ export type FunctionSignature = {
canonicalName?: string;
aliasing?: AliasingSignature | null | undefined;
aliasing?: AliasingSignature | null;
todo_aliasing?: AliasingSignature | null;
};
/*
@@ -461,24 +320,24 @@ addObject(BUILTIN_SHAPES, BuiltInArrayId, [
calleeEffect: Effect.Store,
returnValueKind: ValueKind.Primitive,
aliasing: {
receiver: '@receiver',
receiver: makeIdentifierId(0),
params: [],
rest: '@rest',
returns: '@returns',
rest: makeIdentifierId(1),
returns: makeIdentifierId(2),
temporaries: [],
effects: [
// Push directly mutates the array itself
{kind: 'Mutate', value: '@receiver'},
{kind: 'Mutate', value: signatureArgument(0)},
// The arguments are captured into the array
{
kind: 'Capture',
from: '@rest',
into: '@receiver',
from: signatureArgument(1),
into: signatureArgument(0),
},
// Returns the new length, a primitive
{
kind: 'Create',
into: '@returns',
into: signatureArgument(2),
value: ValueKind.Primitive,
reason: ValueReason.KnownReturnSignature,
},
@@ -515,56 +374,58 @@ addObject(BUILTIN_SHAPES, BuiltInArrayId, [
noAlias: true,
mutableOnlyIfOperandsAreMutable: true,
aliasing: {
receiver: '@receiver',
params: ['@callback'],
receiver: makeIdentifierId(0),
params: [makeIdentifierId(1)],
rest: null,
returns: '@returns',
returns: makeIdentifierId(2),
temporaries: [
// Temporary representing captured items of the receiver
'@item',
signatureArgument(3),
// Temporary representing the result of the callback
'@callbackReturn',
signatureArgument(4),
/*
* Undefined `this` arg to the callback. Note the signature does not
* support passing an explicit thisArg second param
*/
'@thisArg',
signatureArgument(5),
],
effects: [
// Map creates a new mutable array
{
kind: 'Create',
into: '@returns',
into: signatureArgument(2),
value: ValueKind.Mutable,
reason: ValueReason.KnownReturnSignature,
},
// The first arg to the callback is an item extracted from the receiver array
{
kind: 'CreateFrom',
from: '@receiver',
into: '@item',
from: signatureArgument(0),
into: signatureArgument(3),
},
// The undefined this for the callback
{
kind: 'Create',
into: '@thisArg',
into: signatureArgument(5),
value: ValueKind.Primitive,
reason: ValueReason.KnownReturnSignature,
},
// calls the callback, returning the result into a temporary
{
kind: 'Apply',
receiver: '@thisArg',
args: ['@item', {kind: 'Hole'}, '@receiver'],
function: '@callback',
into: '@callbackReturn',
receiver: signatureArgument(5),
args: [signatureArgument(3), {kind: 'Hole'}, signatureArgument(0)],
function: signatureArgument(1),
into: signatureArgument(4),
signature: null,
mutatesFunction: false,
loc: GeneratedSource,
},
// captures the result of the callback into the return array
{
kind: 'Capture',
from: '@callbackReturn',
into: '@returns',
from: signatureArgument(4),
into: signatureArgument(2),
},
],
},
@@ -716,28 +577,28 @@ addObject(BUILTIN_SHAPES, BuiltInSetId, [
// returnValueKind is technically dependent on the ValueKind of the set itself
returnValueKind: ValueKind.Mutable,
aliasing: {
receiver: '@receiver',
receiver: makeIdentifierId(0),
params: [],
rest: '@rest',
returns: '@returns',
rest: makeIdentifierId(1),
returns: makeIdentifierId(2),
temporaries: [],
effects: [
// Set.add returns the receiver Set
{
kind: 'Assign',
from: '@receiver',
into: '@returns',
from: signatureArgument(0),
into: signatureArgument(2),
},
// Set.add mutates the set itself
{
kind: 'Mutate',
value: '@receiver',
value: signatureArgument(0),
},
// Captures the rest params into the set
{
kind: 'Capture',
from: '@rest',
into: '@receiver',
from: signatureArgument(1),
into: signatureArgument(0),
},
],
},
@@ -1441,34 +1302,6 @@ export const DefaultNonmutatingHook = addHook(
calleeEffect: Effect.Read,
hookKind: 'Custom',
returnValueKind: ValueKind.Frozen,
aliasing: {
receiver: '@receiver',
params: [],
rest: '@rest',
returns: '@returns',
temporaries: [],
effects: [
// Freeze the arguments
{
kind: 'Freeze',
value: '@rest',
reason: ValueReason.HookCaptured,
},
// Returns a frozen value
{
kind: 'Create',
into: '@returns',
value: ValueKind.Frozen,
reason: ValueReason.HookReturn,
},
// May alias any arguments into the return
{
kind: 'Alias',
from: '@rest',
into: '@returns',
},
],
},
},
'DefaultNonmutatingHook',
);

View File

@@ -8,12 +8,7 @@
import {isValidIdentifier} from '@babel/types';
import {z} from 'zod';
import {Effect, ValueKind} from '..';
import {
EffectSchema,
ValueKindSchema,
ValueReason,
ValueReasonSchema,
} from './HIR';
import {EffectSchema, ValueKindSchema} from './HIR';
export type ObjectPropertiesConfig = {[key: string]: TypeConfig};
export const ObjectPropertiesSchema: z.ZodType<ObjectPropertiesConfig> = z
@@ -36,194 +31,6 @@ export const ObjectTypeSchema: z.ZodType<ObjectTypeConfig> = z.object({
properties: ObjectPropertiesSchema.nullable(),
});
export const LifetimeIdSchema = z.string().refine(id => id.startsWith('@'), {
message: "Placeholder names must start with '@'",
});
export type FreezeEffectConfig = {
kind: 'Freeze';
value: string;
reason: ValueReason;
};
export const FreezeEffectSchema: z.ZodType<FreezeEffectConfig> = z.object({
kind: z.literal('Freeze'),
value: LifetimeIdSchema,
reason: ValueReasonSchema,
});
export type MutateEffectConfig = {
kind: 'Mutate';
value: string;
};
export const MutateEffectSchema: z.ZodType<MutateEffectConfig> = z.object({
kind: z.literal('Mutate'),
value: LifetimeIdSchema,
});
export type MutateTransitiveConditionallyConfig = {
kind: 'MutateTransitiveConditionally';
value: string;
};
export const MutateTransitiveConditionallySchema: z.ZodType<MutateTransitiveConditionallyConfig> =
z.object({
kind: z.literal('MutateTransitiveConditionally'),
value: LifetimeIdSchema,
});
export type CreateEffectConfig = {
kind: 'Create';
into: string;
value: ValueKind;
reason: ValueReason;
};
export const CreateEffectSchema: z.ZodType<CreateEffectConfig> = z.object({
kind: z.literal('Create'),
into: LifetimeIdSchema,
value: ValueKindSchema,
reason: ValueReasonSchema,
});
export type AssignEffectConfig = {
kind: 'Assign';
from: string;
into: string;
};
export const AssignEffectSchema: z.ZodType<AssignEffectConfig> = z.object({
kind: z.literal('Assign'),
from: LifetimeIdSchema,
into: LifetimeIdSchema,
});
export type AliasEffectConfig = {
kind: 'Alias';
from: string;
into: string;
};
export const AliasEffectSchema: z.ZodType<AliasEffectConfig> = z.object({
kind: z.literal('Alias'),
from: LifetimeIdSchema,
into: LifetimeIdSchema,
});
export type CaptureEffectConfig = {
kind: 'Capture';
from: string;
into: string;
};
export const CaptureEffectSchema: z.ZodType<CaptureEffectConfig> = z.object({
kind: z.literal('Capture'),
from: LifetimeIdSchema,
into: LifetimeIdSchema,
});
export type CreateFromEffectConfig = {
kind: 'CreateFrom';
from: string;
into: string;
};
export const CreateFromEffectSchema: z.ZodType<CreateFromEffectConfig> =
z.object({
kind: z.literal('CreateFrom'),
from: LifetimeIdSchema,
into: LifetimeIdSchema,
});
export type ApplyArgConfig =
| string
| {kind: 'Spread'; place: string}
| {kind: 'Hole'};
export const ApplyArgSchema: z.ZodType<ApplyArgConfig> = z.union([
LifetimeIdSchema,
z.object({
kind: z.literal('Spread'),
place: LifetimeIdSchema,
}),
z.object({
kind: z.literal('Hole'),
}),
]);
export type ApplyEffectConfig = {
kind: 'Apply';
receiver: string;
function: string;
mutatesFunction: boolean;
args: Array<ApplyArgConfig>;
into: string;
};
export const ApplyEffectSchema: z.ZodType<ApplyEffectConfig> = z.object({
kind: z.literal('Apply'),
receiver: LifetimeIdSchema,
function: LifetimeIdSchema,
mutatesFunction: z.boolean(),
args: z.array(ApplyArgSchema),
into: LifetimeIdSchema,
});
export type ImpureEffectConfig = {
kind: 'Impure';
place: string;
};
export const ImpureEffectSchema: z.ZodType<ImpureEffectConfig> = z.object({
kind: z.literal('Impure'),
place: LifetimeIdSchema,
});
export type AliasingEffectConfig =
| FreezeEffectConfig
| CreateEffectConfig
| CreateFromEffectConfig
| AssignEffectConfig
| AliasEffectConfig
| CaptureEffectConfig
| ImpureEffectConfig
| MutateEffectConfig
| MutateTransitiveConditionallyConfig
| ApplyEffectConfig;
export const AliasingEffectSchema: z.ZodType<AliasingEffectConfig> = z.union([
FreezeEffectSchema,
CreateEffectSchema,
CreateFromEffectSchema,
AssignEffectSchema,
AliasEffectSchema,
CaptureEffectSchema,
ImpureEffectSchema,
MutateEffectSchema,
MutateTransitiveConditionallySchema,
ApplyEffectSchema,
]);
export type AliasingSignatureConfig = {
receiver: string;
params: Array<string>;
rest: string | null;
returns: string;
effects: Array<AliasingEffectConfig>;
temporaries: Array<string>;
};
export const AliasingSignatureSchema: z.ZodType<AliasingSignatureConfig> =
z.object({
receiver: LifetimeIdSchema,
params: z.array(LifetimeIdSchema),
rest: LifetimeIdSchema.nullable(),
returns: LifetimeIdSchema,
effects: z.array(AliasingEffectSchema),
temporaries: z.array(LifetimeIdSchema),
});
export type FunctionTypeConfig = {
kind: 'function';
positionalParams: Array<Effect>;
@@ -235,7 +42,6 @@ export type FunctionTypeConfig = {
mutableOnlyIfOperandsAreMutable?: boolean | null | undefined;
impure?: boolean | null | undefined;
canonicalName?: string | null | undefined;
aliasing?: AliasingSignatureConfig | null | undefined;
};
export const FunctionTypeSchema: z.ZodType<FunctionTypeConfig> = z.object({
kind: z.literal('function'),
@@ -248,7 +54,6 @@ export const FunctionTypeSchema: z.ZodType<FunctionTypeConfig> = z.object({
mutableOnlyIfOperandsAreMutable: z.boolean().nullable().optional(),
impure: z.boolean().nullable().optional(),
canonicalName: z.string().nullable().optional(),
aliasing: AliasingSignatureSchema.nullable().optional(),
});
export type HookTypeConfig = {
@@ -258,7 +63,6 @@ export type HookTypeConfig = {
returnType: TypeConfig;
returnValueKind?: ValueKind | null | undefined;
noAlias?: boolean | null | undefined;
aliasing?: AliasingSignatureConfig | null | undefined;
};
export const HookTypeSchema: z.ZodType<HookTypeConfig> = z.object({
kind: z.literal('hook'),
@@ -267,7 +71,6 @@ export const HookTypeSchema: z.ZodType<HookTypeConfig> = z.object({
returnType: z.lazy(() => TypeSchema),
returnValueKind: ValueKindSchema.nullable().optional(),
noAlias: z.boolean().nullable().optional(),
aliasing: AliasingSignatureSchema.nullable().optional(),
});
export type BuiltInTypeConfig =

View File

@@ -8,7 +8,6 @@
import {CompilerErrorDetailOptions} from '../CompilerError';
import {
FunctionExpression,
GeneratedSource,
Hole,
IdentifierId,
ObjectMethod,
@@ -19,7 +18,6 @@ import {
ValueReason,
} from '../HIR';
import {FunctionSignature} from '../HIR/ObjectShape';
import {printSourceLocation} from '../HIR/PrintHIR';
/**
* `AliasingEffect` describes a set of "effects" that an instruction/terminal has on one or
@@ -202,19 +200,10 @@ export function hashEffect(effect: AliasingEffect): string {
return [effect.kind, effect.value.identifier.id, effect.reason].join(':');
}
case 'Impure':
case 'Render': {
return [effect.kind, effect.place.identifier.id].join(':');
}
case 'Render':
case 'MutateFrozen':
case 'MutateGlobal': {
return [
effect.kind,
effect.place.identifier.id,
effect.error.severity,
effect.error.reason,
effect.error.description,
printSourceLocation(effect.error.loc ?? GeneratedSource),
].join(':');
return [effect.kind, effect.place.identifier.id].join(':');
}
case 'Mutate':
case 'MutateConditionally':

View File

@@ -20,11 +20,10 @@ import {inferReactiveScopeVariables} from '../ReactiveScopes';
import {rewriteInstructionKindsBasedOnReassignment} from '../SSA';
import {inferMutableRanges} from './InferMutableRanges';
import inferReferenceEffects from './InferReferenceEffects';
import {assertExhaustive, retainWhere} from '../Utils/utils';
import {assertExhaustive} from '../Utils/utils';
import {inferMutationAliasingEffects} from './InferMutationAliasingEffects';
import {inferFunctionExpressionAliasingEffectsSignature} from './InferFunctionExpressionAliasingEffectsSignature';
import {inferMutationAliasingFunctionEffects} from './InferMutationAliasingFunctionEffects';
import {inferMutationAliasingRanges} from './InferMutationAliasingRanges';
import {hashEffect} from './AliasingEffects';
export default function analyseFunctions(func: HIRFunction): void {
for (const [_, block] of func.body.blocks) {
@@ -43,16 +42,8 @@ export default function analyseFunctions(func: HIRFunction): void {
* Reset mutable range for outer inferReferenceEffects
*/
for (const operand of instr.value.loweredFunc.func.context) {
/**
* NOTE: inferReactiveScopeVariables makes identifiers in the scope
* point to the *same* mutableRange instance. Resetting start/end
* here is insufficient, because a later mutation of the range
* for any one identifier could affect the range for other identifiers.
*/
operand.identifier.mutableRange = {
start: makeInstructionId(0),
end: makeInstructionId(0),
};
operand.identifier.mutableRange.start = makeInstructionId(0);
operand.identifier.mutableRange.end = makeInstructionId(0);
operand.identifier.scope = null;
}
break;
@@ -72,7 +63,7 @@ function lowerWithMutationAliasing(fn: HIRFunction): void {
inferMutationAliasingRanges(fn, {isFunctionExpression: true});
rewriteInstructionKindsBasedOnReassignment(fn);
inferReactiveScopeVariables(fn);
const effects = inferFunctionExpressionAliasingEffectsSignature(fn);
const effects = inferMutationAliasingFunctionEffects(fn);
fn.env.logger?.debugLogIRs?.({
kind: 'hir',
name: 'AnalyseFunction (inner)',
@@ -82,17 +73,6 @@ function lowerWithMutationAliasing(fn: HIRFunction): void {
fn.aliasingEffects ??= [];
fn.aliasingEffects?.push(...effects);
}
if (fn.aliasingEffects != null) {
const seen = new Set<string>();
retainWhere(fn.aliasingEffects, effect => {
const hash = hashEffect(effect);
if (seen.has(hash)) {
return false;
}
seen.add(hash);
return true;
});
}
/**
* Phase 2: populate the Effect of each context variable to use in inferring

View File

@@ -341,10 +341,6 @@ export function getWriteErrorReason(abstractValue: AbstractValue): string {
return "Mutating a value returned from 'useReducer()', which should not be mutated. Use the dispatch function to update instead";
} else if (abstractValue.reason.has(ValueReason.Effect)) {
return 'Updating a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the mutation before calling useEffect()';
} else if (abstractValue.reason.has(ValueReason.HookCaptured)) {
return 'Updating a value previously passed as an argument to a hook is not allowed. Consider moving the mutation before calling the hook';
} else if (abstractValue.reason.has(ValueReason.HookReturn)) {
return 'Updating a value returned from a hook is not allowed. Consider moving the mutation into the hook where the value is constructed';
} else {
return 'This mutates a variable that React considers immutable';
}

View File

@@ -38,7 +38,6 @@ import {
import {
eachInstructionValueLValue,
eachInstructionValueOperand,
eachTerminalOperand,
eachTerminalSuccessor,
} from '../HIR/visitors';
import {Ok, Result} from '../Utils/Result';
@@ -50,14 +49,12 @@ import {
} from './InferReferenceEffects';
import {
assertExhaustive,
getOrInsertDefault,
getOrInsertWith,
Set_isSuperset,
} from '../Utils/utils';
import {
printAliasingEffect,
printAliasingSignature,
printFunction,
printIdentifier,
printInstruction,
printInstructionValue,
@@ -197,15 +194,12 @@ export function inferMutationAliasingEffects(
let count = 0;
while (queuedStates.size !== 0) {
count++;
if (count > 100) {
if (count > 1000) {
console.log(
'oops infinite loop',
fn.id,
typeof fn.loc !== 'symbol' ? fn.loc?.filename : null,
);
if (DEBUG) {
console.log(printFunction(fn));
}
throw new Error('infinite loop');
}
for (const [blockId, block] of fn.body.blocks) {
@@ -217,11 +211,6 @@ export function inferMutationAliasingEffects(
statesByBlock.set(blockId, incomingState);
const state = incomingState.clone();
if (DEBUG) {
console.log('*************');
console.log(`bb${block.id}`);
console.log('*************');
}
inferBlock(context, state, block);
for (const nextBlockId of eachTerminalSuccessor(block.terminal)) {
@@ -232,19 +221,8 @@ export function inferMutationAliasingEffects(
return Ok(undefined);
}
function findHoistedContextDeclarations(
fn: HIRFunction,
): Map<DeclarationId, Place | null> {
const hoisted = new Map<DeclarationId, Place | null>();
function visit(place: Place): void {
if (
hoisted.has(place.identifier.declarationId) &&
hoisted.get(place.identifier.declarationId) == null
) {
// If this is the first load of the value, store the location
hoisted.set(place.identifier.declarationId, place);
}
}
function findHoistedContextDeclarations(fn: HIRFunction): Set<DeclarationId> {
const hoisted = new Set<DeclarationId>();
for (const block of fn.body.blocks.values()) {
for (const instr of block.instructions) {
if (instr.value.kind === 'DeclareContext') {
@@ -254,17 +232,10 @@ function findHoistedContextDeclarations(
kind == InstructionKind.HoistedFunction ||
kind == InstructionKind.HoistedLet
) {
hoisted.set(instr.value.lvalue.place.identifier.declarationId, null);
}
} else {
for (const operand of eachInstructionValueOperand(instr.value)) {
visit(operand);
hoisted.add(instr.value.lvalue.place.identifier.declarationId);
}
}
}
for (const operand of eachTerminalOperand(block.terminal)) {
visit(operand);
}
}
return hoisted;
}
@@ -274,40 +245,21 @@ class Context {
instructionSignatureCache: Map<Instruction, InstructionSignature> = new Map();
effectInstructionValueCache: Map<AliasingEffect, InstructionValue> =
new Map();
applySignatureCache: Map<
AliasingSignature,
Map<AliasingEffect, Array<AliasingEffect> | null>
> = new Map();
catchHandlers: Map<BlockId, Place> = new Map();
functionSignatureCache: Map<FunctionExpression, AliasingSignature> =
new Map();
isFuctionExpression: boolean;
fn: HIRFunction;
hoistedContextDeclarations: Map<DeclarationId, Place | null>;
hoistedContextDeclarations: Set<DeclarationId>;
constructor(
isFunctionExpression: boolean,
fn: HIRFunction,
hoistedContextDeclarations: Map<DeclarationId, Place | null>,
hoistedContextDeclarations: Set<DeclarationId>,
) {
this.isFuctionExpression = isFunctionExpression;
this.fn = fn;
this.hoistedContextDeclarations = hoistedContextDeclarations;
}
cacheApplySignature(
signature: AliasingSignature,
effect: Extract<AliasingEffect, {kind: 'Apply'}>,
f: () => Array<AliasingEffect> | null,
): Array<AliasingEffect> | null {
const inner = getOrInsertDefault(
this.applySignatureCache,
signature,
new Map(),
);
return getOrInsertWith(inner, effect, f);
}
internEffect(effect: AliasingEffect): AliasingEffect {
const hash = hashEffect(effect);
let interned = this.internedEffects.get(hash);
@@ -362,11 +314,6 @@ function inferBlock(
} else if (terminal.kind === 'maybe-throw') {
const handlerParam = context.catchHandlers.get(terminal.handler);
if (handlerParam != null) {
CompilerError.invariant(state.kind(handlerParam) != null, {
reason:
'Expected catch binding to be intialized with a DeclareLocal Catch instruction',
loc: terminal.loc,
});
const effects: Array<AliasingEffect> = [];
for (const instr of block.instructions) {
if (
@@ -386,13 +333,11 @@ function inferBlock(
state.appendAlias(handlerParam, instr.lvalue);
const kind = state.kind(instr.lvalue).kind;
if (kind === ValueKind.Mutable || kind == ValueKind.Context) {
effects.push(
context.internEffect({
kind: 'Alias',
from: instr.lvalue,
into: handlerParam,
}),
);
effects.push({
kind: 'Alias',
from: instr.lvalue,
into: handlerParam,
});
}
}
}
@@ -401,11 +346,11 @@ function inferBlock(
} else if (terminal.kind === 'return') {
if (!context.isFuctionExpression) {
terminal.effects = [
context.internEffect({
{
kind: 'Freeze',
value: terminal.value,
reason: ValueReason.JsxCaptured,
}),
},
];
}
}
@@ -481,14 +426,14 @@ function applySignature(
* Track which values we've already aliased once, so that we can switch to
* appendAlias() for subsequent aliases into the same value
*/
const initialized = new Set<IdentifierId>();
const aliased = new Set<IdentifierId>();
if (DEBUG) {
console.log(printInstruction(instruction));
}
for (const effect of signature.effects) {
applyEffect(context, state, effect, initialized, effects);
applyEffect(context, state, effect, aliased, effects);
}
if (DEBUG) {
console.log(
@@ -513,7 +458,7 @@ function applyEffect(
context: Context,
state: InferenceState,
_effect: AliasingEffect,
initialized: Set<IdentifierId>,
aliased: Set<IdentifierId>,
effects: Array<AliasingEffect>,
): void {
const effect = context.internEffect(_effect);
@@ -529,13 +474,6 @@ function applyEffect(
break;
}
case 'Create': {
CompilerError.invariant(!initialized.has(effect.into.identifier.id), {
reason: `Cannot re-initialize variable within an instruction`,
description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`,
loc: effect.into.loc,
});
initialized.add(effect.into.identifier.id);
let value = context.effectInstructionValueCache.get(effect);
if (value == null) {
value = {
@@ -550,7 +488,6 @@ function applyEffect(
reason: new Set([effect.reason]),
});
state.define(effect.into, value);
effects.push(effect);
break;
}
case 'ImmutableCapture': {
@@ -568,13 +505,6 @@ function applyEffect(
break;
}
case 'CreateFrom': {
CompilerError.invariant(!initialized.has(effect.into.identifier.id), {
reason: `Cannot re-initialize variable within an instruction`,
description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`,
loc: effect.into.loc,
});
initialized.add(effect.into.identifier.id);
const fromValue = state.kind(effect.from);
let value = context.effectInstructionValueCache.get(effect);
if (value == null) {
@@ -593,48 +523,29 @@ function applyEffect(
switch (fromValue.kind) {
case ValueKind.Primitive:
case ValueKind.Global: {
effects.push({
kind: 'Create',
value: fromValue.kind,
into: effect.into,
reason: [...fromValue.reason][0] ?? ValueReason.Other,
});
// no need to track this data flow
break;
}
case ValueKind.Frozen: {
effects.push({
kind: 'Create',
value: fromValue.kind,
kind: 'ImmutableCapture',
from: effect.from,
into: effect.into,
reason: [...fromValue.reason][0] ?? ValueReason.Other,
});
applyEffect(
context,
state,
{
kind: 'ImmutableCapture',
from: effect.from,
into: effect.into,
},
initialized,
effects,
);
break;
}
default: {
effects.push(effect);
effects.push({
// OK: recording information flow
kind: 'CreateFrom', // prev Alias
from: effect.from,
into: effect.into,
});
}
}
break;
}
case 'CreateFunction': {
CompilerError.invariant(!initialized.has(effect.into.identifier.id), {
reason: `Cannot re-initialize variable within an instruction`,
description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`,
loc: effect.into.loc,
});
initialized.add(effect.into.identifier.id);
effects.push(effect);
/**
* We consider the function mutable if it has any mutable context variables or
@@ -691,7 +602,7 @@ function applyEffect(
from: capture,
into: effect.into,
},
initialized,
aliased,
effects,
);
}
@@ -699,14 +610,6 @@ function applyEffect(
}
case 'Alias':
case 'Capture': {
CompilerError.invariant(
effect.kind === 'Capture' || initialized.has(effect.into.identifier.id),
{
reason: `Expected destination value to already be initialized within this instruction for Alias effect`,
description: `Destination ${printPlace(effect.into)} is not initialized in this instruction`,
loc: effect.into.loc,
},
);
/*
* Capture describes potential information flow: storing a pointer to one value
* within another. If the destination is not mutable, or the source value has
@@ -736,17 +639,11 @@ function applyEffect(
}
case ValueKind.Frozen: {
isMutableReferenceType = false;
applyEffect(
context,
state,
{
kind: 'ImmutableCapture',
from: effect.from,
into: effect.into,
},
initialized,
effects,
);
effects.push({
kind: 'ImmutableCapture',
from: effect.from,
into: effect.into,
});
break;
}
default: {
@@ -760,13 +657,6 @@ function applyEffect(
break;
}
case 'Assign': {
CompilerError.invariant(!initialized.has(effect.into.identifier.id), {
reason: `Cannot re-initialize variable within an instruction`,
description: `Re-initialized ${printPlace(effect.into)} in ${printAliasingEffect(effect)}`,
loc: effect.into.loc,
});
initialized.add(effect.into.identifier.id);
/*
* Alias represents potential pointer aliasing. If the type is a global,
* a primitive (copy-on-write semantics) then we can prune the effect
@@ -775,17 +665,11 @@ function applyEffect(
const fromKind = fromValue.kind;
switch (fromKind) {
case ValueKind.Frozen: {
applyEffect(
context,
state,
{
kind: 'ImmutableCapture',
from: effect.from,
into: effect.into,
},
initialized,
effects,
);
effects.push({
kind: 'ImmutableCapture',
from: effect.from,
into: effect.into,
});
let value = context.effectInstructionValueCache.get(effect);
if (value == null) {
value = {
@@ -821,7 +705,12 @@ function applyEffect(
break;
}
default: {
state.assign(effect.into, effect.from);
if (aliased.has(effect.into.identifier.id)) {
state.appendAlias(effect.into, effect.from);
} else {
aliased.add(effect.into.identifier.id);
state.alias(effect.into, effect.from);
}
effects.push(effect);
break;
}
@@ -838,33 +727,23 @@ function applyEffect(
* We're calling a locally declared function, we already know it's effects!
* We just have to substitute in the args for the params
*/
const functionExpr = functionValues[0];
let signature = context.functionSignatureCache.get(functionExpr);
if (signature == null) {
signature = buildSignatureFromFunctionExpression(
state.env,
functionExpr,
);
context.functionSignatureCache.set(functionExpr, signature);
}
const signature = buildSignatureFromFunctionExpression(
state.env,
functionValues[0],
);
if (DEBUG) {
console.log(
`constructed alias signature:\n${printAliasingSignature(signature)}`,
);
}
const signatureEffects = context.cacheApplySignature(
const signatureEffects = computeEffectsForSignature(
state.env,
signature,
effect,
() =>
computeEffectsForSignature(
state.env,
signature,
effect.into,
effect.receiver,
effect.args,
functionExpr.loweredFunc.func.context,
effect.loc,
),
effect.into,
effect.receiver,
effect.args,
functionValues[0].loweredFunc.func.context,
effect.loc,
);
if (signatureEffects != null) {
if (DEBUG) {
@@ -874,39 +753,33 @@ function applyEffect(
context,
state,
{kind: 'MutateTransitiveConditionally', value: effect.function},
initialized,
aliased,
effects,
);
for (const signatureEffect of signatureEffects) {
applyEffect(context, state, signatureEffect, initialized, effects);
applyEffect(context, state, signatureEffect, aliased, effects);
}
break;
}
}
let signatureEffects = null;
if (effect.signature?.aliasing != null) {
const signature = effect.signature.aliasing;
signatureEffects = context.cacheApplySignature(
effect.signature.aliasing,
effect,
() =>
computeEffectsForSignature(
const signatureEffects =
effect.signature?.aliasing != null
? computeEffectsForSignature(
state.env,
signature,
effect.signature.aliasing,
effect.into,
effect.receiver,
effect.args,
[],
effect.loc,
),
);
}
)
: null;
if (signatureEffects != null) {
if (DEBUG) {
console.log('apply aliasing signature effects');
}
for (const signatureEffect of signatureEffects) {
applyEffect(context, state, signatureEffect, initialized, effects);
applyEffect(context, state, signatureEffect, aliased, effects);
}
} else if (effect.signature != null) {
if (DEBUG) {
@@ -921,7 +794,7 @@ function applyEffect(
effect.loc,
);
for (const legacyEffect of legacyEffects) {
applyEffect(context, state, legacyEffect, initialized, effects);
applyEffect(context, state, legacyEffect, aliased, effects);
}
} else {
if (DEBUG) {
@@ -936,7 +809,7 @@ function applyEffect(
value: ValueKind.Mutable,
reason: ValueReason.Other,
},
initialized,
aliased,
effects,
);
/*
@@ -959,21 +832,21 @@ function applyEffect(
kind: 'MutateTransitiveConditionally',
value: operand,
},
initialized,
aliased,
effects,
);
}
const mutateIterator =
arg.kind === 'Spread' ? conditionallyMutateIterator(operand) : null;
if (mutateIterator) {
applyEffect(context, state, mutateIterator, initialized, effects);
applyEffect(context, state, mutateIterator, aliased, effects);
}
applyEffect(
context,
state,
// OK: recording information flow
{kind: 'Alias', from: operand, into: effect.into},
initialized,
aliased,
effects,
);
for (const otherArg of [
@@ -1001,7 +874,7 @@ function applyEffect(
from: operand,
into: other,
},
initialized,
aliased,
effects,
);
}
@@ -1028,89 +901,27 @@ function applyEffect(
console.log(prettyFormat(state.debugAbstractValue(value)));
}
if (
mutationKind === 'mutate-frozen' &&
context.hoistedContextDeclarations.has(
effect.value.identifier.declarationId,
)
) {
const description =
effect.value.identifier.name !== null &&
effect.value.identifier.name.kind === 'named'
? `Variable \`${effect.value.identifier.name.value}\` is accessed before it is declared`
: null;
const hoistedAccess = context.hoistedContextDeclarations.get(
effect.value.identifier.declarationId,
);
if (hoistedAccess != null && hoistedAccess.loc != effect.value.loc) {
applyEffect(
context,
state,
{
kind: 'MutateFrozen',
place: effect.value,
error: {
severity: ErrorSeverity.InvalidReact,
reason: `This variable is accessed before it is declared, which may prevent it from updating as the assigned value changes over time`,
description,
loc: hoistedAccess.loc,
suggestions: null,
},
},
initialized,
effects,
);
}
applyEffect(
context,
state,
{
kind: 'MutateFrozen',
place: effect.value,
error: {
severity: ErrorSeverity.InvalidReact,
reason: `This variable is accessed before it is declared, which prevents the earlier access from updating when this value changes over time`,
description,
loc: effect.value.loc,
suggestions: null,
},
},
initialized,
effects,
);
} else {
const reason = getWriteErrorReason({
kind: value.kind,
reason: value.reason,
context: new Set(),
});
const description =
effect.value.identifier.name !== null &&
effect.value.identifier.name.kind === 'named'
? `Found mutation of \`${effect.value.identifier.name.value}\``
: null;
applyEffect(
context,
state,
{
kind:
value.kind === ValueKind.Frozen
? 'MutateFrozen'
: 'MutateGlobal',
place: effect.value,
error: {
severity: ErrorSeverity.InvalidReact,
reason,
description,
loc: effect.value.loc,
suggestions: null,
},
},
initialized,
effects,
);
}
const reason = getWriteErrorReason({
kind: value.kind,
reason: value.reason,
context: new Set(),
});
effects.push({
kind:
value.kind === ValueKind.Frozen ? 'MutateFrozen' : 'MutateGlobal',
place: effect.value,
error: {
severity: ErrorSeverity.InvalidReact,
reason,
description:
effect.value.identifier.name !== null &&
effect.value.identifier.name.kind === 'named'
? `Found mutation of \`${effect.value.identifier.name.value}\``
: null,
loc: effect.value.loc,
suggestions: null,
},
});
}
break;
}
@@ -1214,7 +1025,7 @@ class InferenceState {
}
// Updates the value at @param place to point to the same value as @param value.
assign(place: Place, value: Place): void {
alias(place: Place, value: Place): void {
const values = this.#variables.get(value.identifier.id);
CompilerError.invariant(values != null, {
reason: `[InferMutationAliasingEffects] Expected value for identifier to be initialized`,
@@ -2148,17 +1959,28 @@ function computeEffectsForLegacySignature(
break;
}
case Effect.ConditionallyMutateIterator: {
const mutateIterator = conditionallyMutateIterator(place);
if (mutateIterator != null) {
effects.push(mutateIterator);
// TODO: should we always push to captures?
if (
isArrayType(place.identifier) ||
isSetType(place.identifier) ||
isMapType(place.identifier)
) {
effects.push({
kind: 'Capture',
from: place,
into: lvalue,
});
} else {
effects.push({
kind: 'Capture',
from: place,
into: lvalue,
});
captures.push(place);
effects.push({
kind: 'MutateTransitiveConditionally',
value: place,
});
}
effects.push({
kind: 'Capture',
from: place,
into: lvalue,
});
break;
}
case Effect.Freeze: {
@@ -2348,7 +2170,6 @@ function computeEffectsForSignature(
return null;
}
// Build substitutions
const mutableSpreads = new Set<IdentifierId>();
const substitutions: Map<IdentifierId, Array<Place>> = new Map();
substitutions.set(signature.receiver, [receiver]);
substitutions.set(signature.returns, [lvalue]);
@@ -2366,13 +2187,6 @@ function computeEffectsForSignature(
}
const place = arg.kind === 'Identifier' ? arg : arg.place;
getOrInsertWith(substitutions, signature.rest, () => []).push(place);
if (arg.kind === 'Spread') {
const mutateIterator = conditionallyMutateIterator(arg.place);
if (mutateIterator != null) {
mutableSpreads.add(arg.place.identifier.id);
}
}
} else {
const param = params[i];
substitutions.set(param, [arg]);
@@ -2444,12 +2258,6 @@ function computeEffectsForSignature(
case 'Freeze': {
const values = substitutions.get(effect.value.identifier.id) ?? [];
for (const value of values) {
if (mutableSpreads.has(value.identifier.id)) {
CompilerError.throwTodo({
reason: 'Support spread syntax for hook arguments',
loc: value.loc,
});
}
effects.push({kind: 'Freeze', value, reason: effect.reason});
}
break;

View File

@@ -28,7 +28,7 @@ import {AliasingEffect} from './AliasingEffects';
* This function *also* propagates more ambient-style effects (MutateFrozen, MutateGlobal, Impure, Render)
* from instructions within the function up to the function itself.
*/
export function inferFunctionExpressionAliasingEffectsSignature(
export function inferMutationAliasingFunctionEffects(
fn: HIRFunction,
): Array<AliasingEffect> | null {
const effects: Array<AliasingEffect> = [];

View File

@@ -25,7 +25,7 @@ import {
import {assertExhaustive, getOrInsertWith} from '../Utils/utils';
import {printFunction} from '../HIR';
import {printIdentifier, printPlace} from '../HIR/PrintHIR';
import {MutationKind} from './InferFunctionExpressionAliasingEffectsSignature';
import {MutationKind} from './InferMutationAliasingFunctionEffects';
import {Result} from '../Utils/Result';
const DEBUG = false;

View File

@@ -1,544 +0,0 @@
# The Mutability & Aliasing Model
This document describes the new (as of June 2025) mutability and aliasing model powering React Compiler. The mutability and aliasing system is a conceptual subcomponent whose primary role is to determine minimal sets of values that mutate together, and the range of instructions over which those mutations occur. These minimal sets of values that mutate together, and the corresponding instructions doing those mutations, are ultimately grouped into reactive scopes, which then translate into memoization blocks in the output (after substantial additional processing described in the comments of those passes).
To build an intuition, consider the following example:
```js
function Component() {
// a is created and mutated over the course of these two instructions:
const a = {};
mutate(a);
// b and c are created and mutated together — mutate might modify b via c
const b = {};
const c = {b};
mutate(c);
// does not modify a/b/c
return <Foo a={a} c={c} />
}
```
The goal of mutability and aliasing inference is to understand the set of instructions that create/modify a, b, and c.
In code, the mutability and aliasing model is compromised of the following phases:
* `InferMutationAliasingEffects`. Infers a set of mutation and aliasing effects for each instruction. The approach is to generate a set of candidate effects based purely on the semantics of each instruction and the types of the operands, then use abstract interpretation to determine the actual effects (or errros) that would apply. For example, an instruction that by default has a Capture effect might downgrade to an ImmutableCapture effect if the value is known to be frozen.
* `InferMutationAliasingRanges`. Infers a mutable range (start:end instruction ids) for each value in the program, and annotates each Place with its effect type for usage in later passes. This builds a graph of data flow through the program over time in order to understand which mutations effect which values.
* `InferReactiveScopeVariables`. Given the per-Place effects, determines disjoint sets of values that mutate together and assigns all identifiers in each set to a unique scope, and updates the range to include the ranges of all constituent values.
Finally, `AnalyzeFunctions` needs to understand the mutation and aliasing semantics of nested FunctionExpression and ObjectMethod values. `AnalyzeFunctions` calls `InferFunctionExpressionAliasingEffectsSignature` to determine the publicly observable set of mutation/aliasing effects for nested functions.
## Mutation and Aliasing Effects
The inference model is based on a set of "effects" that describe subtle aspects of mutation, aliasing, and other changes to the state of values over time
### Creation Effects
#### Create
```js
{
kind: 'Create';
into: Place;
value: ValueKind;
reason: ValueReason;
}
```
Describes the creation of a new value with the given kind, and reason for having that kind. For example, `x = 10` might have an effect like `Create x = ValueKind.Primitive [ValueReason.Other]`.
#### CreateFunction
```js
{
kind: 'CreateFunction';
captures: Array<Place>;
function: FunctionExpression | ObjectMethod;
into: Place;
}
```
Describes the creation of new function value, capturing the given set of mutable values. CreateFunction is used to specifically track function types so that we can precisely model calls to those functions with `Apply`.
#### Apply
```js
{
kind: 'Apply';
receiver: Place;
function: Place; // same as receiver for function calls
mutatesFunction: boolean; // indicates if this is a type that we consdier to mutate the function itself by default
args: Array<Place | SpreadPattern | Hole>;
into: Place; // where result is stored
signature: FunctionSignature | null;
}
```
Describes the potential creation of a value by calling a function. This models `new`, function calls, and method calls. The inference algorithm uses the most precise signature it can determine:
* If the function is a locally created function expression, we use a signature inferred from the behavior of that function to interpret the effects of calling it with the given arguments.
* Else if the function has a known aliasing signature (new style precise effects signature), we apply the arguments to that signature to get a precise set of effects.
* Else if the function has a legacy style signature (with per-param effects) we convert the legacy per-Place effects into aliasing effects (described in this doc) and apply those.
* Else fall back to inferring a generic set of effects.
The generic fallback is to assume:
- The return value may alias any of the arguments (Alias param -> return)
- Any arguments *may* be transitively mutated (MutateTransitiveConditionally param)
- Any argument may be captured into any other argument (Capture paramN -> paramM for all N,M where N != M)
### Aliasing Effects
These effects describe data-flow only, separately from mutation or other state-changing semantics.
#### Assign
```js
{
kind: 'Assign';
from: Place;
into: Place;
}
```
Describes an `x = y` assignment, where the receiving (into) value is overwritten with a new (from) value. After this effect, any previous assignments/aliases to the receiving value are dropped. Note that `Alias` initializes the receiving value.
> TODO: InferMutationAliasingRanges may not fully reset aliases on encountering this effect
#### Alias
```js
{
kind: 'Alias';
from: Place;
into: Place;
}
```
Describes that an assignment _may_ occur, but that the possible assignment is non-exclusive. The canonical use-case for `Alias` is a function that may return more than one of its arguments, such as `(x, y, z) => x ? y : z`. Here, the result of this function may be `y` or `z`, but neither one overwrites the other. Note that `Alias` does _not_ initialize the receiving value: it should always be paired with an effect to create the receiving value.
#### Capture
```js
{
kind: 'Capture';
from: Place;
into: Place;
}
```
Describes that a reference to one variable (from) is stored within another value (into). Examples include:
- An array expression captures the items of the array (`array = [capturedValue]`)
- Array.prototype.push captures the pushed values into the array (`array.push(capturedValue)`)
- Property assignment captures the value onto the object (`object.property = capturedValue`)
#### CreateFrom
```js
{
kind: 'CreateFrom';
from: Place;
into: Place;
}
```
This is somewhat the inverse of `Capture`. The `CreateFrom` effect describes that a variable is initialized by extracting _part_ of another value, without taking a direct alias to the full other value. Examples include:
- Indexing into an array (`createdFrom = array[0]`)
- Reading an object property (`createdFrom = object.property`)
- Getting a Map key (`createdFrom = map.get(key)`)
#### ImmutableCapture
Describes immutable data flow from one value to another. This is not currently used for anything, but is intended to eventually power a more sophisticated escape analysis.
### State-Changing Effects
The following effects describe state changes to specific values, not data flow. In many cases, JavaScript semantics will involve a combination of both data-flow effects *and* state-change effects. For example, `object.property = value` has data flow (`Capture object <- value`) and mutation (`Mutate object`).
#### Freeze
```js
{
kind: 'Freeze',
// The reference being frozen
value: Place;
// The reason the value is frozen (passed to a hook, passed to jsx, etc)
reason: ValueReason;
}
```
Once a reference to a value has been passed to React, that value is generally not safe to mutate further. This is not a strictly required property of React, but is a natural consequence of making components and hooks composable without leaking implementation details. Concretely, once a value has been passed as a JSX prop, passed as argument to a hook, or returned from a hook, it must be assumed that the other "side" — receiver of the prop/argument/return value — will use that value as an input to an effect or memoization unit. Mutating that value (instead of creating a new value) will fail to cause the consuming computation to update:
```js
// INVALID DO NOT DO THIS
function Component(props) {
const array = useArray(props.value);
// OOPS! this value is memoized, the array won't get re-created
// when `props.value` changes, so we might just keep pushing new
// values to the same array on every render!
array.push(props.otherValue);
}
function useArray(a) {
return useMemo(() => [a], [a]);
}
```
The **Freeze** effect accepts a variable reference and a reason that the value is being frozen. Note: _freeze only applies to the reference, not the underlying value_. Our inference is conservative, and assumes that there may still be other references to the same underlying value which are mutated later. For example:
```js
const x = {};
const y = [];
x.y = y;
freeze(y); // y _reference_ is frozen
x.y.push(props.value); // but y is still considered mutable bc of this
```
#### Mutate (and MutateConditionally)
```js
{
kind: 'Mutate';
value: Place;
}
```
Mutate indicates that a value is mutated, without modifying any of the values that it may transitively have captured. Canonical examples include:
- Pushing an item onto an array modifies the array, but does not modify any items stored _within_ the array (unless the array has a reference to itself!)
- Assigning a value to an object property modifies the object, but not any values stored in the object's other properties.
This helps explain the distinction between Assign/Alias and Capture: Mutate only affects assign/alias but not captures.
`MutateConditionally` is an alternative in which the mutation _may_ happen depending on the type of the value. The conditional variant is not generally used and included for completeness.
#### MutateTransitiveConditionally (and MutateTransitive)
`MutateTransitiveConditionally` represents an operation that may mutate _any_ aspect of a value, including reaching arbitrarily deep into nested values to mutate them. This is the default semantic for unknown functions — we have no idea what they do, so we assume that they are idempotent but may mutate any aspect of the mutable values that are passed to them.
There is also `MutateTransitive` for completeness, but this is not generally used.
### Side Effects
Finally, there are a few effects that describe error, or potential error, conditions:
- `MutateFrozen` is always an error, because it indicates known mutation of a value that should not be mutated.
- `MutateGlobal` indicates known mutation of a global value, which is not safe during render. This effect is an error if reachable during render, but allowed if only reachable via an event handler or useEffect.
- `Impure` indicates calling some other logic that is impure/side-effecting. This is an error if reachable during render, but allowed if only reachable via an event handler or useEffect.
- TODO: we could probably merge this and MutateGlobal
- `Render` indicates a value that is not mutated, but is known to be called during render. It's used for a few particular places like JSX tags and JSX children, which we assume are accessed during render (while other props may be event handlers etc). This helps to detect more MutateGlobal/Impure effects and reject more invalid programs.
## Rules
### Mutation of Alias Mutates the Source Value
```
Alias a <- b
Mutate a
=>
Mutate b
```
Example:
```js
const a = maybeIdentity(b); // Alias a <- b
a.property = value; // a could be b, so this mutates b
```
### Mutation of Assignment Mutates the Source Value
```
Assign a <- b
Mutate a
=>
Mutate b
```
Example:
```js
const a = b;
a.property = value // a _is_ b, this mutates b
```
### Mutation of CreateFrom Mutates the Source Value
```
CreateFrom a <- b
Mutate a
=>
Mutate b
```
Example:
```js
const a = b[index];
a.property = value // the contents of b are transitively mutated
```
### Mutation of Capture Does *Not* Mutate the Source Value
```
Capture a <- b
Mutate a
!=>
~Mutate b~
```
Example:
```js
const a = {};
a.b = b;
a.property = value; // mutates a, not b
```
### Mutation of Source Affects Alias, Assignment, CreateFrom, and Capture
```
Alias a <- b OR Assign a <- b OR CreateFrom a <- b OR Capture a <- b
Mutate b
=>
Mutate a
```
A derived value changes when it's source value is mutated.
Example:
```js
const x = {};
const y = [x];
x.y = true; // this changes the value within `y` ie mutates y
```
### TransitiveMutation of Alias, Assignment, CreateFrom, or Capture Mutates the Source
```
Alias a <- b OR Assign a <- b OR CreateFrom a <- b OR Capture a <- b
MutateTransitive a
=>
MutateTransitive b
```
Remember, the intuition for a transitive mutation is that it's something that could traverse arbitrarily deep into an object and mutate whatever it finds. Imagine something that recurses into every nested object/array and sets `.field = value`. Given a function `mutate()` that does this, then:
```js
const a = b; // assign
mutate(a); // clearly can transitively mutate b
const a = maybeIdentity(b); // alias
mutate(a); // clearly can transitively mutate b
const a = b[index]; // createfrom
mutate(a); // clearly can transitively mutate b
const a = {};
a.b = b; // capture
mutate(a); // can transitively mutate b
```
### Freeze Does Not Freeze the Value
Freeze does not freeze the value itself:
```
Create x
Assign y <- x OR Alias y <- x OR CreateFrom y <- x OR Capture y <- x
Freeze y
!=>
~Freeze x~
```
This means that subsequent mutations of the original value are valid:
```
Create x
Assign y <- x OR Alias y <- x OR CreateFrom y <- x OR Capture y <- x
Freeze y
Mutate x
=>
Mutate x (mutation is ok)
```
As well as mutations through other assignments/aliases/captures/createfroms of the original value:
```
Create x
Assign y <- x OR Alias y <- x OR CreateFrom y <- x OR Capture y <- x
Freeze y
Alias z <- x OR Capture z <- x OR CreateFrom z <- x OR Assign z <- x
Mutate z
=>
Mutate x (mutation is ok)
```
### Freeze Freezes The Reference
Although freeze doesn't freeze the value, it does affect the reference. The reference cannot be used to mutate.
Conditional mutations of the reference are no-ops:
```
Create x
Assign y <- x OR Alias y <- x OR CreateFrom y <- x OR Capture y <- x
Freeze y
MutateConditional y
=>
(no mutation)
```
And known mutations of the reference are errors:
```
Create x
Assign y <- x OR Alias y <- x OR CreateFrom y <- x OR Capture y <- x
Freeze y
MutateConditional y
=>
MutateFrozen y error=...
```
### Corollary: Transitivity of Assign/Alias/CreateFrom/Capture
A key part of the inference model is inferring a signature for function expressions. The signature is a minimal set of effects that describes the publicly observable behavior of the function. This can include "global" effects like side effects (MutateGlobal/Impure) as well as mutations/aliasing of parameters and free variables.
In order to determine the aliasing of params and free variables into each other and/or the return value, we may encounter chains of assign, alias, createfrom, and capture effects. For example:
```js
const f = (x) => {
const y = [x]; // capture y <- x
const z = y[0]; // createfrom z <- y
return z; // assign return <- z
}
// <Effect> return <- x
```
In this example we can see that there should be some effect on `f` that tracks the flow of data from `x` into the return value. The key constraint is preserving the semantics around how local/transitive mutations of the destination would affect the source.
#### Each of the effects is transitive with itself
```
Assign b <- a
Assign c <- b
=>
Assign c <- a
```
```
Alias b <- a
Alias c <- b
=>
Alias c <- a
```
```
CreateFrom b <- a
CreateFrom c <- b
=>
CreateFrom c <- a
```
```
Capture b <- a
Capture c <- b
=>
Capture c <- a
```
#### Alias > Assign
```
Assign b <- a
Alias c <- b
=>
Alias c <- a
```
```
Alias b <- a
Assign c <- b
=>
Alias c <- a
```
### CreateFrom > Assign/Alias
Intuition:
```
CreateFrom b <- a
Alias c <- b OR Assign c <- b
=>
CreateFrom c <- a
```
```
Alias b <- a OR Assign b <- a
CreateFrom c <- b
=>
CreateFrom c <- a
```
### Capture > Assign/Alias
Intuition: capturing means that a local mutation of the destination will not affect the source, so we preserve the capture.
```
Capture b <- a
Alias c <- b OR Assign c <- b
=>
Capture c <- a
```
```
Alias b <- a OR Assign b <- a
Capture c <- b
=>
Capture c <- a
```
### Capture And CreateFrom
Intuition: these effects are inverses of each other (capturing into an object, extracting from an object). The result is based on the order of operations:
Capture then CreatFrom is equivalent to Alias: we have to assume that the result _is_ the original value and that a local mutation of the result could mutate the original.
```js
const y = [x]; // capture
const z = y[0]; // createfrom
mutate(z); // this clearly can mutate x, so the result must be one of Assign/Alias/CreateFrom
```
We use Alias as the return type because the mutability kind of the result is not derived from the source value (there's a fresh object in between due to the capture), so the full set of effects in practice would be a Create+Alias.
```
Capture b <- a
CreateFrom c <- b
=>
Alias c <- a
```
Meanwhile the opposite direction preservers the capture, because the result is not the same as the source:
```js
const y = x[0]; // createfrom
const z = [y]; // capture
mutate(z); // does not mutate x, so the result must be Capture
```
```
Capture b <- a
CreateFrom c <- b
=>
Capture b <- a
```

View File

@@ -175,14 +175,21 @@ import {
* and mutability.
*/
function Component(t0) {
const $ = _c(2);
const $ = _c(4);
const { prop } = t0;
let t1;
if ($[0] !== prop) {
const obj = shallowCopy(prop);
const aliasedObj = identity(obj);
const id = [obj.id];
let t2;
if ($[2] !== obj) {
t2 = [obj.id];
$[2] = obj;
$[3] = t2;
} else {
t2 = $[3];
}
const id = t2;
mutate(aliasedObj);
setPropertyByKey(aliasedObj, "id", prop.id + 1);

View File

@@ -25,25 +25,17 @@ export const FIXTURE_ENTRYPOINT = {
```javascript
import { c as _c } from "react/compiler-runtime";
function bar(a) {
const $ = _c(4);
let t0;
if ($[0] !== a) {
t0 = [a];
$[0] = a;
$[1] = t0;
} else {
t0 = $[1];
}
const x = t0;
const $ = _c(2);
let y;
if ($[2] !== x[0][1]) {
if ($[0] !== a) {
const x = [a];
y = {};
y = x[0][1];
$[2] = x[0][1];
$[3] = y;
$[0] = a;
$[1] = y;
} else {
y = $[3];
y = $[1];
}
return y;
}

View File

@@ -29,29 +29,20 @@ export const FIXTURE_ENTRYPOINT = {
```javascript
import { c as _c } from "react/compiler-runtime";
function bar(a, b) {
const $ = _c(6);
let t0;
if ($[0] !== a || $[1] !== b) {
t0 = [a, b];
$[0] = a;
$[1] = b;
$[2] = t0;
} else {
t0 = $[2];
}
const x = t0;
const $ = _c(3);
let y;
if ($[3] !== x[0][1] || $[4] !== x[1][0]) {
if ($[0] !== a || $[1] !== b) {
const x = [a, b];
y = {};
let t = {};
y = x[0][1];
t = x[1][0];
$[3] = x[0][1];
$[4] = x[1][0];
$[5] = y;
$[0] = a;
$[1] = b;
$[2] = y;
} else {
y = $[5];
y = $[2];
}
return y;
}

View File

@@ -25,25 +25,17 @@ export const FIXTURE_ENTRYPOINT = {
```javascript
import { c as _c } from "react/compiler-runtime";
function bar(a) {
const $ = _c(4);
let t0;
if ($[0] !== a) {
t0 = [a];
$[0] = a;
$[1] = t0;
} else {
t0 = $[1];
}
const x = t0;
const $ = _c(2);
let y;
if ($[2] !== x[0].a[1]) {
if ($[0] !== a) {
const x = [a];
y = {};
y = x[0].a[1];
$[2] = x[0].a[1];
$[3] = y;
$[0] = a;
$[1] = y;
} else {
y = $[3];
y = $[1];
}
return y;
}

View File

@@ -24,25 +24,17 @@ export const FIXTURE_ENTRYPOINT = {
```javascript
import { c as _c } from "react/compiler-runtime";
function bar(a) {
const $ = _c(4);
let t0;
if ($[0] !== a) {
t0 = [a];
$[0] = a;
$[1] = t0;
} else {
t0 = $[1];
}
const x = t0;
const $ = _c(2);
let y;
if ($[2] !== x[0]) {
if ($[0] !== a) {
const x = [a];
y = {};
y = x[0];
$[2] = x[0];
$[3] = y;
$[0] = a;
$[1] = y;
} else {
y = $[3];
y = $[1];
}
return y;
}

View File

@@ -32,7 +32,7 @@ export const FIXTURE_ENTRYPOINT = {
11 | });
12 |
> 13 | x.value += count;
| ^ InvalidReact: Updating a value previously passed as an argument to a hook is not allowed. Consider moving the mutation before calling the hook (13:13)
| ^ InvalidReact: This mutates a variable that React considers immutable (13:13)
14 | return <Stringify x={x} cb={cb} />;
15 | }
16 |

View File

@@ -32,7 +32,7 @@ export const FIXTURE_ENTRYPOINT = {
11 | });
12 |
> 13 | x.value += count;
| ^ InvalidReact: Updating a value previously passed as an argument to a hook is not allowed. Consider moving the mutation before calling the hook (13:13)
| ^ InvalidReact: This mutates a variable that React considers immutable (13:13)
14 | return <Stringify x={x} cb={cb} />;
15 | }
16 |

View File

@@ -38,15 +38,13 @@ export const FIXTURE_ENTRYPOINT = {
## Error
```
17 | * $2 = Function context=setState
18 | */
> 19 | useEffect(() => setState(2), []);
| ^^^^^^^^ InvalidReact: This variable is accessed before it is declared, which may prevent it from updating as the assigned value changes over time. Variable `setState` is accessed before it is declared (19:19)
InvalidReact: This variable is accessed before it is declared, which prevents the earlier access from updating when this value changes over time. Variable `setState` is accessed before it is declared (21:21)
19 | useEffect(() => setState(2), []);
20 |
21 | const [state, setState] = useState(0);
> 21 | const [state, setState] = useState(0);
| ^^^^^^^^ InvalidReact: Updating a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the mutation before calling useEffect(). Found mutation of `setState` (21:21)
22 | return <Stringify state={state} />;
23 | }
24 |
```

View File

@@ -20,7 +20,7 @@ function Component() {
2 |
3 | function Component() {
> 4 | const date = Date.now();
| ^^^^^^^^^^ InvalidReact: Calling an impure function can produce unstable results. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent). `Date.now` is an impure function whose results may change on every call (4:4)
| ^^^^^^^^ InvalidReact: Calling an impure function can produce unstable results. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent). `Date.now` is an impure function whose results may change on every call (4:4)
InvalidReact: Calling an impure function can produce unstable results. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent). `performance.now` is an impure function whose results may change on every call (5:5)

View File

@@ -27,7 +27,7 @@ function SomeComponent() {
9 | return (
10 | <Button
> 11 | onPress={() => (sharedVal.value = Math.random())}
| ^^^^^^^^^ InvalidReact: Updating a value returned from a hook is not allowed. Consider moving the mutation into the hook where the value is constructed. Found mutation of `sharedVal` (11:11)
| ^^^^^^^^^ InvalidReact: Mutating a value returned from a function whose return value should not be mutated. Found mutation of `sharedVal` (11:11)
12 | title="Randomize"
13 | />
14 | );

View File

@@ -16,8 +16,6 @@ function useHook(a, b) {
1 | function useHook(a, b) {
> 2 | b.test = 1;
| ^ InvalidReact: Mutating component props or hook arguments is not allowed. Consider using a local variable instead (2:2)
InvalidReact: Mutating component props or hook arguments is not allowed. Consider using a local variable instead (3:3)
3 | a.test = 2;
4 | }
5 |

View File

@@ -21,8 +21,6 @@ function Component(props) {
4 | foo(() => {
> 5 | x.a = 10;
| ^ InvalidReact: Writing to a variable defined outside a component or hook is not allowed. Consider using an effect (5:5)
InvalidReact: Writing to a variable defined outside a component or hook is not allowed. Consider using an effect (6:6)
6 | x.a = 20;
7 | });
8 | }

View File

@@ -21,8 +21,6 @@ function Component() {
3 | // Cannot assign to globals
> 4 | someUnknownGlobal = true;
| ^^^^^^^^^^^^^^^^^ InvalidReact: Unexpected reassignment of a variable which was defined outside of the component. Components and hooks should be pure and side-effect free, but variable reassignment is a form of side-effect. If this variable is used in rendering, use useState instead. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render) (4:4)
InvalidReact: Unexpected reassignment of a variable which was defined outside of the component. Components and hooks should be pure and side-effect free, but variable reassignment is a form of side-effect. If this variable is used in rendering, use useState instead. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render) (5:5)
5 | moduleLocal = true;
6 | };
7 | foo();

View File

@@ -18,8 +18,6 @@ function Component() {
2 | // Cannot assign to globals
> 3 | someUnknownGlobal = true;
| ^^^^^^^^^^^^^^^^^ InvalidReact: Unexpected reassignment of a variable which was defined outside of the component. Components and hooks should be pure and side-effect free, but variable reassignment is a form of side-effect. If this variable is used in rendering, use useState instead. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render) (3:3)
InvalidReact: Unexpected reassignment of a variable which was defined outside of the component. Components and hooks should be pure and side-effect free, but variable reassignment is a form of side-effect. If this variable is used in rendering, use useState instead. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render) (4:4)
4 | moduleLocal = true;
5 | }
6 |

View File

@@ -22,7 +22,7 @@ function Component(props) {
7 | return hasErrors;
8 | }
> 9 | return hasErrors();
| ^^^^^^^^^ Invariant: [InferMutationAliasingEffects] Expected value kind to be initialized. <unknown> hasErrors_0$15:TFunction (9:9)
| ^^^^^^^^^ Invariant: [hoisting] Expected value for identifier to be initialized. hasErrors_0$15 (9:9)
10 | }
11 |
```

View File

@@ -34,13 +34,13 @@ export const FIXTURE_ENTRYPOINT = {
## Error
```
11 |
12 | function foo() {
> 13 | return bar();
| ^^^ Todo: [PruneHoistedContexts] Rewrite hoisted function references (13:13)
13 | return bar();
14 | }
15 | function bar() {
> 15 | function bar() {
| ^^^ Todo: [PruneHoistedContexts] Rewrite hoisted function references (15:15)
16 | return 42;
17 | }
18 |
```

View File

@@ -48,7 +48,7 @@ export const FIXTURE_ENTRYPOINT = {
## Logs
```
{"kind":"CompileError","fnLoc":{"start":{"line":5,"column":0,"index":139},"end":{"line":12,"column":1,"index":384},"filename":"mutate-after-useeffect-optional-chain.ts"},"detail":{"reason":"Updating a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the mutation before calling useEffect()","description":null,"severity":"InvalidReact","suggestions":null,"loc":{"start":{"line":10,"column":2,"index":345},"end":{"line":10,"column":5,"index":348},"filename":"mutate-after-useeffect-optional-chain.ts","identifierName":"arr"}}}
{"kind":"CompileError","fnLoc":{"start":{"line":5,"column":0,"index":139},"end":{"line":12,"column":1,"index":384},"filename":"mutate-after-useeffect-optional-chain.ts"},"detail":{"reason":"This mutates a variable that React considers immutable","description":null,"loc":{"start":{"line":10,"column":2,"index":345},"end":{"line":10,"column":5,"index":348},"filename":"mutate-after-useeffect-optional-chain.ts","identifierName":"arr"},"suggestions":null,"severity":"InvalidReact"}}
{"kind":"AutoDepsDecorations","fnLoc":{"start":{"line":9,"column":2,"index":304},"end":{"line":9,"column":39,"index":341},"filename":"mutate-after-useeffect-optional-chain.ts"},"decorations":[{"start":{"line":9,"column":24,"index":326},"end":{"line":9,"column":27,"index":329},"filename":"mutate-after-useeffect-optional-chain.ts","identifierName":"arr"}]}
{"kind":"CompileSuccess","fnLoc":{"start":{"line":5,"column":0,"index":139},"end":{"line":12,"column":1,"index":384},"filename":"mutate-after-useeffect-optional-chain.ts"},"fnName":"Component","memoSlots":0,"memoBlocks":0,"memoValues":0,"prunedMemoBlocks":0,"prunedMemoValues":0}
```

View File

@@ -47,7 +47,7 @@ export const FIXTURE_ENTRYPOINT = {
## Logs
```
{"kind":"CompileError","fnLoc":{"start":{"line":6,"column":0,"index":148},"end":{"line":11,"column":1,"index":311},"filename":"mutate-after-useeffect-ref-access.ts"},"detail":{"reason":"Mutating component props or hook arguments is not allowed. Consider using a local variable instead","description":null,"severity":"InvalidReact","suggestions":null,"loc":{"start":{"line":9,"column":2,"index":269},"end":{"line":9,"column":16,"index":283},"filename":"mutate-after-useeffect-ref-access.ts"}}}
{"kind":"CompileError","fnLoc":{"start":{"line":6,"column":0,"index":148},"end":{"line":11,"column":1,"index":311},"filename":"mutate-after-useeffect-ref-access.ts"},"detail":{"reason":"Mutating component props or hook arguments is not allowed. Consider using a local variable instead","description":null,"loc":{"start":{"line":9,"column":2,"index":269},"end":{"line":9,"column":16,"index":283},"filename":"mutate-after-useeffect-ref-access.ts"},"suggestions":null,"severity":"InvalidReact"}}
{"kind":"AutoDepsDecorations","fnLoc":{"start":{"line":8,"column":2,"index":227},"end":{"line":8,"column":40,"index":265},"filename":"mutate-after-useeffect-ref-access.ts"},"decorations":[{"start":{"line":8,"column":24,"index":249},"end":{"line":8,"column":30,"index":255},"filename":"mutate-after-useeffect-ref-access.ts","identifierName":"arrRef"}]}
{"kind":"CompileSuccess","fnLoc":{"start":{"line":6,"column":0,"index":148},"end":{"line":11,"column":1,"index":311},"filename":"mutate-after-useeffect-ref-access.ts"},"fnName":"Component","memoSlots":0,"memoBlocks":0,"memoValues":0,"prunedMemoBlocks":0,"prunedMemoValues":0}
```

View File

@@ -47,7 +47,7 @@ export const FIXTURE_ENTRYPOINT = {
## Logs
```
{"kind":"CompileError","fnLoc":{"start":{"line":4,"column":0,"index":101},"end":{"line":11,"column":1,"index":222},"filename":"mutate-after-useeffect.ts"},"detail":{"reason":"Updating a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the mutation before calling useEffect()","description":null,"severity":"InvalidReact","suggestions":null,"loc":{"start":{"line":9,"column":2,"index":194},"end":{"line":9,"column":5,"index":197},"filename":"mutate-after-useeffect.ts","identifierName":"arr"}}}
{"kind":"CompileError","fnLoc":{"start":{"line":4,"column":0,"index":101},"end":{"line":11,"column":1,"index":222},"filename":"mutate-after-useeffect.ts"},"detail":{"reason":"This mutates a variable that React considers immutable","description":null,"loc":{"start":{"line":9,"column":2,"index":194},"end":{"line":9,"column":5,"index":197},"filename":"mutate-after-useeffect.ts","identifierName":"arr"},"suggestions":null,"severity":"InvalidReact"}}
{"kind":"AutoDepsDecorations","fnLoc":{"start":{"line":6,"column":2,"index":149},"end":{"line":8,"column":4,"index":190},"filename":"mutate-after-useeffect.ts"},"decorations":[{"start":{"line":7,"column":4,"index":171},"end":{"line":7,"column":7,"index":174},"filename":"mutate-after-useeffect.ts","identifierName":"arr"},{"start":{"line":7,"column":4,"index":171},"end":{"line":7,"column":7,"index":174},"filename":"mutate-after-useeffect.ts","identifierName":"arr"},{"start":{"line":7,"column":13,"index":180},"end":{"line":7,"column":16,"index":183},"filename":"mutate-after-useeffect.ts","identifierName":"foo"}]}
{"kind":"CompileSuccess","fnLoc":{"start":{"line":4,"column":0,"index":101},"end":{"line":11,"column":1,"index":222},"filename":"mutate-after-useeffect.ts"},"fnName":"Component","memoSlots":0,"memoBlocks":0,"memoValues":0,"prunedMemoBlocks":0,"prunedMemoValues":0}
```

View File

@@ -52,7 +52,7 @@ export const FIXTURE_ENTRYPOINT = {
## Logs
```
{"kind":"CompileError","fnLoc":{"start":{"line":5,"column":0,"index":163},"end":{"line":13,"column":1,"index":357},"filename":"retry-no-emit.ts"},"detail":{"reason":"Updating a value previously passed as an argument to a hook is not allowed. Consider moving the mutation before calling the hook","description":null,"severity":"InvalidReact","suggestions":null,"loc":{"start":{"line":11,"column":2,"index":320},"end":{"line":11,"column":6,"index":324},"filename":"retry-no-emit.ts","identifierName":"arr2"}}}
{"kind":"CompileError","fnLoc":{"start":{"line":5,"column":0,"index":163},"end":{"line":13,"column":1,"index":357},"filename":"retry-no-emit.ts"},"detail":{"reason":"This mutates a variable that React considers immutable","description":null,"loc":{"start":{"line":11,"column":2,"index":320},"end":{"line":11,"column":6,"index":324},"filename":"retry-no-emit.ts","identifierName":"arr2"},"suggestions":null,"severity":"InvalidReact"}}
{"kind":"AutoDepsDecorations","fnLoc":{"start":{"line":7,"column":2,"index":216},"end":{"line":7,"column":36,"index":250},"filename":"retry-no-emit.ts"},"decorations":[{"start":{"line":7,"column":31,"index":245},"end":{"line":7,"column":34,"index":248},"filename":"retry-no-emit.ts","identifierName":"arr"}]}
{"kind":"AutoDepsDecorations","fnLoc":{"start":{"line":10,"column":2,"index":274},"end":{"line":10,"column":44,"index":316},"filename":"retry-no-emit.ts"},"decorations":[{"start":{"line":10,"column":25,"index":297},"end":{"line":10,"column":29,"index":301},"filename":"retry-no-emit.ts","identifierName":"arr2"},{"start":{"line":10,"column":25,"index":297},"end":{"line":10,"column":29,"index":301},"filename":"retry-no-emit.ts","identifierName":"arr2"},{"start":{"line":10,"column":35,"index":307},"end":{"line":10,"column":42,"index":314},"filename":"retry-no-emit.ts","identifierName":"propVal"}]}
{"kind":"CompileSuccess","fnLoc":{"start":{"line":5,"column":0,"index":163},"end":{"line":13,"column":1,"index":357},"filename":"retry-no-emit.ts"},"fnName":"Foo","memoSlots":0,"memoBlocks":0,"memoValues":0,"prunedMemoBlocks":0,"prunedMemoValues":0}

View File

@@ -34,28 +34,22 @@ import { print } from "shared-runtime";
* setState types are not enough to determine to omit from deps. Must also take reactivity into account.
*/
function ReactiveRefInEffect(props) {
const $ = _c(4);
const $ = _c(2);
const [, setState1] = useRef("initial value");
const [, setState2] = useRef("initial value");
let setState;
if ($[0] !== props.foo) {
if (props.foo) {
setState = setState1;
} else {
setState = setState2;
}
$[0] = props.foo;
$[1] = setState;
if (props.foo) {
setState = setState1;
} else {
setState = $[1];
setState = setState2;
}
let t0;
if ($[2] !== setState) {
if ($[0] !== setState) {
t0 = () => print(setState);
$[2] = setState;
$[3] = t0;
$[0] = setState;
$[1] = t0;
} else {
t0 = $[3];
t0 = $[1];
}
useEffect(t0, [setState]);
}

View File

@@ -58,62 +58,67 @@ import { Stringify } from "shared-runtime";
* - cb1 is not assumed to be called since it's only used as a call operand
*/
function useFoo(t0) {
const $ = _c(13);
const { arr1, arr2 } = t0;
const $ = _c(14);
let arr1;
let arr2;
let t1;
if ($[0] !== arr1[0]) {
t1 = (e) => arr1[0].value + e.value;
$[0] = arr1[0];
$[1] = t1;
if ($[0] !== t0) {
({ arr1, arr2 } = t0);
let t2;
if ($[4] !== arr1[0]) {
t2 = (e) => arr1[0].value + e.value;
$[4] = arr1[0];
$[5] = t2;
} else {
t2 = $[5];
}
const cb1 = t2;
t1 = () => arr1.map(cb1);
$[0] = t0;
$[1] = arr1;
$[2] = arr2;
$[3] = t1;
} else {
t1 = $[1];
arr1 = $[1];
arr2 = $[2];
t1 = $[3];
}
const cb1 = t1;
const getArrMap1 = t1;
let t2;
if ($[2] !== arr1 || $[3] !== cb1) {
t2 = () => arr1.map(cb1);
$[2] = arr1;
$[3] = cb1;
$[4] = t2;
if ($[6] !== arr2) {
t2 = (e_0) => arr2[0].value + e_0.value;
$[6] = arr2;
$[7] = t2;
} else {
t2 = $[4];
t2 = $[7];
}
const getArrMap1 = t2;
const cb2 = t2;
let t3;
if ($[5] !== arr2) {
t3 = (e_0) => arr2[0].value + e_0.value;
$[5] = arr2;
$[6] = t3;
if ($[8] !== arr1 || $[9] !== cb2) {
t3 = () => arr1.map(cb2);
$[8] = arr1;
$[9] = cb2;
$[10] = t3;
} else {
t3 = $[6];
t3 = $[10];
}
const cb2 = t3;
const getArrMap2 = t3;
let t4;
if ($[7] !== arr1 || $[8] !== cb2) {
t4 = () => arr1.map(cb2);
$[7] = arr1;
$[8] = cb2;
$[9] = t4;
} else {
t4 = $[9];
}
const getArrMap2 = t4;
let t5;
if ($[10] !== getArrMap1 || $[11] !== getArrMap2) {
t5 = (
if ($[11] !== getArrMap1 || $[12] !== getArrMap2) {
t4 = (
<Stringify
getArrMap1={getArrMap1}
getArrMap2={getArrMap2}
shouldInvokeFns={true}
/>
);
$[10] = getArrMap1;
$[11] = getArrMap2;
$[12] = t5;
$[11] = getArrMap1;
$[12] = getArrMap2;
$[13] = t4;
} else {
t5 = $[12];
t4 = $[13];
}
return t5;
return t4;
}
export const FIXTURE_ENTRYPOINT = {

View File

@@ -1,45 +0,0 @@
## Input
```javascript
//@flow @validatePreserveExistingMemoizationGuarantees @enableNewMutationAliasingModel
import {useCallback} from 'react';
import {useIdentity} from 'shared-runtime';
function Component({content, refetch}) {
// This callback function accesses a hoisted const as a dependency,
// but it cannot reference it as a dependency since that would be a
// TDZ violation!
const onRefetch = useCallback(() => {
refetch(data);
}, [refetch]);
// The context variable gets frozen here since it's passed to a hook
const onSubmit = useIdentity(onRefetch);
// This has to error: onRefetch needs to memoize with `content` as a
// dependency, but the dependency comes later
const {data = null} = content;
return <Foo data={data} onSubmit={onSubmit} />;
}
```
## Error
```
9 | // TDZ violation!
10 | const onRefetch = useCallback(() => {
> 11 | refetch(data);
| ^^^^ InvalidReact: This variable is accessed before it is declared, which may prevent it from updating as the assigned value changes over time. Variable `data` is accessed before it is declared (11:11)
InvalidReact: This variable is accessed before it is declared, which prevents the earlier access from updating when this value changes over time. Variable `data` is accessed before it is declared (19:19)
12 | }, [refetch]);
13 |
14 | // The context variable gets frozen here since it's passed to a hook
```

View File

@@ -1,22 +0,0 @@
//@flow @validatePreserveExistingMemoizationGuarantees @enableNewMutationAliasingModel
import {useCallback} from 'react';
import {useIdentity} from 'shared-runtime';
function Component({content, refetch}) {
// This callback function accesses a hoisted const as a dependency,
// but it cannot reference it as a dependency since that would be a
// TDZ violation!
const onRefetch = useCallback(() => {
refetch(data);
}, [refetch]);
// The context variable gets frozen here since it's passed to a hook
const onSubmit = useIdentity(onRefetch);
// This has to error: onRefetch needs to memoize with `content` as a
// dependency, but the dependency comes later
const {data = null} = content;
return <Foo data={data} onSubmit={onSubmit} />;
}

View File

@@ -19,7 +19,7 @@ function Component({a, b}) {
3 | const x = {a};
4 | useFreeze(x);
> 5 | x.y = true;
| ^ InvalidReact: Updating a value previously passed as an argument to a hook is not allowed. Consider moving the mutation before calling the hook (5:5)
| ^ InvalidReact: This mutates a variable that React considers immutable (5:5)
6 | return <div>error</div>;
7 | }
8 |

View File

@@ -1,54 +0,0 @@
## Input
```javascript
// @flow @enableNewMutationAliasingModel
import fbt from 'fbt';
component Component() {
const sections = Object.keys(items);
for (let i = 0; i < sections.length; i += 3) {
chunks.push(
sections.slice(i, i + 3).map(section => {
return <Child />;
})
);
}
return <Child />;
}
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import fbt from "fbt";
function Component() {
const $ = _c(1);
const sections = Object.keys(items);
for (let i = 0; i < sections.length; i = i + 3, i) {
chunks.push(sections.slice(i, i + 3).map(_temp));
}
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = <Child />;
$[0] = t0;
} else {
t0 = $[0];
}
return t0;
}
function _temp(section) {
return <Child />;
}
```
### Eval output
(kind: exception) Fixture not implemented

View File

@@ -1,17 +0,0 @@
// @flow @enableNewMutationAliasingModel
import fbt from 'fbt';
component Component() {
const sections = Object.keys(items);
for (let i = 0; i < sections.length; i += 3) {
chunks.push(
sections.slice(i, i + 3).map(section => {
return <Child />;
})
);
}
return <Child />;
}

View File

@@ -1,80 +0,0 @@
## Input
```javascript
//@flow @validatePreserveExistingMemoizationGuarantees @enableNewMutationAliasingModel
component 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(() => {
onClose(true);
});
return;
}
}, [onAsyncSubmit, onClose]);
// When running inferReactiveScopeVariables here,
// first the existing range gets updated (affecting
// onAsyncSubmit) and then onClose gets assigned a
// 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={() => onClose(false)} />;
}
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
function Component(t0) {
const $ = _c(8);
const { onAsyncSubmit, onClose } = t0;
let t1;
if ($[0] !== onAsyncSubmit || $[1] !== onClose) {
t1 = () => {
if (onAsyncSubmit) {
onAsyncSubmit(() => {
onClose(true);
});
return;
}
};
$[0] = onAsyncSubmit;
$[1] = onClose;
$[2] = t1;
} else {
t1 = $[2];
}
const onSubmit = t1;
let t2;
if ($[3] !== onClose) {
t2 = () => onClose(false);
$[3] = onClose;
$[4] = t2;
} else {
t2 = $[4];
}
let t3;
if ($[5] !== onSubmit || $[6] !== t2) {
t3 = <Dialog onSubmit={onSubmit} onClose={t2} />;
$[5] = onSubmit;
$[6] = t2;
$[7] = t3;
} else {
t3 = $[7];
}
return t3;
}
```
### Eval output
(kind: exception) Fixture not implemented

View File

@@ -1,25 +0,0 @@
//@flow @validatePreserveExistingMemoizationGuarantees @enableNewMutationAliasingModel
component 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(() => {
onClose(true);
});
return;
}
}, [onAsyncSubmit, onClose]);
// When running inferReactiveScopeVariables here,
// first the existing range gets updated (affecting
// onAsyncSubmit) and then onClose gets assigned a
// 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={() => onClose(false)} />;
}

View File

@@ -1,53 +0,0 @@
## Input
```javascript
// @flow @enableNewMutationAliasingModel
import {identity, Stringify, useFragment} from 'shared-runtime';
component Example() {
const data = useFragment();
const {a, b} = identity(data);
const el = <Stringify tooltip={b} />;
identity(a.at(0));
return <Stringify icon={el} />;
}
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { identity, Stringify, useFragment } from "shared-runtime";
function Example() {
const $ = _c(2);
const data = useFragment();
let t0;
if ($[0] !== data) {
const { a, b } = identity(data);
const el = <Stringify tooltip={b} />;
identity(a.at(0));
t0 = <Stringify icon={el} />;
$[0] = data;
$[1] = t0;
} else {
t0 = $[1];
}
return t0;
}
```
### Eval output
(kind: exception) Fixture not implemented

View File

@@ -1,15 +0,0 @@
// @flow @enableNewMutationAliasingModel
import {identity, Stringify, useFragment} from 'shared-runtime';
component Example() {
const data = useFragment();
const {a, b} = identity(data);
const el = <Stringify tooltip={b} />;
identity(a.at(0));
return <Stringify icon={el} />;
}

View File

@@ -52,7 +52,7 @@ export const FIXTURE_ENTRYPOINT = {
## Logs
```
{"kind":"CompileError","fnLoc":{"start":{"line":5,"column":0,"index":195},"end":{"line":13,"column":1,"index":389},"filename":"retry-no-emit.ts"},"detail":{"reason":"Updating a value previously passed as an argument to a hook is not allowed. Consider moving the mutation before calling the hook","description":null,"severity":"InvalidReact","suggestions":null,"loc":{"start":{"line":11,"column":2,"index":352},"end":{"line":11,"column":6,"index":356},"filename":"retry-no-emit.ts","identifierName":"arr2"}}}
{"kind":"CompileError","fnLoc":{"start":{"line":5,"column":0,"index":195},"end":{"line":13,"column":1,"index":389},"filename":"retry-no-emit.ts"},"detail":{"reason":"This mutates a variable that React considers immutable","description":null,"severity":"InvalidReact","suggestions":null,"loc":{"start":{"line":11,"column":2,"index":352},"end":{"line":11,"column":6,"index":356},"filename":"retry-no-emit.ts","identifierName":"arr2"}}}
{"kind":"AutoDepsDecorations","fnLoc":{"start":{"line":7,"column":2,"index":248},"end":{"line":7,"column":36,"index":282},"filename":"retry-no-emit.ts"},"decorations":[{"start":{"line":7,"column":31,"index":277},"end":{"line":7,"column":34,"index":280},"filename":"retry-no-emit.ts","identifierName":"arr"}]}
{"kind":"AutoDepsDecorations","fnLoc":{"start":{"line":10,"column":2,"index":306},"end":{"line":10,"column":44,"index":348},"filename":"retry-no-emit.ts"},"decorations":[{"start":{"line":10,"column":25,"index":329},"end":{"line":10,"column":29,"index":333},"filename":"retry-no-emit.ts","identifierName":"arr2"},{"start":{"line":10,"column":25,"index":329},"end":{"line":10,"column":29,"index":333},"filename":"retry-no-emit.ts","identifierName":"arr2"},{"start":{"line":10,"column":35,"index":339},"end":{"line":10,"column":42,"index":346},"filename":"retry-no-emit.ts","identifierName":"propVal"}]}
{"kind":"CompileSuccess","fnLoc":{"start":{"line":5,"column":0,"index":195},"end":{"line":13,"column":1,"index":389},"filename":"retry-no-emit.ts"},"fnName":"Foo","memoSlots":0,"memoBlocks":0,"memoValues":0,"prunedMemoBlocks":0,"prunedMemoValues":0}

View File

@@ -30,47 +30,60 @@ import { c as _c, useFire } from "react/compiler-runtime"; // @enableFire @enabl
import { fire } from "react";
function Component(t0) {
const $ = _c(9);
const { bar, baz } = t0;
let t1;
if ($[0] !== bar) {
t1 = () => {
console.log(bar);
};
$[0] = bar;
$[1] = t1;
const $ = _c(13);
let bar;
let baz;
let foo;
if ($[0] !== t0) {
({ bar, baz } = t0);
let t1;
if ($[4] !== bar) {
t1 = () => {
console.log(bar);
};
$[4] = bar;
$[5] = t1;
} else {
t1 = $[5];
}
foo = t1;
$[0] = t0;
$[1] = bar;
$[2] = baz;
$[3] = foo;
} else {
t1 = $[1];
bar = $[1];
baz = $[2];
foo = $[3];
}
const foo = t1;
const t2 = useFire(foo);
const t3 = useFire(baz);
let t4;
if ($[2] !== bar || $[3] !== t2 || $[4] !== t3) {
t4 = () => {
t2(bar);
t3(bar);
};
$[2] = bar;
$[3] = t2;
$[4] = t3;
$[5] = t4;
} else {
t4 = $[5];
}
useEffect(t4);
let t5;
if ($[6] !== bar || $[7] !== t2) {
t5 = () => {
const t1 = useFire(foo);
const t2 = useFire(baz);
let t3;
if ($[6] !== bar || $[7] !== t1 || $[8] !== t2) {
t3 = () => {
t1(bar);
t2(bar);
};
$[6] = bar;
$[7] = t2;
$[8] = t5;
$[7] = t1;
$[8] = t2;
$[9] = t3;
} else {
t5 = $[8];
t3 = $[9];
}
useEffect(t5);
useEffect(t3);
let t4;
if ($[10] !== bar || $[11] !== t1) {
t4 = () => {
t1(bar);
};
$[10] = bar;
$[11] = t1;
$[12] = t4;
} else {
t4 = $[12];
}
useEffect(t4);
return null;
}

View File

@@ -1,161 +0,0 @@
## Input
```javascript
import {useMemo} from 'react';
import {
mutate,
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b, c}: {a: number; b: number; c: number}) {
const x = useMemo(() => [{value: a}], [a, b, c]);
if (b === 0) {
// This object should only depend on c, it cannot be affected by the later mutation
x.push({value: c});
} else {
// 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 */}
<ValidateMemoization 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: 1},
{a: 1, b: 1, c: 0},
{a: 1, b: 0, c: 0},
{a: 0, b: 0, c: 0},
],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { useMemo } from "react";
import {
mutate,
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from "shared-runtime";
function Component(t0) {
const $ = _c(22);
const { a, b, c } = t0;
let t1;
let x;
if ($[0] !== a || $[1] !== b || $[2] !== c) {
t1 = [{ value: a }];
x = t1;
if (b === 0) {
x.push({ value: c });
} else {
mutate(x);
}
$[0] = a;
$[1] = b;
$[2] = c;
$[3] = x;
$[4] = t1;
} else {
x = $[3];
t1 = $[4];
}
let t2;
if ($[5] !== a || $[6] !== b || $[7] !== c) {
t2 = [a, b, c];
$[5] = a;
$[6] = b;
$[7] = c;
$[8] = t2;
} else {
t2 = $[8];
}
let t3;
if ($[9] !== t2 || $[10] !== x) {
t3 = <ValidateMemoization inputs={t2} output={x} />;
$[9] = t2;
$[10] = x;
$[11] = t3;
} else {
t3 = $[11];
}
let t4;
if ($[12] !== a || $[13] !== b || $[14] !== c) {
t4 = [a, b, c];
$[12] = a;
$[13] = b;
$[14] = c;
$[15] = t4;
} else {
t4 = $[15];
}
let t5;
if ($[16] !== t4 || $[17] !== x[0]) {
t5 = <ValidateMemoization inputs={t4} output={x[0]} />;
$[16] = t4;
$[17] = x[0];
$[18] = t5;
} else {
t5 = $[18];
}
let t6;
if ($[19] !== t3 || $[20] !== t5) {
t6 = (
<>
{t3};{t5};
</>
);
$[19] = t3;
$[20] = t5;
$[21] = t6;
} else {
t6 = $[21];
}
return t6;
}
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: 1 },
{ a: 1, b: 1, c: 0 },
{ a: 1, b: 0, c: 0 },
{ a: 0, b: 0, c: 0 },
],
};
```
### Eval output
(kind: ok) <div>{"inputs":[0,0,0],"output":[{"value":0},{"value":0}]}</div>;<div>{"inputs":[0,0,0],"output":{"value":0}}</div>;
<div>{"inputs":[0,1,0],"output":[{"value":0},"joe"]}</div>;<div>{"inputs":[0,1,0],"output":{"value":0}}</div>;
<div>{"inputs":[1,1,0],"output":[{"value":1},"joe"]}</div>;<div>{"inputs":[1,1,0],"output":{"value":1}}</div>;
<div>{"inputs":[1,1,1],"output":[{"value":1},"joe"]}</div>;<div>{"inputs":[1,1,1],"output":{"value":1}}</div>;
<div>{"inputs":[1,1,0],"output":[{"value":1},"joe"]}</div>;<div>{"inputs":[1,1,0],"output":{"value":1}}</div>;
<div>{"inputs":[1,0,0],"output":[{"value":1},{"value":0}]}</div>;<div>{"inputs":[1,0,0],"output":{"value":1}}</div>;
<div>{"inputs":[0,0,0],"output":[{"value":0},{"value":0}]}</div>;<div>{"inputs":[0,0,0],"output":{"value":0}}</div>;

View File

@@ -1,41 +0,0 @@
import {useMemo} from 'react';
import {
mutate,
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b, c}: {a: number; b: number; c: number}) {
const x = useMemo(() => [{value: a}], [a, b, c]);
if (b === 0) {
// This object should only depend on c, it cannot be affected by the later mutation
x.push({value: c});
} else {
// 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 */}
<ValidateMemoization 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: 1},
{a: 1, b: 1, c: 0},
{a: 1, b: 0, c: 0},
{a: 0, b: 0, c: 0},
],
};

View File

@@ -1,116 +0,0 @@
## Input
```javascript
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}) {
const x = useMemo(() => [{a}], [a]);
const f = () => {
const y = typedCreateFrom(x);
const z = typedCapture(y);
return z;
};
const z = f();
// does not mutate x, so x should not depend on b
typedMutate(z, b);
// TODO: this *should* only depend on `a`
return <ValidateMemoization inputs={[a, b]} output={x} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { useMemo } from "react";
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from "shared-runtime";
function Component(t0) {
const $ = _c(10);
const { a, b } = t0;
let t1;
let x;
if ($[0] !== a || $[1] !== b) {
t1 = [{ a }];
x = t1;
const f = () => {
const y = typedCreateFrom(x);
const z = typedCapture(y);
return z;
};
const z_0 = f();
typedMutate(z_0, b);
$[0] = a;
$[1] = b;
$[2] = x;
$[3] = t1;
} else {
x = $[2];
t1 = $[3];
}
let t2;
if ($[4] !== a || $[5] !== b) {
t2 = [a, b];
$[4] = a;
$[5] = b;
$[6] = t2;
} else {
t2 = $[6];
}
let t3;
if ($[7] !== t2 || $[8] !== x) {
t3 = <ValidateMemoization inputs={t2} output={x} />;
$[7] = t2;
$[8] = x;
$[9] = t3;
} else {
t3 = $[9];
}
return t3;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{ a: 0, b: 0 }],
sequentialRenders: [
{ a: 0, b: 0 },
{ a: 0, b: 1 },
{ a: 1, b: 1 },
{ a: 0, b: 0 },
],
};
```
### Eval output
(kind: ok) <div>{"inputs":[0,0],"output":[{"a":0}]}</div>
<div>{"inputs":[0,1],"output":[{"a":0}]}</div>
<div>{"inputs":[1,1],"output":[{"a":1}]}</div>
<div>{"inputs":[0,0],"output":[{"a":0}]}</div>

View File

@@ -1,33 +0,0 @@
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}) {
const x = useMemo(() => [{a}], [a]);
const f = () => {
const y = typedCreateFrom(x);
const z = typedCapture(y);
return z;
};
const z = f();
// does not mutate x, so x should not depend on b
typedMutate(z, b);
// TODO: this *should* only depend on `a`
return <ValidateMemoization inputs={[a, b]} output={x} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};

View File

@@ -1,153 +0,0 @@
## Input
```javascript
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}) {
const o: any = useMemo(() => ({a}), [a]);
const x: Array<any> = useMemo(() => [o], [o, b]);
const y = typedCapture(x);
const z = typedCapture(y);
x.push(z);
x.push(b);
return (
<>
<ValidateMemoization inputs={[a]} output={o} />;
<ValidateMemoization inputs={[a, b]} output={x} />;
</>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { useMemo } from "react";
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from "shared-runtime";
function Component(t0) {
const $ = _c(20);
const { a, b } = t0;
let t1;
let t2;
if ($[0] !== a) {
t2 = { a };
$[0] = a;
$[1] = t2;
} else {
t2 = $[1];
}
t1 = t2;
const o = t1;
let t3;
let x;
if ($[2] !== b || $[3] !== o) {
t3 = [o];
x = t3;
const y = typedCapture(x);
const z = typedCapture(y);
x.push(z);
x.push(b);
$[2] = b;
$[3] = o;
$[4] = x;
$[5] = t3;
} else {
x = $[4];
t3 = $[5];
}
let t4;
if ($[6] !== a) {
t4 = [a];
$[6] = a;
$[7] = t4;
} else {
t4 = $[7];
}
let t5;
if ($[8] !== o || $[9] !== t4) {
t5 = <ValidateMemoization inputs={t4} output={o} />;
$[8] = o;
$[9] = t4;
$[10] = t5;
} else {
t5 = $[10];
}
let t6;
if ($[11] !== a || $[12] !== b) {
t6 = [a, b];
$[11] = a;
$[12] = b;
$[13] = t6;
} else {
t6 = $[13];
}
let t7;
if ($[14] !== t6 || $[15] !== x) {
t7 = <ValidateMemoization inputs={t6} output={x} />;
$[14] = t6;
$[15] = x;
$[16] = t7;
} else {
t7 = $[16];
}
let t8;
if ($[17] !== t5 || $[18] !== t7) {
t8 = (
<>
{t5};{t7};
</>
);
$[17] = t5;
$[18] = t7;
$[19] = t8;
} else {
t8 = $[19];
}
return t8;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{ a: 0, b: 0 }],
sequentialRenders: [
{ a: 0, b: 0 },
{ a: 0, b: 1 },
{ a: 1, b: 1 },
{ a: 0, b: 0 },
],
};
```
### Eval output
(kind: ok) <div>{"inputs":[0],"output":{"a":0}}</div>;<div>{"inputs":[0,0],"output":[{"a":0},[["[[ cyclic ref *2 ]]"]],0]}</div>;
<div>{"inputs":[0],"output":{"a":0}}</div>;<div>{"inputs":[0,1],"output":[{"a":0},[["[[ cyclic ref *2 ]]"]],1]}</div>;
<div>{"inputs":[1],"output":{"a":1}}</div>;<div>{"inputs":[1,1],"output":[{"a":1},[["[[ cyclic ref *2 ]]"]],1]}</div>;
<div>{"inputs":[0],"output":{"a":0}}</div>;<div>{"inputs":[0,0],"output":[{"a":0},[["[[ cyclic ref *2 ]]"]],0]}</div>;

View File

@@ -1,34 +0,0 @@
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}) {
const o: any = useMemo(() => ({a}), [a]);
const x: Array<any> = useMemo(() => [o], [o, b]);
const y = typedCapture(x);
const z = typedCapture(y);
x.push(z);
x.push(b);
return (
<>
<ValidateMemoization inputs={[a]} output={o} />;
<ValidateMemoization inputs={[a, b]} output={x} />;
</>
);
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};

View File

@@ -1,115 +0,0 @@
## Input
```javascript
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}: {a: number; b: number}) {
const x = useMemo(() => ({a}), [a, b]);
const f = () => {
const y = typedCapture(x);
const z = typedCreateFrom(y);
return z;
};
const z = f();
// mutates x
typedMutate(z, b);
return <ValidateMemoization inputs={[a, b]} output={x} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { useMemo } from "react";
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from "shared-runtime";
function Component(t0) {
const $ = _c(10);
const { a, b } = t0;
let t1;
let x;
if ($[0] !== a || $[1] !== b) {
t1 = { a };
x = t1;
const f = () => {
const y = typedCapture(x);
const z = typedCreateFrom(y);
return z;
};
const z_0 = f();
typedMutate(z_0, b);
$[0] = a;
$[1] = b;
$[2] = x;
$[3] = t1;
} else {
x = $[2];
t1 = $[3];
}
let t2;
if ($[4] !== a || $[5] !== b) {
t2 = [a, b];
$[4] = a;
$[5] = b;
$[6] = t2;
} else {
t2 = $[6];
}
let t3;
if ($[7] !== t2 || $[8] !== x) {
t3 = <ValidateMemoization inputs={t2} output={x} />;
$[7] = t2;
$[8] = x;
$[9] = t3;
} else {
t3 = $[9];
}
return t3;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{ a: 0, b: 0 }],
sequentialRenders: [
{ a: 0, b: 0 },
{ a: 0, b: 1 },
{ a: 1, b: 1 },
{ a: 0, b: 0 },
],
};
```
### Eval output
(kind: ok) <div>{"inputs":[0,0],"output":{"a":0,"property":0}}</div>
<div>{"inputs":[0,1],"output":{"a":0,"property":1}}</div>
<div>{"inputs":[1,1],"output":{"a":1,"property":1}}</div>
<div>{"inputs":[0,0],"output":{"a":0,"property":0}}</div>

View File

@@ -1,32 +0,0 @@
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}: {a: number; b: number}) {
const x = useMemo(() => ({a}), [a, b]);
const f = () => {
const y = typedCapture(x);
const z = typedCreateFrom(y);
return z;
};
const z = f();
// mutates x
typedMutate(z, b);
return <ValidateMemoization inputs={[a, b]} output={x} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};

View File

@@ -1,106 +0,0 @@
## Input
```javascript
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}: {a: number; b: number}) {
const x = useMemo(() => ({a}), [a, b]);
const y = typedCapture(x);
const z = typedCreateFrom(y);
// mutates x
typedMutate(z, b);
return <ValidateMemoization inputs={[a, b]} output={x} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { useMemo } from "react";
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from "shared-runtime";
function Component(t0) {
const $ = _c(10);
const { a, b } = t0;
let t1;
let x;
if ($[0] !== a || $[1] !== b) {
t1 = { a };
x = t1;
const y = typedCapture(x);
const z = typedCreateFrom(y);
typedMutate(z, b);
$[0] = a;
$[1] = b;
$[2] = x;
$[3] = t1;
} else {
x = $[2];
t1 = $[3];
}
let t2;
if ($[4] !== a || $[5] !== b) {
t2 = [a, b];
$[4] = a;
$[5] = b;
$[6] = t2;
} else {
t2 = $[6];
}
let t3;
if ($[7] !== t2 || $[8] !== x) {
t3 = <ValidateMemoization inputs={t2} output={x} />;
$[7] = t2;
$[8] = x;
$[9] = t3;
} else {
t3 = $[9];
}
return t3;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{ a: 0, b: 0 }],
sequentialRenders: [
{ a: 0, b: 0 },
{ a: 0, b: 1 },
{ a: 1, b: 1 },
{ a: 0, b: 0 },
],
};
```
### Eval output
(kind: ok) <div>{"inputs":[0,0],"output":{"a":0,"property":0}}</div>
<div>{"inputs":[0,1],"output":{"a":0,"property":1}}</div>
<div>{"inputs":[1,1],"output":{"a":1,"property":1}}</div>
<div>{"inputs":[0,0],"output":{"a":0,"property":0}}</div>

View File

@@ -1,28 +0,0 @@
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}: {a: number; b: number}) {
const x = useMemo(() => ({a}), [a, b]);
const y = typedCapture(x);
const z = typedCreateFrom(y);
// mutates x
typedMutate(z, b);
return <ValidateMemoization inputs={[a, b]} output={x} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};

View File

@@ -1,103 +0,0 @@
## Input
```javascript
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}) {
const x = useMemo(() => [{a}], [a]);
const y = typedCreateFrom(x);
const z = typedCapture(y);
// does not mutate x, so x should not depend on b
typedMutate(z, b);
return <ValidateMemoization inputs={[a]} output={x} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { useMemo } from "react";
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from "shared-runtime";
function Component(t0) {
const $ = _c(7);
const { a, b } = t0;
let t1;
let t2;
if ($[0] !== a) {
t2 = [{ a }];
$[0] = a;
$[1] = t2;
} else {
t2 = $[1];
}
t1 = t2;
const x = t1;
const y = typedCreateFrom(x);
const z = typedCapture(y);
typedMutate(z, b);
let t3;
if ($[2] !== a) {
t3 = [a];
$[2] = a;
$[3] = t3;
} else {
t3 = $[3];
}
let t4;
if ($[4] !== t3 || $[5] !== x) {
t4 = <ValidateMemoization inputs={t3} output={x} />;
$[4] = t3;
$[5] = x;
$[6] = t4;
} else {
t4 = $[6];
}
return t4;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{ a: 0, b: 0 }],
sequentialRenders: [
{ a: 0, b: 0 },
{ a: 0, b: 1 },
{ a: 1, b: 1 },
{ a: 0, b: 0 },
],
};
```
### Eval output
(kind: ok) <div>{"inputs":[0],"output":[{"a":0}]}</div>
<div>{"inputs":[0],"output":[{"a":0}]}</div>
<div>{"inputs":[1],"output":[{"a":1}]}</div>
<div>{"inputs":[0],"output":[{"a":0}]}</div>

View File

@@ -1,28 +0,0 @@
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}) {
const x = useMemo(() => [{a}], [a]);
const y = typedCreateFrom(x);
const z = typedCapture(y);
// does not mutate x, so x should not depend on b
typedMutate(z, b);
return <ValidateMemoization inputs={[a]} output={x} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};

View File

@@ -1,122 +0,0 @@
## Input
```javascript
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}) {
const x = useMemo(() => [{a}], [a, b]);
let z: any;
if (b) {
z = x;
} else {
z = typedCapture(x);
}
// could mutate x
typedMutate(z, b);
return <ValidateMemoization inputs={[a, b]} output={x} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { useMemo } from "react";
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from "shared-runtime";
function Component(t0) {
const $ = _c(12);
const { a, b } = t0;
let t1;
let t2;
if ($[0] !== a) {
t2 = { a };
$[0] = a;
$[1] = t2;
} else {
t2 = $[1];
}
let x;
if ($[2] !== b || $[3] !== t2) {
t1 = [t2];
x = t1;
let z;
if (b) {
z = x;
} else {
z = typedCapture(x);
}
typedMutate(z, b);
$[2] = b;
$[3] = t2;
$[4] = x;
$[5] = t1;
} else {
x = $[4];
t1 = $[5];
}
let t3;
if ($[6] !== a || $[7] !== b) {
t3 = [a, b];
$[6] = a;
$[7] = b;
$[8] = t3;
} else {
t3 = $[8];
}
let t4;
if ($[9] !== t3 || $[10] !== x) {
t4 = <ValidateMemoization inputs={t3} output={x} />;
$[9] = t3;
$[10] = x;
$[11] = t4;
} else {
t4 = $[11];
}
return t4;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{ a: 0, b: 0 }],
sequentialRenders: [
{ a: 0, b: 0 },
{ a: 0, b: 1 },
{ a: 1, b: 1 },
{ a: 0, b: 0 },
],
};
```
### Eval output
(kind: ok) <div>{"inputs":[0,0],"output":[{"a":0}]}</div>
<div>{"inputs":[0,1],"output":[{"a":0}]}</div>
<div>{"inputs":[1,1],"output":[{"a":1}]}</div>
<div>{"inputs":[0,0],"output":[{"a":0}]}</div>

View File

@@ -1,32 +0,0 @@
import {useMemo} from 'react';
import {
typedCapture,
typedCreateFrom,
typedMutate,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}) {
const x = useMemo(() => [{a}], [a, b]);
let z: any;
if (b) {
z = x;
} else {
z = typedCapture(x);
}
// could mutate x
typedMutate(z, b);
return <ValidateMemoization inputs={[a, b]} output={x} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{a: 0, b: 0}],
sequentialRenders: [
{a: 0, b: 0},
{a: 0, b: 1},
{a: 1, b: 1},
{a: 0, b: 0},
],
};

View File

@@ -1,121 +0,0 @@
## Input
```javascript
// @enableNewMutationAliasingModel
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
useIdentity(x);
// known to pass-through via aliasing signature
const x2 = typedIdentity(x);
// Unknown function so we assume it conditionally mutates,
// but x2 is frozen so this downgrades to a read.
// x should *not* take b as a dependency
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: 1},
{a: 0, b: 0},
],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime"; // @enableNewMutationAliasingModel
import { useMemo } from "react";
import {
identity,
makeObject_Primitives,
typedIdentity,
useIdentity,
ValidateMemoization,
} from "shared-runtime";
function Component(t0) {
const $ = _c(7);
const { a, b } = t0;
let t1;
let t2;
if ($[0] !== a) {
t2 = makeObject_Primitives(a);
$[0] = a;
$[1] = t2;
} else {
t2 = $[1];
}
t1 = t2;
const x = t1;
useIdentity(x);
const x2 = typedIdentity(x);
identity(x2, b);
let t3;
if ($[2] !== a) {
t3 = [a];
$[2] = a;
$[3] = t3;
} else {
t3 = $[3];
}
let t4;
if ($[4] !== t3 || $[5] !== x) {
t4 = <ValidateMemoization inputs={t3} output={x} />;
$[4] = t3;
$[5] = x;
$[6] = t4;
} else {
t4 = $[6];
}
return t4;
}
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: 1 },
{ a: 0, b: 0 },
],
};
```
### Eval output
(kind: ok) <div>{"inputs":[0],"output":{"a":0,"b":"value1","c":true}}</div>
<div>{"inputs":[1],"output":{"a":0,"b":"value1","c":true}}</div>
<div>{"inputs":[1],"output":{"a":0,"b":"value1","c":true}}</div>
<div>{"inputs":[0],"output":{"a":0,"b":"value1","c":true}}</div>
<div>{"inputs":[0],"output":{"a":0,"b":"value1","c":true}}</div>

View File

@@ -1,40 +0,0 @@
// @enableNewMutationAliasingModel
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
useIdentity(x);
// known to pass-through via aliasing signature
const x2 = typedIdentity(x);
// Unknown function so we assume it conditionally mutates,
// but x2 is frozen so this downgrades to a read.
// x should *not* take b as a dependency
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: 1},
{a: 0, b: 0},
],
};

View File

@@ -1,112 +0,0 @@
## Input
```javascript
// @enableNewMutationAliasingModel
import {
identity,
makeObject_Primitives,
typedIdentity,
useIdentity,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}) {
// create a mutable value with input `a`
const x = makeObject_Primitives(a);
// known to pass-through via aliasing signature
const x2 = typedIdentity(x);
// Unknown function so we assume it conditionally mutates,
// and x is still mutable so
identity(x2, b);
return <ValidateMemoization inputs={[a, b]} 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: 1},
{a: 0, b: 0},
],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime"; // @enableNewMutationAliasingModel
import {
identity,
makeObject_Primitives,
typedIdentity,
useIdentity,
ValidateMemoization,
} from "shared-runtime";
function Component(t0) {
const $ = _c(9);
const { a, b } = t0;
let x;
if ($[0] !== a || $[1] !== b) {
x = makeObject_Primitives(a);
const x2 = typedIdentity(x);
identity(x2, b);
$[0] = a;
$[1] = b;
$[2] = x;
} else {
x = $[2];
}
let t1;
if ($[3] !== a || $[4] !== b) {
t1 = [a, b];
$[3] = a;
$[4] = b;
$[5] = t1;
} else {
t1 = $[5];
}
let t2;
if ($[6] !== t1 || $[7] !== x) {
t2 = <ValidateMemoization inputs={t1} output={x} />;
$[6] = t1;
$[7] = x;
$[8] = t2;
} else {
t2 = $[8];
}
return t2;
}
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: 1 },
{ a: 0, b: 0 },
],
};
```
### Eval output
(kind: ok) <div>{"inputs":[0,0],"output":{"a":0,"b":"value1","c":true}}</div>
<div>{"inputs":[1,0],"output":{"a":0,"b":"value1","c":true}}</div>
<div>{"inputs":[1,1],"output":{"a":0,"b":"value1","c":true}}</div>
<div>{"inputs":[0,1],"output":{"a":0,"b":"value1","c":true}}</div>
<div>{"inputs":[0,0],"output":{"a":0,"b":"value1","c":true}}</div>

View File

@@ -1,35 +0,0 @@
// @enableNewMutationAliasingModel
import {
identity,
makeObject_Primitives,
typedIdentity,
useIdentity,
ValidateMemoization,
} from 'shared-runtime';
function Component({a, b}) {
// create a mutable value with input `a`
const x = makeObject_Primitives(a);
// known to pass-through via aliasing signature
const x2 = typedIdentity(x);
// Unknown function so we assume it conditionally mutates,
// and x is still mutable so
identity(x2, b);
return <ValidateMemoization inputs={[a, b]} 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: 1},
{a: 0, b: 0},
],
};

View File

@@ -27,18 +27,34 @@ import { c as _c } from "react/compiler-runtime";
import { identity, mutate } from "shared-runtime";
function Component(props) {
const $ = _c(2);
let context;
if ($[0] !== props.value) {
const key = {};
context = { [key]: identity([props.value]) };
mutate(key);
$[0] = props.value;
$[1] = context;
const $ = _c(5);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = {};
$[0] = t0;
} else {
context = $[1];
t0 = $[0];
}
const key = t0;
let t1;
if ($[1] !== props.value) {
t1 = identity([props.value]);
$[1] = props.value;
$[2] = t1;
} else {
t1 = $[2];
}
let t2;
if ($[3] !== t1) {
t2 = { [key]: t1 };
$[3] = t1;
$[4] = t2;
} else {
t2 = $[4];
}
const context = t2;
mutate(key);
return context;
}

View File

@@ -27,22 +27,11 @@ import { c as _c } from "react/compiler-runtime";
import { identity, mutate, mutateAndReturn } from "shared-runtime";
function Component(props) {
const $ = _c(4);
const $ = _c(2);
let context;
if ($[0] !== props.value) {
const key = { a: "key" };
const t0 = key.a;
const t1 = identity([props.value]);
let t2;
if ($[2] !== t1) {
t2 = { [t0]: t1 };
$[2] = t1;
$[3] = t2;
} else {
t2 = $[3];
}
context = t2;
context = { [key.a]: identity([props.value]) };
mutate(key);
$[0] = props.value;

View File

@@ -40,46 +40,39 @@ import { useCallback } from "react";
import { Stringify } from "shared-runtime";
function Foo(t0) {
const $ = _c(10);
const $ = _c(8);
const { arr1, arr2, foo } = t0;
let t1;
if ($[0] !== arr1) {
t1 = [arr1];
$[0] = arr1;
$[1] = t1;
} else {
t1 = $[1];
}
const x = t1;
let getVal1;
let t2;
if ($[2] !== arr2 || $[3] !== foo || $[4] !== x) {
let t1;
if ($[0] !== arr1 || $[1] !== arr2 || $[2] !== foo) {
const x = [arr1];
let y = [];
getVal1 = _temp;
t2 = () => [y];
t1 = () => [y];
foo ? (y = x.concat(arr2)) : y;
$[2] = arr2;
$[3] = foo;
$[4] = x;
$[0] = arr1;
$[1] = arr2;
$[2] = foo;
$[3] = getVal1;
$[4] = t1;
} else {
getVal1 = $[3];
t1 = $[4];
}
const getVal2 = t1;
let t2;
if ($[5] !== getVal1 || $[6] !== getVal2) {
t2 = <Stringify val1={getVal1} val2={getVal2} shouldInvokeFns={true} />;
$[5] = getVal1;
$[6] = t2;
$[6] = getVal2;
$[7] = t2;
} else {
getVal1 = $[5];
t2 = $[6];
t2 = $[7];
}
const getVal2 = t2;
let t3;
if ($[7] !== getVal1 || $[8] !== getVal2) {
t3 = <Stringify val1={getVal1} val2={getVal2} shouldInvokeFns={true} />;
$[7] = getVal1;
$[8] = getVal2;
$[9] = t3;
} else {
t3 = $[9];
}
return t3;
return t2;
}
function _temp() {
return { x: 2 };

View File

@@ -36,38 +36,31 @@ import { Stringify } from "shared-runtime";
// We currently produce invalid output (incorrect scoping for `y` declaration)
function useFoo(arr1, arr2) {
const $ = _c(7);
const $ = _c(5);
let t0;
if ($[0] !== arr1) {
t0 = [arr1];
$[0] = arr1;
$[1] = t0;
} else {
t0 = $[1];
}
const x = t0;
let t1;
if ($[2] !== arr2 || $[3] !== x) {
if ($[0] !== arr1 || $[1] !== arr2) {
const x = [arr1];
let y;
t1 = () => ({ y });
t0 = () => ({ y });
(y = x.concat(arr2)), y;
$[2] = arr2;
$[3] = x;
$[0] = arr1;
$[1] = arr2;
$[2] = t0;
} else {
t0 = $[2];
}
const getVal = t0;
let t1;
if ($[3] !== getVal) {
t1 = <Stringify getVal={getVal} shouldInvokeFns={true} />;
$[3] = getVal;
$[4] = t1;
} else {
t1 = $[4];
}
const getVal = t1;
let t2;
if ($[5] !== getVal) {
t2 = <Stringify getVal={getVal} shouldInvokeFns={true} />;
$[5] = getVal;
$[6] = t2;
} else {
t2 = $[6];
}
return t2;
return t1;
}
export const FIXTURE_ENTRYPOINT = {

View File

@@ -30,36 +30,29 @@ import { c as _c } from "react/compiler-runtime";
import { useMemo } from "react";
function useFoo(arr1, arr2) {
const $ = _c(7);
let t0;
if ($[0] !== arr1) {
t0 = [arr1];
$[0] = arr1;
$[1] = t0;
} else {
t0 = $[1];
}
const x = t0;
const $ = _c(5);
let y;
if ($[2] !== arr2 || $[3] !== x) {
if ($[0] !== arr1 || $[1] !== arr2) {
const x = [arr1];
(y = x.concat(arr2)), y;
$[2] = arr2;
$[3] = x;
$[4] = y;
$[0] = arr1;
$[1] = arr2;
$[2] = y;
} else {
y = $[4];
y = $[2];
}
let t0;
let t1;
let t2;
if ($[5] !== y) {
t2 = { y };
$[5] = y;
$[6] = t2;
if ($[3] !== y) {
t1 = { y };
$[3] = y;
$[4] = t1;
} else {
t2 = $[6];
t1 = $[4];
}
t1 = t2;
return t1;
t0 = t1;
return t0;
}
export const FIXTURE_ENTRYPOINT = {

View File

@@ -2,7 +2,6 @@
## Input
```javascript
import {useMemo} from 'react';
import {ValidateMemoization} from 'shared-runtime';
function Component({a, b, c}) {
@@ -14,21 +13,9 @@ function Component({a, b, c}) {
return (
<>
<ValidateMemoization
inputs={[a, c]}
output={map}
onlyCheckCompiled={true}
/>
<ValidateMemoization
inputs={[a, c]}
output={mapAlias}
onlyCheckCompiled={true}
/>
<ValidateMemoization
inputs={[b]}
output={[hasB]}
onlyCheckCompiled={true}
/>
<ValidateMemoization inputs={[a, c]} output={map} />
<ValidateMemoization inputs={[a, c]} output={mapAlias} />
<ValidateMemoization inputs={[b]} output={[hasB]} />
</>
);
}
@@ -57,7 +44,6 @@ export const FIXTURE_ENTRYPOINT = {
```javascript
import { c as _c } from "react/compiler-runtime";
import { useMemo } from "react";
import { ValidateMemoization } from "shared-runtime";
function Component(t0) {
@@ -90,9 +76,7 @@ function Component(t0) {
}
let t2;
if ($[7] !== map || $[8] !== t1) {
t2 = (
<ValidateMemoization inputs={t1} output={map} onlyCheckCompiled={true} />
);
t2 = <ValidateMemoization inputs={t1} output={map} />;
$[7] = map;
$[8] = t1;
$[9] = t2;
@@ -110,13 +94,7 @@ function Component(t0) {
}
let t4;
if ($[13] !== mapAlias || $[14] !== t3) {
t4 = (
<ValidateMemoization
inputs={t3}
output={mapAlias}
onlyCheckCompiled={true}
/>
);
t4 = <ValidateMemoization inputs={t3} output={mapAlias} />;
$[13] = mapAlias;
$[14] = t3;
$[15] = t4;
@@ -141,9 +119,7 @@ function Component(t0) {
}
let t7;
if ($[20] !== t5 || $[21] !== t6) {
t7 = (
<ValidateMemoization inputs={t5} output={t6} onlyCheckCompiled={true} />
);
t7 = <ValidateMemoization inputs={t5} output={t6} />;
$[20] = t5;
$[21] = t6;
$[22] = t7;

View File

@@ -1,4 +1,3 @@
import {useMemo} from 'react';
import {ValidateMemoization} from 'shared-runtime';
function Component({a, b, c}) {
@@ -10,21 +9,9 @@ function Component({a, b, c}) {
return (
<>
<ValidateMemoization
inputs={[a, c]}
output={map}
onlyCheckCompiled={true}
/>
<ValidateMemoization
inputs={[a, c]}
output={mapAlias}
onlyCheckCompiled={true}
/>
<ValidateMemoization
inputs={[b]}
output={[hasB]}
onlyCheckCompiled={true}
/>
<ValidateMemoization inputs={[a, c]} output={map} />
<ValidateMemoization inputs={[a, c]} output={mapAlias} />
<ValidateMemoization inputs={[b]} output={[hasB]} />
</>
);
}

View File

@@ -2,7 +2,6 @@
## Input
```javascript
import {useMemo} from 'react';
import {ValidateMemoization} from 'shared-runtime';
function Component({a, b, c}) {
@@ -14,21 +13,9 @@ function Component({a, b, c}) {
return (
<>
<ValidateMemoization
inputs={[a, c]}
output={set}
onlyCheckCompiled={true}
/>
<ValidateMemoization
inputs={[a, c]}
output={setAlias}
onlyCheckCompiled={true}
/>
<ValidateMemoization
inputs={[b]}
output={[hasB]}
onlyCheckCompiled={true}
/>
<ValidateMemoization inputs={[a, c]} output={set} />
<ValidateMemoization inputs={[a, c]} output={setAlias} />
<ValidateMemoization inputs={[b]} output={[hasB]} />
</>
);
}
@@ -57,7 +44,6 @@ export const FIXTURE_ENTRYPOINT = {
```javascript
import { c as _c } from "react/compiler-runtime";
import { useMemo } from "react";
import { ValidateMemoization } from "shared-runtime";
function Component(t0) {
@@ -90,9 +76,7 @@ function Component(t0) {
}
let t2;
if ($[7] !== set || $[8] !== t1) {
t2 = (
<ValidateMemoization inputs={t1} output={set} onlyCheckCompiled={true} />
);
t2 = <ValidateMemoization inputs={t1} output={set} />;
$[7] = set;
$[8] = t1;
$[9] = t2;
@@ -110,13 +94,7 @@ function Component(t0) {
}
let t4;
if ($[13] !== setAlias || $[14] !== t3) {
t4 = (
<ValidateMemoization
inputs={t3}
output={setAlias}
onlyCheckCompiled={true}
/>
);
t4 = <ValidateMemoization inputs={t3} output={setAlias} />;
$[13] = setAlias;
$[14] = t3;
$[15] = t4;
@@ -141,9 +119,7 @@ function Component(t0) {
}
let t7;
if ($[20] !== t5 || $[21] !== t6) {
t7 = (
<ValidateMemoization inputs={t5} output={t6} onlyCheckCompiled={true} />
);
t7 = <ValidateMemoization inputs={t5} output={t6} />;
$[20] = t5;
$[21] = t6;
$[22] = t7;

View File

@@ -1,4 +1,3 @@
import {useMemo} from 'react';
import {ValidateMemoization} from 'shared-runtime';
function Component({a, b, c}) {
@@ -10,21 +9,9 @@ function Component({a, b, c}) {
return (
<>
<ValidateMemoization
inputs={[a, c]}
output={set}
onlyCheckCompiled={true}
/>
<ValidateMemoization
inputs={[a, c]}
output={setAlias}
onlyCheckCompiled={true}
/>
<ValidateMemoization
inputs={[b]}
output={[hasB]}
onlyCheckCompiled={true}
/>
<ValidateMemoization inputs={[a, c]} output={set} />
<ValidateMemoization inputs={[a, c]} output={setAlias} />
<ValidateMemoization inputs={[b]} output={[hasB]} />
</>
);
}

View File

@@ -30,7 +30,6 @@ export {
export {
Effect,
ValueKind,
ValueReason,
printHIR,
printFunctionWithOutlined,
validateEnvironmentConfig,

View File

@@ -18,11 +18,7 @@ import type {
CompilerReactTarget,
CompilerPipelineValue,
} from 'babel-plugin-react-compiler/src/Entrypoint';
import type {
Effect,
ValueKind,
ValueReason,
} from 'babel-plugin-react-compiler/src/HIR';
import type {Effect, ValueKind} from 'babel-plugin-react-compiler/src/HIR';
import type {parseConfigPragmaForTests as ParseConfigPragma} from 'babel-plugin-react-compiler/src/Utils/TestUtils';
import * as HermesParser from 'hermes-parser';
import invariant from 'invariant';
@@ -46,7 +42,6 @@ function makePluginOptions(
debugIRLogger: (value: CompilerPipelineValue) => void,
EffectEnum: typeof Effect,
ValueKindEnum: typeof ValueKind,
ValueReasonEnum: typeof ValueReason,
): [PluginOptions, Array<{filename: string | null; event: LoggerEvent}>] {
// TODO(@mofeiZ) rewrite snap fixtures to @validatePreserveExistingMemo:false
let validatePreserveExistingMemoizationGuarantees = false;
@@ -82,7 +77,6 @@ function makePluginOptions(
moduleTypeProvider: makeSharedRuntimeTypeProvider({
EffectEnum,
ValueKindEnum,
ValueReasonEnum,
}),
assertValidMutableRanges: true,
validatePreserveExistingMemoizationGuarantees,
@@ -215,7 +209,6 @@ export async function transformFixtureInput(
debugIRLogger: (value: CompilerPipelineValue) => void,
EffectEnum: typeof Effect,
ValueKindEnum: typeof ValueKind,
ValueReasonEnum: typeof ValueReason,
): Promise<{kind: 'ok'; value: TransformResult} | {kind: 'err'; msg: string}> {
// Extract the first line to quickly check for custom test directives
const firstLine = input.substring(0, input.indexOf('\n'));
@@ -244,7 +237,6 @@ export async function transformFixtureInput(
debugIRLogger,
EffectEnum,
ValueKindEnum,
ValueReasonEnum,
);
const forgetResult = transformFromAstSync(inputAst, input, {
filename: virtualFilepath,

View File

@@ -24,7 +24,6 @@ import type {
CompilerPipelineValue,
Effect,
ValueKind,
ValueReason,
} from 'babel-plugin-react-compiler/src';
import chalk from 'chalk';
@@ -79,9 +78,6 @@ async function compile(
const ValueKindEnum = importedCompilerPlugin[
'ValueKind'
] as typeof ValueKind;
const ValueReasonEnum = importedCompilerPlugin[
'ValueReason'
] as typeof ValueReason;
const printFunctionWithOutlined = importedCompilerPlugin[
PRINT_HIR_IMPORT
] as typeof PrintFunctionWithOutlined;
@@ -132,7 +128,6 @@ async function compile(
debugIRLogger,
EffectEnum,
ValueKindEnum,
ValueReasonEnum,
);
if (result.kind === 'err') {

View File

@@ -5,21 +5,15 @@
* LICENSE file in the root directory of this source tree.
*/
import type {
Effect,
ValueKind,
ValueReason,
} from 'babel-plugin-react-compiler/src';
import type {Effect, ValueKind} from 'babel-plugin-react-compiler/src';
import type {TypeConfig} from 'babel-plugin-react-compiler/src/HIR/TypeSchema';
export function makeSharedRuntimeTypeProvider({
EffectEnum,
ValueKindEnum,
ValueReasonEnum,
}: {
EffectEnum: typeof Effect;
ValueKindEnum: typeof ValueKind;
ValueReasonEnum: typeof ValueReason;
}) {
return function sharedRuntimeTypeProvider(
moduleName: string,
@@ -75,127 +69,6 @@ export function makeSharedRuntimeTypeProvider({
returnValueKind: ValueKindEnum.Mutable,
noAlias: true,
},
typedIdentity: {
kind: 'function',
positionalParams: [EffectEnum.Read],
restParam: null,
calleeEffect: EffectEnum.Read,
returnType: {kind: 'type', name: 'Any'},
returnValueKind: ValueKindEnum.Mutable,
aliasing: {
receiver: '@receiver',
params: ['@value'],
rest: null,
returns: '@return',
temporaries: [],
effects: [{kind: 'Assign', from: '@value', into: '@return'}],
},
},
typedAssign: {
kind: 'function',
positionalParams: [EffectEnum.Read],
restParam: null,
calleeEffect: EffectEnum.Read,
returnType: {kind: 'type', name: 'Any'},
returnValueKind: ValueKindEnum.Mutable,
aliasing: {
receiver: '@receiver',
params: ['@value'],
rest: null,
returns: '@return',
temporaries: [],
effects: [{kind: 'Assign', from: '@value', into: '@return'}],
},
},
typedAlias: {
kind: 'function',
positionalParams: [EffectEnum.Read],
restParam: null,
calleeEffect: EffectEnum.Read,
returnType: {kind: 'type', name: 'Any'},
returnValueKind: ValueKindEnum.Mutable,
aliasing: {
receiver: '@receiver',
params: ['@value'],
rest: null,
returns: '@return',
temporaries: [],
effects: [
{
kind: 'Create',
into: '@return',
value: ValueKindEnum.Mutable,
reason: ValueReasonEnum.KnownReturnSignature,
},
{kind: 'Alias', from: '@value', into: '@return'},
],
},
},
typedCapture: {
kind: 'function',
positionalParams: [EffectEnum.Read],
restParam: null,
calleeEffect: EffectEnum.Read,
returnType: {kind: 'type', name: 'Array'},
returnValueKind: ValueKindEnum.Mutable,
aliasing: {
receiver: '@receiver',
params: ['@value'],
rest: null,
returns: '@return',
temporaries: [],
effects: [
{
kind: 'Create',
into: '@return',
value: ValueKindEnum.Mutable,
reason: ValueReasonEnum.KnownReturnSignature,
},
{kind: 'Capture', from: '@value', into: '@return'},
],
},
},
typedCreateFrom: {
kind: 'function',
positionalParams: [EffectEnum.Read],
restParam: null,
calleeEffect: EffectEnum.Read,
returnType: {kind: 'type', name: 'Any'},
returnValueKind: ValueKindEnum.Mutable,
aliasing: {
receiver: '@receiver',
params: ['@value'],
rest: null,
returns: '@return',
temporaries: [],
effects: [{kind: 'CreateFrom', from: '@value', into: '@return'}],
},
},
typedMutate: {
kind: 'function',
positionalParams: [EffectEnum.Read, EffectEnum.Capture],
restParam: null,
calleeEffect: EffectEnum.Store,
returnType: {kind: 'type', name: 'Primitive'},
returnValueKind: ValueKindEnum.Primitive,
aliasing: {
receiver: '@receiver',
params: ['@object', '@value'],
rest: null,
returns: '@return',
temporaries: [],
effects: [
{
kind: 'Create',
into: '@return',
value: ValueKindEnum.Primitive,
reason: ValueReasonEnum.KnownReturnSignature,
},
{kind: 'Mutate', value: '@object'},
{kind: 'Capture', from: '@value', into: '@object'},
],
},
},
},
};
} else if (moduleName === 'ReactCompilerTest') {

View File

@@ -272,7 +272,7 @@ export function ValidateMemoization({
}: {
inputs: Array<any>;
output: any;
onlyCheckCompiled?: boolean;
onlyCheckCompiled: boolean;
}): React.ReactElement {
'use no forget';
// Wrap rawOutput as it might be a function, which useState would invoke.
@@ -280,9 +280,8 @@ export function ValidateMemoization({
const [previousInputs, setPreviousInputs] = React.useState(inputs);
const [previousOutput, setPreviousOutput] = React.useState(output);
if (
!onlyCheckCompiled ||
(onlyCheckCompiled &&
(globalThis as any).__SNAP_EVALUATOR_MODE === 'forget')
onlyCheckCompiled &&
(globalThis as any).__SNAP_EVALUATOR_MODE === 'forget'
) {
if (
inputs.length !== previousInputs.length ||
@@ -397,28 +396,4 @@ export function typedLog(...values: Array<any>): void {
console.log(...values);
}
export function typedIdentity<T>(value: T): T {
return value;
}
export function typedAssign<T>(x: T): T {
return x;
}
export function typedAlias<T>(x: T): T {
return x;
}
export function typedCapture<T>(x: T): Array<T> {
return [x];
}
export function typedCreateFrom<T>(array: Array<T>): T {
return array[0];
}
export function typedMutate(x: any, v: any = null): void {
x.property = v;
}
export default typedLog;