Map React Compiler source tree (@explore subagent)

/home/jm/data/ai/cloudlang-trees/react · 14 messages · 75 parts · · 82,543 tokens
Created Feb 10, 02:29:39 AM · Updated Feb 11, 04:54:40 AM · 1 syncs
userFeb 10, 02:29:39 AM

I need you to thoroughly explore the React Compiler source code. It's likely located somewhere accessible - check these locations:

  • /home/jm/data/ai/cloudlang-trees/react (might be a monorepo)
  • Look for any git submodules
  • Search for directories containing "react-compiler" or "babel-plugin-react-compiler"
  • Check if there's a node_modules or vendor directory with react compiler source

If you can't find it locally, note that so we can clone it.

The React Compiler lives at https://github.com/facebook/react in compiler/ directory. The key source is in:

  • compiler/packages/babel-plugin-react-compiler/src/

I need:

  1. The full directory listing of the compiler source
  2. The main entry point and pipeline orchestration file
  3. List of all compilation passes/phases
  4. The HIR (High-level IR) type definitions
  5. The inference passes (especially around aliasing, effects, mutation)

Return comprehensive file listings and key architectural observations.

assistantFeb 10, 02:29:39 AM
claude-opus-4.6 · github-copilot

I'll systematically explore the React Compiler source code. Let me start by checking the local repository structure.

bashcompleted
List root directory contents
Output
total 36
drwxrwxr-x 1 jm jm  272 Feb 10 02:11 .
drwxrwxr-x 1 jm jm   10 Feb 10 02:11 ..
drwxrwxr-x 1 jm jm   14 Feb 10 02:11 .claude
-rw-rw-r-- 1 jm jm   56 Feb 10 02:11 .git
drwxrwxr-x 1 jm jm   18 Feb 10 02:11 .github
-rw-rw-r-- 1 jm jm  401 Feb 10 02:11 .gitignore
-rw-rw-r-- 1 jm jm   17 Feb 10 02:11 .ocamlformat
drwxrwxr-x 1 jm jm   58 Feb 10 02:17 .opencode
-rw-rw-r-- 1 jm jm 7364 Feb 10 02:11 AGENTS.md
-rw-rw-r-- 1 jm jm  351 Feb 10 02:11 LICENSE.md
-rw-rw-r-- 1 jm jm  671 Feb 10 02:11 README.md
drwxrwxr-x 1 jm jm   22 Feb 10 02:11 bin
-rw-rw-r-- 1 jm jm  709 Feb 10 02:11 cloudlang.opam
drwxrwxr-x 1 jm jm   56 Feb 10 02:11 docs
-rw-rw-r-- 1 jm jm  371 Feb 10 02:11 dune-project
drwxrwxr-x 1 jm jm  130 Feb 10 02:11 examples
drwxrwxr-x 1 jm jm  446 Feb 10 02:11 lib
drwxrwxr-x 1 jm jm  338 Feb 10 02:11 test
drwxrwxr-x 1 jm jm   48 Feb 10 02:11 tools
drwxrwxr-x 1 jm jm   66 Feb 10 02:11 verify
bashcompleted
Check for git submodules
globcompleted
Output
No files found
globcompleted
Output
No files found
557in / 249out
assistantFeb 10, 02:29:43 AM
claude-opus-4.6 · github-copilot

No compiler directory locally. Let me check if this is a git worktree or submodule pointing elsewhere, and look for the React source in parent/sibling directories.

bashcompleted
Check if .git is a file (worktree/submodule)
Output
gitdir: /home/jm/data/ai/cloudlang/.git/worktrees/react
bashcompleted
List sibling directories
Output
react
bashcompleted
Search for react compiler directory
1,536in / 293out
assistantFeb 10, 02:29:48 AM
claude-opus-4.6 · github-copilot
bashcompleted
Check main cloudlang repo
Output
AGENTS.md
LICENSE.md
README.md
_build
bin
cloudlang.opam
docs
dune-project
dune.lock
examples
lib
out
session-ses_3cfd.md
test
tools
verify
bashcompleted
Broader search for react compiler
409in / 248out
assistantFeb 10, 02:29:54 AM
claude-opus-4.6 · github-copilot

The React Compiler source is not available locally. Let me fetch it from the GitHub repository directly.

webfetchcompleted
https://github.com/facebook/react/tree/main/compiler/packages/babel-plugin-react-compiler/src (text/html; charset=utf-8)
Output
                     react/compiler/packages/babel-plugin-react-compiler/src at main · facebook/react · GitHub                                             

[Skip to content](#start-of-content)   

## Navigation Menu

Toggle navigation

[](/)

[Sign in](/login?return_to=https%3A%2F%2Fgithub.com%2Ffacebook%2Freact%2Ftree%2Fmain%2Fcompiler%2Fpackages%2Fbabel-plugin-react-compiler%2Fsrc)

Appearance settings

  

-   Platform
    
    -   AI CODE CREATION
        
        -   [
            
            GitHub CopilotWrite better code with AI
            
            ](https://github.com/features/copilot)
        -   [
            
            GitHub SparkBuild and deploy intelligent apps
            
            ](https://github.com/features/spark)
        -   [
            
            GitHub ModelsManage and compare prompts
            
            ](https://github.com/features/models)
        -   [
            
            MCP RegistryNewIntegrate external tools
            
            ](https://github.com/mcp)
        
    -   DEVELOPER WORKFLOWS
        
        -   [
            
            ActionsAutomate any workflow
            
            ](https://github.com/features/actions)
        -   [
            
            CodespacesInstant dev environments
            
            ](https://github.com/features/codespaces)
        -   [
            
            IssuesPlan and track work
            
            ](https://github.com/features/issues)
        -   [
            
            Code ReviewManage code changes
            
            ](https://github.com/features/code-review)
        
    -   APPLICATION SECURITY
        
        -   [
            
            GitHub Advanced SecurityFind and fix vulnerabilities
            
            ](https://github.com/security/advanced-security)
        -   [
            
            Code securitySecure your code as you build
            
            ](https://github.com/security/advanced-security/code-security)
    ...
webfetchcompleted
https://github.com/facebook/react/tree/main/compiler (text/html; charset=utf-8)
Output
                     react/compiler at main · facebook/react · GitHub                                             

[Skip to content](#start-of-content)   

## Navigation Menu

Toggle navigation

[](/)

[Sign in](/login?return_to=https%3A%2F%2Fgithub.com%2Ffacebook%2Freact%2Ftree%2Fmain%2Fcompiler)

Appearance settings

  

-   Platform
    
    -   AI CODE CREATION
        
        -   [
            
            GitHub CopilotWrite better code with AI
            
            ](https://github.com/features/copilot)
        -   [
            
            GitHub SparkBuild and deploy intelligent apps
            
            ](https://github.com/features/spark)
        -   [
            
            GitHub ModelsManage and compare prompts
            
            ](https://github.com/features/models)
        -   [
            
            MCP RegistryNewIntegrate external tools
            
            ](https://github.com/mcp)
        
    -   DEVELOPER WORKFLOWS
        
        -   [
            
            ActionsAutomate any workflow
            
            ](https://github.com/features/actions)
        -   [
            
            CodespacesInstant dev environments
            
            ](https://github.com/features/codespaces)
        -   [
            
            IssuesPlan and track work
            
            ](https://github.com/features/issues)
        -   [
            
            Code ReviewManage code changes
            
            ](https://github.com/features/code-review)
        
    -   APPLICATION SECURITY
        
        -   [
            
            GitHub Advanced SecurityFind and fix vulnerabilities
            
            ](https://github.com/security/advanced-security)
        -   [
            
            Code securitySecure your code as you build
            
            ](https://github.com/security/advanced-security/code-security)
        -   [
            
            Secret protectionStop leaks before they start
       ...
373in / 184out
assistantFeb 10, 02:29:58 AM
claude-opus-4.6 · github-copilot

GitHub's web UI requires authentication. Let me use the GitHub API directly to get directory listings.

bashcompleted
List compiler src directory via GitHub API
Output
Babel/
CompilerError.ts
Entrypoint/
Flood/
HIR/
Inference/
Optimization/
ReactiveScopes/
SSA/
Transform/
TypeInference/
Utils/
Validation/
__tests__/
index.ts
bashcompleted
List compiler root directory via GitHub API
Output
.claude/
.eslintrc.js
.gitignore
CHANGELOG.md
CLAUDE.md
README.md
apps/
docs/
fixtures/
package.json
packages/
scripts/
yarn.lock
5,436in / 260out
assistantFeb 10, 02:30:03 AM
claude-opus-4.6 · github-copilot

Excellent! I have access via the GitHub CLI. Now let me systematically explore every subdirectory and fetch key files.

bashcompleted
List compiler packages
Output
babel-plugin-react-compiler/
eslint-plugin-react-compiler/
make-read-only-util/
react-compiler-healthcheck/
react-compiler-runtime/
react-forgive/
react-mcp-server/
snap/
bashcompleted
List all subdirectories in compiler src
Output
=== Babel ===
  BabelPlugin.ts
  RunReactCompilerBabelPlugin.ts
=== CompilerError ===
{"message":"Not Found","documentation_url":"https://docs.github.com/rest/repos/contents#get-repository-content","status":"404"}=== Entrypoint ===
  Gating.ts
  Imports.ts
  Options.ts
  Pipeline.ts
  Program.ts
  Reanimated.ts
  Suppression.ts
  ValidateNoUntransformedReferences.ts
  index.ts
=== Flood ===
  FlowTypes.ts
  TypeErrors.ts
  TypeUtils.ts
  Types.ts
=== HIR ===
  AssertConsistentIdentifiers.ts
  AssertTerminalBlocksExist.ts
  AssertValidBlockNesting.ts
  AssertValidMutableRanges.ts
  BuildHIR.ts
  BuildReactiveScopeTerminalsHIR.ts
  CollectHoistablePropertyLoads.ts
  CollectOptionalChainDependencies.ts
  ComputeUnconditionalBlocks.ts
  DefaultModuleTypeProvider.ts
  DeriveMinimalDependenciesHIR.ts
  Dominator.ts
  Environment.ts
  FindContextIdentifiers.ts
  Globals.ts
  HIR.ts
  HIRBuilder.ts
  MergeConsecutiveBlocks.ts
  MergeOverlappingReactiveScopesHIR.ts
  ObjectShape.ts
  PrintHIR.ts
  PropagateScopeDependenciesHIR.ts
  PruneUnusedLabelsHIR.ts
  ScopeDependencyUtils.ts
  TypeSchema.ts
  Types.ts
  index.ts
  visitors.ts
=== Inference ===
  AliasingEffects.ts
  AnalyseFunctions.ts
  ControlDominators.ts
  DropManualMemoization.ts
  InferEffectDependencies.ts
  InferMutationAliasingEffects.ts
  InferMutationAliasingRanges.ts
  InferReactivePlaces.ts
  InlineImmediatelyInvokedFunctionExpressions.ts
  MUTABILITY_ALIASING_MODEL.md
  index.ts
=== Optimization ===
  ConstantPropagation.ts
  DeadCodeElimination.ts
  InlineJsxTransform.ts
  InstructionReordering.ts
  LowerContextAccess.ts
  OptimizeForSSR.ts
  OptimizePropsMethodCalls.ts
  OutlineFunctions.ts
  OutlineJsx.ts
  PruneMaybeThrows.ts
  index.ts
=== ReactiveScopes ===
  AlignMethodCallScopes.ts
  AlignObjectMethodScopes.ts
  AlignReactiveScopesToBlockScopesHIR.ts
  AssertScopeInstructionsWithinScope.ts
  AssertWellFormedBreakTargets.ts
  BuildReactiveFunction.ts
  CodegenReactiveFunction.ts
  CollectReactiveId...
438in / 299out
assistantFeb 10, 02:30:10 AM
claude-opus-4.6 · github-copilot

Now let me fetch the key architectural files -- the pipeline, entry point, HIR types, and inference passes:

bashcompleted
Fetch Pipeline.ts - main compilation pipeline
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {NodePath} from '@babel/traverse';
import * as t from '@babel/types';
import prettyFormat from 'pretty-format';
import {CompilerOutputMode, Logger, ProgramContext} from '.';
import {
  HIRFunction,
  ReactiveFunction,
  assertConsistentIdentifiers,
  assertTerminalPredsExist,
  assertTerminalSuccessorsExist,
  assertValidBlockNesting,
  assertValidMutableRanges,
  buildReactiveScopeTerminalsHIR,
  lower,
  mergeConsecutiveBlocks,
  mergeOverlappingReactiveScopesHIR,
  pruneUnusedLabelsHIR,
} from '../HIR';
import {
  Environment,
  EnvironmentConfig,
  ReactFunctionType,
} from '../HIR/Environment';
import {findContextIdentifiers} from '../HIR/FindContextIdentifiers';
import {
  analyseFunctions,
  dropManualMemoization,
  inferReactivePlaces,
  inlineImmediatelyInvokedFunctionExpressions,
  inferEffectDependencies,
} from '../Inference';
import {
  constantPropagation,
  deadCodeElimination,
  pruneMaybeThrows,
  inlineJsxTransform,
} from '../Optimization';
import {instructionReordering} from '../Optimization/InstructionReordering';
import {
  CodegenFunction,
  alignObjectMethodScopes,
  assertScopeInstructionsWithinScopes,
  assertWellFormedBreakTargets,
  buildReactiveFunction,
  codegenFunction,
  extractScopeDeclarationsFromDestructuring,
  inferReactiveScopeVariables,
  memoizeFbtAndMacroOperandsInSameScope,
  mergeReactiveScopesThatInvalidateTogether,
  promoteUsedTemporaries,
  propagateEarlyReturns,
  pruneHoistedContexts,
  pruneNonEscapingScopes,
  pruneNonReactiveDependencies,
  pruneUnusedLValues,
  pruneUnusedLabels,
  pruneUnusedScopes,
  renameVariables,
} from '../ReactiveScopes';
import {alignMethodCallScopes} from '../ReactiveScopes/AlignMethodCallScopes';
import {alignReactiveScopesToBlockScopesHIR} from '../ReactiveScopes/AlignReactiveScopesToBlock...
bashcompleted
Fetch main index.ts entry point
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

export {runBabelPluginReactCompiler} from './Babel/RunReactCompilerBabelPlugin';
export {
  CompilerError,
  CompilerErrorDetail,
  CompilerDiagnostic,
  CompilerSuggestionOperation,
  ErrorSeverity,
  ErrorCategory,
  LintRules,
  LintRulePreset,
  type CompilerErrorDetailOptions,
  type CompilerDiagnosticOptions,
  type CompilerDiagnosticDetail,
  type LintRule,
} from './CompilerError';
export {
  compileFn as compile,
  compileProgram,
  parsePluginOptions,
  OPT_OUT_DIRECTIVES,
  OPT_IN_DIRECTIVES,
  ProgramContext,
  tryFindDirectiveEnablingMemoization as findDirectiveEnablingMemoization,
  findDirectiveDisablingMemoization,
  defaultOptions,
  type CompilerPipelineValue,
  type Logger,
  type LoggerEvent,
  type PluginOptions,
  type AutoDepsDecorationsEvent,
  type CompileSuccessEvent,
} from './Entrypoint';
export {
  Effect,
  ValueKind,
  ValueReason,
  printHIR,
  printFunctionWithOutlined,
  validateEnvironmentConfig,
  type EnvironmentConfig,
  type ExternalFunction,
  type Hook,
  type SourceLocation,
} from './HIR';
export {
  printReactiveFunction,
  printReactiveFunctionWithOutlined,
} from './ReactiveScopes';
export {parseConfigPragmaForTests} from './Utils/TestUtils';
declare global {
  // @internal
  let __DEV__: boolean | null | undefined;
}

import BabelPluginReactCompiler from './Babel/BabelPlugin';
export default BabelPluginReactCompiler;
bashcompleted
Fetch Entrypoint index.ts
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

export * from './Gating';
export * from './Imports';
export * from './Options';
export * from './Pipeline';
export * from './Program';
export * from './Suppression';
2,016in / 341out
assistantFeb 10, 02:30:15 AM
claude-opus-4.6 · github-copilot

Now let me fetch the HIR type definitions and the key inference files:

bashcompleted
Fetch HIR.ts - core type definitions
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {BindingKind} from '@babel/traverse';
import * as t from '@babel/types';
import {
  CompilerDiagnostic,
  CompilerError,
  ErrorCategory,
} from '../CompilerError';
import {assertExhaustive} from '../Utils/utils';
import {Environment, ReactFunctionType} from './Environment';
import type {HookKind} from './ObjectShape';
import {Type, makeType} from './Types';
import {z} from 'zod/v4';
import type {AliasingEffect} from '../Inference/AliasingEffects';
import {isReservedWord} from '../Utils/Keyword';
import {Err, Ok, Result} from '../Utils/Result';

/*
 * *******************************************************************************************
 * *******************************************************************************************
 * ************************************* Core Data Model *************************************
 * *******************************************************************************************
 * *******************************************************************************************
 */

// AST -> (lowering) -> HIR -> (analysis) -> Reactive Scopes -> (codegen) -> AST

/*
 * A location in a source file, intended to be used for providing diagnostic information and
 * transforming code while preserving source information (ie to emit source maps).
 *
 * `GeneratedSource` indicates that there is no single source location from which the code derives.
 */
export const GeneratedSource = Symbol();
export type SourceLocation = t.SourceLocation | typeof GeneratedSource;

/*
 * A React function defines a computation that takes some set of reactive inputs
 * (props, hook arguments) and return a result (JSX, hook return value). Unlike
 * HIR, the data model is tree-shaped:
 *
 * ReactFunction
 *    ReactiveBlock
 *      ReactiveBlockScope*
 *       Plac...
bashcompleted
Fetch InferMutationAliasingEffects.ts
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {
  CompilerDiagnostic,
  CompilerError,
  Effect,
  SourceLocation,
  ValueKind,
} from '..';
import {
  BasicBlock,
  BlockId,
  DeclarationId,
  Environment,
  FunctionExpression,
  GeneratedSource,
  getHookKind,
  HIRFunction,
  Hole,
  IdentifierId,
  Instruction,
  InstructionKind,
  InstructionValue,
  isArrayType,
  isJsxType,
  isMapType,
  isPrimitiveType,
  isRefOrRefValue,
  isSetType,
  makeIdentifierId,
  Phi,
  Place,
  SpreadPattern,
  Type,
  ValueReason,
} from '../HIR';
import {
  eachInstructionValueOperand,
  eachPatternItem,
  eachTerminalOperand,
  eachTerminalSuccessor,
} from '../HIR/visitors';
import {Ok, Result} from '../Utils/Result';
import {
  assertExhaustive,
  getOrInsertDefault,
  getOrInsertWith,
  Set_isSuperset,
} from '../Utils/utils';
import {
  printAliasingEffect,
  printAliasingSignature,
  printIdentifier,
  printInstruction,
  printInstructionValue,
  printPlace,
} from '../HIR/PrintHIR';
import {FunctionSignature} from '../HIR/ObjectShape';
import prettyFormat from 'pretty-format';
import {createTemporaryPlace} from '../HIR/HIRBuilder';
import {
  AliasingEffect,
  AliasingSignature,
  hashEffect,
  MutationReason,
} from './AliasingEffects';
import {ErrorCategory} from '../CompilerError';

const DEBUG = false;

/**
 * Infers the mutation/aliasing effects for instructions and terminals and annotates
 * them on the HIR, making the effects of builtin instructions/functions as well as
 * user-defined functions explicit. These effects then form the basis for subsequent
 * analysis to determine the mutable range of each value in the program — the set of
 * instructions over which the value is created and mutated — as well as validation
 * against invalid code.
 *
 * At a high level the approach is:
 * - Determine a set of candidat...
bashcompleted
Fetch AliasingEffects.ts - effect definitions
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {CompilerDiagnostic} from '../CompilerError';
import {
  FunctionExpression,
  GeneratedSource,
  Hole,
  IdentifierId,
  ObjectMethod,
  Place,
  SourceLocation,
  SpreadPattern,
  ValueKind,
  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
 * more values in a program. These effects include mutation of values, freezing values,
 * tracking data flow between values, and other specialized cases.
 */
export type AliasingEffect =
  /**
   * Marks the given value and its direct aliases as frozen.
   *
   * Captured values are *not* considered frozen, because we cannot be sure that a previously
   * captured value will still be captured at the point of the freeze.
   *
   * For example:
   * const x = {};
   * const y = [x];
   * y.pop(); // y dosn't contain x anymore!
   * freeze(y);
   * mutate(x); // safe to mutate!
   *
   * The exception to this is FunctionExpressions - since it is impossible to change which
   * value a function closes over[1] we can transitively freeze functions and their captures.
   *
   * [1] Except for `let` values that are reassigned and closed over by a function, but we
   * handle this explicitly with StoreContext/LoadContext.
   */
  | {kind: 'Freeze'; value: Place; reason: ValueReason}
  /**
   * Mutate the value and any direct aliases (not captures). Errors if the value is not mutable.
   */
  | {kind: 'Mutate'; value: Place; reason?: MutationReason | null}
  /**
   * Mutate the value and any direct aliases (not captures), but only if the value is known mutable.
   * This should be rare.
   *
   * TODO: this is only used for IteratorNext, but even then MutateT...
7,323in / 410out
assistantFeb 10, 02:30:23 AM
claude-opus-4.6 · github-copilot

Now let me fetch the remaining key inference files and the other important modules:

bashcompleted
Fetch InferMutationAliasingRanges.ts header
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {CompilerError, SourceLocation} from '..';
import {
  BlockId,
  Effect,
  HIRFunction,
  Identifier,
  IdentifierId,
  InstructionId,
  isJsxType,
  makeInstructionId,
  ValueKind,
  ValueReason,
  Place,
  isPrimitiveType,
} from '../HIR/HIR';
import {
  eachInstructionLValue,
  eachInstructionValueOperand,
  eachTerminalOperand,
} from '../HIR/visitors';
import {assertExhaustive, getOrInsertWith} from '../Utils/utils';
import {Err, Ok, Result} from '../Utils/Result';
import {AliasingEffect, MutationReason} from './AliasingEffects';

/**
 * This pass builds an abstract model of the heap and interprets the effects of the
 * given function in order to determine the following:
 * - The mutable ranges of all identifiers in the function
 * - The externally-visible effects of the function, such as mutations of params and
 *   context-vars, aliasing between params/context-vars/return-value, and impure side
 *   effects.
 * - The legacy `Effect` to store on each Place.
 *
 * This pass builds a data flow graph using the effects, tracking an abstract notion
 * of "when" each effect occurs relative to the others. It then walks each mutation
 * effect against the graph, updating the range of each node that would be reachable
 * at the "time" that the effect occurred.
 *
 * This pass also validates against invalid effects: any function that is reachable
 * by being called, or via a Render effect, is validated against mutating globals
 * or calling impure code.
 *
 * Note that this function also populates the outer function's aliasing effects with
 * any mutations that apply to its params or context variables.
 *
 * ## Example
 * A function expression such as the following:
 *
 * ```
 * (x) => { x.y = true }
 * ```
 *
 * Would populate a `Mutate x` aliasing effect on the outer funct...
bashcompleted
Fetch InferReactivePlaces.ts header
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {CompilerError} from '..';
import {
  Effect,
  Environment,
  HIRFunction,
  Identifier,
  IdentifierId,
  Instruction,
  Place,
  evaluatesToStableTypeOrContainer,
  getHookKind,
  isStableType,
  isStableTypeContainer,
  isUseOperator,
} from '../HIR';
import {
  eachInstructionLValue,
  eachInstructionOperand,
  eachInstructionValueOperand,
  eachTerminalOperand,
} from '../HIR/visitors';
import {
  findDisjointMutableValues,
  isMutable,
} from '../ReactiveScopes/InferReactiveScopeVariables';
import DisjointSet from '../Utils/DisjointSet';
import {assertExhaustive} from '../Utils/utils';
import {createControlDominators} from './ControlDominators';

/**
 * Side map to track and propagate sources of stability (i.e. hook calls such as
 * `useRef()` and property reads such as `useState()[1]). Note that this
 * requires forward data flow analysis since stability is not part of React
 * Compiler's type system.
 */
class StableSidemap {
  map: Map<IdentifierId, {isStable: boolean}> = new Map();
  env: Environment;

  constructor(env: Environment) {
    this.env = env;
  }

  handleInstruction(instr: Instruction): void {
    const {value, lvalue} = instr;

    switch (value.kind) {
      case 'CallExpression':
      case 'MethodCall': {
        /**
         * Sources of stability are known hook calls
         */
        if (evaluatesToStableTypeOrContainer(this.env, instr)) {
          if (isStableType(lvalue.identifier)) {
            this.map.set(lvalue.identifier.id, {
              isStable: true,
            });
          } else {
            this.map.set(lvalue.identifier.id, {
              isStable: false,
            });
          }
        }
        break;
      }

      case 'Destructure':
      case 'PropertyLoad': {
        /**
         * PropertyLoads may from...
bashcompleted
Fetch AnalyseFunctions.ts header
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {CompilerError} from '../CompilerError';
import {Effect, HIRFunction, IdentifierId, makeInstructionId} from '../HIR';
import {deadCodeElimination} from '../Optimization';
import {inferReactiveScopeVariables} from '../ReactiveScopes';
import {rewriteInstructionKindsBasedOnReassignment} from '../SSA';
import {assertExhaustive} from '../Utils/utils';
import {inferMutationAliasingEffects} from './InferMutationAliasingEffects';
import {inferMutationAliasingRanges} from './InferMutationAliasingRanges';

export default function analyseFunctions(func: HIRFunction): void {
  for (const [_, block] of func.body.blocks) {
    for (const instr of block.instructions) {
      switch (instr.value.kind) {
        case 'ObjectMethod':
        case 'FunctionExpression': {
          lowerWithMutationAliasing(instr.value.loweredFunc.func);

          /**
           * 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.scope = null;
          }
          break;
        }
      }
    }
  }
}

function lowerWithMutationAliasing(fn: HIRFunction): void {
  /**
   * Phase 1: similar to lower(), but using the new mutation/aliasing inference
   */
  analyseFunctions(fn);
  inferMutationAliasingEffe...
bashcompleted
Fetch mutability aliasing model docs
Output
# 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 whi...
34,518in / 481out
assistantFeb 10, 02:30:32 AM
claude-opus-4.6 · github-copilot

Now let me fetch the remaining important files for a comprehensive view:

bashcompleted
Fetch Options.ts header
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import * as t from '@babel/types';
import {z} from 'zod/v4';
import {
  CompilerDiagnostic,
  CompilerError,
  CompilerErrorDetail,
  CompilerErrorDetailOptions,
} from '../CompilerError';
import {
  EnvironmentConfig,
  ExternalFunction,
  parseEnvironmentConfig,
  tryParseExternalFunction,
} from '../HIR/Environment';
import {hasOwnProperty} from '../Utils/utils';
import {fromZodError} from 'zod-validation-error/v4';
import {CompilerPipelineValue} from './Pipeline';

const PanicThresholdOptionsSchema = z.enum([
  /*
   * Any errors will panic the compiler by throwing an exception, which will
   * bubble up to the nearest exception handler above the Forget transform.
   * If Forget is invoked through `BabelPluginReactCompiler`, this will at the least
   * skip Forget compilation for the rest of current file.
   */
  'all_errors',
  /*
   * Panic by throwing an exception only on critical or unrecognized errors.
   * For all other errors, skip the erroring function without inserting
   * a Forget-compiled version (i.e. same behavior as noEmit).
   */
  'critical_errors',
  // Never panic by throwing an exception.
  'none',
]);

export type PanicThresholdOptions = z.infer<typeof PanicThresholdOptionsSchema>;
const DynamicGatingOptionsSchema = z.object({
  source: z.string(),
});
export type DynamicGatingOptions = z.infer<typeof DynamicGatingOptionsSchema>;
const CustomOptOutDirectiveSchema = z
  .nullable(z.array(z.string()))
  .default(null);
type CustomOptOutDirective = z.infer<typeof CustomOptOutDirectiveSchema>;

export type PluginOptions = Partial<{
  environment: Partial<EnvironmentConfig>;

  logger: Logger | null;

  /*
   * Specifying a `gating` config, makes Forget compile and emit a separate
   * version of the function gated by importing the `gating.importSpecifierNam...
bashcompleted
Fetch Environment.ts header
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import * as t from '@babel/types';
import {ZodError, z} from 'zod/v4';
import {fromZodError} from 'zod-validation-error/v4';
import {CompilerError} from '../CompilerError';
import {CompilerOutputMode, Logger, ProgramContext} from '../Entrypoint';
import {Err, Ok, Result} from '../Utils/Result';
import {
  DEFAULT_GLOBALS,
  DEFAULT_SHAPES,
  Global,
  GlobalRegistry,
  getReanimatedModuleType,
  installTypeConfig,
} from './Globals';
import {
  BlockId,
  BuiltInType,
  Effect,
  FunctionType,
  GeneratedSource,
  HIRFunction,
  IdentifierId,
  NonLocalBinding,
  PolyType,
  ScopeId,
  SourceLocation,
  Type,
  ValidatedIdentifier,
  ValueKind,
  getHookKindForType,
  makeBlockId,
  makeIdentifierId,
  makeIdentifierName,
  makeScopeId,
} from './HIR';
import {
  BuiltInMixedReadonlyId,
  DefaultMutatingHook,
  DefaultNonmutatingHook,
  FunctionSignature,
  ShapeRegistry,
  addHook,
} from './ObjectShape';
import {Scope as BabelScope, NodePath} from '@babel/traverse';
import {TypeSchema} from './TypeSchema';
import {FlowTypeEnv} from '../Flood/Types';
import {defaultModuleTypeProvider} from './DefaultModuleTypeProvider';
import {assertExhaustive} from '../Utils/utils';

export const ReactElementSymbolSchema = z.object({
  elementSymbol: z.union([
    z.literal('react.element'),
    z.literal('react.transitional.element'),
  ]),
  globalDevVar: z.string(),
});

export const ExternalFunctionSchema = z.object({
  // Source for the imported module that exports the `importSpecifierName` functions
  source: z.string(),

  // Unique name for the feature flag test condition, eg `isForgetEnabled_ProjectName`
  importSpecifierName: z.string(),
});

export const InstrumentationSchema = z
  .object({
    fn: ExternalFunctionSchema,
    gating: ExternalFunctionSchema.nullable(),
    globalG...
bashcompleted
Fetch HIR index.ts exports
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

export {assertConsistentIdentifiers} from './AssertConsistentIdentifiers';
export {
  assertTerminalSuccessorsExist,
  assertTerminalPredsExist,
} from './AssertTerminalBlocksExist';
export {assertValidBlockNesting} from './AssertValidBlockNesting';
export {assertValidMutableRanges} from './AssertValidMutableRanges';
export {lower} from './BuildHIR';
export {buildReactiveScopeTerminalsHIR} from './BuildReactiveScopeTerminalsHIR';
export {computeDominatorTree, computePostDominatorTree} from './Dominator';
export {
  Environment,
  validateEnvironmentConfig,
  type EnvironmentConfig,
  type ExternalFunction,
  type Hook,
} from './Environment';
export * from './HIR';
export {
  markInstructionIds,
  markPredecessors,
  removeUnnecessaryTryCatch,
  reversePostorderBlocks,
} from './HIRBuilder';
export {mergeConsecutiveBlocks} from './MergeConsecutiveBlocks';
export {mergeOverlappingReactiveScopesHIR} from './MergeOverlappingReactiveScopesHIR';
export {printFunction, printHIR, printFunctionWithOutlined} from './PrintHIR';
export {pruneUnusedLabelsHIR} from './PruneUnusedLabelsHIR';
bashcompleted
Fetch Inference index.ts exports
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

export {default as analyseFunctions} from './AnalyseFunctions';
export {dropManualMemoization} from './DropManualMemoization';
export {inferReactivePlaces} from './InferReactivePlaces';
export {inlineImmediatelyInvokedFunctionExpressions} from './InlineImmediatelyInvokedFunctionExpressions';
export {inferEffectDependencies} from './InferEffectDependencies';
8,286in / 433out
assistantFeb 10, 02:30:38 AM
claude-opus-4.6 · github-copilot

Now let me get the remaining important files for completeness:

bashcompleted
Fetch HIR Types.ts
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {CompilerError} from '../CompilerError';
import {GeneratedSource, PropertyLiteral} from './HIR';

export type BuiltInType = PrimitiveType | FunctionType | ObjectType;

export type Type =
  | BuiltInType
  | PhiType
  | TypeVar
  | PolyType
  | PropType
  | ObjectMethod;
export type PrimitiveType = {kind: 'Primitive'};

/*
 * An {@link FunctionType} or {@link ObjectType} (also a JS object) may be associated with an
 * inferred "object shape", i.e. a known property (key -> Type) map. This is
 * subtly different from JS language semantics - `shape` represents both
 * OwnPropertyDescriptors and properties present in the prototype chain.
 *
 * {@link ObjectShape.functionType} is always present on the shape of a {@link FunctionType},
 * and it represents the call signature of the function. Note that Forget thinks of a
 * {@link FunctionType} as any "callable object" (not to be confused with objects that
 *   extend the global `Function`.)
 *
 * If `shapeId` is present, it is a key into the ShapeRegistry used to infer this
 * FunctionType or ObjectType instance (i.e. from an Environment).
 */

export type FunctionType = {
  kind: 'Function';
  shapeId: string | null;
  return: Type;
  isConstructor: boolean;
};

export type ObjectType = {
  kind: 'Object';
  shapeId: string | null;
};

export type TypeVar = {
  kind: 'Type';
  id: TypeId;
};
export type PolyType = {
  kind: 'Poly';
};
export type PhiType = {
  kind: 'Phi';
  operands: Array<Type>;
};
export type PropType = {
  kind: 'Property';
  objectType: Type;
  objectName: string;
  propertyName:
    | {
        kind: 'literal';
        value: PropertyLiteral;
      }
    | {
        kind: 'computed';
        value: Type;
      };
};

export type ObjectMethod = {
  kind: 'ObjectMethod';
};

/*
 * Simulated opaque type for ...
bashcompleted
Fetch Program.ts header
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {NodePath} from '@babel/core';
import * as t from '@babel/types';
import {
  CompilerError,
  CompilerErrorDetail,
  ErrorCategory,
} from '../CompilerError';
import {ExternalFunction, ReactFunctionType} from '../HIR/Environment';
import {CodegenFunction} from '../ReactiveScopes';
import {isComponentDeclaration} from '../Utils/ComponentDeclaration';
import {isHookDeclaration} from '../Utils/HookDeclaration';
import {assertExhaustive} from '../Utils/utils';
import {insertGatedFunctionDeclaration} from './Gating';
import {
  addImportsToProgram,
  ProgramContext,
  validateRestrictedImports,
} from './Imports';
import {
  CompilerOutputMode,
  CompilerReactTarget,
  ParsedPluginOptions,
  PluginOptions,
} from './Options';
import {compileFn} from './Pipeline';
import {
  filterSuppressionsThatAffectFunction,
  findProgramSuppressions,
  suppressionsToCompilerError,
} from './Suppression';
import {GeneratedSource} from '../HIR';
import {Err, Ok, Result} from '../Utils/Result';

export type CompilerPass = {
  opts: ParsedPluginOptions;
  filename: string | null;
  comments: Array<t.CommentBlock | t.CommentLine>;
  code: string | null;
};
export const OPT_IN_DIRECTIVES = new Set(['use forget', 'use memo']);
export const OPT_OUT_DIRECTIVES = new Set(['use no forget', 'use no memo']);
const DYNAMIC_GATING_DIRECTIVE = new RegExp('^use memo if\\(([^\\)]*)\\)$');

export function tryFindDirectiveEnablingMemoization(
  directives: Array<t.Directive>,
  opts: ParsedPluginOptions,
): Result<t.Directive | null, CompilerError> {
  const optIn = directives.find(directive =>
    OPT_IN_DIRECTIVES.has(directive.value.value),
  );
  if (optIn != null) {
    return Ok(optIn);
  }
  const dynamicGating = findDirectivesDynamicGating(directives, opts);
  if (dynamicGating.isOk()) {
    return ...
bashcompleted
Fetch CodegenReactiveFunction.ts header
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import * as t from '@babel/types';
import {createHmac} from 'crypto';
import {
  pruneHoistedContexts,
  pruneUnusedLValues,
  pruneUnusedLabels,
  renameVariables,
} from '.';
import {CompilerError, ErrorCategory} from '../CompilerError';
import {Environment, ExternalFunction} from '../HIR';
import {
  ArrayPattern,
  BlockId,
  DeclarationId,
  GeneratedSource,
  Identifier,
  IdentifierId,
  InstructionKind,
  JsxAttribute,
  ObjectMethod,
  ObjectPropertyKey,
  Pattern,
  Place,
  PrunedReactiveScopeBlock,
  ReactiveBlock,
  ReactiveFunction,
  ReactiveInstruction,
  ReactiveScope,
  ReactiveScopeBlock,
  ReactiveScopeDeclaration,
  ReactiveScopeDependency,
  ReactiveTerminal,
  ReactiveValue,
  SourceLocation,
  SpreadPattern,
  ValidIdentifierName,
  getHookKind,
  makeIdentifierName,
} from '../HIR/HIR';
import {printIdentifier, printInstruction, printPlace} from '../HIR/PrintHIR';
import {eachPatternOperand} from '../HIR/visitors';
import {Err, Ok, Result} from '../Utils/Result';
import {GuardKind} from '../Utils/RuntimeDiagnosticConstants';
import {assertExhaustive} from '../Utils/utils';
import {buildReactiveFunction} from './BuildReactiveFunction';
import {SINGLE_CHILD_FBT_TAGS} from './MemoizeFbtAndMacroOperandsInSameScope';
import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
import {EMIT_FREEZE_GLOBAL_GATING, ReactFunctionType} from '../HIR/Environment';
import {ProgramContext} from '../Entrypoint';

export const MEMO_CACHE_SENTINEL = 'react.memo_cache_sentinel';
export const EARLY_RETURN_SENTINEL = 'react.early_return_sentinel';

export type CodegenFunction = {
  type: 'CodegenFunction';
  id: t.Identifier | null;
  nameHint: string | null;
  params: t.FunctionDeclaration['params'];
  body: t.BlockStatement;
  generator: boolean;
  async: bo...
bashcompleted
Fetch BabelPlugin.ts header
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import type * as BabelCore from '@babel/core';
import {compileProgram, Logger, parsePluginOptions} from '../Entrypoint';
import {
  injectReanimatedFlag,
  pipelineUsesReanimatedPlugin,
} from '../Entrypoint/Reanimated';
import validateNoUntransformedReferences from '../Entrypoint/ValidateNoUntransformedReferences';
import {CompilerError} from '..';

const ENABLE_REACT_COMPILER_TIMINGS =
  process.env['ENABLE_REACT_COMPILER_TIMINGS'] === '1';

/*
 * The React Forget Babel Plugin
 * @param {*} _babel
 * @returns
 */
export default function BabelPluginReactCompiler(
  _babel: typeof BabelCore,
): BabelCore.PluginObj {
  return {
    name: 'react-forget',
    visitor: {
      /*
       * Note: Babel does some "smart" merging of visitors across plugins, so even if A is inserted
       * prior to B, if A does not have a Program visitor and B does, B will run first. We always
       * want Forget to run true to source as possible.
       */
      Program: {
        enter(prog, pass): void {
          try {
            const filename = pass.filename ?? 'unknown';
            if (ENABLE_REACT_COMPILER_TIMINGS === true) {
              performance.mark(`${filename}:start`, {
                detail: 'BabelPlugin:Program:start',
              });
            }
            let opts = parsePluginOptions(pass.opts);
            const isDev =
              (typeof __DEV__ !== 'undefined' && __DEV__ === true) ||
              process.env['NODE_ENV'] === 'development';
            if (
              opts.enableReanimatedCheck === true &&
2,759in / 449out
assistantFeb 10, 02:30:44 AM
claude-opus-4.6 · github-copilot

Excellent! I now have a comprehensive picture. Let me compile the final summary with the remaining structural pieces:

bashcompleted
Fetch BuildHIR.ts header - lowering pass
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {NodePath, Scope} from '@babel/traverse';
import * as t from '@babel/types';
import invariant from 'invariant';
import {
  CompilerDiagnostic,
  CompilerError,
  CompilerSuggestionOperation,
  ErrorCategory,
} from '../CompilerError';
import {Err, Ok, Result} from '../Utils/Result';
import {assertExhaustive, hasNode} from '../Utils/utils';
import {Environment} from './Environment';
import {
  ArrayExpression,
  ArrayPattern,
  BlockId,
  BranchTerminal,
  BuiltinTag,
  Case,
  Effect,
  GeneratedSource,
  GotoVariant,
  HIRFunction,
  IfTerminal,
  InstructionKind,
  InstructionValue,
  JsxAttribute,
  LoweredFunction,
  ObjectPattern,
  ObjectProperty,
  ObjectPropertyKey,
  Place,
  PropertyLiteral,
  ReturnTerminal,
  SourceLocation,
  SpreadPattern,
  ThrowTerminal,
  Type,
  makeInstructionId,
  makePropertyLiteral,
  makeType,
  promoteTemporary,
  validateIdentifierName,
} from './HIR';
import HIRBuilder, {Bindings, createTemporaryPlace} from './HIRBuilder';
import {BuiltInArrayId} from './ObjectShape';

/*
 * *******************************************************************************************
 * *******************************************************************************************
 * ************************************* Lowering to HIR *************************************
 * *******************************************************************************************
 * *******************************************************************************************
bashcompleted
Fetch BuildReactiveFunction.ts header
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {CompilerError} from '../CompilerError';
import {
  BasicBlock,
  BlockId,
  GeneratedSource,
  GotoVariant,
  HIR,
  InstructionId,
  Place,
  ReactiveBlock,
  SourceLocation,
} from '../HIR';
import {
  HIRFunction,
  ReactiveBreakTerminal,
  ReactiveContinueTerminal,
  ReactiveFunction,
  ReactiveInstruction,
  ReactiveLogicalValue,
  ReactiveSequenceValue,
  ReactiveTerminalStatement,
  ReactiveTerminalTargetKind,
  ReactiveTernaryValue,
  ReactiveValue,
  Terminal,
} from '../HIR/HIR';
import {assertExhaustive} from '../Utils/utils';

/*
 * Converts from HIR (lower-level CFG) to ReactiveFunction, a tree representation
 * that is closer to an AST. This pass restores the original control flow constructs,
 * including break/continue to labeled statements. Note that this pass naively emits
 * labels for *all* terminals: see PruneUnusedLabels which removes unnecessary labels.
 */
export function buildReactiveFunction(fn: HIRFunction): ReactiveFunction {
  const cx = new Context(fn.body);
  const driver = new Driver(cx);
  const body = driver.traverseBlock(cx.block(fn.body.entry));
  return {
    loc: fn.loc,
    id: fn.id,
    nameHint: fn.nameHint,
    params: fn.params,
bashcompleted
Fetch ObjectShape.ts header - function signatures
Output
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {CompilerError} from '../CompilerError';
import {AliasingEffect, AliasingSignature} from '../Inference/AliasingEffects';
import {assertExhaustive} from '../Utils/utils';
import {
  Effect,
  GeneratedSource,
  Hole,
  makeDeclarationId,
  makeIdentifierId,
  makeInstructionId,
  Place,
  SourceLocation,
  SpreadPattern,
  ValueKind,
  ValueReason,
} from './HIR';
import {
  BuiltInType,
  FunctionType,
  makeType,
  ObjectType,
  PolyType,
  PrimitiveType,
} from './Types';
import {AliasingEffectConfig, AliasingSignatureConfig} from './TypeSchema';

/*
 * This file exports types and defaults for JavaScript object shapes. These are
 * stored and used by a Forget `Environment`. See comments in `Types.ts`,
 * `Globals.ts`, and `Environment.ts` for more details.
 */

const PRIMITIVE_TYPE: PrimitiveType = {
  kind: 'Primitive',
};

let nextAnonId = 0;
/*
 * We currently use strings for anonymous ShapeIds since they are easily
 * debuggable, even though `Symbol()` might be more performant
 */
function createAnonId(): string {
  return `<generated_${nextAnonId++}>`;
}

/*
 * Add a non-hook function to an existing ShapeRegistry.
 *
 * @returns a {@link FunctionType} representing the added function.
 */
export function addFunction(
  registry: ShapeRegistry,
  properties: Iterable<[string, BuiltInType | PolyType]>,
  fn: Omit<FunctionSignature, 'hookKind' | 'aliasing'> & {
    aliasing?: AliasingSignatureConfig | null | undefined;
  },
  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,
  })...
4,733in / 368out
assistantFeb 10, 02:30:50 AM
claude-opus-4.6 · github-copilot

I now have a thorough understanding of the React Compiler source. Here is the comprehensive report.


React Compiler Source Code: Comprehensive Exploration Report

Location Status

The React Compiler source is NOT available locally. The working directory (/home/jm/data/ai/cloudlang-trees/react) is a git worktree of a CloudLang OCaml project, not the facebook/react repository. All data below was retrieved via the GitHub API (gh api repos/facebook/react/...).

To clone locally, run:

git clone --depth=1 --filter=blob:none --sparse https://github.com/facebook/react.git
cd react && git sparse-checkout set compiler

1. Full Directory Listing of the Compiler Source

Top-level compiler packages (compiler/packages/):

babel-plugin-react-compiler/     (THE core compiler)
eslint-plugin-react-compiler/
make-read-only-util/
react-compiler-healthcheck/
react-compiler-runtime/
react-forgive/
react-mcp-server/
snap/

Core source tree (compiler/packages/babel-plugin-react-compiler/src/):

index.ts                          # Package entry point
Babel/
  BabelPlugin.ts                  # Babel plugin wrapper (visitor pattern)
  RunReactCompilerBabelPlugin.ts
CompilerError.ts                  # (standalone file, not a directory)
Entrypoint/
  Gating.ts                       # Feature flag gating support
  Imports.ts                      # Import management
  Options.ts                      # Plugin configuration/options parsing
  Pipeline.ts                     # THE COMPILATION PIPELINE ORCHESTRATOR
  Program.ts                      # Program-level traversal (find components/hooks)
  Reanimated.ts                   # Reanimated integration support
  Suppression.ts                  # Suppression comment handling
  ValidateNoUntransformedReferences.ts
  index.ts
Flood/
  FlowTypes.ts
  TypeErrors.ts
  TypeUtils.ts
  Types.ts
HIR/
  AssertConsistentIdentifiers.ts
  AssertTerminalBlocksExist.ts
  AssertValidBlockNesting.ts
  AssertValidMutableRanges.ts
  BuildHIR.ts                     # AST -> HIR lowering
  BuildReactiveScopeTerminalsHIR.ts
  CollectHoistablePropertyLoads.ts
  CollectOptionalChainDependencies.ts
  ComputeUnconditionalBlocks.ts
  DefaultModuleTypeProvider.ts
  DeriveMinimalDependenciesHIR.ts
  Dominator.ts                    # Dominator tree computation
  Environment.ts                  # Compiler environment/config state
  FindContextIdentifiers.ts
  Globals.ts                      # Built-in type/shape definitions
  HIR.ts                          # CORE TYPE DEFINITIONS (1700+ lines)
  HIRBuilder.ts                   # HIR construction helpers
  MergeConsecutiveBlocks.ts
  MergeOverlappingReactiveScopesHIR.ts
  ObjectShape.ts                  # Function signature / shape system
  PrintHIR.ts                     # Debug printing
  PropagateScopeDependenciesHIR.ts
  PruneUnusedLabelsHIR.ts
  ScopeDependencyUtils.ts
  TypeSchema.ts
  Types.ts                        # Type system types (Type, FunctionType, ObjectType, etc.)
  index.ts
  visitors.ts                     # HIR traversal utilities
Inference/
  AliasingEffects.ts              # AliasingEffect type definitions
  AnalyseFunctions.ts             # Nested function analysis
  ControlDominators.ts
  DropManualMemoization.ts
  InferEffectDependencies.ts
  InferMutationAliasingEffects.ts # Abstract interpretation for effects
  InferMutationAliasingRanges.ts  # Mutable range computation
  InferReactivePlaces.ts          # Reactivity inference
  InlineImmediatelyInvokedFunctionExpressions.ts
  MUTABILITY_ALIASING_MODEL.md    # Design doc for the aliasing model
  index.ts
Optimization/
  ConstantPropagation.ts
  DeadCodeElimination.ts
  InlineJsxTransform.ts
  InstructionReordering.ts
  LowerContextAccess.ts
  OptimizeForSSR.ts
  OptimizePropsMethodCalls.ts
  OutlineFunctions.ts
  OutlineJsx.ts
  PruneMaybeThrows.ts
  index.ts
ReactiveScopes/
  AlignMethodCallScopes.ts
  AlignObjectMethodScopes.ts
  AlignReactiveScopesToBlockScopesHIR.ts
  AssertScopeInstructionsWithinScope.ts
  AssertWellFormedBreakTargets.ts
  BuildReactiveFunction.ts        # HIR CFG -> Reactive tree conversion
  CodegenReactiveFunction.ts      # FINAL CODE GENERATION (reactive -> Babel AST)
  CollectReactiveIdentifiers.ts
  CollectReferencedGlobals.ts
  ExtractScopeDeclarationsFromDestructuring.ts
  FlattenReactiveLoopsHIR.ts
  FlattenScopesWithHooksOrUseHIR.ts
  InferReactiveScopeVariables.ts  # Group mutating-together values into scopes
  MemoizeFbtAndMacroOperandsInSameScope.ts
  MergeReactiveScopesThatInvalidateTogether.ts
  PrintReactiveFunction.ts
  PromoteUsedTemporaries.ts
  PropagateEarlyReturns.ts
  PruneAllReactiveScopes.ts
  PruneAlwaysInvalidatingScopes.ts
  PruneHoistedContexts.ts
  PruneInitializationDependencies.ts
  PruneNonEscapingScopes.ts
  PruneNonReactiveDependencies.ts
  PruneTemporaryLValues.ts
  PruneUnusedLabels.ts
  PruneUnusedScopes.ts
  RenameVariables.ts
  StabilizeBlockIds.ts
  index.ts
  visitors.ts
SSA/
  EliminateRedundantPhi.ts
  EnterSSA.ts
  RewriteInstructionKindsBasedOnReassignment.ts
  index.ts
Transform/
  NameAnonymousFunctions.ts
  TransformFire.ts
  index.ts
TypeInference/
  InferTypes.ts
  index.ts
Utils/
  ComponentDeclaration.ts
  DisjointSet.ts
  HookDeclaration.ts
  Keyword.ts
  Result.ts
  RuntimeDiagnosticConstants.ts
  Stack.ts
  TestUtils.ts
  todo.ts
  types.d.ts
  utils.ts
Validation/
  ValidateContextVariableLValues.ts
  ValidateExhaustiveDependencies.ts
  ValidateHooksUsage.ts
  ValidateLocalsNotReassignedAfterRender.ts
  ValidateMemoizedEffectDependencies.ts
  ValidateNoCapitalizedCalls.ts
  ValidateNoDerivedComputationsInEffects.ts
  ValidateNoDerivedComputationsInEffects_exp.ts
  ValidateNoFreezingKnownMutableFunctions.ts
  ValidateNoImpureFunctionsInRender.ts
  ValidateNoJSXInTryStatement.ts
  ValidateNoRefAccessInRender.ts
  ValidateNoSetStateInEffects.ts
  ValidateNoSetStateInRender.ts
  ValidatePreservedManualMemoization.ts
  ValidateSourceLocations.ts
  ValidateStaticComponents.ts
  ValidateUseMemo.ts
  index.ts
__tests__/
  DisjointSet-test.ts
  Logger-test.ts
  Result-test.ts
  e2e/
  envConfig-test.ts
  fixtures/
  parseConfigPragma-test.ts
  test-utils/

2. Main Entry Point and Pipeline Orchestration

Entry chain:

  1. index.ts -- Package root. Default export is BabelPluginReactCompiler from Babel/BabelPlugin.ts. Also re-exports compileFn as compile and compileProgram from Entrypoint/.
  2. Babel/BabelPlugin.ts -- Babel plugin object with Program.enter visitor. Calls compileProgram().
  3. Entrypoint/Program.ts -- Traverses the Babel AST to find React components and hooks, then calls compileFn() for each.
  4. Entrypoint/Pipeline.ts -- THE core pipeline orchestrator. Contains compileFn() which calls run() then runWithEnvironment(). This is a ~400-line function that calls every compilation pass in sequence.

3. Complete List of Compilation Passes (in exact pipeline order)

The runWithEnvironment() function in Pipeline.ts executes these passes sequentially. The pipeline operates in three major phases:

Phase 1: HIR Construction & Analysis

# Pass Module Description
1 lower() HIR/BuildHIR.ts Babel AST -> HIR CFG lowering
2 pruneMaybeThrows() Optimization/PruneMaybeThrows.ts Remove unnecessary try/catch
3 validateContextVariableLValues() Validation/ Validate context variable assignments
4 validateUseMemo() Validation/ Validate useMemo usage
5 dropManualMemoization() Inference/ (conditional) Remove useMemo/useCallback markers
6 inlineImmediatelyInvokedFunctionExpressions() Inference/ Inline IIFEs
7 mergeConsecutiveBlocks() HIR/ Simplify CFG by merging straight-line blocks

Phase 2: SSA, Type Inference & Mutation/Aliasing Analysis

# Pass Module Description
8 enterSSA() SSA/EnterSSA.ts Convert to SSA form
9 eliminateRedundantPhi() SSA/EliminateRedundantPhi.ts Remove trivial phi nodes
10 constantPropagation() Optimization/ Forward-propagate constants
11 inferTypes() TypeInference/InferTypes.ts Infer types for identifiers
12 validateHooksUsage() Validation/ (conditional) Validate Rules of Hooks
13 validateNoCapitalizedCalls() Validation/ (conditional)
14 transformFire() Transform/TransformFire.ts (conditional) Fire transform
15 lowerContextAccess() Optimization/ (conditional) Lower context access
16 optimizePropsMethodCalls() Optimization/ Optimize props method calls
17 analyseFunctions() Inference/AnalyseFunctions.ts Recursively analyze nested function expressions
18 inferMutationAliasingEffects() Inference/InferMutationAliasingEffects.ts Core pass: abstract interpretation to determine mutation/aliasing effects
19 optimizeForSSR() Optimization/ (conditional) SSR optimizations
20 deadCodeElimination() Optimization/ Remove unreachable/unused code
21 instructionReordering() Optimization/ (conditional) Reorder instructions
22 pruneMaybeThrows() Optimization/ Second pass of MaybeThrow pruning
23 inferMutationAliasingRanges() Inference/InferMutationAliasingRanges.ts Core pass: compute mutable ranges for each value

Phase 3: Validations (post-analysis)

# Pass Module Description
24 validateLocalsNotReassignedAfterRender() Validation/
25 assertValidMutableRanges() HIR/ (conditional)
26 validateNoRefAccessInRender() Validation/ (conditional)
27 validateNoSetStateInRender() Validation/ (conditional)
28 validateNoDerivedComputationsInEffects() Validation/ (conditional, two variants)
29 validateNoSetStateInEffects() Validation/ (conditional, lint mode)
30 validateNoJSXInTryStatement() Validation/ (conditional, lint mode)
31 validateNoImpureFunctionsInRender() Validation/ (conditional)
32 validateNoFreezingKnownMutableFunctions() Validation/

Phase 4: Reactivity & Scope Inference

# Pass Module Description
33 inferReactivePlaces() Inference/InferReactivePlaces.ts Mark places as reactive based on effects
34 validateExhaustiveDependencies() Validation/ (conditional)
35 rewriteInstructionKindsBasedOnReassignment() SSA/ Fix instruction kinds post-SSA
36 validateStaticComponents() Validation/ (conditional, lint mode)
37 inferReactiveScopeVariables() ReactiveScopes/InferReactiveScopeVariables.ts Group co-mutating values into reactive scopes
38 memoizeFbtAndMacroOperandsInSameScope() ReactiveScopes/ Fbt/macro handling
39 outlineJSX() Optimization/OutlineJsx.ts (conditional) Outline JSX
40 nameAnonymousFunctions() Transform/ (conditional)
41 outlineFunctions() Optimization/OutlineFunctions.ts (conditional)

Phase 5: Scope Alignment & Dependency Propagation (still on HIR)

# Pass Module Description
42 alignMethodCallScopes() ReactiveScopes/ Align scopes for method calls
43 alignObjectMethodScopes() ReactiveScopes/ Align scopes for object methods
44 pruneUnusedLabelsHIR() HIR/ Remove unused labels
45 alignReactiveScopesToBlockScopesHIR() ReactiveScopes/ Align reactive scopes to JS block scopes
46 mergeOverlappingReactiveScopesHIR() HIR/ Merge overlapping scopes
47 buildReactiveScopeTerminalsHIR() HIR/ Create scope terminal nodes
48 flattenReactiveLoopsHIR() ReactiveScopes/ Flatten scopes in loops
49 flattenScopesWithHooksOrUseHIR() ReactiveScopes/ Flatten scopes containing hooks
50 propagateScopeDependenciesHIR() HIR/PropagateScopeDependenciesHIR.ts Compute scope dependencies
51 inferEffectDependencies() Inference/ (conditional) Infer useEffect deps
52 inlineJsxTransform() Optimization/ (conditional)

Phase 6: HIR -> Reactive Function (tree form)

# Pass Module Description
53 buildReactiveFunction() ReactiveScopes/BuildReactiveFunction.ts Convert CFG to tree-shaped ReactiveFunction

Phase 7: Reactive Function Optimization & Pruning

# Pass Module Description
54 pruneUnusedLabels() ReactiveScopes/
55 pruneNonEscapingScopes() ReactiveScopes/ Remove scopes for non-escaping values
56 pruneNonReactiveDependencies() ReactiveScopes/
57 pruneUnusedScopes() ReactiveScopes/
58 mergeReactiveScopesThatInvalidateTogether() ReactiveScopes/
59 pruneAlwaysInvalidatingScopes() ReactiveScopes/
60 pruneInitializationDependencies() ReactiveScopes/ (conditional)
61 propagateEarlyReturns() ReactiveScopes/ Handle early returns in scopes
62 pruneUnusedLValues() ReactiveScopes/
63 promoteUsedTemporaries() ReactiveScopes/ Promote temps to named variables
64 extractScopeDeclarationsFromDestructuring() ReactiveScopes/
65 stabilizeBlockIds() ReactiveScopes/
66 renameVariables() ReactiveScopes/
67 pruneHoistedContexts() ReactiveScopes/

Phase 8: Final Validation & Code Generation

# Pass Module Description
68 validateMemoizedEffectDependencies() Validation/ (conditional)
69 validatePreservedManualMemoization() Validation/ (conditional)
70 codegenFunction() ReactiveScopes/CodegenReactiveFunction.ts Final codegen: ReactiveFunction -> Babel AST with useMemoCache
71 validateSourceLocations() Validation/ (conditional)

4. HIR Type Definitions (from HIR/HIR.ts)

The HIR is the central data model. Key comment from source: AST -> (lowering) -> HIR -> (analysis) -> Reactive Scopes -> (codegen) -> AST

Core Graph Structure

  • HIR: { entry: BlockId, blocks: Map<BlockId, BasicBlock> } -- CFG in reverse postorder
  • BasicBlock: { kind: BlockKind, id: BlockId, instructions: Instruction[], terminal: Terminal, preds: Set<BlockId>, phis: Set<Phi> }
  • BlockKind: 'block' | 'value' | 'loop' | 'sequence' | 'catch'

Instructions

  • Instruction: { id: InstructionId, lvalue: Place, value: InstructionValue, effects: AliasingEffect[] | null, loc: SourceLocation }
  • InstructionValue: Large discriminated union (~40 variants) including LoadLocal, StoreLocal, DeclareLocal, Primitive, BinaryExpression, CallExpression, MethodCall, NewExpression, PropertyLoad, PropertyStore, ComputedLoad, ComputedStore, ObjectExpression, ArrayExpression, JsxExpression, FunctionExpression, Destructure, LoadGlobal, StoreGlobal, Await, GetIterator, IteratorNext, TemplateLiteral, TaggedTemplateExpression, StartMemoize, FinishMemoize, etc.
  • InstructionKind: Const | Let | Reassign | Catch | HoistedConst | HoistedLet | HoistedFunction | Function

Places & Identifiers

  • Place: { kind: 'Identifier', identifier: Identifier, effect: Effect, reactive: boolean, loc: SourceLocation } -- a reference to a storage location
  • Identifier: { id: IdentifierId, declarationId: DeclarationId, name: IdentifierName | null, mutableRange: MutableRange, scope: ReactiveScope | null, type: Type, loc: SourceLocation }
  • MutableRange: { start: InstructionId, end: InstructionId } -- range where a value is being created/mutated

Terminals (Control Flow)

  • Terminal: Discriminated union of 20 variants including goto, if, branch, switch, for, for-of, for-in, do-while, while, logical, ternary, optional, label, sequence, try, maybe-throw, return, throw, unreachable, scope (reactive scope), pruned-scope

Effects & Values

  • Effect enum: Unknown | Freeze | Read | Capture | ConditionallyMutateIterator | ConditionallyMutate | Mutate | Store
  • ValueKind enum: MaybeFrozen | Frozen | Primitive | Global | Mutable | Context
  • ValueReason enum: Global | JsxCaptured | HookCaptured | HookReturn | Effect | KnownReturnSignature | Context | State | ReducerState | ReactiveFunctionArgument | Other

Reactive Scopes

  • ReactiveScope: { id: ScopeId, range: MutableRange, dependencies: ReactiveScopeDependencies, declarations: Map<IdentifierId, ReactiveScopeDeclaration>, reassignments: Set<Identifier>, earlyReturnValue: ... | null, merged: Set<ScopeId>, loc }
  • ReactiveScopeDependency: { identifier: Identifier, reactive: boolean, path: DependencyPath }

Reactive Function (Tree Form)

  • ReactiveFunction: { loc, id, params, body: ReactiveBlock, env, directives, ... }
  • ReactiveBlock: Array<ReactiveStatement> (tree-shaped, not CFG)
  • ReactiveStatement: ReactiveInstructionStatement | ReactiveTerminalStatement | ReactiveScopeBlock | PrunedReactiveScopeBlock

Function Representation

  • HIRFunction: { loc, id, fnType, env, params, returns, context, body: HIR, generator, async, directives, aliasingEffects }
  • LoweredFunction: { func: HIRFunction } -- wrapper for nested functions

Type System (from HIR/Types.ts)

  • Type: BuiltInType | PhiType | TypeVar | PolyType | PropType | ObjectMethod
  • BuiltInType: PrimitiveType | FunctionType | ObjectType
  • FunctionType: { kind: 'Function', shapeId: string | null, return: Type, isConstructor: boolean }
  • ObjectType: { kind: 'Object', shapeId: string | null }

Opaque ID Types (simulated branded types)

  • BlockId, ScopeId, IdentifierId, DeclarationId, InstructionId -- all number & { [symbol]: brand }

5. Inference Passes: Aliasing, Effects, and Mutation

The inference system was redesigned in June 2025 (per MUTABILITY_ALIASING_MODEL.md).

AliasingEffects.ts -- Effect Type Definitions

AliasingEffect is a discriminated union with 17 variants:

Effect Purpose
Freeze Mark value as frozen (immutable from this reference)
Mutate Direct mutation, errors if immutable
MutateConditionally Mutation only if value is mutable
MutateTransitive Deep/transitive mutation
MutateTransitiveConditionally Deep mutation only if mutable (default for unknown functions)
Capture Data flow where local mutation of dest does NOT mutate source
Alias Data flow where local mutation of dest DOES mutate source
MaybeAlias Potential aliasing (for unknown function returns)
Assign Direct assignment into = from
Create Create new value of given kind
CreateFrom Create value derived from another (property load, index)
CreateFunction Create function value with captured variables
ImmutableCapture Immutable data flow (for escape analysis)
Apply Function call with receiver, args, signature
MutateFrozen Error: mutation of frozen value
MutateGlobal Error: mutation of global (ok in effects/handlers)
Impure Side-effect not safe during render
Render Value accessed during render

Also defines AliasingSignature: { receiver, params, rest, returns, effects, temporaries } for encoding function aliasing behavior.

InferMutationAliasingEffects.ts -- Abstract Interpretation

This is the most complex pass in the compiler. Its approach:

  1. Candidate effects: For each instruction, compute a signature of candidate effects based purely on instruction semantics and operand types. These are cached per instruction.

  2. Abstract interpretation: Iterate over the HIR CFG until fixpoint. Track:

    • AbstractValue per value: { kind: ValueKind, reason: Set<ValueReason>, context: Set<Place> }
    • InferenceState: maps InstructionValue -> AbstractValue and IdentifierId -> Set<InstructionValue> (pointer set for phi nodes)
  3. Effect application (applyEffect()): Each candidate effect is resolved against current abstract state:

    • MutateConditionally x: dropped if x is not mutable
    • Mutate y on frozen value: converted to MutateFrozen error
    • Capture a -> b: pruned if source is primitive/global or destination is not mutable
    • Apply: resolves to locally-known function signature, known aliasing signature, legacy signature, or generic fallback
    • CreateFunction: determines if function is mutable based on whether it captures mutable/context values or has tracked side effects
  4. Key state operations:

    • state.freeze(place, reason): Transitively freeze a reference
    • state.mutate(variant, place): Returns 'none' | 'mutate' | 'mutate-frozen' | 'mutate-global' | 'mutate-ref'
    • state.assign(place, value): Direct aliasing
    • state.merge(other): Lattice join for fixpoint iteration
    • state.kind(place): Lookup abstract value kind
  5. Special handling:

    • Props spreading (findNonMutatedDestructureSpreads): treats {...otherProps} as frozen when source is frozen and spread is never mutated
    • Hoisted context declarations
    • Catch handler bindings (aliased to call results in try blocks)
    • Return terminals get Freeze effect for non-function-expression functions

InferMutationAliasingRanges.ts -- Mutable Range Computation

Builds on the effects computed by the previous pass:

  1. Constructs a data flow graph with ordered edges and mutations
  2. Tracks "when" each effect occurs relative to others
  3. Walks each mutation effect against the graph, updating the MutableRange (start:end instruction IDs) of each reachable node
  4. Populates legacy Effect on each Place
  5. Validates against invalid effects (mutations of globals/frozen values) for render-reachable code
  6. Computes externally-visible effects for function expressions (mutations of params/context-vars)

AnalyseFunctions.ts -- Nested Function Analysis

Recursively processes nested FunctionExpression and ObjectMethod values by running a mini-pipeline on each:

  1. analyseFunctions() (recursive)
  2. inferMutationAliasingEffects() (as function expression)
  3. deadCodeElimination()
  4. inferMutationAliasingRanges() (as function expression)
  5. rewriteInstructionKindsBasedOnReassignment()
  6. inferReactiveScopeVariables()
  7. Stores computed aliasingEffects on the function node

Then populates Effect on each context variable for the outer function's analysis.

InferReactivePlaces.ts -- Reactivity Inference

Uses a StableSidemap to track sources of stability (hook calls like useRef(), useState(), etc.) and propagates stability through assignments and destructuring. Marks Place.reactive based on whether values change between renders, using ControlDominators for conditional reactivity analysis.

Key Design Insight from MUTABILITY_ALIASING_MODEL.md

The model distinguishes between:

  • Alias (local mutation propagates): const a = identity(b) -- mutating a might mutate b
  • Capture (local mutation does NOT propagate): array.push(item) -- mutating array does not mutate item
  • CreateFrom (inverse of Capture): const a = obj.prop -- mutating a transitively mutates obj
  • Assign (direct assignment): const a = b -- a IS b
  • Freeze freezes the reference, not the underlying value. Other aliases to the same value can still mutate it.
  • MaybeAlias represents uncertain aliasing from unknown functions, making downstream mutations conditional.

The transitivity rules between these effects are carefully defined to preserve mutation semantics when computing function signatures (e.g., Capture then CreateFrom = Alias, but CreateFrom then Capture = Capture).

2,189in / 7,955out