react-nitro-hermes 0.0.1-alpha.8 → 0.0.1-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/hermes/CMakeLists.txt +874 -0
  2. package/hermes/android/HostObjectJniTest.cpp +178 -0
  3. package/hermes/android/build-logic/build.gradle.kts +31 -0
  4. package/hermes/android/build-logic/settings.gradle.kts +17 -0
  5. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/helpers/internal/SerializeHermesCompilerPackageJson.kt +33 -0
  6. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/plugins/internal/TestUtilsPlugin.kt +80 -0
  7. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/tasks/internal/CustomExecTask.kt +46 -0
  8. package/hermes/android/build-logic/src/main/kotlin/publish.gradle.kts +82 -0
  9. package/hermes/android/build.gradle.kts +332 -0
  10. package/hermes/android/cppruntime/build.gradle +72 -0
  11. package/hermes/android/cppruntime/src/main/AndroidManifest.xml +2 -0
  12. package/hermes/android/cppruntime/src/main/cpp/CMakeLists.txt +8 -0
  13. package/hermes/android/cppruntime/src/main/cpp/stub.cpp +12 -0
  14. package/hermes/android/cross-compile/swift-libicu.patch +13 -0
  15. package/hermes/android/cross-compile/toolchain-android-arm-api13-gnustl.cmake +13 -0
  16. package/hermes/android/cross-compile/toolchain-android-arm-api15-gnustl.cmake +14 -0
  17. package/hermes/android/gradle/libs.versions.toml +30 -0
  18. package/hermes/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  19. package/hermes/android/gradle/wrapper/gradle-wrapper.properties +7 -0
  20. package/hermes/android/gradle.properties +3 -0
  21. package/hermes/android/gradlew +248 -0
  22. package/hermes/android/gradlew.bat +93 -0
  23. package/hermes/android/intltest/build.gradle +147 -0
  24. package/hermes/android/intltest/java/com/facebook/hermes/test/CMakeLists.txt +45 -0
  25. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.cpp +68 -0
  26. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.h +44 -0
  27. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.java +45 -0
  28. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogueTestData.java +32 -0
  29. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesInstrumentationTest.java +150 -0
  30. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesIntlAndroidTest.java +147 -0
  31. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesIntlTest262.java +470 -0
  32. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesRuntimeFactory.cpp +73 -0
  33. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.cpp +90 -0
  34. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.h +62 -0
  35. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.java +155 -0
  36. package/hermes/android/intltest/java/com/facebook/hermes/test/MappedFileBuffer.cpp +48 -0
  37. package/hermes/android/intltest/java/com/facebook/hermes/test/MappedFileBuffer.h +36 -0
  38. package/hermes/android/intltest/java/com/facebook/hermes/test/OnLoad.cpp +13 -0
  39. package/hermes/android/intltest/java/com/facebook/hermes/test/OnLoadEpilogue.cpp +13 -0
  40. package/hermes/android/intltest/src/main/AndroidManifest.xml +2 -0
  41. package/hermes/android/ios-artifacts/build.gradle.kts +65 -0
  42. package/hermes/android/settings.gradle.kts +27 -0
  43. package/hermes/cmake/modules/Hermes.cmake +481 -0
  44. package/hermes/cmake/modules/Lit.cmake +96 -0
  45. package/hermes/doc/Branches.md +38 -0
  46. package/hermes/doc/BuildingAndRunning.md +121 -0
  47. package/hermes/doc/CodingStandards.md +112 -0
  48. package/hermes/doc/CrossCompilation.md +79 -0
  49. package/hermes/doc/Design.md +217 -0
  50. package/hermes/doc/Emscripten.md +156 -0
  51. package/hermes/doc/Features.md +143 -0
  52. package/hermes/doc/GCSafeCoding.md +563 -0
  53. package/hermes/doc/GenGC.md +300 -0
  54. package/hermes/doc/Hades.md +344 -0
  55. package/hermes/doc/HighLevelOptimizations.md +37 -0
  56. package/hermes/doc/IR.md +1306 -0
  57. package/hermes/doc/IntlAPIs.md +196 -0
  58. package/hermes/doc/JIT.md +999 -0
  59. package/hermes/doc/LazyEvalCompilation.md +84 -0
  60. package/hermes/doc/MemoryProfilers.md +316 -0
  61. package/hermes/doc/Modules.md +144 -0
  62. package/hermes/doc/Optimizer.md +83 -0
  63. package/hermes/doc/PerfProfiling.md +29 -0
  64. package/hermes/doc/ProhibitInvoke.md +329 -0
  65. package/hermes/doc/ReactNative.md +40 -0
  66. package/hermes/doc/ReactNativeIntegration.md +94 -0
  67. package/hermes/doc/RegExp.md +24 -0
  68. package/hermes/doc/SpecIncompat.md +85 -0
  69. package/hermes/doc/Strings.md +140 -0
  70. package/hermes/doc/TypedLanguage.md +432 -0
  71. package/hermes/doc/VM.md +174 -0
  72. package/hermes/doc/blog/2024-11-09-octane-benchmark-jit-progress.md +17 -0
  73. package/hermes/doc/blog/2024-12-19-static-hermes-update-dec-2024.md +47 -0
  74. package/hermes/doc/blog/2024-12-23-compiling-javascript-to-wasm.md +267 -0
  75. package/hermes/doc/blog/2025-06-09-jsi-runtime-data-apis.md +23 -0
  76. package/hermes/doc/blog/2025-07-15-static-h-performance-june-2025.md +18 -0
  77. package/hermes/doc/blog/2025-11-02-hermes-compilation-runtime-modes.md +23 -0
  78. package/hermes/doc/blog/2025-11-06-hermes-memory-modes.md +35 -0
  79. package/hermes/doc/blog/2025-11-24-json-parsing-performance.md +17 -0
  80. package/hermes/doc/blog/2025-12-02-iserialization.md +11 -0
  81. package/hermes/doc/blog/2025-12-12-new-way-to-contribute.md +68 -0
  82. package/hermes/doc/blog/2026-06-05-new-hermes-stable-release.md +51 -0
  83. package/hermes/doc/blog/README.md +25 -0
  84. package/hermes/doc/blog/images/2024-11-09-octane-pi3.jpeg +0 -0
  85. package/hermes/doc/blog/images/2024-11-09-octane-pi5.jpeg +0 -0
  86. package/hermes/doc/blog/images/2025-07-15-perf-hv32-interpreter.jpeg +0 -0
  87. package/hermes/doc/blog/images/2025-07-15-perf-hv32-jit.jpeg +0 -0
  88. package/hermes/doc/icu_license.txt +420 -0
  89. package/hermes/doc/img/heap_snapshot_retainers.png +0 -0
  90. package/hermes/doc/img/logo.svg +1 -0
  91. package/hermes/doc/img/object_captured_by_environment.png +0 -0
  92. package/hermes/doc/img/root_categories.png +0 -0
  93. package/hermes/doc/plans/ir-type/flow-type-system.md +324 -0
  94. package/hermes/doc/plans/ir-type/ir-type-system-v2-design.md +652 -0
  95. package/hermes/doc/plans/ir-type/ir-type-system.md +220 -0
  96. package/hermes/doc/plans/ir-type/ir-type-v2-implementation.md +1187 -0
  97. package/hermes/doc/plans/ir-type/memory.md +48 -0
  98. package/hermes/doc/plans/ir-type/phase1-steps.md +512 -0
  99. package/hermes/doc/plans/ir-type/progress.md +239 -0
  100. package/hermes/doc/plans/ir-type/typeinference-primitive-fastpath-design.md +203 -0
  101. package/hermes/doc/plans/ir-type/typeinference-primitive-fastpath-results.md +71 -0
  102. package/hermes/doc/superpowers/plans/2026-07-28-worker-arraybuffer-input.md +597 -0
  103. package/hermes/doc/superpowers/plans/2026-08-18-jitemitter-split.md +1149 -0
  104. package/hermes/doc/superpowers/plans/2026-08-20-jit-type-asserts.md +969 -0
  105. package/hermes/doc/superpowers/plans/2026-08-23-jit-shared-compiler-driver.md +478 -0
  106. package/hermes/doc/superpowers/plans/2026-08-23-x86-64-jit-skeleton.md +797 -0
  107. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-arith.md +444 -0
  108. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-calls.md +261 -0
  109. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-props.md +240 -0
  110. package/hermes/doc/superpowers/plans/2026-10-26-regexp-bytecode-sharing.md +2197 -0
  111. package/hermes/doc/superpowers/plans/2026-10-28-regexp-start-filter-and-exec-fast-paths.md +3981 -0
  112. package/hermes/doc/superpowers/specs/2026-07-28-worker-arraybuffer-input-design.md +206 -0
  113. package/hermes/doc/superpowers/specs/2026-08-18-jitemitter-split-design.md +530 -0
  114. package/hermes/doc/superpowers/specs/2026-08-20-jit-type-asserts-design.md +360 -0
  115. package/hermes/doc/superpowers/specs/2026-08-23-x86-64-jit-design.md +246 -0
  116. package/hermes/doc/superpowers/specs/2026-08-26-icu-free-normalize-design.md +355 -0
  117. package/hermes/doc/superpowers/specs/2026-08-27-icu-free-convert-to-case-design.md +305 -0
  118. package/hermes/doc/superpowers/specs/2026-08-27-icu-free-locale-compare-design.md +429 -0
  119. package/hermes/doc/superpowers/specs/2026-08-29-icu-free-date-format-design.md +297 -0
  120. package/hermes/doc/superpowers/specs/2026-10-26-regexp-bytecode-sharing-design.md +605 -0
  121. package/hermes/doc/superpowers/specs/2026-10-28-regexp-start-filter-and-exec-fast-paths-design.md +551 -0
  122. package/hermes/doc/typescript-stripping.md +90 -0
  123. package/hermes/external/CMakeLists.txt +20 -0
  124. package/hermes/utils/IntlGen/IntlGen.java +531 -0
  125. package/hermes/utils/bench_with_stats.py +827 -0
  126. package/hermes/utils/build-apple-framework.sh +323 -0
  127. package/hermes/utils/chrome_snapshot_parser.py +210 -0
  128. package/hermes/utils/cmake-dev-build.sh +18 -0
  129. package/hermes/utils/commons.sh +55 -0
  130. package/hermes/utils/dump-cpp-funcs.sh +3 -0
  131. package/hermes/utils/es5objects.js +198 -0
  132. package/hermes/utils/format.sh +145 -0
  133. package/hermes/utils/gen-promise-internal-bc.sh +66 -0
  134. package/hermes/utils/genUnicodeTable.py +2503 -0
  135. package/hermes/utils/hermes-lit/CMakeLists.txt +22 -0
  136. package/hermes/utils/hermes-lit/hermes-lit.in +15 -0
  137. package/hermes/utils/jit/README.md +134 -0
  138. package/hermes/utils/jit/jit-diff.sh +160 -0
  139. package/hermes/utils/jit/jit-dump.sh +193 -0
  140. package/hermes/utils/lit-expect-gen/generate.py +217 -0
  141. package/hermes/utils/promise/index.js +15 -0
  142. package/hermes/utils/promise/package.json +13 -0
  143. package/hermes/utils/promise/rollup.config.js +19 -0
  144. package/hermes/utils/promise/yarn.lock +247 -0
  145. package/hermes/utils/scripts/hermes/consts.js +26 -0
  146. package/hermes/utils/scripts/hermes/create-tarball.js +75 -0
  147. package/hermes/utils/scripts/hermes/get-hermes-version.js +57 -0
  148. package/hermes/utils/scripts/hermes/hermes-utils.js +122 -0
  149. package/hermes/utils/scripts/hermes/package.json +6 -0
  150. package/hermes/utils/scripts/hermes/prepare-artifacts.js +113 -0
  151. package/hermes/utils/scripts/hermes/publish-artifacts.js +109 -0
  152. package/hermes/utils/scripts/hermes/publish-npm.js +96 -0
  153. package/hermes/utils/scripts/hermes/scm-utils.js +41 -0
  154. package/hermes/utils/scripts/hermes/set-artifacts-version.js +64 -0
  155. package/hermes/utils/scripts/hermes/version-utils.js +98 -0
  156. package/hermes/utils/scripts/hermes/yarn.lock +240 -0
  157. package/hermes/utils/summarize_sizes.py +184 -0
  158. package/hermes/utils/symbolicate-nativecall-stats.py +112 -0
  159. package/hermes/utils/test_runner.py +13 -0
  160. package/hermes/utils/testsuite/README.facebook +3 -0
  161. package/hermes/utils/testsuite/README.md +69 -0
  162. package/hermes/utils/testsuite/cli.py +547 -0
  163. package/hermes/utils/testsuite/es_ast.py +337 -0
  164. package/hermes/utils/testsuite/external/LICENSE +28 -0
  165. package/hermes/utils/testsuite/external/README.facebook +8 -0
  166. package/hermes/utils/testsuite/external/__init__.py +0 -0
  167. package/hermes/utils/testsuite/external/_monkeyYaml.py +164 -0
  168. package/hermes/utils/testsuite/external/parse_test262.py +141 -0
  169. package/hermes/utils/testsuite/hermes.py +522 -0
  170. package/hermes/utils/testsuite/preprocess.py +365 -0
  171. package/hermes/utils/testsuite/progress.py +377 -0
  172. package/hermes/utils/testsuite/skiplist.json +4356 -0
  173. package/hermes/utils/testsuite/skiplist.py +270 -0
  174. package/hermes/utils/testsuite/test_run_defs.py +435 -0
  175. package/hermes/utils/testsuite/typing_defs.py +52 -0
  176. package/hermes/utils/testsuite/utils.py +214 -0
  177. package/hermes/utils/tidy.sh +22 -0
  178. package/hermes/utils/update-fbcode-hermes.sh +53 -0
  179. package/hermes/utils/updateErrorTest.py +193 -0
  180. package/hermes/utils/wasm-compile.sh +65 -0
  181. package/package.json +1 -1
@@ -0,0 +1,652 @@
1
+ # IR Type System v2 — Design Proposal
2
+
3
+ ## Problem
4
+
5
+ The current IR `Type` is a 16-bit bitmask of 13 primitive kinds. It can express
6
+ "this value might be a number or a string" but cannot express "this value is an
7
+ instance of class Foo" or "this is an array of numbers". The Flow type system
8
+ (FlowContext) has full nominal classes, typed arrays, function signatures, tuples,
9
+ and exact objects — but none of that information survives lowering into IR.
10
+
11
+ We want to enrich the IR type system so it can carry Flow-level type information
12
+ through optimization and into codegen. The type system will also generate runtime
13
+ type representations for soundness enforcement, checked casts, and type guards.
14
+
15
+ ## Design Goals
16
+
17
+ 1. **Expressive**: can represent everything the Flow type system expresses —
18
+ nominal classes, typed arrays, function signatures, tuples, exact objects,
19
+ and arbitrary unions thereof.
20
+
21
+ 2. **Correct**: every type operation (union, intersect, subset, etc.) is
22
+ well-defined and sound for all type combinations. Every operation
23
+ produces a valid result for every input — no "returns garbage" fallback
24
+ paths. Some operations (notably `subtract`) may return a conservative
25
+ approximation when the exact result is not representable.
26
+
27
+ 3. **Orthogonal**: Union is the single, uniform composition mechanism for all
28
+ types. The type hierarchy has clean, independent dimensions with no ad-hoc
29
+ encoding distinctions.
30
+
31
+ 4. **Backwards-compatible**: the existing IR type system is a proper subset.
32
+ All current types and operations continue to work. Flow types lower to IR
33
+ types.
34
+
35
+ 5. **Suitable for runtime**: types can be lowered to compact runtime type
36
+ descriptors for checked casts and type guards.
37
+
38
+ 6. **Efficient** (deferred): performance optimizations (bitmask fast paths,
39
+ compact encoding) can be layered on without changing the type algebra.
40
+
41
+ ## Type Hierarchy
42
+
43
+ A Type represents a **set of possible runtime values**. Every runtime value
44
+ belongs to exactly one *base type*. A Type is either a base type, a union of
45
+ types, or the empty type (NoType).
46
+
47
+ ```
48
+ Type
49
+ ├── NoType -- empty set (bottom, unreachable)
50
+ ├── Primitives
51
+ │ ├── Undefined
52
+ │ ├── Null
53
+ │ ├── Boolean
54
+ │ ├── Number (fp64)
55
+ │ │ ├── Int32 -- fp64, value in int32 range
56
+ │ │ └── Uint32 -- fp64, value in uint32 range
57
+ │ ├── BigInt
58
+ │ ├── String
59
+ │ └── Symbol
60
+ ├── Object -- any object, no refinement
61
+ │ ├── ClassInstance(classId) -- nominal, with inheritance
62
+ │ ├── Array(elemType) -- known element type
63
+ │ ├── Tuple(elemTypes...) -- fixed-length, positional
64
+ │ ├── Function(signature) -- known param/return types
65
+ │ └── ExactObject(fields...) -- known exact field set
66
+ ├── Internal
67
+ │ ├── Empty -- TDZ
68
+ │ ├── Uninit -- declared, not initialized
69
+ │ ├── Environment
70
+ │ ├── PrivateName
71
+ │ ├── FunctionCode
72
+ │ └── bits32 -- physical 32-bit integer, signless
73
+ └── Union(Type, Type, ...) -- union of two or more types
74
+ ```
75
+
76
+ ### Primitive Types
77
+
78
+ Primitives correspond to JS primitive values. Each is a distinct kind — a
79
+ runtime value is exactly one primitive kind.
80
+
81
+ | Type | Description |
82
+ |------|-------------|
83
+ | Undefined | The JS `undefined` value |
84
+ | Null | The JS `null` value |
85
+ | Boolean | `true` or `false` |
86
+ | Number | IEEE 754 double-precision float |
87
+ | BigInt | Arbitrary-precision integer |
88
+ | String | JS string |
89
+ | Symbol | ES2015 symbol |
90
+
91
+ **Number subtypes**: `Int32` and `Uint32` are subtypes of `Number`. They
92
+ represent values that are still fp64 at runtime but are known to be integers
93
+ within a specific range. They are not separate runtime kinds — they are
94
+ refinements that enable integer-specific optimizations.
95
+
96
+ - `Int32`: integer value in [-2³¹, 2³¹ - 1].
97
+ - `Uint32`: integer value in [0, 2³² - 1].
98
+ - `Int32` and `Uint32` overlap (both contain [0, 2³¹ - 1]) but neither is a
99
+ subtype of the other.
100
+
101
+ ### Object Types
102
+
103
+ `Object` is the base type for all JS objects. It represents "some object, no
104
+ further information." Object refinements narrow this to specific categories:
105
+
106
+ | Refinement | Description |
107
+ |------------|-------------|
108
+ | ClassInstance(classId) | Instance of a specific nominal class. Subtyping follows the class inheritance chain. |
109
+ | Array(elemType) | Array with a known element type. Legacy arrays use `Array(any)`. Invariant (not covariant) because arrays are mutable. |
110
+ | Tuple(elemTypes...) | Fixed-length array with known positional types. Invariant. |
111
+ | Function(signature) | Callable with known parameter and return types. Signature is immutable (derived from FunctionCode). Legacy functions use `Function(any, ...) => any`. |
112
+ | ExactObject(fields...) | Object with a known exact set of typed fields. No extra properties. |
113
+
114
+ All object refinements are subtypes of `Object`. Different refinement categories
115
+ are disjoint — a value cannot be both a ClassInstance and an Array.
116
+
117
+ **Legacy vs typed objects**: the type system does NOT distinguish between
118
+ "legacy" (dynamic shape) and "typed" (fixed shape) objects. Legacy JS objects
119
+ can be typed with their known type information (e.g., a legacy function's
120
+ signature comes from its FunctionCode). The distinction between dynamic and
121
+ fixed shapes is encoded in the instructions that access them (PrLoad/PrStore
122
+ for typed access, LoadProperty/StoreProperty for legacy), not in the type
123
+ system.
124
+
125
+ ### Internal Types
126
+
127
+ Internal types represent values that exist in the IR but are not JS-visible:
128
+
129
+ | Type | Description |
130
+ |------|-------------|
131
+ | Empty | Temporal Dead Zone — variable before its declaration |
132
+ | Uninit | After declaration, before initialization (maps to `undefined` at runtime) |
133
+ | Environment | Lexical scope |
134
+ | PrivateName | Private class field name |
135
+ | FunctionCode | IR function reference (the code, not a closure). Will carry the precise function signature in the future; currently untyped for backwards compatibility. |
136
+ | bits32 | Physical 32-bit integer, signless. Sign is a property of the consuming operation. Fits in a NaN-boxed register. |
137
+
138
+ `bits32` is fundamentally different from `Number` and its subtypes. `Number`
139
+ (including `Int32` and `Uint32`) is a JS value with fp64 representation.
140
+ `bits32` is a physical 32-bit integer with integer representation.
141
+ Specialized instructions handle conversion between `bits32` and `Number`.
142
+
143
+ ### Union Types
144
+
145
+ Union is the **single, uniform composition mechanism**. `Union(A, B, ...)`
146
+ represents a value that could be any one of its member types.
147
+
148
+ ```
149
+ Union(Number, String) -- number or string
150
+ Union(ClassA, ClassB) -- instance of ClassA or ClassB
151
+ Union(Number, ClassA, Null) -- number, ClassA instance, or null
152
+ ```
153
+
154
+ There is no conceptual distinction between unions of primitives and unions of
155
+ refined types. The bitmask encoding in the current IR is an implementation
156
+ optimization of primitive unions, not a separate concept.
157
+
158
+ **Canonical form**: unions are maintained in canonical form:
159
+ - Nested unions are flattened: `Union(A, Union(B, C))` = `Union(A, B, C)`.
160
+ - Single-element unions collapse: `Union(A)` = `A`.
161
+ - Duplicate arms are removed.
162
+ - Subsumed arms are removed: `Union(Int32, Number)` = `Number`.
163
+ - Arms are sorted for deterministic comparison.
164
+
165
+ ### Special Types
166
+
167
+ - **NoType**: the empty set. No possible values. Bottom of the type lattice.
168
+ Represents unreachable code.
169
+ - **AnyType**: the union of all JS-observable types (all primitives + Object).
170
+ Top of the JS type lattice. Equivalent to today's `TYPE_ANY_MASK`.
171
+
172
+ `any` is not a distinct type kind — it is the maximal union. When Flow's `any`
173
+ type requires checked casts on output, that is an instruction-level decision
174
+ made during IRGen, not a property of the IR type.
175
+
176
+ ## Subtype Relationships
177
+
178
+ The subtype relation `A <: B` means every value of type A is also a value of
179
+ type B (set inclusion).
180
+
181
+ ### Rules
182
+
183
+ **Primitives:**
184
+ - `Int32 <: Number`.
185
+ - `Uint32 <: Number`.
186
+ - All other primitive kinds are pairwise disjoint.
187
+
188
+ **Objects:**
189
+ - Every object refinement `<: Object`.
190
+ - `ClassB <: ClassA` if ClassB extends ClassA (nominal inheritance chain).
191
+ - Two ClassInstances with no inheritance relationship are disjoint.
192
+ - Different refinement categories are disjoint (ClassInstance ∩ Array = ∅).
193
+
194
+ **Unions:**
195
+ - `A <: Union(..., A, ...)` — every type is a subtype of any union containing it.
196
+ - `Union(A₁, ..., Aₙ) <: B` iff `Aᵢ <: B` for all i.
197
+
198
+ **General:**
199
+ - `NoType <: T` for all T.
200
+ - `T <: AnyType` for all JS-observable T.
201
+ - Reflexive: `T <: T`.
202
+ - Transitive: `A <: B` and `B <: C` implies `A <: C`.
203
+
204
+ ## Type Operations
205
+
206
+ ### union(A, B)
207
+
208
+ Returns the smallest type containing all values of both A and B.
209
+
210
+ ```
211
+ union(A, B):
212
+ if A == B: return A
213
+ if A == NoType: return B
214
+ if B == NoType: return A
215
+ if A <: B: return B
216
+ if B <: A: return A
217
+ return canonical Union(A, B)
218
+ ```
219
+
220
+ For object refinements:
221
+ - `union(ClassA, ClassB)` where A extends B → B (the superclass).
222
+ - `union(ClassA, ClassB)` unrelated → `Union(ClassA, ClassB)`.
223
+ - `union(Array(T), Array(T))` → `Array(T)`.
224
+ - `union(Array(S), Array(T))` where S ≠ T → `Union(Array(S), Array(T))`.
225
+ NOT `Array(union(S, T))` — arrays are invariant because they are mutable.
226
+
227
+ ### intersect(A, B)
228
+
229
+ Returns the largest type whose values are in both A and B.
230
+
231
+ ```
232
+ intersect(A, B):
233
+ if A == B: return A
234
+ if A <: B: return A
235
+ if B <: A: return B
236
+ if A and B are disjoint: return NoType
237
+ distribute over unions:
238
+ intersect(Union(A₁,...,Aₙ), B) = union(intersect(A₁,B), ..., intersect(Aₙ,B))
239
+ ```
240
+
241
+ Key cases:
242
+ - `intersect(Number, Int32)` = Int32.
243
+ - `intersect(Object, ClassA)` = ClassA.
244
+ - `intersect(ClassA, ClassB)` unrelated = NoType.
245
+ - `intersect(Number, String)` = NoType.
246
+
247
+ ### subtract(A, B)
248
+
249
+ Removes from A all values that are in B. Returns a conservative approximation
250
+ (superset of the true result) when the exact difference is not representable.
251
+
252
+ ```
253
+ subtract(A, B):
254
+ if A <: B: return NoType
255
+ if A and B are disjoint: return A
256
+ distribute over unions:
257
+ subtract(Union(A₁,...,Aₙ), B) = union(subtract(A₁,B), ..., subtract(Aₙ,B))
258
+ ```
259
+
260
+ Key cases:
261
+ - `subtract(Union(Number, String), Number)` = String (exact).
262
+ - `subtract(Union(ClassA, ClassB), ClassA)` = ClassB (exact).
263
+ - `subtract(Object, ClassA)` = Object (conservative — "all objects except
264
+ ClassA" is not representable).
265
+ - `subtract(Number, Int32)` = Number (conservative).
266
+
267
+ ### isSubsetOf(A, B)
268
+
269
+ Returns true iff `A <: B`. See Subtype Relationships above.
270
+
271
+ ## Function Signatures
272
+
273
+ ```
274
+ FunctionSignature:
275
+ returnType : Type
276
+ thisType : Type -- NoType if no `this` parameter
277
+ restType : Type -- NoType if no rest parameter
278
+ params : [(Type, bool)] -- (type, isOptional) per parameter
279
+ isAsync : bool
280
+ isGenerator : bool
281
+ ```
282
+
283
+ Note: `restType` represents the element type of a trailing rest parameter
284
+ (e.g., `...args: string[]` has `restType = String`). Flow's
285
+ `TypedFunctionType` does not currently represent rest parameters; this field
286
+ is forward-looking.
287
+
288
+ **Subtyping** uses standard variance:
289
+ - Contravariant in parameters (callee accepts at least what caller provides).
290
+ - Covariant in return type (callee returns at most what caller expects).
291
+ - Async/generator flags must match exactly.
292
+
293
+ Two `Function` types with different signatures are disjoint unless related
294
+ by the variance rules above.
295
+
296
+ ## Class Types and Inheritance
297
+
298
+ Classes are nominal — identity is the type table index, not structure. Two
299
+ classes with identical fields are different types if they come from different
300
+ class declarations.
301
+
302
+ A `ClassInstance` type entry stores the superclass relationship, class name,
303
+ and field layout directly in its `TypeEntry` payload:
304
+
305
+ ```
306
+ ClassInstance payload:
307
+ superClassTypeId : uint32 -- type table ID of parent ClassInstance
308
+ (kNoTypeId if no parent)
309
+ className : Identifier -- for runtime type descriptors and
310
+ error messages
311
+ fields : [(name, Type)] -- direct fields
312
+ ```
313
+
314
+ There is no separate class registry or class ID namespace. The type table
315
+ entry's own `id_` serves as the class identity. The `createClassInstance()`
316
+ method on `TypeContext` creates a new (non-interned) entry for each
317
+ class declaration.
318
+
319
+ **Subtyping**: `ClassInstance(A) <: ClassInstance(B)` iff B is an ancestor
320
+ of A in the inheritance chain. The chain is walked via the
321
+ `superClassTypeId` field in the type table entries.
322
+
323
+ **Disjointness**: two classes with no inheritance relationship are disjoint.
324
+ This enables precise intersection (`intersect(ClassA, ClassB)` = NoType for
325
+ unrelated classes).
326
+
327
+ ## Relationship to Flow Types
328
+
329
+ | Flow Type | IR Type |
330
+ |-----------|---------|
331
+ | `void` | Undefined |
332
+ | `null` | Null |
333
+ | `number` | Number |
334
+ | `string` | String |
335
+ | `boolean` | Boolean |
336
+ | `bigint` | BigInt |
337
+ | `symbol` | Symbol |
338
+ | `any` | AnyType |
339
+ | `mixed` | AnyType (`mixed` is a compilation-level concept, not present in IR) |
340
+ | `ClassFoo` | ClassInstance(classFooId) |
341
+ | `Array<number>` | Array(Number) |
342
+ | `[number, string]` | Tuple(Number, String) |
343
+ | `(x: number) => string` | Function({params: [Number], return: String}) |
344
+ | `{x: number, y: string}` | ExactObject({x: Number, y: String}) |
345
+ | `ClassA \| null` | Union(ClassInstance(A), Null) |
346
+ | `ClassA \| ClassB` | Union(ClassInstance(A), ClassInstance(B)) |
347
+ | `number \| string` | Union(Number, String) |
348
+
349
+ **Not lowered to IR** (resolved before IR):
350
+ - Generics (monomorphized or erased).
351
+ - Type aliases (resolved to concrete types).
352
+ - `InferencePlaceholder` (resolved during checking).
353
+
354
+ **Lowered indirectly**:
355
+ - `ClassConstructorType` → `Function(constructorSignature)`. A class
356
+ constructor is a callable with a known signature; until now lowered to
357
+ unrefined `Object` due to limitations of the old type system.
358
+
359
+ ## Relationship to Current IR Type System
360
+
361
+ Every type in the current 16-bit bitmask system maps directly:
362
+
363
+ | Current IR | New IR |
364
+ |------------|--------|
365
+ | `Number` bit | Number |
366
+ | `String` bit | String |
367
+ | `Boolean` bit | Boolean |
368
+ | `Object` bit | Object |
369
+ | `Null` bit | Null |
370
+ | `Undefined` bit | Undefined |
371
+ | `BigInt` bit | BigInt |
372
+ | `Symbol` bit | Symbol |
373
+ | `Empty` bit | Empty |
374
+ | `Uninit` bit | Uninit |
375
+ | `Environment` bit | Environment |
376
+ | `PrivateName` bit | PrivateName |
377
+ | `FunctionCode` bit | FunctionCode |
378
+ | Multiple bits set | Union of corresponding types |
379
+ | `notype` (0) | NoType |
380
+ | `any` mask | AnyType |
381
+
382
+ The new system is a strict superset. All existing type queries (`canBeNumber()`,
383
+ `isPrimitive()`, `isSubsetOf()`, etc.) have direct equivalents with identical
384
+ semantics for the primitive-only case.
385
+
386
+ ## Runtime Type Representation
387
+
388
+ The type system must produce compact runtime type descriptors for:
389
+
390
+ 1. **Checked casts**: `CheckedTypeCastInst` carries a target type. The runtime
391
+ verifies the value matches.
392
+ 2. **Type guards**: conditional branches narrow types; the narrowed type may
393
+ need runtime verification.
394
+ 3. **Soundness enforcement**: typed function parameters are checked at call
395
+ boundaries when called from untyped code.
396
+
397
+ Runtime type checks by category:
398
+
399
+ | Check | Mechanism |
400
+ |-------|-----------|
401
+ | Primitive kind (number, string, ...) | Runtime type tag comparison |
402
+ | ClassInstance(id) | Class ID lookup in instance's class chain |
403
+ | Array(elemType) | Tag check (is array) + element type from array metadata |
404
+ | Function(sig) | Tag check (is callable) + signature from FunctionCode metadata |
405
+ | Union | Check each arm in sequence |
406
+
407
+ The specific encoding of runtime type descriptors is an implementation detail
408
+ to be determined when codegen support is added.
409
+
410
+ ## Representation (Implementation Sketch)
411
+
412
+ The following is a sketch — specific encoding decisions are deferred until
413
+ performance requirements are clearer.
414
+
415
+ ### Type Value
416
+
417
+ A `Type` is a small, copyable value (ideally 4 bytes). It acts as an opaque
418
+ handle into a type table owned by the Module.
419
+
420
+ ### TypeContext
421
+
422
+ Owned by each `Module`. Stores all interned types and the class inheritance
423
+ information needed for subtype checks. Type operations that involve refined
424
+ types (union, intersect, isSubsetOf on non-primitive types) access the context
425
+ to consult the type table.
426
+
427
+ ### Primitive Optimization (deferred)
428
+
429
+ As an optimization, the common case of primitive-only types (unions of
430
+ primitives with no object refinement) can be encoded directly in the handle
431
+ without a table lookup — e.g., via a bitmask embedded in the handle. This is
432
+ purely an implementation optimization and does not affect the type algebra.
433
+
434
+ ## Interning Algorithm: Flow Types to IR Types
435
+
436
+ When lowering Flow types to IR types, each unique Flow type must be assigned
437
+ a unique `IRTypeID`. Structurally identical Flow types (even with different
438
+ pointers) must receive the same ID, so that IR type equality is a simple
439
+ integer comparison.
440
+
441
+ ### Challenge: Looping Types
442
+
443
+ Flow types can be recursive (looping). For example:
444
+
445
+ ```
446
+ type Tree = null | {val: number, left: Tree, right: Tree}
447
+ ```
448
+
449
+ This creates a cycle: the union contains an ExactObject whose fields refer
450
+ back to the union. Flow's `FindLoopingTypes` pass marks every type node on
451
+ a cycle with `isLooping = true` — not just union arms, but every intermediate
452
+ node (the ExactObject, Array, etc.).
453
+
454
+ Looping types cannot be deeply hashed or structurally compared by normal
455
+ recursion — the traversal would never terminate. Flow already solves this:
456
+ - `TypeInfo::hash()` uses shallow hashing for looping types (kind + arity).
457
+ - `TypeInfo::equals()` uses co-inductive comparison with a visited-pairs set.
458
+
459
+ Flow also provides `TypesDenseMapInfo` (in `FlowTypesDumper.h`), a
460
+ `DenseMapInfo<const TypeInfo *>` specialization that delegates to `hash()` and
461
+ `equals()`. This can be reused as the basis for interning tables.
462
+
463
+ ### Data Structures
464
+
465
+ Three tables:
466
+
467
+ 1. **Identity table**: `DenseMap<const TypeInfo *, IRTypeID>` — keyed by
468
+ pointer identity. This is the fast path: once a Flow type has been
469
+ processed, its pointer maps directly to an IR ID with no hashing or
470
+ structural comparison.
471
+
472
+ 2. **Non-looping dedup table**: `DenseMap<const TypeInfo *, IRTypeID,
473
+ TypesDenseMapInfo>` — keyed by deep structural hash + structural equals.
474
+ Ensures that two different `TypeInfo *` pointers representing structurally
475
+ identical non-looping types receive the same IR ID.
476
+
477
+ 3. **Looping dedup table**: `DenseMap<const TypeInfo *, IRTypeID,
478
+ LoopingTypesDenseMapInfo>` — keyed by shallow hash + co-inductive equals.
479
+ Ensures that structurally identical cycles receive the same IR IDs.
480
+
481
+ The non-looping and looping dedup tables are separate because their
482
+ hash/equality semantics differ: deep structural comparison terminates for
483
+ non-looping types but would recurse infinitely for looping types. Mixing them
484
+ in one table would require every lookup to handle both cases, complicating the
485
+ `DenseMapInfo` and risking subtle bugs.
486
+
487
+ ### Algorithm
488
+
489
+ ```
490
+ intern(type) → IRTypeID:
491
+
492
+ // 1. Fast path: already processed this exact pointer?
493
+ Look up type in identity table (pointer equality).
494
+ If found → return existing ID.
495
+
496
+ // 2. Non-looping type.
497
+ if !type->isLooping:
498
+ Look up type in non-looping dedup table (deep structural hash + equals).
499
+ If found → record in identity table, return existing ID.
500
+ Recursively intern all sub-types.
501
+ Allocate new IRTypeID.
502
+ Insert into both identity table and non-looping dedup table.
503
+ Return new ID.
504
+
505
+ // 3. Looping type.
506
+ Walk the type graph from type, collecting all reachable looping types
507
+ not already in the identity table — the "cycle cluster."
508
+ Intern any non-looping sub-types encountered along the way (step 2).
509
+ Deduplicate the cluster against the looping dedup table
510
+ (shallow hash + co-inductive equals).
511
+ If equivalent cycle found → map all nodes to existing IDs.
512
+ Otherwise → batch-allocate IRTypeIDs for all nodes in the cluster.
513
+ Insert all cluster nodes into both identity table and looping dedup table.
514
+ Return the ID for type.
515
+ ```
516
+
517
+ ### Motivation and Design Rationale
518
+
519
+ **Why three tables?**
520
+
521
+ The identity table is an optimization: most lookups during recursive interning
522
+ revisit types that have already been processed (e.g., `Number` appears in many
523
+ field types). A pointer-keyed lookup is O(1) with no hashing and avoids the
524
+ cost of structural comparison entirely.
525
+
526
+ The two dedup tables handle the case where different `TypeInfo *` pointers
527
+ represent structurally identical types. Flow's own interning is partial —
528
+ it deduplicates within unions but does not globally deduplicate all types.
529
+ Without dedup tables, structurally identical types from different parts of
530
+ the Flow type graph would receive different IR IDs, breaking the invariant
531
+ that IR type equality is an integer comparison.
532
+
533
+ **Why separate dedup tables for looping vs non-looping?**
534
+
535
+ Non-looping types use deep structural hashing: the hash incorporates the
536
+ full structure of the type, including all sub-types recursively. This gives
537
+ excellent hash distribution and precise equality. It terminates because
538
+ there are no cycles.
539
+
540
+ Looping types cannot use deep hashing — the recursion would not terminate.
541
+ They use shallow hashing (kind + arity) which produces more collisions, and
542
+ co-inductive equality (with a visited-pairs set to detect cycles). Mixing
543
+ these in one table would mean either: (a) using shallow hashing for all types
544
+ (poor distribution for non-looping), or (b) checking `isLooping` inside the
545
+ `DenseMapInfo` methods (fragile, since the hash strategy must be consistent
546
+ across all entries in the table).
547
+
548
+ **Why batch-allocate looping types?**
549
+
550
+ A cycle like `Tree → ExactObject → Array(Tree)` contains multiple type nodes
551
+ that reference each other. You cannot fully intern any one without the others
552
+ having IDs. Batch allocation assigns IDs to all nodes in the cycle
553
+ simultaneously, then fills in cross-references using those IDs.
554
+
555
+ Every node in the cycle needs its own ID — not just the "root." Intermediate
556
+ nodes (like `Array(Tree)`) are real types that can appear independently in
557
+ other contexts and must be internable.
558
+
559
+ **Why is the identity table sufficient as a fast path?**
560
+
561
+ During recursive interning, the same `TypeInfo *` pointer is encountered
562
+ repeatedly — once when first processing a type, and again each time it appears
563
+ as a sub-type of another type. The identity table caches the result of the
564
+ first processing, making subsequent encounters O(1). The dedup tables are
565
+ only consulted once per unique pointer, during initial processing.
566
+
567
+ **Leveraging Flow's infrastructure.**
568
+
569
+ Flow already provides `TypeInfo::hash()`, `TypeInfo::equals()`, the
570
+ `isLooping` flag on every cycle node, and `TypesDenseMapInfo`. The interning
571
+ algorithm builds on these rather than reimplementing structural comparison.
572
+ This ensures consistency with Flow's type identity semantics and avoids
573
+ duplicating complex cycle-handling logic.
574
+
575
+ ## Migration Plan
576
+
577
+ ### Phase 1: Type representation and context (API-compatible)
578
+
579
+ - Define `Type` as a handle into `TypeContext`.
580
+ - Implement `TypeContext` with interning. Owned by `Module`.
581
+ - Use a **thread-local pointer** to maintain the "current" `TypeContext`.
582
+ An RAII guard (`TypeContextRAII`) sets the thread-local at pass entry
583
+ points. All type operations (`unionTy`, `intersectTy`, `isSubsetOf`, etc.)
584
+ use `TypeContext::current()` when they need the table.
585
+ - Register all existing primitive types as interned entries.
586
+ - All existing type operations delegate to the new implementation but produce
587
+ identical results. **No call-site changes required.**
588
+ - All existing tests pass unchanged.
589
+ - **Risk**: low. Semantics are unchanged; the thread-local is invisible to
590
+ callers.
591
+
592
+ ### Phase 2: Explicit context parameter (mechanical)
593
+
594
+ - Mechanically transform all call sites of `unionTy`, `intersectTy`,
595
+ `subtractTy`, `isSubsetOf`, etc. to accept an explicit `TypeContext &`
596
+ parameter.
597
+ - Remove the thread-local from `TypeContext`.
598
+ - This is a large but purely mechanical change with no semantic effect.
599
+ The thread-local from Phase 1 provides a working system to migrate from
600
+ incrementally.
601
+
602
+ ### Phase 3: Class types
603
+
604
+ - Add `ClassInstance` to the type system.
605
+ - Lower Flow `ClassType` to `ClassInstance` during IRGen.
606
+ - `CheckedTypeCastInst` carries class types.
607
+ - Implement class subtype checking via inheritance chain.
608
+
609
+ ### Phase 4: Function signatures and arrays
610
+
611
+ - Add `Function(signature)` and `Array(elemType)`.
612
+ - Lower Flow function and array types during IRGen.
613
+ - Enable signature-aware call-site analysis.
614
+
615
+ ### Phase 5: Tuple, ExactObject
616
+
617
+ - Add remaining object refinements.
618
+ - Complete union/intersect/subset logic for all type combinations.
619
+
620
+ ### Phase 6: Number subtypes and bits32
621
+
622
+ - Add `Int32`, `Uint32` subtypes of Number.
623
+ - Add `bits32` internal type.
624
+
625
+ ### Phase 7: Runtime type descriptors
626
+
627
+ - Generate compact runtime type descriptors from IR types.
628
+ - Codegen emits type checks using descriptors.
629
+
630
+ ### Phase 8: Exploitation in optimization
631
+
632
+ - Type inference produces and propagates refined types.
633
+ - InstSimplify uses refined types for more aggressive simplification.
634
+ - Codegen emits specialized code paths for known types.
635
+
636
+ ## Open Questions
637
+
638
+ 1. **Number subtype precision**: `Int32 ∩ Uint32` = non-negative int32 values.
639
+ This is not directly representable. Is conservative approximation sufficient,
640
+ or do we need finer number subtypes?
641
+
642
+ 3. **Per-Module vs shared type context**: per-Module is simpler. Shared enables
643
+ cross-module type identity but requires index translation.
644
+
645
+ 4. **Class inheritance storage**: should the type context store the full
646
+ superclass chain per class, or just the parent with a separate lookup?
647
+ Tradeoff: faster subtype checks vs. compact storage.
648
+
649
+ 5. **FunctionCode typing**: FunctionCode will carry the precise function
650
+ signature in the future. Currently untyped for backwards compatibility.
651
+ The migration path is to add an optional signature to FunctionCode's type
652
+ representation when ready.