WP1: HIR types & construction (@analyzer subagent)

/home/jm/data/ai/cloudlang-trees/react · 6 messages · 31 parts · · 138,669 tokens
Created Feb 10, 02:47:22 AM · Updated Feb 10, 03:10:08 AM · 2 syncs
userFeb 10, 02:47:22 AM

You are analyzing the React Compiler's HIR (High-level Intermediate Representation) type system and construction. This is research only -- do NOT edit any files.

The goal is to produce a structured analysis document that will help us adapt these concepts for CloudLang, an OCaml compiler that decomposes TypeScript closures into Cloudflare Workers.

Files to read and analyze (all under /home/jm/data/ai/cloudlang-trees/react/react/compiler/packages/babel-plugin-react-compiler/src/):

  1. HIR/HIR.ts - Core type definitions (this is ~1700+ lines, read it thoroughly in chunks)
  2. HIR/Types.ts - Type system types
  3. HIR/ObjectShape.ts - Function signature / shape system
  4. HIR/BuildHIR.ts - AST -> HIR lowering
  5. HIR/HIRBuilder.ts - HIR construction helpers
  6. HIR/visitors.ts - HIR traversal utilities
  7. HIR/PrintHIR.ts - Debug printing (useful for understanding structure)

Also read the existing CloudLang types for comparison:

  • /home/jm/data/ai/cloudlang-trees/react/lib/ast.ml - Current AST (19 node types)
  • /home/jm/data/ai/cloudlang-trees/react/lib/ir.ml - Current IR (Cloudflare config)

For each major component, produce documentation in this template format:

# Component Name

## File
## Purpose
## Input Invariants
## Output Guarantees
## Algorithm (detailed, step-by-step)
## Key Data Structures (with type signatures)
## Edge Cases
## Mapping to CloudLang
  - What we'd adapt and how
  - What we'd skip and why  
  - OCaml type sketches for the adapted versions
## Example (before/after transformation)

Specific questions to answer:

  1. HIR Core Model: What are Place, Identifier, Instruction, InstructionValue, Terminal, BasicBlock, HIR, HIRFunction? How do they relate? Draw the ownership/containment hierarchy.

  2. Identity System: How are BlockId, InstructionId, IdentifierId, ScopeId generated and used? Why branded/opaque types?

  3. InstructionValue variants: List ALL ~40 variants. For each, note: (a) is it relevant to CloudLang's TypeScript subset? (b) what data does it carry? (c) what are its effects/semantics? Group them by category (loads, stores, expressions, control flow, etc.)

  4. Terminal variants: List ALL ~20 variants. Same treatment.

  5. The Place/Identifier distinction: Why separate Place from Identifier? What does effect, reactive, mutableRange, scope on these types buy you?

  6. BuildHIR lowering: How does it convert Babel AST nodes to HIR instructions? What's the approach for handling control flow (if/else, loops, try/catch)? How are scopes and variables handled?

  7. Type System (Types.ts): What types exist? How does the shape system work (ObjectShape.ts)? How do shapes encode function signatures?

  8. Visitor patterns (visitors.ts): What traversal abstractions exist? How do passes consume the HIR?

CloudLang context: CloudLang currently has a flat ESTree AST (19 node types, no position info) and a Cloudflare-config IR. There's no proper HIR between them. The scope analysis works directly on the AST. We want to design an HIR that:

  • Represents TypeScript constructs relevant to closure/mutation analysis
  • Is extensible (start with current 19 node types, grow incrementally)
  • Supports SSA, effect annotation, mutable ranges
  • Can be implemented in OCaml with algebraic data types

Return your complete analysis as a single structured markdown document. Be thorough -- this is the foundational data model everything else depends on.

assistantFeb 10, 02:47:22 AM
glm-4.7 · zai-coding-plan
This is a research task to analyze the React Compiler's HIR (High-level Intermediate Representation) type system and construction. I need to: 1. Read and analyze the React Compiler HIR files 2. Read CloudLang's existing types for comparison 3. Produce a structured analysis document Let me start by reading the files in parallel to understand the structure. The key files are: 1. `HIR/HIR.ts` - Core type definitions (~1700+ lines) 2. `HIR/Types.ts` - Type system types 3. `HIR/ObjectShape.ts` - Function signature / shape system 4. `HIR/BuildHIR.ts` - AST -> HIR lowering 5. `HIR/HIRBuilder.ts` - HIR construction helpers 6. `HIR/visitors.ts` - HIR traversal utilities 7. `HIR/PrintHIR.ts` - Debug printing And CloudLang files: - `/home/jm/data/ai/cloudlang-trees/react/lib/ast.ml` - `/home/jm/data/ai/cloudlang-trees/react/lib/ir.ml` Since `HIR.ts` is ~1700+ lines, I'll need to read it in chunks. Let me start with the first batch of files.

I'll analyze the React Compiler's HIR type system and construction. Let me start by reading the key files in parallel.

readcompleted
react/compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts
Output
<file>
00001| /**
00002|  * Copyright (c) Meta Platforms, Inc. and affiliates.
00003|  *
00004|  * This source code is licensed under the MIT license found in the
00005|  * LICENSE file in the root directory of this source tree.
00006|  */
00007| 
00008| import {BindingKind} from '@babel/traverse';
00009| import * as t from '@babel/types';
00010| import {
00011|   CompilerDiagnostic,
00012|   CompilerError,
00013|   ErrorCategory,
00014| } from '../CompilerError';
00015| import {assertExhaustive} from '../Utils/utils';
00016| import {Environment, ReactFunctionType} from './Environment';
00017| import type {HookKind} from './ObjectShape';
00018| import {Type, makeType} from './Types';
00019| import {z} from 'zod/v4';
00020| import type {AliasingEffect} from '../Inference/AliasingEffects';
00021| import {isReservedWord} from '../Utils/Keyword';
00022| import {Err, Ok, Result} from '../Utils/Result';
00023| 
00024| /*
00025|  * *******************************************************************************************
00026|  * *******************************************************************************************
00027|  * ************************************* Core Data Model *************************************
00028|  * *******************************************************************************************
00029|  * *******************************************************************************************
00030|  */
00031| 
00032| // AST -> (lowering) -> HIR -> (analysis) -> Reactive Scopes -> (codegen) -> AST
00033| 
00034| /*
00035|  * A location in a source file, intended to be used for providing diagnostic information and
00036|  * transforming code while preserving source information (ie to emit source maps).
00037|  *
00038|  * `GeneratedSource` indicates that there is no single source location from which the code derives.
00039|  */
00040| export const GeneratedSource = Symbol();
00041| export type SourceLocation = t.SourceLocation | typeof Generate...
readcompleted
react/compiler/packages/babel-plugin-react-compiler/src/HIR/Types.ts
Output
<file>
00001| /**
00002|  * Copyright (c) Meta Platforms, Inc. and affiliates.
00003|  *
00004|  * This source code is licensed under the MIT license found in the
00005|  * LICENSE file in the root directory of this source tree.
00006|  */
00007| 
00008| import {CompilerError} from '../CompilerError';
00009| import {GeneratedSource, PropertyLiteral} from './HIR';
00010| 
00011| export type BuiltInType = PrimitiveType | FunctionType | ObjectType;
00012| 
00013| export type Type =
00014|   | BuiltInType
00015|   | PhiType
00016|   | TypeVar
00017|   | PolyType
00018|   | PropType
00019|   | ObjectMethod;
00020| export type PrimitiveType = {kind: 'Primitive'};
00021| 
00022| /*
00023|  * An {@link FunctionType} or {@link ObjectType} (also a JS object) may be associated with an
00024|  * inferred "object shape", i.e. a known property (key -> Type) map. This is
00025|  * subtly different from JS language semantics - `shape` represents both
00026|  * OwnPropertyDescriptors and properties present in the prototype chain.
00027|  *
00028|  * {@link ObjectShape.functionType} is always present on the shape of a {@link FunctionType},
00029|  * and it represents the call signature of the function. Note that Forget thinks of a
00030|  * {@link FunctionType} as any "callable object" (not to be confused with objects that
00031|  *   extend the global `Function`.)
00032|  *
00033|  * If `shapeId` is present, it is a key into the ShapeRegistry used to infer this
00034|  * FunctionType or ObjectType instance (i.e. from an Environment).
00035|  */
00036| 
00037| export type FunctionType = {
00038|   kind: 'Function';
00039|   shapeId: string | null;
00040|   return: Type;
00041|   isConstructor: boolean;
00042| };
00043| 
00044| export type ObjectType = {
00045|   kind: 'Object';
00046|   shapeId: string | null;
00047| };
00048| 
00049| export type TypeVar = {
00050|   kind: 'Type';
00051|   id: TypeId;
00052| };
00053| export type PolyType = {
00054|   kind: 'Poly';
00055| };
00056| e...
readcompleted
react/compiler/packages/babel-plugin-react-compiler/src/HIR/ObjectShape.ts
Output
<file>
00001| /**
00002|  * Copyright (c) Meta Platforms, Inc. and affiliates.
00003|  *
00004|  * This source code is licensed under the MIT license found in the
00005|  * LICENSE file in the root directory of this source tree.
00006|  */
00007| 
00008| import {CompilerError} from '../CompilerError';
00009| import {AliasingEffect, AliasingSignature} from '../Inference/AliasingEffects';
00010| import {assertExhaustive} from '../Utils/utils';
00011| import {
00012|   Effect,
00013|   GeneratedSource,
00014|   Hole,
00015|   makeDeclarationId,
00016|   makeIdentifierId,
00017|   makeInstructionId,
00018|   Place,
00019|   SourceLocation,
00020|   SpreadPattern,
00021|   ValueKind,
00022|   ValueReason,
00023| } from './HIR';
00024| import {
00025|   BuiltInType,
00026|   FunctionType,
00027|   makeType,
00028|   ObjectType,
00029|   PolyType,
00030|   PrimitiveType,
00031| } from './Types';
00032| import {AliasingEffectConfig, AliasingSignatureConfig} from './TypeSchema';
00033| 
00034| /*
00035|  * This file exports types and defaults for JavaScript object shapes. These are
00036|  * stored and used by a Forget `Environment`. See comments in `Types.ts`,
00037|  * `Globals.ts`, and `Environment.ts` for more details.
00038|  */
00039| 
00040| const PRIMITIVE_TYPE: PrimitiveType = {
00041|   kind: 'Primitive',
00042| };
00043| 
00044| let nextAnonId = 0;
00045| /*
00046|  * We currently use strings for anonymous ShapeIds since they are easily
00047|  * debuggable, even though `Symbol()` might be more performant
00048|  */
00049| function createAnonId(): string {
00050|   return `<generated_${nextAnonId++}>`;
00051| }
00052| 
00053| /*
00054|  * Add a non-hook function to an existing ShapeRegistry.
00055|  *
00056|  * @returns a {@link FunctionType} representing the added function.
00057|  */
00058| export function addFunction(
00059|   registry: ShapeRegistry,
00060|   properties: Iterable<[string, BuiltInType | PolyType]>,
00061|   fn: Omit<FunctionSignature, 'hookKind...
readcompleted
lib/ast.ml
Output
<file>
00001| (** ESTree-compatible AST subset for TypeScript.
00002| 
00003|     This represents the minimal set of TypeScript constructs needed for
00004|     closure analysis and Worker decomposition. Node types follow the ESTree
00005|     specification used by @typescript-eslint/typescript-estree. *)
00006| 
00007| type var_kind = Const | Let | Var
00008| 
00009| type literal_value =
00010|   | LString of string
00011|   | LNumber of float
00012|   | LBool of bool
00013|   | LNull
00014|   | LUndefined
00015| 
00016| (** A single AST node. The variant name matches the ESTree "type" field. *)
00017| type node =
00018|   | Program of { body : node list }
00019|   | VariableDeclaration of { kind : var_kind; declarations : node list }
00020|   | VariableDeclarator of { id : node; init : node option }
00021|   | Identifier of { name : string }
00022|   | Literal of { value : literal_value }
00023|   | ArrowFunctionExpression of {
00024|       params : node list;
00025|       body : node;
00026|       async_ : bool;
00027|     }
00028|   | BlockStatement of { body : node list }
00029|   | ReturnStatement of { argument : node option }
00030|   | IfStatement of { test : node; consequent : node; alternate : node option }
00031|   | ExpressionStatement of { expression : node }
00032|   | CallExpression of { callee : node; arguments : node list }
00033|   | MemberExpression of { object_ : node; property : node }
00034|   | NewExpression of { callee : node; arguments : node list }
00035|   | BinaryExpression of { operator : string; left : node; right : node }
00036|   | LogicalExpression of { operator : string; left : node; right : node }
00037|   | AwaitExpression of { argument : node }
00038|   | RawCode of { code : string }
00039|       (** Verbatim TypeScript fragment. Used by the lowering pass for
00040|           constructs that don't have AST representation (e.g. object
00041|           literals for fetch options). Not produced by the parser. *)
00042|   | ExportNam...
readcompleted
lib/ir.ml
Output
<file>
00001| type binding =
00002|   | D1Binding of { name : string; database_id : string }
00003|   | KVBinding of { name : string; namespace_id : string }
00004|   | R2Binding of { name : string; bucket_name : string }
00005|   | ServiceBinding of { name : string; service : string }
00006| 
00007| type do_marker =
00008|   | SerialConflictHotspot
00009|   | GlobalSingletonNeeded
00010|   | EntityAffinityKeyed of { key_hint : string option }
00011|   | StrictOrderingRequired
00012|   | ConsistencyBoundaryCrossed
00013|   | RealtimeFanout
00014|   | DurableTimerNeeded
00015|   | HighFanInCoordinator
00016|   | StatelessFastPathPreferWorker
00017| 
00018| type coordination_intent =
00019|   | PerEntitySerial of { key_expr : string; reason : string }
00020|   | GlobalSingleton of { name : string; reason : string }
00021|   | RealtimeRoom of { room_key_expr : string }
00022|   | ScheduledQueue of { queue_key_expr : string }
00023| 
00024| type routing_policy =
00025|   | DeterministicName of { key_expr : string }
00026|   | ShardedName of { key_expr : string; shards : int }
00027|   | UniqueIdPool of { pool : string }
00028| 
00029| type storage_backend = DoSqlite | DoSyncKv
00030| type alarm_mode = NoAlarm | SingleAlarm | QueuedAlarm
00031| 
00032| type durability_policy = {
00033|   storage_backend : storage_backend;
00034|   alarm_mode : alarm_mode;
00035|   pitr_required : bool;
00036| }
00037| 
00038| type do_annotation = {
00039|   class_name : string;
00040|   binding_name : string;
00041|   markers : do_marker list;
00042|   intent : coordination_intent;
00043|   routing : routing_policy;
00044|   durability : durability_policy;
00045|   do_fit_score : int;
00046|   reasons : string list;
00047| }
00048| 
00049| type worker = {
00050|   name : string;
00051|   script : string;
00052|   bindings : binding list;
00053|   routes : string list;
00054|   do_annotation : do_annotation option;
00055| }
00056| 
00057| type durable_object = { class_name : string; scrip...
batchcompleted
Batch execution (5/5 successful)
Output
All 5 tools executed successfully.

Keep using the batch tool for optimal performance in your next response!
10,853in / 486out / 255reasoning
assistantFeb 10, 02:47:28 AM
glm-4.7 · zai-coding-plan
Good, I have the initial files. Now let me continue reading more of HIR.ts since it's a large file (~1700 lines). I need to read the rest of the core HIR types including InstructionValue, Instruction, Identifier, Place, etc.

Let me continue reading the HIR.ts file to get the complete core type definitions.

readcompleted
react/compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts
Output
<file>
00501|   id: InstructionId;
00502|   loc: SourceLocation;
00503| };
00504| 
00505| export type DoWhileTerminal = {
00506|   kind: 'do-while';
00507|   loop: BlockId;
00508|   test: BlockId;
00509|   fallthrough: BlockId;
00510|   id: InstructionId;
00511|   loc: SourceLocation;
00512| };
00513| 
00514| export type WhileTerminal = {
00515|   kind: 'while';
00516|   loc: SourceLocation;
00517|   test: BlockId;
00518|   loop: BlockId;
00519|   fallthrough: BlockId;
00520|   id: InstructionId;
00521| };
00522| 
00523| export type ForTerminal = {
00524|   kind: 'for';
00525|   loc: SourceLocation;
00526|   init: BlockId;
00527|   test: BlockId;
00528|   update: BlockId | null;
00529|   loop: BlockId;
00530|   fallthrough: BlockId;
00531|   id: InstructionId;
00532| };
00533| 
00534| export type ForOfTerminal = {
00535|   kind: 'for-of';
00536|   loc: SourceLocation;
00537|   init: BlockId;
00538|   test: BlockId;
00539|   loop: BlockId;
00540|   fallthrough: BlockId;
00541|   id: InstructionId;
00542| };
00543| 
00544| export type ForInTerminal = {
00545|   kind: 'for-in';
00546|   loc: SourceLocation;
00547|   init: BlockId;
00548|   loop: BlockId;
00549|   fallthrough: BlockId;
00550|   id: InstructionId;
00551| };
00552| 
00553| export type LogicalTerminal = {
00554|   kind: 'logical';
00555|   operator: t.LogicalExpression['operator'];
00556|   test: BlockId;
00557|   fallthrough: BlockId;
00558|   id: InstructionId;
00559|   loc: SourceLocation;
00560| };
00561| 
00562| export type TernaryTerminal = {
00563|   kind: 'ternary';
00564|   test: BlockId;
00565|   fallthrough: BlockId;
00566|   id: InstructionId;
00567|   loc: SourceLocation;
00568| };
00569| 
00570| export type LabelTerminal = {
00571|   kind: 'label';
00572|   block: BlockId;
00573|   fallthrough: BlockId;
00574|   id: InstructionId;
00575|   loc: SourceLocation;
00576| };
00577| 
00578| export type OptionalTerminal = {
00579|   kind: 'optional';
00580|   /*
00581|    * Specifies whether this no...
readcompleted
react/compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts
Output
<file>
01001| 
01002|   // store `object.property = value`
01003|   | {
01004|       kind: 'PropertyStore';
01005|       object: Place;
01006|       property: PropertyLiteral;
01007|       value: Place;
01008|       loc: SourceLocation;
01009|     }
01010|   // load `object.property`
01011|   | PropertyLoad
01012|   // `delete object.property`
01013|   | {
01014|       kind: 'PropertyDelete';
01015|       object: Place;
01016|       property: PropertyLiteral;
01017|       loc: SourceLocation;
01018|     }
01019| 
01020|   // store `object[index] = value` - like PropertyStore but with a dynamic property
01021|   | {
01022|       kind: 'ComputedStore';
01023|       object: Place;
01024|       property: Place;
01025|       value: Place;
01026|       loc: SourceLocation;
01027|     }
01028|   // load `object[index]` - like PropertyLoad but with a dynamic property
01029|   | {
01030|       kind: 'ComputedLoad';
01031|       object: Place;
01032|       property: Place;
01033|       loc: SourceLocation;
01034|     }
01035|   // `delete object[property]`
01036|   | {
01037|       kind: 'ComputedDelete';
01038|       object: Place;
01039|       property: Place;
01040|       loc: SourceLocation;
01041|     }
01042|   | LoadGlobal
01043|   | StoreGlobal
01044|   | FunctionExpression
01045|   | {
01046|       kind: 'TaggedTemplateExpression';
01047|       tag: Place;
01048|       value: {raw: string; cooked?: string};
01049|       loc: SourceLocation;
01050|     }
01051|   | {
01052|       kind: 'TemplateLiteral';
01053|       subexprs: Array<Place>;
01054|       quasis: Array<{raw: string; cooked?: string}>;
01055|       loc: SourceLocation;
01056|     }
01057|   | {
01058|       kind: 'Await';
01059|       value: Place;
01060|       loc: SourceLocation;
01061|     }
01062|   | {
01063|       kind: 'GetIterator';
01064|       collection: Place; // the collection
01065|       loc: SourceLocation;
01066|     }
01067|   | {
01068|       kind: 'IteratorNext';
01069|       iterator...
readcompleted
react/compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts
Output
<file>
01501|   ValueReason.HookReturn,
01502|   ValueReason.JsxCaptured,
01503|   ValueReason.KnownReturnSignature,
01504|   ValueReason.Other,
01505|   ValueReason.ReactiveFunctionArgument,
01506|   ValueReason.ReducerState,
01507|   ValueReason.State,
01508| ]);
01509| 
01510| // The effect with which a value is modified.
01511| export enum Effect {
01512|   // Default value: not allowed after lifetime inference
01513|   Unknown = '<unknown>',
01514|   // This reference freezes the value (corresponds to a place where codegen should emit a freeze instruction)
01515|   Freeze = 'freeze',
01516|   // This reference reads the value
01517|   Read = 'read',
01518|   // This reference reads and stores the value
01519|   Capture = 'capture',
01520|   ConditionallyMutateIterator = 'mutate-iterator?',
01521|   /*
01522|    * This reference *may* write to (mutate) the value. This covers two similar cases:
01523|    * - The compiler is being conservative and assuming that a value *may* be mutated
01524|    * - The effect is polymorphic: mutable values may be mutated, non-mutable values
01525|    *   will not be mutated.
01526|    * In both cases, we conservatively assume that mutable values will be mutated.
01527|    * But we do not error if the value is known to be immutable.
01528|    */
01529|   ConditionallyMutate = 'mutate?',
01530| 
01531|   /*
01532|    * This reference *does* write to (mutate) the value. It is an error (invalid input)
01533|    * if an immutable value flows into a location with this effect.
01534|    */
01535|   Mutate = 'mutate',
01536|   // This reference may alias to (mutate) the value
01537|   Store = 'store',
01538| }
01539| export const EffectSchema = z.enum([
01540|   Effect.Read,
01541|   Effect.Mutate,
01542|   Effect.ConditionallyMutate,
01543|   Effect.ConditionallyMutateIterator,
01544|   Effect.Capture,
01545|   Effect.Store,
01546|   Effect.Freeze,
01547| ]);
01548| 
01549| export function isMutableEffect(
01550|   effect: Effect,
01551...
38,132in / 212out / 53reasoning
assistantFeb 10, 02:47:37 AM
glm-4.7 · zai-coding-plan
Now I have the complete core HIR types. Let me continue reading the remaining key files: 1. BuildHIR.ts - AST -> HIR lowering 2. HIRBuilder.ts - HIR construction helpers 3. visitors.ts - HIR traversal utilities 4. PrintHIR.ts - Debug printing Let me read these files to understand the construction patterns and visitor abstractions.

Now let me read the BuildHIR and HIRBuilder files to understand how HIR is constructed from AST:

readcompleted
react/compiler/packages/babel-plugin-react-compiler/src/HIR/BuildHIR.ts
Output
<file>
00001| /**
00002|  * Copyright (c) Meta Platforms, Inc. and affiliates.
00003|  *
00004|  * This source code is licensed under the MIT license found in the
00005|  * LICENSE file in the root directory of this source tree.
00006|  */
00007| 
00008| import {NodePath, Scope} from '@babel/traverse';
00009| import * as t from '@babel/types';
00010| import invariant from 'invariant';
00011| import {
00012|   CompilerDiagnostic,
00013|   CompilerError,
00014|   CompilerSuggestionOperation,
00015|   ErrorCategory,
00016| } from '../CompilerError';
00017| import {Err, Ok, Result} from '../Utils/Result';
00018| import {assertExhaustive, hasNode} from '../Utils/utils';
00019| import {Environment} from './Environment';
00020| import {
00021|   ArrayExpression,
00022|   ArrayPattern,
00023|   BlockId,
00024|   BranchTerminal,
00025|   BuiltinTag,
00026|   Case,
00027|   Effect,
00028|   GeneratedSource,
00029|   GotoVariant,
00030|   HIRFunction,
00031|   IfTerminal,
00032|   InstructionKind,
00033|   InstructionValue,
00034|   JsxAttribute,
00035|   LoweredFunction,
00036|   ObjectPattern,
00037|   ObjectProperty,
00038|   ObjectPropertyKey,
00039|   Place,
00040|   PropertyLiteral,
00041|   ReturnTerminal,
00042|   SourceLocation,
00043|   SpreadPattern,
00044|   ThrowTerminal,
00045|   Type,
00046|   makeInstructionId,
00047|   makePropertyLiteral,
00048|   makeType,
00049|   promoteTemporary,
00050|   validateIdentifierName,
00051| } from './HIR';
00052| import HIRBuilder, {Bindings, createTemporaryPlace} from './HIRBuilder';
00053| import {BuiltInArrayId} from './ObjectShape';
00054| 
00055| /*
00056|  * *******************************************************************************************
00057|  * *******************************************************************************************
00058|  * ************************************* Lowering to HIR *************************************
00059|  * ***************************************************************...
readcompleted
react/compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts
Output
<file>
00001| /**
00002|  * Copyright (c) Meta Platforms, Inc. and affiliates.
00003|  *
00004|  * This source code is licensed under the MIT license found in the
00005|  * LICENSE file in the root directory of this source tree.
00006|  */
00007| 
00008| import {Binding, NodePath} from '@babel/traverse';
00009| import * as t from '@babel/types';
00010| import {CompilerError, ErrorCategory} from '../CompilerError';
00011| import {Environment} from './Environment';
00012| import {
00013|   BasicBlock,
00014|   BlockId,
00015|   BlockKind,
00016|   Effect,
00017|   GeneratedSource,
00018|   GotoVariant,
00019|   HIR,
00020|   Identifier,
00021|   IdentifierId,
00022|   Instruction,
00023|   Place,
00024|   SourceLocation,
00025|   Terminal,
00026|   VariableBinding,
00027|   makeBlockId,
00028|   makeDeclarationId,
00029|   makeIdentifierName,
00030|   makeInstructionId,
00031|   makeTemporaryIdentifier,
00032|   makeType,
00033| } from './HIR';
00034| import {printInstruction} from './PrintHIR';
00035| import {
00036|   eachTerminalSuccessor,
00037|   mapTerminalSuccessors,
00038|   terminalFallthrough,
00039| } from './visitors';
00040| 
00041| /*
00042|  * *******************************************************************************************
00043|  * *******************************************************************************************
00044|  * ************************************* Lowering to HIR *************************************
00045|  * *******************************************************************************************
00046|  * *******************************************************************************************
00047|  */
00048| 
00049| // A work-in-progress block that does not yet have a terminator
00050| export type WipBlock = {
00051|   id: BlockId;
00052|   instructions: Array<Instruction>;
00053|   kind: BlockKind;
00054| };
00055| 
00056| type Scope = LoopScope | LabelScope | SwitchScope;
00057| 
00058| type LoopScope = {
00...
readcompleted
react/compiler/packages/babel-plugin-react-compiler/src/HIR/visitors.ts
Output
<file>
00001| /**
00002|  * Copyright (c) Meta Platforms, Inc. and affiliates.
00003|  *
00004|  * This source code is licensed under the MIT license found in the
00005|  * LICENSE file in the root directory of this source tree.
00006|  */
00007| 
00008| import {assertExhaustive} from '../Utils/utils';
00009| import {CompilerError} from '..';
00010| import {
00011|   BasicBlock,
00012|   BlockId,
00013|   Instruction,
00014|   InstructionKind,
00015|   InstructionValue,
00016|   makeInstructionId,
00017|   Pattern,
00018|   Place,
00019|   ReactiveInstruction,
00020|   ReactiveScope,
00021|   ReactiveValue,
00022|   ScopeId,
00023|   SpreadPattern,
00024|   Terminal,
00025| } from './HIR';
00026| 
00027| export function* eachInstructionLValue(
00028|   instr: ReactiveInstruction,
00029| ): Iterable<Place> {
00030|   if (instr.lvalue !== null) {
00031|     yield instr.lvalue;
00032|   }
00033|   yield* eachInstructionValueLValue(instr.value);
00034| }
00035| 
00036| export function* eachInstructionLValueWithKind(
00037|   instr: ReactiveInstruction,
00038| ): Iterable<[Place, InstructionKind]> {
00039|   switch (instr.value.kind) {
00040|     case 'DeclareContext':
00041|     case 'StoreContext':
00042|     case 'DeclareLocal':
00043|     case 'StoreLocal': {
00044|       yield [instr.value.lvalue.place, instr.value.lvalue.kind];
00045|       break;
00046|     }
00047|     case 'Destructure': {
00048|       const kind = instr.value.lvalue.kind;
00049|       for (const place of eachPatternOperand(instr.value.lvalue.pattern)) {
00050|         yield [place, kind];
00051|       }
00052|       break;
00053|     }
00054|     case 'PostfixUpdate':
00055|     case 'PrefixUpdate': {
00056|       yield [instr.value.lvalue, InstructionKind.Reassign];
00057|       break;
00058|     }
00059|   }
00060| }
00061| 
00062| export function* eachInstructionValueLValue(
00063|   value: ReactiveValue,
00064| ): Iterable<Place> {
00065|   switch (value.kind) {
00066|     case 'DeclareCont...
readcompleted
react/compiler/packages/babel-plugin-react-compiler/src/HIR/PrintHIR.ts
Output
<file>
00001| /**
00002|  * Copyright (c) Meta Platforms, Inc. and affiliates.
00003|  *
00004|  * This source code is licensed under the MIT license found in the
00005|  * LICENSE file in the root directory of this source tree.
00006|  */
00007| 
00008| import {CompilerError} from '../CompilerError';
00009| import {printReactiveScopeSummary} from '../ReactiveScopes/PrintReactiveFunction';
00010| import DisjointSet from '../Utils/DisjointSet';
00011| import {assertExhaustive} from '../Utils/utils';
00012| import type {
00013|   FunctionExpression,
00014|   HIR,
00015|   HIRFunction,
00016|   Identifier,
00017|   IdentifierName,
00018|   Instruction,
00019|   InstructionValue,
00020|   LValue,
00021|   ManualMemoDependency,
00022|   MutableRange,
00023|   ObjectMethod,
00024|   ObjectPropertyKey,
00025|   Pattern,
00026|   Phi,
00027|   Place,
00028|   ReactiveInstruction,
00029|   ReactiveScope,
00030|   ReactiveValue,
00031|   SourceLocation,
00032|   SpreadPattern,
00033|   Terminal,
00034|   Type,
00035| } from './HIR';
00036| import {GotoVariant, InstructionKind} from './HIR';
00037| import {AliasingEffect, AliasingSignature} from '../Inference/AliasingEffects';
00038| 
00039| export type Options = {
00040|   indent: number;
00041| };
00042| 
00043| export function printFunctionWithOutlined(fn: HIRFunction): string {
00044|   const output = [printFunction(fn)];
00045|   for (const outlined of fn.env.getOutlinedFunctions()) {
00046|     output.push(`\nfunction ${outlined.fn.id}:\n${printHIR(outlined.fn.body)}`);
00047|   }
00048|   return output.join('\n');
00049| }
00050| 
00051| export function printFunction(fn: HIRFunction): string {
00052|   const output = [];
00053|   let definition = '';
00054|   if (fn.id !== null) {
00055|     definition += fn.id;
00056|   } else {
00057|     definition += '<<anonymous>>';
00058|   }
00059|   if (fn.nameHint != null) {
00060|     definition += ` ${fn.nameHint}`;
00061|   }
00062|   if (fn.params.length !== 0) {
00063|    ...
15,618in / 277out / 77reasoning
assistantFeb 10, 02:47:46 AM
glm-4.7 · zai-coding-plan
Now I have a comprehensive understanding of the React Compiler's HIR system. Let me continue reading more of the BuildHIR to understand control flow lowering, and also check what other relevant files I might need. Let me also read more of BuildHIR to understand loops, switch, and other control flow patterns.

Let me read more of BuildHIR to understand the control flow lowering patterns for loops and other constructs:

readcompleted
react/compiler/packages/babel-plugin-react-compiler/src/HIR/BuildHIR.ts
Output
<file>
00601|           continuationBlock.id,
00602|           () => {
00603|             const body = stmt.get('body');
00604|             lowerStatement(builder, body);
00605|             return {
00606|               kind: 'goto',
00607|               block: updateBlock ?? testBlock.id,
00608|               variant: GotoVariant.Continue,
00609|               id: makeInstructionId(0),
00610|               loc: body.node.loc ?? GeneratedSource,
00611|             };
00612|           },
00613|         );
00614|       });
00615| 
00616|       builder.terminateWithContinuation(
00617|         {
00618|           kind: 'for',
00619|           loc: stmtNode.loc ?? GeneratedSource,
00620|           init: initBlock,
00621|           test: testBlock.id,
00622|           update: updateBlock,
00623|           loop: bodyBlock,
00624|           fallthrough: continuationBlock.id,
00625|           id: makeInstructionId(0),
00626|         },
00627|         testBlock,
00628|       );
00629| 
00630|       const test = stmt.get('test');
00631|       if (test.node == null) {
00632|         builder.errors.push({
00633|           reason: `(BuildHIR::lowerStatement) Handle empty test in ForStatement`,
00634|           category: ErrorCategory.Todo,
00635|           loc: stmt.node.loc ?? null,
00636|           suggestions: null,
00637|         });
00638|       } else {
00639|         builder.terminateWithContinuation(
00640|           {
00641|             kind: 'branch',
00642|             test: lowerExpressionToTemporary(
00643|               builder,
00644|               test as NodePath<t.Expression>,
00645|             ),
00646|             consequent: bodyBlock,
00647|             alternate: continuationBlock.id,
00648|             fallthrough: continuationBlock.id,
00649|             id: makeInstructionId(0),
00650|             loc: stmt.node.loc ?? GeneratedSource,
00651|           },
00652|           continuationBlock,
00653|         );
00654|       }
00655|       return;
00656|   ...
72,961in / 130out / 61reasoning
assistantFeb 10, 02:48:28 AM
glm-4.7 · zai-coding-plan