@geastack/compiler 1.0.33 → 1.0.34

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 (215) hide show
  1. package/README.md +1 -1
  2. package/dist/cli-coverage.js +2 -4
  3. package/dist/cli-emit.js +1 -1
  4. package/dist/cli-module-graph.js +1 -1
  5. package/dist/cli.js +2 -1
  6. package/dist/compiler.js +14 -6
  7. package/dist/conversion/array-view.js +9 -0
  8. package/dist/conversion/build.js +15 -8
  9. package/dist/conversion/dictionary-view.js +2 -2
  10. package/dist/conversion/nodes.d.ts +7 -0
  11. package/dist/conversion/nodes.js +58 -11
  12. package/dist/identity/ids.d.ts +4 -0
  13. package/dist/identity/ids.js +4 -0
  14. package/dist/ir/build.d.ts +4 -3
  15. package/dist/ir/build.js +14 -5
  16. package/dist/ir/call-dispatch.js +67 -7
  17. package/dist/ir/call-entry.js +1 -1
  18. package/dist/ir/callable-class-flow.d.ts +4 -0
  19. package/dist/ir/callable-class-flow.js +123 -1
  20. package/dist/ir/certify/parallel-region.js +698 -20
  21. package/dist/ir/certify.d.ts +3 -0
  22. package/dist/ir/certify.js +44 -9
  23. package/dist/ir/class-allocation-domain.js +2 -2
  24. package/dist/ir/class-construction-status.d.ts +10 -0
  25. package/dist/ir/class-construction-status.js +36 -0
  26. package/dist/ir/convert-carriers.d.ts +10 -1
  27. package/dist/ir/convert-carriers.js +18 -1
  28. package/dist/ir/dynamic-constructor-conversions.js +4 -2
  29. package/dist/ir/finite-iterator-close.d.ts +14 -0
  30. package/dist/ir/finite-iterator-close.js +50 -0
  31. package/dist/ir/host-template-conversions.js +9 -0
  32. package/dist/ir/lower-allocation.js +1 -1
  33. package/dist/ir/lower-flow.js +24 -3
  34. package/dist/ir/lower-operands.js +88 -7
  35. package/dist/ir/lower-protocol.js +1 -1
  36. package/dist/ir/lower.js +9 -4
  37. package/dist/ir/model.d.ts +39 -1
  38. package/dist/ir/native-accessor-definition.d.ts +3 -2
  39. package/dist/ir/native-accessor-definition.js +29 -10
  40. package/dist/ir/native-array-transport.js +2 -2
  41. package/dist/ir/native-field-view-domains.d.ts +23 -0
  42. package/dist/ir/native-field-view-domains.js +115 -9
  43. package/dist/ir/native-field-view-facts.d.ts +46 -2
  44. package/dist/ir/native-field-view-facts.js +159 -4
  45. package/dist/ir/native-iterable.d.ts +17 -0
  46. package/dist/ir/native-iterable.js +72 -0
  47. package/dist/ir/native-key-query.js +1 -1
  48. package/dist/ir/operation-conversions.js +15 -3
  49. package/dist/ir/program-conversions.js +2 -2
  50. package/dist/ir/publish-native-field-view-facts.js +9 -4
  51. package/dist/ir/pure-conversion-reuse.d.ts +58 -0
  52. package/dist/ir/pure-conversion-reuse.js +263 -0
  53. package/dist/ir/queries.js +1 -0
  54. package/dist/ir/reflection-demand.js +70 -18
  55. package/dist/ir/shake.js +2 -2
  56. package/dist/ir/unobserved-callable-inputs.d.ts +37 -0
  57. package/dist/ir/unobserved-callable-inputs.js +111 -0
  58. package/dist/native-signatures.d.ts +1 -1
  59. package/dist/native-signatures.js +27 -2
  60. package/dist/plugins/gea/component-classes.d.ts +2 -1
  61. package/dist/plugins/gea/component-classes.js +3 -3
  62. package/dist/plugins/gea/contract.d.ts +26 -3
  63. package/dist/plugins/gea/contract.js +42 -43
  64. package/dist/plugins/gea/host.d.ts +9 -0
  65. package/dist/plugins/gea/host.js +25 -4
  66. package/dist/plugins/gea/plugin.js +12 -6
  67. package/dist/plugins/gea/producer.d.ts +2 -2
  68. package/dist/plugins/gea/producer.js +2 -2
  69. package/dist/plugins/load.js +18 -1
  70. package/dist/plugins/model.d.ts +5 -0
  71. package/dist/plugins/native-iterable-providers.d.ts +18 -0
  72. package/dist/plugins/native-iterable-providers.js +51 -0
  73. package/dist/project-preparation.d.ts +8 -0
  74. package/dist/project-preparation.js +49 -7
  75. package/dist/projection/bindings.d.ts +13 -0
  76. package/dist/projection/bindings.js +20 -1
  77. package/dist/projection/classes.d.ts +4 -2
  78. package/dist/projection/classes.js +12 -5
  79. package/dist/representation/collections.js +2 -0
  80. package/dist/representation/derive.js +1 -0
  81. package/dist/representation/model.d.ts +2 -0
  82. package/dist/representation/model.js +1 -0
  83. package/dist/representation/policies.d.ts +2 -0
  84. package/dist/representation/primitive-domain.d.ts +1 -1
  85. package/dist/representation/primitive-domain.js +1 -1
  86. package/dist/representation/unassigned-binding-cells.js +6 -1
  87. package/dist/representation/union.js +6 -6
  88. package/dist/semantics/frontend.d.ts +2 -0
  89. package/dist/semantics/frontend.js +34 -5
  90. package/dist/semantics/host-methods.js +4 -1
  91. package/dist/semantics/jsx-runtime-provider.d.ts +5 -0
  92. package/dist/semantics/jsx-runtime-provider.js +16 -0
  93. package/dist/semantics/model/native-iterable.d.ts +14 -0
  94. package/dist/semantics/model/native-iterable.js +7 -0
  95. package/dist/semantics/model/operands.d.ts +30 -0
  96. package/dist/semantics/model/operations.d.ts +15 -0
  97. package/dist/semantics/model/primitive-domain.d.ts +15 -0
  98. package/dist/semantics/model/primitive-domain.js +27 -4
  99. package/dist/semantics/module-resolution.js +13 -2
  100. package/dist/semantics/normalize/any-cast-member-call.d.ts +1 -1
  101. package/dist/semantics/normalize/callback-parameter-contracts.d.ts +32 -4
  102. package/dist/semantics/normalize/callback-parameter-contracts.js +66 -6
  103. package/dist/semantics/normalize/census.d.ts +3 -0
  104. package/dist/semantics/normalize/census.js +17 -12
  105. package/dist/semantics/normalize/deferred-intrinsic-protocols.d.ts +4 -1
  106. package/dist/semantics/normalize/deferred-intrinsic-protocols.js +29 -9
  107. package/dist/semantics/normalize/flow/callable-reach.js +94 -3
  108. package/dist/semantics/normalize/flow/component-solver.js +144 -55
  109. package/dist/semantics/normalize/flow/member-call-forwarding.d.ts +9 -0
  110. package/dist/semantics/normalize/flow/member-call-forwarding.js +30 -4
  111. package/dist/semantics/normalize/flow/proof-hypotheses.d.ts +2 -0
  112. package/dist/semantics/normalize/flow/proof-hypotheses.js +27 -0
  113. package/dist/semantics/normalize/flow/source-callable-own-data.js +87 -14
  114. package/dist/semantics/normalize/flow/source-commonjs-exports.d.ts +2 -0
  115. package/dist/semantics/normalize/flow/source-commonjs-exports.js +2 -0
  116. package/dist/semantics/normalize/flow/source-native-iterable-integrity.d.ts +17 -0
  117. package/dist/semantics/normalize/flow/source-native-iterable-integrity.js +125 -0
  118. package/dist/semantics/normalize/flow/source-native-origin.d.ts +6 -0
  119. package/dist/semantics/normalize/flow/source-native-origin.js +38 -0
  120. package/dist/semantics/normalize/flow/source-proxy-operation.d.ts +37 -0
  121. package/dist/semantics/normalize/flow/source-proxy-operation.js +201 -0
  122. package/dist/semantics/normalize/flow/source-raw-constructor-entry.d.ts +20 -0
  123. package/dist/semantics/normalize/flow/source-raw-constructor-entry.js +73 -0
  124. package/dist/semantics/normalize/flow/source-value-session.d.ts +50 -1
  125. package/dist/semantics/normalize/flow/source-value-session.js +596 -57
  126. package/dist/semantics/normalize/flow/value-flow.d.ts +17 -0
  127. package/dist/semantics/normalize/flow/value-flow.js +84 -0
  128. package/dist/semantics/normalize/fresh-dictionary-storage.js +2 -2
  129. package/dist/semantics/normalize/fresh-table-last-use.d.ts +52 -0
  130. package/dist/semantics/normalize/fresh-table-last-use.js +129 -0
  131. package/dist/semantics/normalize/gating.js +5 -1
  132. package/dist/semantics/normalize/global-host-mutations.js +190 -13
  133. package/dist/semantics/normalize/identities.js +20 -1
  134. package/dist/semantics/normalize/local-bindings.js +2 -2
  135. package/dist/semantics/normalize/parameter-bindings.js +10 -1
  136. package/dist/semantics/normalize/producer-context.d.ts +5 -0
  137. package/dist/semantics/normalize/producers/binding-kind.js +2 -0
  138. package/dist/semantics/normalize/producers/cited-value-type.d.ts +2 -2
  139. package/dist/semantics/normalize/producers/cited-value-type.js +2 -2
  140. package/dist/semantics/normalize/producers/class-lifecycle.js +39 -9
  141. package/dist/semantics/normalize/producers/computations.js +36 -5
  142. package/dist/semantics/normalize/producers/conditional-guard.d.ts +6 -0
  143. package/dist/semantics/normalize/producers/conditional-guard.js +5 -0
  144. package/dist/semantics/normalize/producers/control.js +7 -1
  145. package/dist/semantics/normalize/producers/destructuring.js +8 -9
  146. package/dist/semantics/normalize/producers/invocations.js +55 -2
  147. package/dist/semantics/normalize/producers/properties.d.ts +13 -0
  148. package/dist/semantics/normalize/producers/properties.js +21 -3
  149. package/dist/semantics/normalize/producers/references.js +8 -4
  150. package/dist/semantics/normalize/reachability.d.ts +15 -3
  151. package/dist/semantics/normalize/reachability.js +128 -20
  152. package/dist/semantics/normalize/return-bindings.js +3 -3
  153. package/dist/semantics/normalize/source-native-iterable.d.ts +19 -0
  154. package/dist/semantics/normalize/source-native-iterable.js +74 -0
  155. package/dist/semantics/normalize/structural-any-binding-consumer.d.ts +1 -1
  156. package/dist/semantics/normalize/structural-declarations.js +1 -1
  157. package/dist/semantics/normalize/structural-indexed-access.js +9 -0
  158. package/dist/semantics/normalize/structural.js +11 -0
  159. package/dist/semantics/normalize/unshared-array-result.d.ts +42 -0
  160. package/dist/semantics/normalize/unshared-array-result.js +269 -0
  161. package/dist/semantics/package-sources.js +3 -2
  162. package/dist/semantics/program.d.ts +8 -0
  163. package/dist/semantics/program.js +55 -0
  164. package/dist/semantics/source-transform-exports.d.ts +8 -0
  165. package/dist/semantics/source-transform-exports.js +145 -0
  166. package/dist/semantics/source-transform-protocol.d.ts +22 -0
  167. package/dist/semantics/this-constructor-source-transform.js +19 -1
  168. package/dist/targets/cpp/class-layout.d.ts +2 -0
  169. package/dist/targets/cpp/class-layout.js +35 -1
  170. package/dist/targets/cpp/class-properties/emit-class-properties.d.ts +11 -1
  171. package/dist/targets/cpp/class-properties/emit-class-properties.js +33 -4
  172. package/dist/targets/cpp/conversions.js +6 -3
  173. package/dist/targets/cpp/emit-callable.js +73 -7
  174. package/dist/targets/cpp/emit-context.d.ts +23 -9
  175. package/dist/targets/cpp/emit-context.js +19 -8
  176. package/dist/targets/cpp/emit-equality.js +41 -1
  177. package/dist/targets/cpp/emit-exceptions.js +29 -11
  178. package/dist/targets/cpp/emit-iterator-object-view.js +2 -2
  179. package/dist/targets/cpp/emit-iterator.js +33 -9
  180. package/dist/targets/cpp/emit-live-field-view.js +6 -1
  181. package/dist/targets/cpp/emit-narrowing.d.ts +11 -3
  182. package/dist/targets/cpp/emit-narrowing.js +58 -18
  183. package/dist/targets/cpp/emit-native-field-view.d.ts +3 -1
  184. package/dist/targets/cpp/emit-native-field-view.js +84 -8
  185. package/dist/targets/cpp/emit-properties.d.ts +1 -0
  186. package/dist/targets/cpp/emit-properties.js +26 -7
  187. package/dist/targets/cpp/emit-protocol-iterator.js +5 -2
  188. package/dist/targets/cpp/emit-record-view.js +14 -2
  189. package/dist/targets/cpp/emit-tostring.js +23 -1
  190. package/dist/targets/cpp/emit-union-properties.js +1 -1
  191. package/dist/targets/cpp/emit.d.ts +1 -1
  192. package/dist/targets/cpp/emit.js +99 -13
  193. package/dist/targets/cpp/host/emit-host-invoke.js +2 -2
  194. package/dist/targets/cpp/host/emit-host-object.js +28 -2
  195. package/dist/targets/cpp/host/emit-host-properties.js +9 -1
  196. package/dist/targets/cpp/host/emit-host-value.d.ts +1 -1
  197. package/dist/targets/cpp/host/emit-host-value.js +8 -6
  198. package/dist/targets/cpp/host/host-members.js +2 -1
  199. package/dist/targets/cpp/prototype/emit-prototype-array.js +69 -5
  200. package/dist/targets/cpp/prototype/emit-prototype-invoke.js +9 -9
  201. package/dist/targets/cpp/prototype/emit-prototype-iterator.js +2 -2
  202. package/dist/targets/cpp/prototype/emit-prototype-promise.js +7 -7
  203. package/dist/targets/cpp/records.d.ts +1 -0
  204. package/dist/targets/cpp/records.js +16 -7
  205. package/dist/targets/cpp/translation-unit.js +30 -16
  206. package/package.json +8 -7
  207. package/src/targets/cpp/runtime/gea_dynamic_proxy.h +42 -3
  208. package/src/targets/cpp/runtime/gea_eval.h +3 -0
  209. package/src/targets/cpp/runtime/gea_runtime.h +2399 -676
  210. package/dist/representation/any-null-record-members.d.ts +0 -41
  211. package/dist/representation/any-null-record-members.js +0 -115
  212. package/dist/semantics/any-null-member-declarations.d.ts +0 -32
  213. package/dist/semantics/any-null-member-declarations.js +0 -90
  214. package/dist/semantics/normalize/fresh-array-result.d.ts +0 -32
  215. package/dist/semantics/normalize/fresh-array-result.js +0 -125
@@ -42,7 +42,24 @@
42
42
  #include <unordered_map>
43
43
  #include <unordered_set>
44
44
  #if defined(GEA_PROFILE_ALLOCATIONS)
45
+ // The allocation profile's backtraces (the leak probe and the allocation-site
46
+ // census). Windows has no <execinfo.h>; its frames come from
47
+ // RtlCaptureStackBackTrace, declared exactly as <windows.h> declares it rather
48
+ // than by including that header, whose `near`/`far` macros this one cannot take.
49
+ #if defined(_WIN32)
50
+ extern "C" __declspec(dllimport) unsigned short __stdcall RtlCaptureStackBackTrace(unsigned long skip, unsigned long count, void** frames,
51
+ unsigned long* hash);
52
+ inline int gea_profile_backtrace(void** frames, int size) {
53
+ return static_cast<int>(::RtlCaptureStackBackTrace(0, static_cast<unsigned long>(size), frames, nullptr));
54
+ }
55
+ inline void gea_profile_print_backtrace(void* const* frames, int count) {
56
+ for (int index = 0; index < count; ++index) std::fprintf(stderr, " %p\n", frames[index]);
57
+ }
58
+ #else
45
59
  #include <execinfo.h>
60
+ inline int gea_profile_backtrace(void** frames, int size) { return ::backtrace(frames, size); }
61
+ inline void gea_profile_print_backtrace(void* const* frames, int count) { ::backtrace_symbols_fd(frames, count, 2); }
62
+ #endif
46
63
  #endif
47
64
  #include <string>
48
65
  #include <string_view>
@@ -57,11 +74,25 @@
57
74
  #include <cstring>
58
75
  #include <tuple>
59
76
  #include "gea_pcm.h"
77
+ #if defined(_WIN32)
78
+ #include <fcntl.h> // _O_BINARY
79
+ #include <io.h> // _setmode, _fileno
80
+ #endif
60
81
  #if defined(GEA_RUNTIME_PARALLEL) && GEA_RUNTIME_PARALLEL
61
82
  #include <thread>
62
83
  #if defined(__linux__)
63
84
  #include <malloc.h>
64
85
  #endif
86
+ #if defined(__linux__) && defined(__GLIBC__)
87
+ #include <pthread.h>
88
+ #include <sched.h>
89
+ #endif
90
+ #if defined(_WIN64) && defined(_MSC_VER)
91
+ // `GEA_PARALLEL_AFFINITY` (RegionPool::pin), declared exactly as <windows.h>
92
+ // declares it rather than by including that header, whose `near`/`far`
93
+ // macros this one cannot take.
94
+ extern "C" __declspec(dllimport) unsigned __int64 __stdcall SetThreadAffinityMask(void* thread, unsigned __int64 mask);
95
+ #endif
65
96
  #endif
66
97
 
67
98
  /**
@@ -231,7 +262,8 @@ template <typename Tag, typename T, int Lifetime = 0, typename Factory>
231
262
  T& realmSlot(Factory factory) {
232
263
  // Only the first access in a realm hashes. Audio processing's steady path
233
264
  // reads a TLS cache and one identity, without a lock or allocation.
234
- static const char key = 0;
265
+ // Mutable: its address is the slot's identity (see `PayloadTypeTag`).
266
+ static char key = 0;
235
267
  static thread_local std::uint64_t identity = 0;
236
268
  static thread_local T* value = nullptr;
237
269
  RuntimeRealm& realm = currentRuntimeRealm();
@@ -268,6 +300,26 @@ T& realmSlot() { return realmSlot<Tag, T, Lifetime>([] { return new T{}; }); }
268
300
  #define GEA_REALM_IMMORTAL_LOCAL(Type, Name, ...) static Type& Name = *new Type __VA_ARGS__
269
301
  #endif
270
302
 
303
+ #if defined(_WIN32)
304
+ /**
305
+ * The standard streams in binary mode on Windows, before main.
306
+ *
307
+ * The Windows CRT opens stdout and stderr in TEXT mode, which writes every
308
+ * `\n` as `\r\n`. Node writes `console.log`'s newline as the one byte on every
309
+ * platform, so a program compiled from JavaScript printed something other than
310
+ * the program it was compiled from -- every output comparison against Node
311
+ * failed on Windows alone. A process without a console (a GUI-subsystem app)
312
+ * has no stream descriptors to switch, and is left alone.
313
+ */
314
+ inline const bool standardStreamsBinary = [] {
315
+ for (std::FILE* stream : {stdout, stderr}) {
316
+ const int descriptor = _fileno(stream);
317
+ if (descriptor >= 0) _setmode(descriptor, _O_BINARY);
318
+ }
319
+ return true;
320
+ }();
321
+ #endif
322
+
271
323
  /**
272
324
  * How this runtime DIES -- the one place, so every guard dies the same way.
273
325
  *
@@ -1111,17 +1163,56 @@ namespace detail {
1111
1163
  target += concatStrings(pieces);
1112
1164
  }
1113
1165
  [[gnu::noinline, noreturn]] inline void stringLengthExceeded() { throw std::length_error("string concatenation exceeds max_size"); }
1114
- // Pieces copied end to end from `buffer`, the terminator after them, and the
1115
- // length stored: one pass rather than an `_M_append` per piece rechecking the
1116
- // capacity. The length is the word after the data pointer, as
1117
- // `GEA_FAST_SMALL_STRING_COPY` below relies on too (defined after this point).
1118
- [[gnu::always_inline]] inline void fillPieces(std::string& out, char* buffer, std::initializer_list<std::string_view> pieces, std::size_t length) {
1166
+ // Check each addition before it can wrap, including on 32-bit targets. A check
1167
+ // of the final sum alone can admit a small result for oversized pieces and
1168
+ // then copy them into the string's inline buffer.
1169
+ [[gnu::always_inline]] inline void addStringLength(std::size_t& total, std::size_t length, std::size_t maximum) {
1170
+ if (length > maximum - total) [[unlikely]] stringLengthExceeded();
1171
+ total += length;
1172
+ }
1173
+ // Reserve alone does not make the spare bytes writable string elements. Let
1174
+ // the library own that transition and the final length/terminator, rather than
1175
+ // writing through its object layout. Older libc++ exposes the C++23 operation
1176
+ // in C++20 as `__resize_and_overwrite`; libstdc++ and current libc++ before
1177
+ // C++23 have neither, so there `resize` makes the elements, zero-filling them
1178
+ // first, a measurable share of string building at -std=c++20.
1179
+ // The writer is a lambda handed to a library template, which the inliner left
1180
+ // out of line; then every literal piece was re-measured with a runtime strlen.
1181
+ // Force both calls inline where the compiler allows it.
1182
+ #if defined(__clang__)
1183
+ #define GEA_INLINE_CALLS [[clang::always_inline]]
1184
+ #else
1185
+ #define GEA_INLINE_CALLS
1186
+ #endif
1187
+ template <typename String, typename Writer>
1188
+ [[gnu::always_inline]] inline void overwriteString(String& out, std::size_t size, Writer&& writer) {
1189
+ if constexpr (requires { out.resize_and_overwrite(size, writer); }) {
1190
+ GEA_INLINE_CALLS out.resize_and_overwrite(size, writer);
1191
+ } else if constexpr (requires { out.__resize_and_overwrite(size, writer); }) {
1192
+ GEA_INLINE_CALLS out.__resize_and_overwrite(size, writer);
1193
+ } else {
1194
+ out.resize(size);
1195
+ const std::size_t used = writer(out.data(), size);
1196
+ if (used != size) out.resize(used);
1197
+ }
1198
+ }
1199
+ template <typename String>
1200
+ inline constexpr bool overwritesInPlace =
1201
+ requires(String& out) { out.resize_and_overwrite(0, [](char*, std::size_t) { return std::size_t{0}; }); } ||
1202
+ requires(String& out) { out.__resize_and_overwrite(0, [](char*, std::size_t) { return std::size_t{0}; }); };
1203
+ // How many bytes to hand `overwriteString` for `used` bytes of content. Where
1204
+ // the library overwrites in place, the whole capacity, so a formatted number's
1205
+ // 8-byte store may run past `used`; where `resize` zero-fills, only `used`.
1206
+ template <typename String>
1207
+ [[gnu::always_inline]] inline std::size_t overwriteWindow(const String& out, std::size_t used) {
1208
+ if constexpr (overwritesInPlace<String>) return out.capacity();
1209
+ else return used;
1210
+ }
1211
+ [[gnu::always_inline]] inline void fillPieces(char* buffer, std::initializer_list<std::string_view> pieces) {
1119
1212
  for (auto piece : pieces) {
1120
1213
  copyPieceBytes(buffer, piece.data(), piece.size());
1121
1214
  buffer += piece.size();
1122
1215
  }
1123
- *buffer = '\0';
1124
- std::memcpy(reinterpret_cast<char*>(&out) + sizeof(void*), &length, sizeof(length));
1125
1216
  }
1126
1217
  } // namespace detail
1127
1218
 
@@ -1135,7 +1226,7 @@ namespace detail {
1135
1226
  for (auto piece : pieces) {
1136
1227
  const auto at = reinterpret_cast<std::uintptr_t>(piece.data());
1137
1228
  aliases = aliases || (piece.size() != 0 && at >= begin && at < end);
1138
- total += piece.size();
1229
+ detail::addStringLength(total, piece.size(), out.max_size());
1139
1230
  }
1140
1231
  if (aliases) [[unlikely]] {
1141
1232
  detail::concatStringsAliased(out, pieces);
@@ -1147,10 +1238,13 @@ namespace detail {
1147
1238
  // reallocating. A buffer that already holds `total` is kept as it is.
1148
1239
  if (out.capacity() < total) [[unlikely]] {
1149
1240
  out.clear();
1150
- out.reserve(total + 16);
1241
+ out.reserve(total + std::min<std::size_t>(16, out.max_size() - total));
1151
1242
  }
1152
1243
  #if defined(__GLIBCXX__) && defined(_GLIBCXX_USE_CXX11_ABI) && _GLIBCXX_USE_CXX11_ABI
1153
- detail::fillPieces(out, out.data(), pieces, total);
1244
+ detail::overwriteString(out, total, [&](char* buffer, std::size_t) __attribute__((always_inline)) {
1245
+ detail::fillPieces(buffer, pieces);
1246
+ return total;
1247
+ });
1154
1248
  #else
1155
1249
  out.clear();
1156
1250
  for (auto piece : pieces) out.append(piece.data(), piece.size());
@@ -1176,6 +1270,11 @@ template <typename Piece>
1176
1270
  return pieceView(piece).size();
1177
1271
  }
1178
1272
  // Literals and formatted numbers own their bytes; anything else may view the destination.
1273
+ // An EMPTY piece starting in the destination counts too: a typed piece is
1274
+ // viewed again while the pieces are written, and where `overwriteString`
1275
+ // falls back to `resize` (libstdc++ before C++23) the destination itself, as
1276
+ // a piece, has grown to the whole capacity by then (`s = s + n` on an empty
1277
+ // `s` wrote NULs and pushed the digits past the end).
1179
1278
  template <typename Piece>
1180
1279
  [[gnu::always_inline]] inline bool pieceViews(const Piece& piece, std::uintptr_t begin, std::uintptr_t end) {
1181
1280
  if constexpr (std::is_array_v<Piece> || DigitWordPiece<Piece>) {
@@ -1183,7 +1282,7 @@ template <typename Piece>
1183
1282
  } else {
1184
1283
  const auto view = pieceView(piece);
1185
1284
  const auto at = reinterpret_cast<std::uintptr_t>(view.data());
1186
- return view.size() != 0 && at >= begin && at < end;
1285
+ return at >= begin && at < end;
1187
1286
  }
1188
1287
  }
1189
1288
  // A formatted number's digits go from the register they were computed in to
@@ -1194,7 +1293,7 @@ template <typename Piece>
1194
1293
  [[gnu::always_inline]] inline char* writePiece(char* to, const char* limit, const Piece& piece) {
1195
1294
  if constexpr (DigitWordPiece<Piece>) {
1196
1295
  const std::uint64_t word = piece.digitWord();
1197
- if (word != 0 && to + 8 <= limit) {
1296
+ if (word != 0 && static_cast<std::size_t>(limit - to) >= 8) {
1198
1297
  std::memcpy(to, &word, 8);
1199
1298
  return to + piece.digitCount();
1200
1299
  }
@@ -1204,11 +1303,8 @@ template <typename Piece>
1204
1303
  return to + view.size();
1205
1304
  }
1206
1305
  template <typename... Pieces>
1207
- [[gnu::always_inline]] inline void fillTypedPieces(std::string& out, char* buffer, std::size_t length, const Pieces&... pieces) {
1208
- const char* const limit = out.data() + out.capacity() + 1;
1306
+ [[gnu::always_inline]] inline void fillTypedPieces(char* buffer, const char* limit, const Pieces&... pieces) {
1209
1307
  ((buffer = writePiece(buffer, limit, pieces)), ...);
1210
- *buffer = '\0';
1211
- std::memcpy(reinterpret_cast<char*>(&out) + sizeof(void*), &length, sizeof(length));
1212
1308
  }
1213
1309
  } // namespace detail
1214
1310
 
@@ -1224,13 +1320,16 @@ template <typename... Pieces> requires(sizeof...(Pieces) > 0)
1224
1320
  detail::concatStringsAliased(out, {detail::pieceView(pieces)...});
1225
1321
  return;
1226
1322
  }
1227
- const std::size_t total = (detail::pieceSize(pieces) + ...);
1228
- if (total > out.max_size()) [[unlikely]] detail::stringLengthExceeded();
1323
+ std::size_t total = 0;
1324
+ (detail::addStringLength(total, detail::pieceSize(pieces), out.max_size()), ...);
1229
1325
  if (out.capacity() < total) [[unlikely]] {
1230
1326
  out.clear();
1231
- out.reserve(total + 16);
1327
+ out.reserve(total + std::min<std::size_t>(16, out.max_size() - total));
1232
1328
  }
1233
- detail::fillTypedPieces(out, out.data(), total, pieces...);
1329
+ detail::overwriteString(out, detail::overwriteWindow(out, total), [&](char* buffer, std::size_t count) __attribute__((always_inline)) {
1330
+ detail::fillTypedPieces(buffer, buffer + count, pieces...);
1331
+ return total;
1332
+ });
1234
1333
  #else
1235
1334
  concatStringsInto(out, {std::string_view(pieces)...});
1236
1335
  #endif
@@ -1246,7 +1345,7 @@ template <typename... Pieces> requires(sizeof...(Pieces) > 0)
1246
1345
  std::size_t added = 0;
1247
1346
  bool aliases = false;
1248
1347
  for (auto piece : pieces) {
1249
- added += piece.size();
1348
+ detail::addStringLength(added, piece.size(), target.max_size() - size);
1250
1349
  const auto data = reinterpret_cast<std::uintptr_t>(piece.data());
1251
1350
  aliases = aliases || (data >= begin && data <= end);
1252
1351
  }
@@ -1257,7 +1356,10 @@ template <typename... Pieces> requires(sizeof...(Pieces) > 0)
1257
1356
  if (added > target.max_size() - size) [[unlikely]] detail::stringLengthExceeded();
1258
1357
  if (target.capacity() - size < added) [[unlikely]] target.reserve(size + added);
1259
1358
  #if defined(__GLIBCXX__) && defined(_GLIBCXX_USE_CXX11_ABI) && _GLIBCXX_USE_CXX11_ABI
1260
- detail::fillPieces(target, target.data() + size, pieces, size + added);
1359
+ detail::overwriteString(target, size + added, [&](char* buffer, std::size_t count) __attribute__((always_inline)) {
1360
+ detail::fillPieces(buffer + size, pieces);
1361
+ return count;
1362
+ });
1261
1363
  #else
1262
1364
  for (auto piece : pieces) target.append(piece.data(), piece.size());
1263
1365
  #endif
@@ -1273,10 +1375,13 @@ template <typename... Pieces> requires(sizeof...(Pieces) > 0)
1273
1375
  detail::appendStringsAliased(target, {detail::pieceView(pieces)...});
1274
1376
  return;
1275
1377
  }
1276
- const std::size_t added = (detail::pieceSize(pieces) + ...);
1277
- if (added > target.max_size() - size) [[unlikely]] detail::stringLengthExceeded();
1378
+ std::size_t added = 0;
1379
+ (detail::addStringLength(added, detail::pieceSize(pieces), target.max_size() - size), ...);
1278
1380
  if (target.capacity() - size < added) [[unlikely]] target.reserve(size + added);
1279
- detail::fillTypedPieces(target, target.data() + size, size + added, pieces...);
1381
+ detail::overwriteString(target, detail::overwriteWindow(target, size + added), [&](char* buffer, std::size_t count) __attribute__((always_inline)) {
1382
+ detail::fillTypedPieces(buffer + size, buffer + count, pieces...);
1383
+ return size + added;
1384
+ });
1280
1385
  #else
1281
1386
  appendStrings(target, {std::string_view(pieces)...});
1282
1387
  #endif
@@ -1342,6 +1447,138 @@ struct ScopeExit {
1342
1447
  template <typename Body>
1343
1448
  ScopeExit(Body) -> ScopeExit<Body>;
1344
1449
 
1450
+ /**
1451
+ * How a native `try` statement is spelled: every one the compiler emits, and
1452
+ * every one in this header that code can be inlined from, is written with the
1453
+ * `GEA_EH_*` macros below. Where `GEA_EH_FENCED` is 0 -- every target but the
1454
+ * MSVC ABI -- they expand to exactly the plain statement:
1455
+ *
1456
+ * GEA_EH_TRY_VALUE(s) { B } GEA_EH_CATCH_VALUE(s, e) { H } GEA_EH_END
1457
+ * == try { B } catch (const gea::Value& e) { H }
1458
+ *
1459
+ * Under the MSVC ABI they spell the same statement for two LLVM defects in its
1460
+ * funclet EH lowering (clang 16 through trunk, every -O level above -O0):
1461
+ *
1462
+ * { std::optional<gea::Value> s;
1463
+ * { gea::EhFence f; try { gea::EhFence b; { B } }
1464
+ * catch (const gea::Value& t) { gea::detail::recordThrown(s, t); } }
1465
+ * if (s) if (const gea::Value& e = *s; true) { H } }
1466
+ *
1467
+ * - CoroSplit (CoroFrame's `rewritePHIsForCleanupPad`) rewrites a cleanuppad
1468
+ * that a catchswitch unwinds to, when anything else unwinds to it too, into
1469
+ * IR where a value defined in the handler no longer dominates its use. A
1470
+ * coroutine -- or any function inlined into one before it is split -- with
1471
+ * `try { co_await p } catch (e) { x = f() }` and a reference-counted local
1472
+ * outside the try was enough; unverified, clang crashed in a later pass or
1473
+ * emitted a wrong program. The outer fence gives the catchswitch a
1474
+ * cleanuppad of its own, and the handler only RECORDS (`noexcept`, no
1475
+ * unwind edge), so that pad has one predecessor and nothing to rewrite.
1476
+ * The handler's code runs after the statement, as the language describes.
1477
+ * - WinEHPrepare's PHI demotion spills `poison` for a PHI in a catchswitch
1478
+ * block whose value reaches another catchswitch's PHI through a cleanup --
1479
+ * nested try statements -- and the outer handler reads an uninitialized
1480
+ * stack slot. The inner fence makes every throwing call in the block unwind
1481
+ * into a cleanup first, so a catchswitch has one predecessor and no PHI.
1482
+ *
1483
+ * A fence's destructor is one relaxed volatile byte store into the fence
1484
+ * itself: the one instruction LLVM keeps in a cleanup that touches nothing
1485
+ * else. Not an empty asm statement: clang gives a volatile asm no memory
1486
+ * effects, so the optimizer took one as a read and write of all memory -- two
1487
+ * compiler barriers on the normal path of every try statement, makeRef's
1488
+ * included, after which no load could be forwarded across it. The store is
1489
+ * relaxed (`__iso_volatile_store8`) because a plain volatile store under
1490
+ * /volatile:ms is a release store. The slots are `std::optional`, so the
1491
+ * normal path never destroys an `exception_ptr` (an out-of-line call under
1492
+ * MSVC's STL). Define `GEA_EH_FENCED` to 1 to run the fenced shape on another
1493
+ * target.
1494
+ */
1495
+ #ifndef GEA_EH_FENCED
1496
+ #if defined(_MSC_VER)
1497
+ #define GEA_EH_FENCED 1
1498
+ #else
1499
+ #define GEA_EH_FENCED 0
1500
+ #endif
1501
+ #endif
1502
+
1503
+ #if GEA_EH_FENCED
1504
+ struct EhFence {
1505
+ EhFence() = default;
1506
+ EhFence(const EhFence&) = delete;
1507
+ EhFence& operator=(const EhFence&) = delete;
1508
+ ~EhFence() {
1509
+ #if defined(_MSC_VER)
1510
+ __iso_volatile_store8(reinterpret_cast<volatile __int8*>(&mark_), 0);
1511
+ #else
1512
+ *static_cast<volatile char*>(&mark_) = 0;
1513
+ #endif
1514
+ }
1515
+
1516
+ private:
1517
+ char mark_;
1518
+ };
1519
+
1520
+ namespace detail {
1521
+ /** A record-only handler's one action: `noexcept`, so it is a call and never an `invoke`. */
1522
+ template <typename Thrown>
1523
+ inline void recordThrown(std::optional<Thrown>& slot, const Thrown& thrown) noexcept {
1524
+ static_assert(std::is_nothrow_copy_constructible_v<Thrown>, "a record-only catch handler must not be able to throw");
1525
+ slot.emplace(thrown);
1526
+ }
1527
+
1528
+ /** `recordThrown` for any exception: the one in flight. */
1529
+ inline void recordCurrentException(std::optional<std::exception_ptr>& slot) noexcept { slot.emplace(std::current_exception()); }
1530
+
1531
+ /** An assignment of the caught value inside a handler, made a call rather than an `invoke`. */
1532
+ template <typename Target, typename Thrown>
1533
+ inline void assignThrown(Target& target, const Thrown& thrown) noexcept {
1534
+ target = thrown;
1535
+ }
1536
+ } // namespace detail
1537
+
1538
+ #define GEA_EH_FENCE_OPEN { ::gea::EhFence gea_eh_fence;
1539
+ #define GEA_EH_FENCE_CLOSE }
1540
+ #define GEA_EH_BODY_FENCE ::gea::EhFence gea_eh_body;
1541
+ #define GEA_EH_NOINLINE [[gnu::noinline]]
1542
+ #define GEA_EH_TRY_VALUE(slot) { std::optional<::gea::Value> slot; { ::gea::EhFence gea_eh_fence; try { ::gea::EhFence gea_eh_body;
1543
+ #define GEA_EH_CATCH_VALUE(slot, name) \
1544
+ } catch (const ::gea::Value& gea_eh_thrown) { ::gea::detail::recordThrown(slot, gea_eh_thrown); } } if (slot) if (const ::gea::Value& name = *slot; true)
1545
+ #define GEA_EH_CATCH_VALUE_UNNAMED(slot) \
1546
+ } catch (const ::gea::Value& gea_eh_thrown) { ::gea::detail::recordThrown(slot, gea_eh_thrown); } } if (slot)
1547
+ #define GEA_EH_RETHROW_VALUE(slot) throw *slot
1548
+ #define GEA_EH_TRY_ANY(slot) { std::optional<std::exception_ptr> slot; { ::gea::EhFence gea_eh_fence; try { ::gea::EhFence gea_eh_body;
1549
+ #define GEA_EH_CATCH_ANY(slot) } catch (...) { ::gea::detail::recordCurrentException(slot); } } if (slot)
1550
+ #define GEA_EH_CURRENT(slot) (*slot)
1551
+ #define GEA_EH_RETHROW_ANY(slot) std::rethrow_exception(*slot)
1552
+ #define GEA_EH_TRY_VALUE_OR_ANY(slot, other) \
1553
+ { std::optional<::gea::Value> slot; bool other = false; { ::gea::EhFence gea_eh_fence; try { ::gea::EhFence gea_eh_body;
1554
+ #define GEA_EH_CATCH_VALUE_OR_ANY(slot, other, name) \
1555
+ } catch (const ::gea::Value& gea_eh_thrown) { ::gea::detail::recordThrown(slot, gea_eh_thrown); } catch (...) { other = true; } } \
1556
+ if (slot) if (const ::gea::Value& name = *slot; true)
1557
+ #define GEA_EH_CATCH_REMAINDER(slot, other) if (other)
1558
+ #define GEA_EH_ASSIGN_THROWN(target, thrown) ::gea::detail::assignThrown(target, thrown)
1559
+ #define GEA_EH_END }
1560
+ #define GEA_EH_UNREACHABLE __builtin_unreachable();
1561
+ #else
1562
+ #define GEA_EH_FENCE_OPEN
1563
+ #define GEA_EH_FENCE_CLOSE
1564
+ #define GEA_EH_BODY_FENCE
1565
+ #define GEA_EH_NOINLINE
1566
+ #define GEA_EH_TRY_VALUE(slot) try
1567
+ #define GEA_EH_CATCH_VALUE(slot, name) catch (const gea::Value& name)
1568
+ #define GEA_EH_CATCH_VALUE_UNNAMED(slot) catch (const gea::Value&)
1569
+ #define GEA_EH_RETHROW_VALUE(slot) throw
1570
+ #define GEA_EH_TRY_ANY(slot) try
1571
+ #define GEA_EH_CATCH_ANY(slot) catch (...)
1572
+ #define GEA_EH_CURRENT(slot) std::current_exception()
1573
+ #define GEA_EH_RETHROW_ANY(slot) throw
1574
+ #define GEA_EH_TRY_VALUE_OR_ANY(slot, other) try
1575
+ #define GEA_EH_CATCH_VALUE_OR_ANY(slot, other, name) catch (const gea::Value& name)
1576
+ #define GEA_EH_CATCH_REMAINDER(slot, other) catch (...)
1577
+ #define GEA_EH_ASSIGN_THROWN(target, thrown) target = thrown
1578
+ #define GEA_EH_END
1579
+ #define GEA_EH_UNREACHABLE
1580
+ #endif
1581
+
1345
1582
  /** A function pointer over the plan's exact ABI, plus its environment -- a separate field, not a lambda, since the ABI is a *physical* fact the plan publishes and a std::function erasure would hide it behind an allocation never chosen. Capture-free callables pass `nullptr`; the thunk ignores it. */
1346
1583
  template <typename Signature>
1347
1584
  struct CallableObject;
@@ -1460,8 +1697,8 @@ inline const void*& leakProbeTarget() {
1460
1697
  inline void leakProbeEvent(const char* what, const void* object, std::uint32_t strong) {
1461
1698
  std::fprintf(stderr, "PROBE %s %p strong=%u\n", what, object, strong);
1462
1699
  void* frames[16];
1463
- const int count = ::backtrace(frames, 16);
1464
- ::backtrace_symbols_fd(frames, count, 2);
1700
+ const int count = ::gea_profile_backtrace(frames, 16);
1701
+ ::gea_profile_print_backtrace(frames, count);
1465
1702
  std::fprintf(stderr, "PROBE end\n");
1466
1703
  }
1467
1704
  // Leak probe: every live element buffer (`PooledAllocator<T>::allocate`), by address.
@@ -1557,7 +1794,7 @@ inline void profileRefCreationSite() {
1557
1794
  }();
1558
1795
  if (census == nullptr) return;
1559
1796
  void* frames[10];
1560
- const int count = ::backtrace(frames, 10);
1797
+ const int count = ::gea_profile_backtrace(frames, 10);
1561
1798
  AllocationSiteKey key;
1562
1799
  for (int index = 3; index < count && index < 9; ++index) key.frames[static_cast<std::size_t>(index - 3)] = frames[index];
1563
1800
  ++census->sites[key];
@@ -1727,6 +1964,163 @@ inline void tagGranules(const void* start, std::size_t bytes, std::uint64_t tag)
1727
1964
  }
1728
1965
  }
1729
1966
 
1967
+ /**
1968
+ * Region memory is recycled a GRANULE at a time, never a cell at a time.
1969
+ *
1970
+ * A region thread bump-allocates from granules tagged with its region's tag,
1971
+ * and that tag is the whole of how a count operation tells an object the
1972
+ * thread built in THIS region from one any thread may now hold. So a cell
1973
+ * freed after its region ended cannot simply be handed to a later region: the
1974
+ * granule it sits in still holds objects of the earlier region, and tagging it
1975
+ * for the new one would make them owned. Nor can it go to the freeing thread's
1976
+ * ordinary free list, which is where it used to go: no region allocates from
1977
+ * those lists, so a program that allocates mostly inside regions -- a frame
1978
+ * loop of parallel maps -- grew that list by everything its regions built,
1979
+ * frame after frame.
1980
+ *
1981
+ * Instead every region granule counts its live cells in a header at its start.
1982
+ * A cell freed anywhere is subtracted there and goes on no list beyond its
1983
+ * own region's; a granule that no region is bumping (`retired`) and whose
1984
+ * count reaches zero holds nothing at all, and goes back to one process-wide
1985
+ * pool from which any region thread takes its next granule and tags it anew.
1986
+ * The count is written by one thread at a time: during a region only the
1987
+ * thread whose region tagged the granule frees into it (anything else is
1988
+ * foreign to it, and its counts are deferred to the join), and between regions
1989
+ * only the joining thread runs.
1990
+ *
1991
+ * Memory still never goes back to the system, the bargain `AllocationPool`
1992
+ * makes: a process holds its regions' high-water mark of granules, plus any
1993
+ * granule a long-lived object keeps from emptying.
1994
+ */
1995
+ struct RegionGranule {
1996
+ /** The pool's link, while the granule is in it. */
1997
+ RegionGranule* next;
1998
+ /** Cells bumped or reused from this granule that are not yet freed. */
1999
+ std::uint32_t live;
2000
+ /** Granules in this span: 1, except for a cell too large for one granule. */
2001
+ std::uint32_t span;
2002
+ std::uint8_t state;
2003
+ /** Already in its thread's `ThreadRegion::spent`, so it is checked once at the region's end. */
2004
+ bool listed;
2005
+ };
2006
+ inline constexpr std::size_t granuleHeaderBytes = 64;
2007
+ static_assert(sizeof(RegionGranule) <= granuleHeaderBytes, "the region granule header must fit before the first cell");
2008
+ inline constexpr std::uint8_t granuleFree = 0;
2009
+ /** A thread's current bump granule, kept across regions: never pooled, whatever its count. */
2010
+ inline constexpr std::uint8_t granuleActive = 1;
2011
+ /** No longer bumped: pooled once its count reaches zero. */
2012
+ inline constexpr std::uint8_t granuleRetired = 2;
2013
+
2014
+ [[gnu::always_inline]] inline RegionGranule* granuleOf(const void* cell) {
2015
+ return reinterpret_cast<RegionGranule*>(reinterpret_cast<std::uintptr_t>(cell) & ~(static_cast<std::uintptr_t>(granuleBytes) - 1));
2016
+ }
2017
+ inline unsigned char* granuleCells(RegionGranule* granule) { return reinterpret_cast<unsigned char*>(granule) + granuleHeaderBytes; }
2018
+ inline unsigned char* granuleEnd(RegionGranule* granule) { return reinterpret_cast<unsigned char*>(granule) + granuleBytes; }
2019
+
2020
+ /** The process-wide pool of empty region granules. */
2021
+ class RegionGranules {
2022
+ public:
2023
+ static RegionGranules& instance() {
2024
+ static RegionGranules* pool = new RegionGranules;
2025
+ return *pool;
2026
+ }
2027
+
2028
+ /**
2029
+ * An empty span of `span` granules, its header reset and untagged by this
2030
+ * call (the taker tags it). A single granule comes from the taking thread's
2031
+ * own run first, then from the pool; a larger span is its own allocation,
2032
+ * and joins the pool granule by granule once it empties.
2033
+ *
2034
+ * A refill of `regionChunkBytes` stays with the thread that made it, which
2035
+ * bumps through it in address order. Pushing the rest of the refill onto the
2036
+ * shared pool handed each of twenty threads every twentieth granule,
2037
+ * highest address first, and a thread building a tree walked memory no
2038
+ * prefetcher could follow. A thread holds at most one refill unused.
2039
+ */
2040
+ RegionGranule* take(std::size_t span) {
2041
+ if (span == 1) {
2042
+ ThreadRun& run = threadRun();
2043
+ if (run.left != 0) {
2044
+ auto* granule = reinterpret_cast<RegionGranule*>(run.next);
2045
+ run.next += granuleBytes;
2046
+ --run.left;
2047
+ return reset(granule, 1);
2048
+ }
2049
+ }
2050
+ if (span == 1) {
2051
+ std::lock_guard lock(mutex_);
2052
+ if (RegionGranule* granule = free_) {
2053
+ free_ = granule->next;
2054
+ return reset(granule, 1);
2055
+ }
2056
+ }
2057
+ const std::size_t bytes = span == 1 ? regionChunkBytes : span * granuleBytes;
2058
+ void* memory = nullptr;
2059
+ #if defined(_WIN32)
2060
+ // The Windows CRT has no posix_memalign. Granules never go back to the
2061
+ // system (see above), so no matching _aligned_free is owed.
2062
+ memory = ::_aligned_malloc(bytes, granuleBytes);
2063
+ if (memory == nullptr) throw std::bad_alloc();
2064
+ #else
2065
+ if (::posix_memalign(&memory, granuleBytes, bytes) != 0) throw std::bad_alloc();
2066
+ #endif
2067
+ auto* first = static_cast<RegionGranule*>(memory);
2068
+ if (span == 1) {
2069
+ ThreadRun& run = threadRun();
2070
+ run.next = static_cast<unsigned char*>(memory) + granuleBytes;
2071
+ run.left = bytes / granuleBytes - 1;
2072
+ }
2073
+ return reset(first, static_cast<std::uint32_t>(span));
2074
+ }
2075
+
2076
+ /** Back to the pool: an empty, retired span, split into its granules. */
2077
+ void give(RegionGranule* granule) {
2078
+ const std::size_t span = granule->span;
2079
+ std::lock_guard lock(mutex_);
2080
+ for (std::size_t index = 0; index < span; ++index) push(reinterpret_cast<RegionGranule*>(reinterpret_cast<unsigned char*>(granule) + index * granuleBytes));
2081
+ }
2082
+
2083
+ private:
2084
+ /** The untaken rest of this thread's latest refill. */
2085
+ struct ThreadRun {
2086
+ unsigned char* next = nullptr;
2087
+ std::size_t left = 0;
2088
+ };
2089
+ static ThreadRun& threadRun() {
2090
+ static thread_local ThreadRun run;
2091
+ return run;
2092
+ }
2093
+
2094
+ static RegionGranule* reset(RegionGranule* granule, std::uint32_t span) {
2095
+ granule->next = nullptr;
2096
+ granule->live = 0;
2097
+ granule->span = span;
2098
+ granule->state = granuleRetired;
2099
+ granule->listed = false;
2100
+ return granule;
2101
+ }
2102
+ void push(RegionGranule* granule) {
2103
+ granule->state = granuleFree;
2104
+ granule->span = 1;
2105
+ granule->live = 0;
2106
+ granule->listed = false;
2107
+ granule->next = free_;
2108
+ free_ = granule;
2109
+ }
2110
+
2111
+ std::mutex mutex_;
2112
+ RegionGranule* free_ = nullptr;
2113
+ };
2114
+
2115
+ /**
2116
+ * A region cell freed where no region is active: by the joining thread
2117
+ * applying the counts its regions deferred, or by any later serial code.
2118
+ */
2119
+ [[gnu::noinline]] inline void releaseRegionCell(void* cell) {
2120
+ RegionGranule* granule = granuleOf(cell);
2121
+ if (--granule->live == 0 && granule->state == granuleRetired) RegionGranules::instance().give(granule);
2122
+ }
2123
+
1730
2124
  /** What a deferred count needs to be applied later without knowing its type. */
1731
2125
  struct DeferredCountOperations {
1732
2126
  void (*addStrong)(void* object, std::uint32_t count);
@@ -1742,7 +2136,11 @@ struct DeferredCount {
1742
2136
  std::int64_t weak;
1743
2137
  };
1744
2138
 
1745
- /** A size class's free cells left in a region's chunks at its end, handed to the joining thread's own pool. */
2139
+ /**
2140
+ * A size class's cells a region freed that are not region memory at all (see
2141
+ * `AllocationPool::giveInRegion`), handed at its end to the joining thread's
2142
+ * own pool. Region memory itself is never donated: it goes back to its granule.
2143
+ */
1746
2144
  struct Donation {
1747
2145
  void (*donate)(void* head, void* tail);
1748
2146
  void* head;
@@ -1750,11 +2148,40 @@ struct Donation {
1750
2148
  void* tail;
1751
2149
  };
1752
2150
 
1753
- struct ThreadRegion {
2151
+ // One cache line at least per thread: the threads' regions sit side by side in
2152
+ // `RegionPool::regions_`, and each one's hot words (`chunk`, `limit`, `bump`,
2153
+ // `ownedGranule`) are written by its thread while its neighbour's thread reads
2154
+ // its own -- sharing a line made the owned-granule cache below a slowdown.
2155
+ struct alignas(64) ThreadRegion {
1754
2156
  std::uint64_t tag = 0;
1755
2157
  unsigned char* chunk = nullptr;
1756
2158
  unsigned char* bump = nullptr;
1757
2159
  unsigned char* limit = nullptr;
2160
+ /**
2161
+ * The last granule the ownership map named this region's, by index. Every
2162
+ * retain and release inside a region asks `owns`, and `[chunk, limit)`
2163
+ * covers only the granule being bumped: a binary tree of a few megabytes
2164
+ * spans dozens of granules, and each lookup outside it was two dependent
2165
+ * loads into the map on the hot retain/release path.
2166
+ * Remembering one granule is exact: a granule tagged with this region's tag
2167
+ * was tagged when this region took it or retagged it whole (`begin`,
2168
+ * `takeGranule`), and nothing pools it before this thread's `finish`. It
2169
+ * is forgotten in `begin`, where the tag changes.
2170
+ */
2171
+ mutable std::uintptr_t ownedGranule = ~std::uintptr_t{0};
2172
+ /** The granule `bump` points into. Kept from region to region, so a short region does not start a granule of its own. */
2173
+ RegionGranule* current = nullptr;
2174
+ /**
2175
+ * Where this region began inside `current` when an earlier region had
2176
+ * tagged it, once `current` has moved on: `[head, headEnd)` is this region's
2177
+ * although the ownership map says otherwise. Re-tagging that granule would
2178
+ * claim the earlier region's objects below `head`, which other threads may
2179
+ * now hold.
2180
+ */
2181
+ unsigned char* head = nullptr;
2182
+ unsigned char* headEnd = nullptr;
2183
+ /** Granules this region retired or emptied: pooled at its end if nothing in them is live. */
2184
+ std::vector<RegionGranule*> spent;
1758
2185
  std::vector<DeferredCount> table;
1759
2186
  std::vector<std::uint32_t> used;
1760
2187
  std::size_t mask = 0;
@@ -1768,17 +2195,127 @@ struct ThreadRegion {
1768
2195
  [[gnu::always_inline]] bool owns(const void* address) const {
1769
2196
  const auto* bytes = static_cast<const unsigned char*>(address);
1770
2197
  if (bytes >= chunk && bytes < limit) return true;
1771
- return ownerOf(address) == tag;
2198
+ const auto granule = reinterpret_cast<std::uintptr_t>(address) >> granuleShift;
2199
+ if (granule == ownedGranule) [[likely]] return true;
2200
+ if (bytes >= head && bytes < headEnd) [[unlikely]] return true;
2201
+ if (ownerOf(address) != tag) return false;
2202
+ ownedGranule = granule;
2203
+ return true;
1772
2204
  }
1773
2205
 
1774
- [[gnu::noinline]] void* takeChunk(std::size_t size, std::size_t align) {
1775
- const std::size_t bytes = size + align > regionChunkBytes ? (size + align + granuleBytes - 1) & ~(granuleBytes - 1) : regionChunkBytes;
1776
- void* memory = nullptr;
1777
- if (::posix_memalign(&memory, granuleBytes, bytes) != 0) throw std::bad_alloc();
1778
- tagGranules(memory, bytes, tag);
1779
- chunk = static_cast<unsigned char*>(memory);
1780
- bump = chunk;
1781
- limit = chunk + bytes;
2206
+ /**
2207
+ * Starts a region (its `tag` given) where the last one left off: in the
2208
+ * same granule, after whatever of the earlier region's is still live there,
2209
+ * or at the granule's start, tagged anew, when nothing is. A fresh chunk per
2210
+ * region and thread abandoned the untouched rest of the previous one, and
2211
+ * where an allocation is committed when it is made (Windows) a frame of
2212
+ * short regions on every core leaked a megabyte per thread per region.
2213
+ */
2214
+ void begin(std::uint64_t regionTag) {
2215
+ tag = regionTag;
2216
+ ownedGranule = ~std::uintptr_t{0};
2217
+ head = headEnd = nullptr;
2218
+ if (current == nullptr) {
2219
+ chunk = bump = limit = nullptr;
2220
+ return;
2221
+ }
2222
+ if (current->live == 0) {
2223
+ tagGranules(current, granuleBytes, tag);
2224
+ bump = granuleCells(current);
2225
+ }
2226
+ chunk = bump;
2227
+ limit = granuleEnd(current);
2228
+ }
2229
+
2230
+ /**
2231
+ * Gives this thread its first granule, faulted in and with its ownership-map
2232
+ * entries made, before any region needs it. Left to the first region, every
2233
+ * pool thread took its first chunk, faulted its pages and grew the map at the
2234
+ * same moment, each fault queueing on the address space's lock behind the
2235
+ * others': a region that allocated one result per task ran ~10% past its
2236
+ * schedule at 20 threads. Runs on
2237
+ * the region's own thread, which is the only one that touches `current`.
2238
+ */
2239
+ void prepare() {
2240
+ if (current != nullptr) return;
2241
+ current = RegionGranules::instance().take(1);
2242
+ current->state = granuleActive;
2243
+ std::memset(granuleCells(current), 0, granuleBytes - granuleHeaderBytes);
2244
+ tagGranules(current, granuleBytes, 0);
2245
+ // The deferred-count table and the lists a region fills, sized now for
2246
+ // the same reason: their first growth is an allocation and page faults.
2247
+ if (table.empty()) grow();
2248
+ used.reserve(table.size() / 2);
2249
+ spent.reserve(64);
2250
+ donations.reserve(16);
2251
+ donors.reserve(16);
2252
+ }
2253
+ /** Runs on the region's own thread once its tasks are done and its cell lists dropped: pools each granule it left empty. */
2254
+ void finish() {
2255
+ for (RegionGranule* granule : spent) {
2256
+ granule->listed = false;
2257
+ if (granule->live == 0 && granule->state == granuleRetired) RegionGranules::instance().give(granule);
2258
+ }
2259
+ spent.clear();
2260
+ }
2261
+
2262
+ void noteSpent(RegionGranule* granule) {
2263
+ if (granule->listed) return;
2264
+ granule->listed = true;
2265
+ spent.push_back(granule);
2266
+ }
2267
+
2268
+ /**
2269
+ * A cell this region frees, back to its granule's count. False when the
2270
+ * cell is not region memory at all, which the caller keeps apart. True with
2271
+ * `reusable` false when it is an earlier region's: counted, but not for this
2272
+ * region to build in, since the ownership map would call what it built
2273
+ * there foreign.
2274
+ */
2275
+ [[gnu::always_inline]] bool recycle(const void* cell, bool& reusable) {
2276
+ const auto* bytes = static_cast<const unsigned char*>(cell);
2277
+ if (bytes >= chunk && bytes < limit) [[likely]] {
2278
+ --current->live;
2279
+ reusable = true;
2280
+ return true;
2281
+ }
2282
+ if (owns(cell)) {
2283
+ reusable = true;
2284
+ } else {
2285
+ const std::uint64_t owner = ownerOf(cell);
2286
+ if (owner == 0) return false;
2287
+ reusable = false;
2288
+ }
2289
+ RegionGranule* granule = granuleOf(cell);
2290
+ if (--granule->live == 0 && granule->state == granuleRetired) noteSpent(granule);
2291
+ return true;
2292
+ }
2293
+
2294
+ [[gnu::noinline]] void* takeGranule(std::size_t size, std::size_t align) {
2295
+ if (granuleHeaderBytes + size + align > granuleBytes) {
2296
+ // Too large for a granule: a span of its own, retired from the start.
2297
+ const std::size_t span = (granuleHeaderBytes + size + align + granuleBytes - 1) / granuleBytes;
2298
+ RegionGranule* large = RegionGranules::instance().take(span);
2299
+ tagGranules(large, span * granuleBytes, tag);
2300
+ large->live = 1;
2301
+ noteSpent(large);
2302
+ const auto bits = (reinterpret_cast<std::uintptr_t>(granuleCells(large)) + align - 1) & ~(static_cast<std::uintptr_t>(align) - 1);
2303
+ return reinterpret_cast<void*>(bits);
2304
+ }
2305
+ if (current != nullptr) {
2306
+ // This region's part of a granule an earlier region tagged stays its own.
2307
+ if (ownerOf(current) != tag) {
2308
+ head = chunk;
2309
+ headEnd = limit;
2310
+ }
2311
+ current->state = granuleRetired;
2312
+ noteSpent(current);
2313
+ }
2314
+ current = RegionGranules::instance().take(1);
2315
+ current->state = granuleActive;
2316
+ tagGranules(current, granuleBytes, tag);
2317
+ chunk = bump = granuleCells(current);
2318
+ limit = granuleEnd(current);
1782
2319
  return take(size, align);
1783
2320
  }
1784
2321
 
@@ -1786,8 +2323,9 @@ struct ThreadRegion {
1786
2323
  auto bits = reinterpret_cast<std::uintptr_t>(bump);
1787
2324
  bits = (bits + align - 1) & ~(static_cast<std::uintptr_t>(align) - 1);
1788
2325
  auto* cell = reinterpret_cast<unsigned char*>(bits);
1789
- if (bump == nullptr || cell + size > limit) [[unlikely]] return takeChunk(size, align);
2326
+ if (bump == nullptr || cell + size > limit) [[unlikely]] return takeGranule(size, align);
1790
2327
  bump = cell + size;
2328
+ ++current->live;
1791
2329
  return cell;
1792
2330
  }
1793
2331
 
@@ -1834,6 +2372,23 @@ struct ThreadRegion {
1834
2372
 
1835
2373
  /** The region the CURRENT thread is running region code under; null everywhere else, which is every thread almost always. */
1836
2374
  inline thread_local ThreadRegion* activeRegion = nullptr;
2375
+ /**
2376
+ * How many `RegionPool::run` calls are in flight, process-wide. Zero means no
2377
+ * thread is inside a region, so no thread's `activeRegion` is set: the count
2378
+ * is raised before a region's epoch is published (which every helper acquires
2379
+ * before it sets its own `activeRegion`) and lowered only after the join,
2380
+ * when every helper has cleared it again. Every reference count change and
2381
+ * pool allocation asks `currentRegion()`, and outside regions -- nearly
2382
+ * always, on a frame thread -- that is one load of this word instead of the
2383
+ * thread-local chain (`_tls_index`, the TEB's TLS array, the slot) that
2384
+ * made up ~5% of the frame thread's samples in a three.js game.
2385
+ */
2386
+ inline std::atomic<std::uint32_t> regionsInFlight{0};
2387
+ /** This thread's region, or none: `activeRegion` asked only while some region runs. */
2388
+ [[gnu::always_inline]] inline ThreadRegion* currentRegion() {
2389
+ if (regionsInFlight.load(std::memory_order_relaxed) == 0) [[likely]] return nullptr;
2390
+ return activeRegion;
2391
+ }
1837
2392
 
1838
2393
  /**
1839
2394
  * The address-keyed side tables -- expandos, pending and logged key orders,
@@ -1870,7 +2425,7 @@ class SideTableGuard {
1870
2425
  }
1871
2426
 
1872
2427
  [[gnu::always_inline]] inline ThreadRegion* foreignRegionFor(const void* object) {
1873
- ThreadRegion* region = activeRegion;
2428
+ ThreadRegion* region = currentRegion();
1874
2429
  if (region == nullptr) [[likely]] return nullptr;
1875
2430
  return region->owns(object) ? nullptr : region;
1876
2431
  }
@@ -1943,7 +2498,7 @@ struct AllocationPool {
1943
2498
  */
1944
2499
  [[gnu::always_inline]] static void* take() {
1945
2500
  #if defined(GEA_RUNTIME_PARALLEL) && GEA_RUNTIME_PARALLEL
1946
- if (parallel::ThreadRegion* region = parallel::activeRegion) [[unlikely]] return takeInRegion(*region);
2501
+ if (parallel::ThreadRegion* region = parallel::currentRegion()) [[unlikely]] return takeInRegion(*region);
1947
2502
  #endif
1948
2503
  auto& pool = state();
1949
2504
  // A freed cell is the common case in a steady state, and it is three
@@ -1992,7 +2547,10 @@ struct AllocationPool {
1992
2547
 
1993
2548
  static void give(void* block) {
1994
2549
  #if defined(GEA_RUNTIME_PARALLEL) && GEA_RUNTIME_PARALLEL
1995
- if (parallel::ThreadRegion* region = parallel::activeRegion) [[unlikely]] return giveInRegion(*region, block);
2550
+ if (parallel::ThreadRegion* region = parallel::currentRegion()) [[unlikely]] return giveInRegion(*region, block);
2551
+ // A cell a region built goes back to its granule, never onto this list:
2552
+ // no region allocates from here (see `parallel::RegionGranule`).
2553
+ if (parallel::ownerOf(block) != 0) [[unlikely]] return parallel::releaseRegionCell(block);
1996
2554
  #endif
1997
2555
  auto& available = state().available;
1998
2556
  Cell* cell = static_cast<Cell*>(block);
@@ -2003,21 +2561,23 @@ struct AllocationPool {
2003
2561
  #if defined(GEA_RUNTIME_PARALLEL) && GEA_RUNTIME_PARALLEL
2004
2562
  /**
2005
2563
  * This size class's cells inside the current region. A region allocates
2006
- * only from its own tagged chunks -- a cell off the thread's ordinary free
2564
+ * only from its own tagged granules -- a cell off the thread's ordinary free
2007
2565
  * list could be anywhere, and the region would not recognise what it built
2008
- * there as its own -- so a cell freed inside the region is kept here for
2009
- * reuse in the same region, and what is left at its end is donated to the
2010
- * joining thread's ordinary pool (`ThreadRegion::donations`).
2566
+ * there as its own -- so a cell this region built and freed is kept here for
2567
+ * reuse in the same region. The list is dropped at the region's end: each
2568
+ * cell on it was already subtracted from its granule's count when it was
2569
+ * freed, so the granule, not this list, is what keeps it.
2011
2570
  */
2012
2571
  struct RegionCells {
2013
2572
  std::uint64_t tag = 0;
2014
2573
  Cell* available = nullptr;
2015
- // Cells are pushed and popped at the head, so the cell pushed onto an
2016
- // empty list stays last until the list empties. Walking to it at the join
2017
- // instead was serial work over every cell a region freed: a tree workload's
2018
- // 52 million nodes held the joining thread for 50 ms after every worker
2019
- // had finished.
2020
- Cell* tail = nullptr;
2574
+ // A cell freed in the region that is not region memory at all (a block
2575
+ // from an ordinary pool, released by an object the region owns) cannot be
2576
+ // counted against a granule; it is kept apart and donated at the end to
2577
+ // the joining thread's pool, as every leftover cell once was. The tail is
2578
+ // kept as the list is built, so the join splices rather than walks.
2579
+ Cell* strays = nullptr;
2580
+ Cell* strayTail = nullptr;
2021
2581
  };
2022
2582
  static RegionCells& regionCells() {
2023
2583
  static thread_local RegionCells cells;
@@ -2028,21 +2588,23 @@ struct AllocationPool {
2028
2588
  if (cells.tag != region.tag) [[unlikely]] {
2029
2589
  cells.tag = region.tag;
2030
2590
  cells.available = nullptr;
2031
- cells.tail = nullptr;
2591
+ cells.strays = nullptr;
2592
+ cells.strayTail = nullptr;
2032
2593
  region.donors.push_back(&donateRegionCells);
2033
2594
  }
2034
2595
  return cells;
2035
2596
  }
2036
- /** Runs on the region thread at its end: hand what is left to the record the joining thread drains. */
2597
+ /** Runs on the region thread at its end: drop the reuse list, and hand any strays to the record the joining thread drains. */
2037
2598
  static void donateRegionCells() {
2038
2599
  auto& cells = regionCells();
2039
- if (cells.available != nullptr && parallel::activeRegion != nullptr)
2040
- parallel::activeRegion->donations.push_back({&adoptDonatedCells, cells.available, cells.tail});
2600
+ if (cells.strays != nullptr && parallel::activeRegion != nullptr)
2601
+ parallel::activeRegion->donations.push_back({&adoptDonatedCells, cells.strays, cells.strayTail});
2041
2602
  cells.available = nullptr;
2042
- cells.tail = nullptr;
2603
+ cells.strays = nullptr;
2604
+ cells.strayTail = nullptr;
2043
2605
  cells.tag = 0;
2044
2606
  }
2045
- /** Runs on the joining thread: the region's leftover cells join its ordinary free list. */
2607
+ /** Runs on the joining thread: a region's stray cells join its ordinary free list. */
2046
2608
  static void adoptDonatedCells(void* head, void* last) {
2047
2609
  Cell* tail = static_cast<Cell*>(last);
2048
2610
  auto& available = state().available;
@@ -2053,6 +2615,7 @@ struct AllocationPool {
2053
2615
  auto& cells = regionCellsFor(region);
2054
2616
  if (Cell* cell = cells.available) {
2055
2617
  cells.available = cell->next;
2618
+ ++parallel::granuleOf(cell)->live;
2056
2619
  return cell;
2057
2620
  }
2058
2621
  return region.take(sizeof(Cell), alignof(Cell));
@@ -2060,7 +2623,14 @@ struct AllocationPool {
2060
2623
  [[gnu::noinline]] static void giveInRegion(parallel::ThreadRegion& region, void* block) {
2061
2624
  auto& cells = regionCellsFor(region);
2062
2625
  Cell* cell = static_cast<Cell*>(block);
2063
- if (cells.available == nullptr) cells.tail = cell;
2626
+ bool reusable = false;
2627
+ if (!region.recycle(block, reusable)) [[unlikely]] {
2628
+ if (cells.strays == nullptr) cells.strayTail = cell;
2629
+ cell->next = cells.strays;
2630
+ cells.strays = cell;
2631
+ return;
2632
+ }
2633
+ if (!reusable) [[unlikely]] return;
2064
2634
  cell->next = cells.available;
2065
2635
  cells.available = cell;
2066
2636
  }
@@ -2347,7 +2917,7 @@ struct RefHeader {
2347
2917
  };
2348
2918
 
2349
2919
  /** How far past its block a non-standalone object sits; see `RefStride`. */
2350
- inline constexpr std::size_t refHeaderStride = 16;
2920
+ inline constexpr std::size_t refHeaderStride = std::max<std::size_t>(alignof(std::max_align_t), 16);
2351
2921
 
2352
2922
  /** An ownership edge, including the exact allocation's destruction recipe. */
2353
2923
  struct CycleReference {
@@ -3038,12 +3608,12 @@ class CycleGraphStorage {
3038
3608
  if (memory == nullptr) throw CycleGraphExhausted();
3039
3609
  // The chunk table holds one pointer per chunk (a few dozen), so its own
3040
3610
  // growth is never the large request this class exists to avoid.
3041
- try {
3611
+ GEA_EH_TRY_ANY(gea_eh_failed) {
3042
3612
  chunks_.push_back(static_cast<T*>(memory));
3043
- } catch (...) {
3613
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
3044
3614
  ::operator delete(memory);
3045
- throw;
3046
- }
3615
+ GEA_EH_RETHROW_ANY(gea_eh_failed);
3616
+ } GEA_EH_END
3047
3617
  }
3048
3618
  std::vector<T*> chunks_;
3049
3619
  std::size_t size_ = 0;
@@ -3243,13 +3813,13 @@ inline void filterBufferedCandidates(CycleState& state) {
3243
3813
  flushDipCache(state);
3244
3814
  if (state.filtered < state.candidates.size()) {
3245
3815
  state.collecting = true;
3246
- try {
3816
+ GEA_EH_TRY_ANY(gea_eh_failed) {
3247
3817
  filterCycleCandidates(state.candidates, state.filtered, /* pin = */ true, /* prefix = */ false);
3248
- } catch (...) {
3818
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
3249
3819
  state.collecting = false;
3250
3820
  state.filtered = 0;
3251
- throw;
3252
- }
3821
+ GEA_EH_RETHROW_ANY(gea_eh_failed);
3822
+ } GEA_EH_END
3253
3823
  state.collecting = false;
3254
3824
  }
3255
3825
  state.filtered = state.candidates.size();
@@ -3342,7 +3912,7 @@ inline void filterBufferedCandidates(CycleState& state) {
3342
3912
  * `strong`, so `WeakRef` expiration (which only ever reads `strong`)
3343
3913
  * is unchanged.
3344
3914
  */
3345
- inline void collectReferenceCycles(bool full = false) {
3915
+ GEA_EH_NOINLINE inline void collectReferenceCycles(bool full = false) {
3346
3916
  // Small embedded heaps trade generational throughput for one complete tracing path.
3347
3917
  if constexpr (!cycleGenerational) full = true;
3348
3918
  auto& state = cycleState();
@@ -4010,7 +4580,13 @@ struct RefOperationsFor {
4010
4580
  return +[](const void* object) -> const void* { return static_cast<const T*>(object)->identity(); };
4011
4581
  else return nullptr;
4012
4582
  }
4013
- static inline const RefOperations table{&RefOperationsFor<T>::destroy, &RefOperationsFor<T>::release, &RefOperationsFor<T>::drop,
4583
+ // Mutable static storage, never written: the table's ADDRESS is the class
4584
+ // identity (`classIdentity`, `classIdentityExtends`), and a linker may merge
4585
+ // identical read-only tables -- link.exe's /OPT:ICF does, address-taken or
4586
+ // not, and two types whose destroy/release/trace code was folded have
4587
+ // identical tables. `PlainObjectOperationsFor<T>`'s table is byte-identical
4588
+ // to a root class's by construction. Writable data is never merged.
4589
+ static inline constinit RefOperations table{&RefOperationsFor<T>::destroy, &RefOperationsFor<T>::release, &RefOperationsFor<T>::drop,
4014
4590
  TraceEdges<T>::supported ? &RefOperationsFor<T>::trace : nullptr,
4015
4591
  cycleGenerational && TraceEdges<T>::supported ? &RefOperationsFor<T>::holdsTracedEdge : nullptr,
4016
4592
  RefOperationsFor<T>::classBase(), inlineKeyOrderOffsetOf<T>(), inlineKeyOrderLayoutOf<T>()
@@ -4103,12 +4679,12 @@ inline void filterRegionCandidates(ThreadRegion& region, CycleState& state) {
4103
4679
  [&](const CycleReference& reference) { return !region.owns(reference.counts); });
4104
4680
  const auto from = static_cast<std::size_t>(owned - list.begin());
4105
4681
  state.collecting = true;
4106
- try {
4682
+ GEA_EH_TRY_ANY(gea_eh_failed) {
4107
4683
  filterCycleCandidates(list, from, /* pin = */ true, /* prefix = */ false);
4108
- } catch (...) {
4684
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
4109
4685
  state.collecting = false;
4110
- throw;
4111
- }
4686
+ GEA_EH_RETHROW_ANY(gea_eh_failed);
4687
+ } GEA_EH_END
4112
4688
  state.collecting = false;
4113
4689
  state.filterAt = list.size() + (state.filterInterval != 0 ? state.filterInterval : state.candidateThreshold);
4114
4690
  }
@@ -4865,7 +5441,7 @@ inline Ref<T> makeRef(Arguments&&... arguments) {
4865
5441
  }
4866
5442
  void* block = detail::AllocationPool<detail::refBlockSize<T>, detail::refBlockAlign<T>>::take();
4867
5443
  T* object = reinterpret_cast<T*>(static_cast<unsigned char*>(block) + detail::refStride<T>);
4868
- try {
5444
+ GEA_EH_TRY_ANY(gea_eh_failed) {
4869
5445
  // `T()` with no arguments is VALUE-initialization: for a type whose
4870
5446
  // default constructor is not user-provided, that zero-fills the whole
4871
5447
  // object before a single member constructor runs. An emitted record's
@@ -4878,10 +5454,10 @@ inline Ref<T> makeRef(Arguments&&... arguments) {
4878
5454
  // default-initialized instead, which runs exactly those constructors.
4879
5455
  if constexpr (sizeof...(Arguments) == 0 && requires { typename T::gea_default_init; }) ::new (static_cast<void*>(object)) T;
4880
5456
  else ::new (static_cast<void*>(object)) T(static_cast<Arguments&&>(arguments)...);
4881
- } catch (...) {
5457
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
4882
5458
  detail::AllocationPool<detail::refBlockSize<T>, detail::refBlockAlign<T>>::give(block);
4883
- throw;
4884
- }
5459
+ GEA_EH_RETHROW_ANY(gea_eh_failed);
5460
+ } GEA_EH_END
4885
5461
  detail::RefCounts* counts = static_cast<detail::RefCounts*>(block);
4886
5462
  counts->strong = 1;
4887
5463
  counts->weak = 0;
@@ -4949,6 +5525,9 @@ class RegionPool {
4949
5525
  failure_ = nullptr;
4950
5526
  const std::size_t helpers = std::min(workers_.size(), count - 1);
4951
5527
  finished_.store(0, std::memory_order_relaxed);
5528
+ // Raised before the release store below, which every helper acquires
5529
+ // before its `work` sets `activeRegion` (see `regionsInFlight`).
5530
+ regionsInFlight.fetch_add(1, std::memory_order_relaxed);
4952
5531
  bool sleeping;
4953
5532
  {
4954
5533
  std::lock_guard lock(mutex_);
@@ -4965,6 +5544,9 @@ class RegionPool {
4965
5544
  joining_ = false;
4966
5545
  }
4967
5546
  join(helpers + 1);
5547
+ // Every helper has finished `work` (and cleared its `activeRegion`) before
5548
+ // `finished_` reached `helpers`, which the join above acquired.
5549
+ regionsInFlight.fetch_sub(1, std::memory_order_relaxed);
4968
5550
  if (failure_ != nullptr && failedIndex_ < decidedIndex_) {
4969
5551
  std::exception_ptr failure = failure_;
4970
5552
  failure_ = nullptr;
@@ -4982,8 +5564,42 @@ class RegionPool {
4982
5564
  if (count == 0) count = 1;
4983
5565
  if (count > 255) count = 255;
4984
5566
  regions_ = std::vector<ThreadRegion>(count);
4985
- for (std::size_t slot = 1; slot < count; ++slot) workers_.emplace_back([this, slot] { serve(slot); });
5567
+ const std::uint64_t affinity = workerAffinity();
5568
+ for (std::size_t slot = 1; slot < count; ++slot) {
5569
+ workers_.emplace_back([this, slot] { serve(slot); });
5570
+ if (affinity != 0) pin(workers_.back(), affinity);
5571
+ }
4986
5572
  for (auto& worker : workers_) worker.detach();
5573
+ regions_[0].prepare();
5574
+ }
5575
+
5576
+ /**
5577
+ * `GEA_PARALLEL_AFFINITY`: a hex mask of logical processors (`0xfff` or
5578
+ * `fff`) the pool's own worker threads are confined to; the thread that
5579
+ * starts regions keeps whatever affinity its host gave it. Unset, empty or
5580
+ * zero leaves the workers where the system puts them. A host that pins its
5581
+ * frame thread to one cache complex (a dual-CCD part's V-Cache die) sets it
5582
+ * to the same complex, so the region's helpers share that cache instead of
5583
+ * reading the frame's data across the fabric. Read once, when the first
5584
+ * region creates the pool; the first 64 processors only.
5585
+ */
5586
+ static std::uint64_t workerAffinity() {
5587
+ const char* text = std::getenv("GEA_PARALLEL_AFFINITY");
5588
+ if (text == nullptr || *text == '\0') return 0;
5589
+ return static_cast<std::uint64_t>(std::strtoull(text, nullptr, 16));
5590
+ }
5591
+
5592
+ static void pin([[maybe_unused]] std::thread& worker, [[maybe_unused]] std::uint64_t mask) {
5593
+ #if defined(_WIN64) && defined(_MSC_VER)
5594
+ // MSVC's STL hands out the thread's HANDLE.
5595
+ ::SetThreadAffinityMask(worker.native_handle(), mask);
5596
+ #elif defined(__linux__) && defined(__GLIBC__)
5597
+ cpu_set_t set;
5598
+ CPU_ZERO(&set);
5599
+ for (unsigned cpu = 0; cpu < 64 && cpu < CPU_SETSIZE; ++cpu)
5600
+ if ((mask >> cpu) & 1) CPU_SET(cpu, &set);
5601
+ ::pthread_setaffinity_np(worker.native_handle(), sizeof(set), &set);
5602
+ #endif
4987
5603
  }
4988
5604
 
4989
5605
  /**
@@ -5007,6 +5623,8 @@ class RegionPool {
5007
5623
  // The epoch and its helper count travel in ONE word: read separately, a
5008
5624
  // worker could pair one region's epoch with the next region's count.
5009
5625
  void serve(std::size_t slot) {
5626
+ regions_[slot].prepare();
5627
+ cycleState();
5010
5628
  std::uint64_t seen = 0;
5011
5629
  for (;;) {
5012
5630
  std::uint64_t epoch = 0;
@@ -5033,8 +5651,7 @@ class RegionPool {
5033
5651
  }
5034
5652
 
5035
5653
  void work(ThreadRegion& region, std::uint64_t epoch, std::size_t slot) {
5036
- region.tag = (epoch << 8) | slot;
5037
- region.chunk = region.bump = region.limit = nullptr;
5654
+ region.begin((epoch << 8) | slot);
5038
5655
  for (const std::uint32_t index : region.used) region.table[index] = DeferredCount{nullptr, nullptr, 0, 0};
5039
5656
  region.used.clear();
5040
5657
  region.last = nullptr;
@@ -5067,6 +5684,7 @@ class RegionPool {
5067
5684
  }
5068
5685
  for (auto donor : region.donors) donor();
5069
5686
  flushDipCache(cycles);
5687
+ region.finish();
5070
5688
  activeRegion = nullptr;
5071
5689
  --cycles.deferDepth;
5072
5690
  }
@@ -5194,7 +5812,13 @@ namespace detail {
5194
5812
  */
5195
5813
  template <typename T>
5196
5814
  struct PlainObjectOperationsFor {
5197
- static inline const RefOperations table{&RefOperationsFor<T>::destroy, &RefOperationsFor<T>::release, &RefOperationsFor<T>::drop,
5815
+ // Mutable static storage, never written: the table's ADDRESS is the class
5816
+ // identity (`classIdentity`, `classIdentityExtends`), and a linker may merge
5817
+ // identical read-only tables -- link.exe's /OPT:ICF does, address-taken or
5818
+ // not, and two types whose destroy/release/trace code was folded have
5819
+ // identical tables. `PlainObjectOperationsFor<T>`'s table is byte-identical
5820
+ // to a root class's by construction. Writable data is never merged.
5821
+ static inline constinit RefOperations table{&RefOperationsFor<T>::destroy, &RefOperationsFor<T>::release, &RefOperationsFor<T>::drop,
5198
5822
  TraceEdges<T>::supported ? &RefOperationsFor<T>::trace : nullptr,
5199
5823
  cycleGenerational && TraceEdges<T>::supported ? &RefOperationsFor<T>::holdsTracedEdge : nullptr, nullptr,
5200
5824
  inlineKeyOrderOffsetOf<T>(), inlineKeyOrderLayoutOf<T>()
@@ -6536,6 +7160,27 @@ struct NativeCallableFrame {
6536
7160
  bool receivesThis = false;
6537
7161
  };
6538
7162
 
7163
+ namespace detail {
7164
+ /**
7165
+ * One program-wide address per emitted `[[Construct]]` CONVENTION, so a lookup
7166
+ * cannot return an entry of a different signature. Mutable, like every tag
7167
+ * whose address is an identity in this header: a linker may merge identical
7168
+ * READ-ONLY data (link.exe's /OPT:ICF does, address-taken or not), and every
7169
+ * tag is the same zero byte. No linker merges writable data.
7170
+ */
7171
+ template <typename Construct>
7172
+ struct ConstructEntryTag {
7173
+ static inline char id = 0;
7174
+ };
7175
+
7176
+ /** One `[[Construct]]` entry a declaration published in its record (`CallableObject::entryWithConstruct`). */
7177
+ struct ConstructEntryNode {
7178
+ const void* convention;
7179
+ void* construct;
7180
+ const ConstructEntryNode* next;
7181
+ };
7182
+ } // namespace detail
7183
+
6539
7184
  template <typename Result, typename... Arguments>
6540
7185
  struct CallableObject<Result(Arguments...)> {
6541
7186
  friend void geaTraceRefs(const CallableObject& value, detail::RefVisitor& visitor) {
@@ -6548,65 +7193,119 @@ struct CallableObject<Result(Arguments...)> {
6548
7193
  using Invoke = Result (*)(void*, Arguments...);
6549
7194
  using InvokeWithReceiver = Result (*)(void*, const NativeCallReceiver&, Arguments...);
6550
7195
 
6551
- struct ArgumentFrameRegistration {
6552
- Invoke entry;
6553
- NativeCallableFrame frame;
6554
- NativeCallableFrame (*resolve)(void*);
6555
- // The declaration's own thunk a framed entry forwards to unchanged, or
6556
- // null for an adapter whose entry is not one declaration's.
6557
- Invoke framedEntry;
6558
- const ArgumentFrameRegistration* next;
6559
- ArgumentFrameRegistration(Invoke entry_, NativeCallableFrame frame_, NativeCallableFrame (*resolve_)(void*) = nullptr,
6560
- Invoke framedEntry_ = nullptr)
6561
- : entry(entry_), frame(frame_), resolve(resolve_), framedEntry(framedEntry_) {
6562
- auto& head = argumentFrameRegistrations();
6563
- next = head.load(std::memory_order_relaxed);
6564
- while (!head.compare_exchange_weak(next, this, std::memory_order_release, std::memory_order_relaxed)) {}
6565
- }
7196
+ /**
7197
+ * What `name`, `length` and `Function.prototype.toString` answer for a
7198
+ * function object: ECMA-262's [[Name]] (from the declaration itself, or from
7199
+ * `NamedEvaluation` at the syntax position an anonymous function/arrow
7200
+ * literal was defined), the formal-parameter count `length` reports (leading
7201
+ * parameters up to the first default/rest one, `ExpectedArgumentCount`) and
7202
+ * [[SourceText]]. All three are facts about the SYNTAX, decided once by the
7203
+ * compiler at the allocation site, so they live in the entry's record
7204
+ * (`EntryRecord`) rather than on every `CallableObject` copy.
7205
+ */
7206
+ struct CallableFacts {
7207
+ std::string_view name;
7208
+ std::string_view text;
7209
+ std::size_t length;
6566
7210
  };
6567
- static std::atomic<const ArgumentFrameRegistration*>& argumentFrameRegistrations() {
6568
- static std::atomic<const ArgumentFrameRegistration*> head{nullptr};
6569
- return head;
6570
- }
6571
- static NativeCallableFrame argumentFrameFor(Invoke entry, void* environment) {
6572
- for (auto* frame = argumentFrameRegistrations().load(std::memory_order_acquire); frame; frame = frame->next)
6573
- if (frame->entry == entry) return frame->resolve ? frame->resolve(environment) : frame->frame;
6574
- return {};
6575
- }
6576
- NativeCallableFrame argumentFrame() const { return argumentFrameFor(invoke, environment); }
6577
- /** The declaration thunk an `entryWithArgumentFrame` wrapper forwards to,
6578
- * or `entry` itself. The wrapper only states the argument frame; per-
6579
- * declaration facts published against the thunk (its `[[Construct]]` entry)
6580
- * still belong to the value. */
6581
- static Invoke declarationEntryOf(Invoke entry) {
6582
- for (auto* frame = argumentFrameRegistrations().load(std::memory_order_acquire); frame; frame = frame->next)
6583
- if (frame->entry == entry) return frame->framedEntry != nullptr ? frame->framedEntry : entry;
6584
- return entry;
7211
+
7212
+ /**
7213
+ * Everything the runtime knows about one entry beyond how to call it: its
7214
+ * receiver entry (a method view's logical `this`), its argument frame, its
7215
+ * function facts, the declaration a forwarding wrapper stands for, and the
7216
+ * `[[Construct]]` entries that declaration published.
7217
+ *
7218
+ * A carrier reaches these through `record`, never through `invoke`. The
7219
+ * entry's ADDRESS identifies nothing: a release link folds functions whose
7220
+ * machine code is identical (lld-link and link.exe with /OPT:ICF, ld64's
7221
+ * deduplication, lld with --icf=all), address-taken ones included, so
7222
+ * `callUnboundMethod<Writable>` and `callUnboundMethod<Duplex>` -- one body,
7223
+ * two receiver checks -- may share one address in a shipped binary. A record
7224
+ * is a separate object per entry instantiation (`recordOf<Entry>`), mutable
7225
+ * static storage that no linker folds, so a folded pair still carries two
7226
+ * records and each value keeps its own receiver check, frame and facts. The
7227
+ * call itself may then land in the shared code, which is correct: folding
7228
+ * only merges functions that behave identically.
7229
+ *
7230
+ * Static lifetime, no allocation per value or call. A record's fields are
7231
+ * written once, by the function-local static initializer of the site that
7232
+ * mints the entry, before the first carrier holding the record exists; every
7233
+ * later reader holds such a carrier, so it observes the writes.
7234
+ */
7235
+ struct EntryRecord {
7236
+ InvokeWithReceiver withReceiver = nullptr;
7237
+ NativeCallableFrame frame{};
7238
+ NativeCallableFrame (*resolveFrame)(void*) = nullptr;
7239
+ bool hasFacts = false;
7240
+ std::string_view name{};
7241
+ std::size_t length = 0;
7242
+ std::string_view text{};
7243
+ CallableFacts (*resolveFacts)(void*) = nullptr;
7244
+ // The declaration's own record a forwarding wrapper stands for
7245
+ // (`entryWithArgumentFrame`): facts and `[[Construct]]` entries published
7246
+ // for the declaration still belong to the wrapped value.
7247
+ const EntryRecord* declaration = nullptr;
7248
+ std::atomic<const detail::ConstructEntryNode*> constructs{nullptr};
7249
+ };
7250
+
7251
+ /** One entry's record: one per `Entry` instantiation, distinct even where the linker folded two entries' code. */
7252
+ template <Invoke Entry>
7253
+ static inline constinit EntryRecord recordOf{};
7254
+
7255
+ /** An entry as a minting site stores it: the function to call and its record (null: an entry the runtime knows nothing about). */
7256
+ struct RecordedEntry {
7257
+ Invoke invoke = nullptr;
7258
+ const EntryRecord* record = nullptr;
7259
+ constexpr RecordedEntry() = default;
7260
+ constexpr RecordedEntry(Invoke invoke_, const EntryRecord* record_ = nullptr) : invoke(invoke_), record(record_) {}
7261
+ };
7262
+ template <Invoke Entry>
7263
+ static constexpr RecordedEntry recorded() {
7264
+ return RecordedEntry{Entry, &recordOf<Entry>};
7265
+ }
7266
+
7267
+ /** The declaration record `record` stands for: its `declaration` when it is a forwarding wrapper's, else itself. */
7268
+ static const EntryRecord* declarationRecordOf(const EntryRecord* record) {
7269
+ return record != nullptr && record->declaration != nullptr ? record->declaration : record;
6585
7270
  }
6586
7271
 
7272
+ static NativeCallableFrame argumentFrameFor(const EntryRecord* record, void* environment) {
7273
+ if (record == nullptr) return {};
7274
+ return record->resolveFrame ? record->resolveFrame(environment) : record->frame;
7275
+ }
7276
+ NativeCallableFrame argumentFrame() const { return argumentFrameFor(record, environment); }
7277
+
6587
7278
  template <Invoke Entry, int RestFrom, bool ActualArguments, bool ReceivesThis>
6588
- static Invoke entryWithArgumentFrame(Invoke actual = Entry, void* environment = nullptr) {
7279
+ static RecordedEntry entryWithArgumentFrame(RecordedEntry actual = recorded<Entry>(), void* environment = nullptr) {
6589
7280
  static_assert(RestFrom == -1 || RestFrom + 1 == sizeof...(Arguments), "a packing frame names the last physical slot");
6590
7281
  static_assert(!ActualArguments || RestFrom >= 0, "an actual-arguments frame requires a native packed slot");
6591
7282
  if constexpr (Entry == nullptr) {
6592
7283
  // A function-pointer adapter's default value is null; only its actual
6593
7284
  // entry can be called. Its existing frame must agree exactly. In
6594
- // particular, an unregistered pointer cannot acquire a rest/method
7285
+ // particular, an entry without a record cannot acquire a rest/method
6595
7286
  // frame merely because it has the same C++ parameter types.
6596
- if (actual == nullptr) throw std::runtime_error("a native callable adapter has no entry");
6597
- const auto frame = argumentFrameFor(actual, environment);
7287
+ if (actual.invoke == nullptr) throw std::runtime_error("a native callable adapter has no entry");
7288
+ const auto frame = argumentFrameFor(actual.record, environment);
6598
7289
  if (frame.restFrom != RestFrom || frame.actualArguments != ActualArguments || frame.receivesThis != ReceivesThis)
6599
7290
  throw std::runtime_error("a native callable adapter has no matching argument frame");
6600
7291
  return actual;
6601
7292
  } else {
6602
- if (actual != Entry) throw std::runtime_error("a native callable adapter changed its constant entry");
7293
+ // Folding-safe: `actual` was spelled from this same `Entry`, so the two
7294
+ // name one function whether or not its code was folded with another's.
7295
+ if (actual.invoke != Entry) throw std::runtime_error("a native callable adapter changed its constant entry");
6603
7296
  constexpr Invoke framed = &callArgumentFrame<Entry, RestFrom, ActualArguments, ReceivesThis>;
6604
- static const ArgumentFrameRegistration frame{framed, {RestFrom, ActualArguments, ReceivesThis}, nullptr, Entry};
6605
- static const SourceRegistration source{framed, {}, 0, {}, +[](void* environment) -> CallableFacts {
6606
- return factsFor(Entry, environment);
6607
- }};
6608
- static const ReceiverRegistration receiver{framed, &callArgumentFrameWithReceiver<Entry, RestFrom, ActualArguments, ReceivesThis>};
6609
- return framed;
7297
+ // `callArgumentFrame` instantiations that differ only in the frame have
7298
+ // one body each and are folded together, so the frame lives in the
7299
+ // wrapper's own record.
7300
+ static const bool published = [] {
7301
+ auto& record = recordOf<framed>;
7302
+ record.frame = NativeCallableFrame{RestFrom, ActualArguments, ReceivesThis};
7303
+ record.declaration = &recordOf<Entry>;
7304
+ record.withReceiver = &callArgumentFrameWithReceiver<Entry, RestFrom, ActualArguments, ReceivesThis>;
7305
+ return true;
7306
+ }();
7307
+ (void)published;
7308
+ return recorded<framed>();
6610
7309
  }
6611
7310
  }
6612
7311
  template <Invoke Entry, int RestFrom, bool ActualArguments, bool ReceivesThis>
@@ -6615,109 +7314,53 @@ struct CallableObject<Result(Arguments...)> {
6615
7314
  }
6616
7315
  template <Invoke Entry, int RestFrom, bool ActualArguments, bool ReceivesThis>
6617
7316
  static Result callArgumentFrameWithReceiver(void* environment, const NativeCallReceiver& receiver, Arguments... arguments) {
6618
- return CallableObject{Entry, PackedEnvironment{environment, {}, nullptr}}.callWithReceiver(receiver, std::forward<Arguments>(arguments)...);
7317
+ return CallableObject{recorded<Entry>(), PackedEnvironment{environment, {}, nullptr}}.callWithReceiver(receiver,
7318
+ std::forward<Arguments>(arguments)...);
6619
7319
  }
6620
7320
  template <Invoke Entry, typename Source, int ReceiverSlots = 0>
6621
- static void registerArgumentFrameAdapter() {
6622
- static const ArgumentFrameRegistration frame{Entry, {}, +[](void* environment) -> NativeCallableFrame {
7321
+ static RecordedEntry registerArgumentFrameAdapter() {
7322
+ static const bool published = (recordOf<Entry>.resolveFrame = +[](void* environment) -> NativeCallableFrame {
6623
7323
  if constexpr (requires(const Source& source) { source.argumentFrame(); }) {
6624
7324
  auto frame = static_cast<const Source*>(environment)->argumentFrame();
6625
7325
  if (frame.restFrom >= 0) frame.restFrom -= ReceiverSlots;
6626
7326
  if constexpr (ReceiverSlots > 0) frame.receivesThis = false;
6627
7327
  return frame;
6628
7328
  } else return {};
6629
- }};
7329
+ }, true);
7330
+ (void)published;
7331
+ return recorded<Entry>();
6630
7332
  }
6631
7333
 
6632
- // Only method views register a second entry. Ordinary callables retain the
6633
- // same carrier size and invoke path, and ignore logical this as before.
6634
- struct ReceiverRegistration {
6635
- Invoke entry;
6636
- InvokeWithReceiver withReceiver;
6637
- const ReceiverRegistration* next;
6638
- ReceiverRegistration(Invoke entry_, InvokeWithReceiver withReceiver_) : entry(entry_), withReceiver(withReceiver_) {
6639
- auto& head = receiverRegistrations();
6640
- next = head.load(std::memory_order_relaxed);
6641
- while (!head.compare_exchange_weak(next, this, std::memory_order_release, std::memory_order_relaxed)) {}
6642
- }
6643
- };
6644
- static std::atomic<const ReceiverRegistration*>& receiverRegistrations() {
6645
- static std::atomic<const ReceiverRegistration*> head{nullptr};
6646
- return head;
6647
- }
6648
- static void registerRuntimeReceiverEntry(Invoke entry, InvokeWithReceiver withReceiver) {
6649
- if (entry == nullptr || withReceiver == nullptr) throw std::runtime_error("a native callable receiver adapter has no entry");
6650
- static std::mutex mutex;
6651
- std::lock_guard<std::mutex> lock(mutex);
6652
- for (auto* registered = receiverRegistrations().load(std::memory_order_acquire); registered; registered = registered->next) {
6653
- if (registered->entry != entry) continue;
6654
- if (registered->withReceiver != withReceiver)
6655
- throw std::runtime_error("a native callable adapter has conflicting receiver entries");
6656
- return;
6657
- }
6658
- // The registry owns these metadata nodes for the process lifetime, one
6659
- // per actual entry. They do not allocate a callable environment or retain
6660
- // a source object, and invocation performs no registration/allocation.
6661
- (void)new ReceiverRegistration(entry, withReceiver);
6662
- }
7334
+ // Only method views have a receiver entry. Ordinary callables keep the same
7335
+ // invoke path, and ignore logical this as before.
6663
7336
  template <Invoke Entry, InvokeWithReceiver WithReceiver>
6664
- static void registerReceiverEntry() {
6665
- static const ReceiverRegistration registration{Entry, WithReceiver};
7337
+ static RecordedEntry registerReceiverEntry() {
7338
+ static const bool published = (recordOf<Entry>.withReceiver = WithReceiver, true);
7339
+ (void)published;
7340
+ return recorded<Entry>();
6666
7341
  }
6667
7342
 
6668
7343
  /**
6669
- * The three per-declaration static facts ECMA-262 attaches to a function
6670
- * object at creation time and never recomputes afterward: [[SourceText]],
6671
- * [[Name]] (from the declaration itself, or from `NamedEvaluation` at the
6672
- * syntax position an anonymous function/arrow literal was defined) and the
6673
- * formal-parameter count `length` reports (leading parameters up to the
6674
- * first default/rest one, ECMA-262 `ExpectedArgumentCount`). All three are
6675
- * facts about the SYNTAX, decided once by the compiler at the allocation
6676
- * site, so they travel through the identical registry `sourceText()`
6677
- * already used: one static table keyed by the thunk pointer, walked once
6678
- * per read rather than carried on every `CallableObject` copy.
7344
+ * The record of an adapter handed in at run time as a function pointer,
7345
+ * which has no `recordOf` instantiation of its own: one per distinct
7346
+ * (receiver entry, facts resolver) pair, allocated once and kept for the
7347
+ * process lifetime, never per value or call. Interned by CONTENT, so two
7348
+ * adapters folded into one address simply share a record that is right for
7349
+ * both; nothing here can be confused by folding.
6679
7350
  */
6680
- struct CallableFacts {
6681
- std::string_view name;
6682
- std::string_view text;
6683
- std::size_t length;
6684
- };
6685
-
6686
- // Registrations have static lifetime. Ordinary calls and closure allocations
6687
- // do no registry work, and the carrier's layout remains unchanged.
6688
- struct SourceRegistration {
6689
- Invoke entry;
6690
- std::string_view name;
6691
- std::size_t length;
6692
- std::string_view text;
6693
- CallableFacts (*resolve)(void*);
6694
- const SourceRegistration* next;
6695
- SourceRegistration(Invoke entry_, std::string_view name_, std::size_t length_, std::string_view text_, CallableFacts (*resolve_)(void*))
6696
- : entry(entry_), name(name_), length(length_), text(text_), resolve(resolve_) {
6697
- auto& head = sourceRegistrations();
6698
- next = head.load(std::memory_order_relaxed);
6699
- while (!head.compare_exchange_weak(next, this, std::memory_order_release, std::memory_order_relaxed)) {}
6700
- }
6701
- };
6702
-
6703
- static std::atomic<const SourceRegistration*>& sourceRegistrations() {
6704
- static std::atomic<const SourceRegistration*> head{nullptr};
6705
- return head;
6706
- }
6707
- static void registerRuntimeSourceEntry(Invoke entry, CallableFacts (*resolve)(void*)) {
6708
- if (entry == nullptr || resolve == nullptr) throw std::runtime_error("a native callable source adapter has no entry");
7351
+ static const EntryRecord* runtimeAdapterRecord(InvokeWithReceiver withReceiver, CallableFacts (*resolveFacts)(void*)) {
6709
7352
  static std::mutex mutex;
7353
+ static auto* records = new std::vector<const EntryRecord*>();
6710
7354
  std::lock_guard<std::mutex> lock(mutex);
6711
- for (auto* registered = sourceRegistrations().load(std::memory_order_acquire); registered; registered = registered->next) {
6712
- if (registered->entry != entry) continue;
6713
- if (registered->resolve != resolve)
6714
- throw std::runtime_error("a native callable adapter has conflicting source entries");
6715
- return;
6716
- }
6717
- // Static-lifetime metadata is allocated once per runtime entry/resolver,
6718
- // never per invocation or per adapted Source/environment allocation.
6719
- (void)new SourceRegistration(entry, {}, 0, {}, resolve);
7355
+ for (const EntryRecord* record : *records)
7356
+ if (record->withReceiver == withReceiver && record->resolveFacts == resolveFacts) return record;
7357
+ auto* record = new EntryRecord();
7358
+ record->withReceiver = withReceiver;
7359
+ record->resolveFacts = resolveFacts;
7360
+ records->push_back(record);
7361
+ return record;
6720
7362
  }
7363
+
6721
7364
  template <typename Source>
6722
7365
  static CallableFacts sourceAdapterFacts(void* environment) {
6723
7366
  const auto source = static_cast<const Source*>(environment)->facts();
@@ -6725,17 +7368,18 @@ struct CallableObject<Result(Arguments...)> {
6725
7368
  }
6726
7369
  template <auto Known, typename Source>
6727
7370
  static CallableFacts sourceInPlaceAdapterFacts(void* environment) {
6728
- const auto source = Source::factsFor(Known, environment);
7371
+ const auto source = Source::factsFor(&Source::template recordOf<Known>, environment);
6729
7372
  return CallableFacts{source.name, source.text, source.length};
6730
7373
  }
6731
7374
 
7375
+ /** Publishes `Entry`'s facts in its record; for a carrier the caller builds from `recorded<Entry>()`. */
6732
7376
  template <Invoke Entry>
6733
7377
  static bool registerSource(std::string_view name, std::size_t length, std::string_view text) {
6734
- static const SourceRegistration registration{Entry, name, length, text, nullptr};
7378
+ (void)entryWithFacts<Entry>(name, length, text);
6735
7379
  return true;
6736
7380
  }
6737
7381
 
6738
- // The same registration, performed where a function OBJECT is minted from
7382
+ // The same publication, performed where a function OBJECT is minted from
6739
7383
  // the thunk rather than by a namespace-scope initializer beside the thunk.
6740
7384
  // A namespace-scope registration is a static initializer that takes the
6741
7385
  // thunk's address, and a static initializer with a side effect is a GC
@@ -6743,37 +7387,71 @@ struct CallableObject<Result(Arguments...)> {
6743
7387
  // emitted function -- and its source text -- in the binary whether or not
6744
7388
  // anything reached it. One `EventEmitter` boxing a listener turned the
6745
7389
  // registry on for a whole program, and that pinned every function of the
6746
- // program. Here the registration is reachable only from a site
7390
+ // program. Here the publication is reachable only from a site
6747
7391
  // that creates the function object, which is the only site that can later
6748
7392
  // observe its `name`/`length`/source. The function-local static is one
6749
7393
  // per `Entry`, so several minting sites of one declaration share a single
6750
- // registration, and a site costs one guard-variable load per mint.
7394
+ // publication, and a site costs one guard-variable load per mint.
6751
7395
  template <Invoke Entry>
6752
- static Invoke entryWithFacts(std::string_view name, std::size_t length, std::string_view text) {
6753
- static const SourceRegistration registration{Entry, name, length, text, nullptr};
6754
- return Entry;
7396
+ static RecordedEntry entryWithFacts(std::string_view name, std::size_t length, std::string_view text) {
7397
+ static const bool published = [&] {
7398
+ auto& record = recordOf<Entry>;
7399
+ record.name = name;
7400
+ record.length = length;
7401
+ record.text = text;
7402
+ record.hasFacts = true;
7403
+ return true;
7404
+ }();
7405
+ (void)published;
7406
+ return recorded<Entry>();
7407
+ }
7408
+
7409
+ /**
7410
+ * `entry`, minted from `Declaration`'s thunk, with the declaration's
7411
+ * `[[Construct]]` entry `Construct` published in its record
7412
+ * (`gea::withConstructEntry` reads it back). Published at the mint for the
7413
+ * reason `entryWithFacts` is, and once per pair.
7414
+ */
7415
+ template <Invoke Declaration, auto Construct>
7416
+ static RecordedEntry entryWithConstruct(RecordedEntry entry) {
7417
+ static detail::ConstructEntryNode node{&detail::ConstructEntryTag<decltype(Construct)>::id, reinterpret_cast<void*>(Construct), nullptr};
7418
+ static const bool published = [] {
7419
+ auto& head = recordOf<Declaration>.constructs;
7420
+ node.next = head.load(std::memory_order_relaxed);
7421
+ while (!head.compare_exchange_weak(node.next, &node, std::memory_order_release, std::memory_order_relaxed)) {}
7422
+ return true;
7423
+ }();
7424
+ (void)published;
7425
+ if (entry.record == nullptr) entry.record = &recordOf<Declaration>;
7426
+ return entry;
6755
7427
  }
6756
7428
 
6757
7429
  // An adapter (`dropArguments` and its siblings below) shares ONE thunk
6758
- // pointer across every closure it wraps, so the facts it reports cannot
6759
- // live in this registration -- they belong to whichever `Source` closure
6760
- // was actually wrapped, reached back out through the environment exactly as
6761
- // `sourceText()`'s own resolve already did before `facts()` folded it in.
7430
+ // across every closure it wraps, so the facts it reports cannot live in
7431
+ // its record -- they belong to whichever `Source` closure was actually
7432
+ // wrapped, reached back out through the environment.
6762
7433
  template <Invoke Entry, typename Source>
6763
- static void registerSourceAdapter() {
6764
- static const SourceRegistration registration{Entry, {}, 0, {}, +[](void* environment_) -> CallableFacts {
7434
+ static RecordedEntry registerSourceAdapter() {
7435
+ static const bool published = (recordOf<Entry>.resolveFacts = +[](void* environment_) -> CallableFacts {
6765
7436
  const auto source = static_cast<const Source*>(environment_)->facts();
6766
7437
  return CallableFacts{source.name, source.text, source.length};
6767
- }};
7438
+ }, true);
7439
+ (void)published;
7440
+ return recorded<Entry>();
6768
7441
  }
6769
7442
 
6770
- template <int RestFrom = -1, bool ActualArguments = false, bool ReceivesThis = false, typename Source, typename Adapter>
7443
+ template <int RestFrom = -1, bool ActualArguments = false, bool ReceivesThis = false, typename Source, typename Adapter>
6771
7444
  static CallableObject adaptSource(Source source, Adapter adapter) {
6772
7445
  CallableObject adapted{+adapter, packEnvironment(std::move(source))};
6773
- adapted.invoke = entryWithArgumentFrame<+Adapter{}, RestFrom, ActualArguments, ReceivesThis>(+adapter, adapted.environment);
6774
- if constexpr (std::is_pointer_v<Adapter>) registerRuntimeSourceEntry(+adapter, &sourceAdapterFacts<Source>);
6775
- else {
6776
- static const SourceRegistration registration{+adapter, {}, 0, {}, &sourceAdapterFacts<Source>};
7446
+ if constexpr (std::is_pointer_v<Adapter>) {
7447
+ adapted.invoke = entryWithArgumentFrame<nullptr, RestFrom, ActualArguments, ReceivesThis>(+adapter, adapted.environment).invoke;
7448
+ adapted.record = runtimeAdapterRecord(nullptr, &sourceAdapterFacts<Source>);
7449
+ } else {
7450
+ static const bool published = (recordOf<+Adapter{}>.resolveFacts = &sourceAdapterFacts<Source>, true);
7451
+ (void)published;
7452
+ const auto entry = entryWithArgumentFrame<+Adapter{}, RestFrom, ActualArguments, ReceivesThis>(+adapter, adapted.environment);
7453
+ adapted.invoke = entry.invoke;
7454
+ adapted.record = entry.record;
6777
7455
  }
6778
7456
  adapted.shareFunctionObject(*static_cast<const Source*>(adapted.environment));
6779
7457
  return adapted;
@@ -6794,10 +7472,15 @@ struct CallableObject<Result(Arguments...)> {
6794
7472
  template <auto Known, int RestFrom = -1, bool ActualArguments = false, bool ReceivesThis = false, typename Source, typename Adapter>
6795
7473
  static CallableObject adaptSourceInPlace(const Source& source, Adapter adapter) {
6796
7474
  CallableObject adapted{+adapter, PackedEnvironment{source.environment, source.environmentOwner, nullptr}};
6797
- adapted.invoke = entryWithArgumentFrame<+Adapter{}, RestFrom, ActualArguments, ReceivesThis>(+adapter, adapted.environment);
6798
- if constexpr (std::is_pointer_v<Adapter>) registerRuntimeSourceEntry(+adapter, &sourceInPlaceAdapterFacts<Known, Source>);
6799
- else {
6800
- static const SourceRegistration registration{+adapter, {}, 0, {}, &sourceInPlaceAdapterFacts<Known, Source>};
7475
+ if constexpr (std::is_pointer_v<Adapter>) {
7476
+ adapted.invoke = entryWithArgumentFrame<nullptr, RestFrom, ActualArguments, ReceivesThis>(+adapter, adapted.environment).invoke;
7477
+ adapted.record = runtimeAdapterRecord(nullptr, &sourceInPlaceAdapterFacts<Known, Source>);
7478
+ } else {
7479
+ static const bool published = (recordOf<+Adapter{}>.resolveFacts = &sourceInPlaceAdapterFacts<Known, Source>, true);
7480
+ (void)published;
7481
+ const auto entry = entryWithArgumentFrame<+Adapter{}, RestFrom, ActualArguments, ReceivesThis>(+adapter, adapted.environment);
7482
+ adapted.invoke = entry.invoke;
7483
+ adapted.record = entry.record;
6801
7484
  }
6802
7485
  adapted.shareFunctionObject(source);
6803
7486
  return adapted;
@@ -6806,10 +7489,15 @@ struct CallableObject<Result(Arguments...)> {
6806
7489
  template <int RestFrom = -1, bool ActualArguments = false, bool ReceivesThis = false, typename Source, typename Adapter, typename ReceiverAdapter>
6807
7490
  static CallableObject adaptSourceWithReceiver(Source source, Adapter adapter, ReceiverAdapter receiverAdapter) {
6808
7491
  auto adapted = adaptSource<RestFrom, ActualArguments, ReceivesThis>(std::move(source), adapter);
6809
- if constexpr (std::is_pointer_v<Adapter> || std::is_pointer_v<ReceiverAdapter>)
6810
- registerRuntimeReceiverEntry(+adapter, +receiverAdapter);
6811
- else {
6812
- static const ReceiverRegistration registration{+adapter, +receiverAdapter};
7492
+ if constexpr (std::is_pointer_v<Adapter> || std::is_pointer_v<ReceiverAdapter>) {
7493
+ if (+receiverAdapter == nullptr) throw std::runtime_error("a native callable receiver adapter has no entry");
7494
+ // A record of its own (the pair handed in), whatever wrapper the frame
7495
+ // check returned: the adapter itself is the entry, as in `adaptSource`.
7496
+ adapted.invoke = +adapter;
7497
+ adapted.record = runtimeAdapterRecord(+receiverAdapter, &sourceAdapterFacts<Source>);
7498
+ } else {
7499
+ static const bool published = (recordOf<+Adapter{}>.withReceiver = +ReceiverAdapter{}, true);
7500
+ (void)published;
6813
7501
  }
6814
7502
  return adapted;
6815
7503
  }
@@ -6817,25 +7505,31 @@ struct CallableObject<Result(Arguments...)> {
6817
7505
  template <auto Known, int RestFrom = -1, bool ActualArguments = false, bool ReceivesThis = false, typename Source, typename Adapter, typename ReceiverAdapter>
6818
7506
  static CallableObject adaptSourceInPlaceWithReceiver(const Source& source, Adapter adapter, ReceiverAdapter receiverAdapter) {
6819
7507
  auto adapted = adaptSourceInPlace<Known, RestFrom, ActualArguments, ReceivesThis>(source, adapter);
6820
- if constexpr (std::is_pointer_v<Adapter> || std::is_pointer_v<ReceiverAdapter>)
6821
- registerRuntimeReceiverEntry(+adapter, +receiverAdapter);
6822
- else {
6823
- static const ReceiverRegistration registration{+adapter, +receiverAdapter};
7508
+ if constexpr (std::is_pointer_v<Adapter> || std::is_pointer_v<ReceiverAdapter>) {
7509
+ if (+receiverAdapter == nullptr) throw std::runtime_error("a native callable receiver adapter has no entry");
7510
+ adapted.invoke = +adapter;
7511
+ adapted.record = runtimeAdapterRecord(+receiverAdapter, &sourceInPlaceAdapterFacts<Known, Source>);
7512
+ } else {
7513
+ static const bool published = (recordOf<+Adapter{}>.withReceiver = +ReceiverAdapter{}, true);
7514
+ (void)published;
6824
7515
  }
6825
7516
  return adapted;
6826
7517
  }
6827
7518
 
6828
- static CallableFacts factsFor(Invoke invoke, void* environment) {
6829
- for (auto* entry = sourceRegistrations().load(std::memory_order_acquire); entry; entry = entry->next) {
6830
- if (entry->entry == invoke) return entry->resolve ? entry->resolve(environment) : CallableFacts{entry->name, entry->text, entry->length};
7519
+ static CallableFacts factsFor(const EntryRecord* record, void* environment) {
7520
+ // A forwarding wrapper's record publishes no facts of its own; its
7521
+ // declaration's does.
7522
+ for (; record != nullptr; record = record->declaration) {
7523
+ if (record->resolveFacts) return record->resolveFacts(environment);
7524
+ if (record->hasFacts) return CallableFacts{record->name, record->text, record->length};
6831
7525
  }
6832
7526
  // Runtime-created native builtins carry no ECMAScript [[SourceText]] and
6833
- // no registered [[Name]]/length either -- reflecting those is a host
7527
+ // no published [[Name]]/length either -- reflecting those is a host
6834
7528
  // built-in's own concern, not this carrier's.
6835
7529
  return CallableFacts{{}, "function () { [native code] }", 0};
6836
7530
  }
6837
7531
 
6838
- CallableFacts facts() const { return factsFor(invoke, environment); }
7532
+ CallableFacts facts() const { return factsFor(record, environment); }
6839
7533
 
6840
7534
  std::string_view sourceText() const { return facts().text; }
6841
7535
  /** ECMA-262 [[Name]] -- the declared name, or the `NamedEvaluation` name from where an anonymous literal was defined; empty when neither applies. */
@@ -6844,6 +7538,8 @@ struct CallableObject<Result(Arguments...)> {
6844
7538
  std::size_t length() const { return facts().length; }
6845
7539
 
6846
7540
  Invoke invoke = nullptr;
7541
+ /** What the runtime knows about `invoke` (`EntryRecord`), or null for an entry it knows nothing about. */
7542
+ const EntryRecord* record = nullptr;
6847
7543
  void* environment = nullptr;
6848
7544
  /** Empty for a capture-free callable and for an inline environment, which is owned by nothing because it IS `environment`. A heap environment's block, otherwise: see `PackedEnvironment`. */
6849
7545
  Ref<void> environmentOwner;
@@ -6868,6 +7564,10 @@ struct CallableObject<Result(Arguments...)> {
6868
7564
  CallableObject(Invoke invoke_, void* environment_) : invoke(invoke_), environment(environment_) {}
6869
7565
  CallableObject(Invoke invoke_, PackedEnvironment packed)
6870
7566
  : invoke(invoke_), environment(packed.pointer), environmentOwner(std::move(packed.owner)), identityHeader(packed.identityHeader) {}
7567
+ CallableObject(RecordedEntry entry_, void* environment_) : invoke(entry_.invoke), record(entry_.record), environment(environment_) {}
7568
+ CallableObject(RecordedEntry entry_, PackedEnvironment packed)
7569
+ : invoke(entry_.invoke), record(entry_.record), environment(packed.pointer), environmentOwner(std::move(packed.owner)),
7570
+ identityHeader(packed.identityHeader) {}
6871
7571
  // A copy SHARES the identity owner the source already has and mints none:
6872
7572
  // the emitter identifies, at allocation, every callable whose identity the
6873
7573
  // program can observe (`ir/program-facts.ts`'s callable-identity census,
@@ -6884,14 +7584,15 @@ struct CallableObject<Result(Arguments...)> {
6884
7584
  // return slot and a destruction, and each of those touched two handles
6885
7585
  // through an out-of-line call until this.
6886
7586
  [[gnu::always_inline]] CallableObject(const CallableObject& source)
6887
- : invoke(source.invoke), environment(source.environment), environmentOwner(source.environmentOwner),
7587
+ : invoke(source.invoke), record(source.record), environment(source.environment), environmentOwner(source.environmentOwner),
6888
7588
  functionObject(source.functionObject), identityHeader(source.identityHeader) {}
6889
7589
  [[gnu::always_inline]] CallableObject(CallableObject&& source) noexcept
6890
- : invoke(source.invoke), environment(source.environment), environmentOwner(std::move(source.environmentOwner)),
7590
+ : invoke(source.invoke), record(source.record), environment(source.environment), environmentOwner(std::move(source.environmentOwner)),
6891
7591
  functionObject(std::move(source.functionObject)), identityHeader(source.identityHeader) {}
6892
7592
  [[gnu::always_inline]] CallableObject& operator=(const CallableObject& source) {
6893
7593
  if (this == &source) return *this;
6894
7594
  invoke = source.invoke;
7595
+ record = source.record;
6895
7596
  environment = source.environment;
6896
7597
  environmentOwner = source.environmentOwner;
6897
7598
  functionObject = source.functionObject;
@@ -6900,6 +7601,7 @@ struct CallableObject<Result(Arguments...)> {
6900
7601
  }
6901
7602
  [[gnu::always_inline]] CallableObject& operator=(CallableObject&& source) noexcept {
6902
7603
  invoke = source.invoke;
7604
+ record = source.record;
6903
7605
  environment = source.environment;
6904
7606
  environmentOwner = std::move(source.environmentOwner);
6905
7607
  functionObject = std::move(source.functionObject);
@@ -7004,7 +7706,7 @@ struct CallableObject<Result(Arguments...)> {
7004
7706
  * carry their environments.
7005
7707
  */
7006
7708
  template <typename Source, typename = std::enable_if_t<std::is_same_v<Source, CallableObject<Result()>> && sizeof...(Arguments) != 0>>
7007
- CallableObject(const Source& source) : CallableObject(&dropArguments, packEnvironment(source)) {
7709
+ CallableObject(const Source& source) : CallableObject(recorded<&dropArguments>(), packEnvironment(source)) {
7008
7710
  shareFunctionObject(source);
7009
7711
  registerSourceAdapter<&dropArguments, Source>();
7010
7712
  registerReceiverEntry<&dropArguments, &dropArgumentsWithReceiver>();
@@ -7031,7 +7733,7 @@ struct CallableObject<Result(Arguments...)> {
7031
7733
  static CallableObject unboundMethod(const CallableObject<Result(Ref<Held>, Arguments...)>& source) {
7032
7734
  using Source = CallableObject<Result(Ref<Held>, Arguments...)>;
7033
7735
  source.identified();
7034
- CallableObject value{&callUnboundMethod<Held>, packEnvironment(source)};
7736
+ CallableObject value{recorded<&callUnboundMethod<Held>>(), packEnvironment(source)};
7035
7737
  value.shareFunctionObject(source);
7036
7738
  registerSourceAdapter<&callUnboundMethod<Held>, Source>();
7037
7739
  registerArgumentFrameAdapter<&callUnboundMethod<Held>, Source, 1>();
@@ -7057,7 +7759,7 @@ struct CallableObject<Result(Arguments...)> {
7057
7759
  using Source = CallableObject<Result(Receiver, Arguments...)>;
7058
7760
  static_assert(std::is_empty_v<Resolver>, "native receiver resolution must not capture the object read");
7059
7761
  source.identified();
7060
- CallableObject value{&callUnboundMethodAs<Receiver, Resolver>, packEnvironment(source)};
7762
+ CallableObject value{recorded<&callUnboundMethodAs<Receiver, Resolver>>(), packEnvironment(source)};
7061
7763
  value.shareFunctionObject(source);
7062
7764
  registerSourceAdapter<&callUnboundMethodAs<Receiver, Resolver>, Source>();
7063
7765
  registerArgumentFrameAdapter<&callUnboundMethodAs<Receiver, Resolver>, Source, 1>();
@@ -7100,7 +7802,7 @@ struct CallableObject<Result(Arguments...)> {
7100
7802
  template <typename Receiver>
7101
7803
  static CallableObject bindReceiver(const CallableObject<Result(Receiver, Arguments...)>& source, Receiver receiver) {
7102
7804
  using Bound = BoundReceiver<Receiver>;
7103
- CallableObject bound{&callBoundReceiver<Receiver>, packEnvironment(Bound{source, std::move(receiver)})};
7805
+ CallableObject bound{recorded<&callBoundReceiver<Receiver>>(), packEnvironment(Bound{source, std::move(receiver)})};
7104
7806
  bound.shareFunctionObject(source);
7105
7807
  registerSourceAdapter<&callBoundReceiver<Receiver>, Bound>();
7106
7808
  return bound;
@@ -7149,7 +7851,7 @@ struct CallableObject<Result(Arguments...)> {
7149
7851
  template <typename Held>
7150
7852
  static CallableObject bindHolder(const CallableObject<Result(Ref<Held>, Arguments...)>& source, const Ref<Held>& holder) {
7151
7853
  using Bound = HolderReceiver<Held>;
7152
- CallableObject bound{&callHolder<Held>, packEnvironment(Bound{source, WeakRef<Held>(holder)})};
7854
+ CallableObject bound{recorded<&callHolder<Held>>(), packEnvironment(Bound{source, WeakRef<Held>(holder)})};
7153
7855
  bound.shareFunctionObject(source);
7154
7856
  registerSourceAdapter<&callHolder<Held>, Bound>();
7155
7857
  return bound;
@@ -7189,11 +7891,12 @@ struct CallableObject<Result(Arguments...)> {
7189
7891
 
7190
7892
  template <auto Known, typename Source, typename Held>
7191
7893
  static CallableObject bindHolderInPlace(const Source& source, const Ref<Held>& holder) {
7192
- static const SourceRegistration registration{&callOwnedHolder<Known, Held>, {}, 0, {}, +[](void*) -> CallableFacts {
7193
- const auto own = Source::factsFor(Known, nullptr);
7894
+ static const bool published = (recordOf<&callOwnedHolder<Known, Held>>.resolveFacts = +[](void*) -> CallableFacts {
7895
+ const auto own = Source::factsFor(&Source::template recordOf<Known>, nullptr);
7194
7896
  return CallableFacts{own.name, own.text, own.length};
7195
- }};
7196
- CallableObject bound{&callOwnedHolder<Known, Held>, packTransientEnvironment(HolderEnvironment<Held>{holder})};
7897
+ }, true);
7898
+ (void)published;
7899
+ CallableObject bound{recorded<&callOwnedHolder<Known, Held>>(), packTransientEnvironment(HolderEnvironment<Held>{holder})};
7197
7900
  bound.shareFunctionObject(source);
7198
7901
  return bound;
7199
7902
  }
@@ -7255,7 +7958,7 @@ struct CallableObject<Result(Arguments...)> {
7255
7958
  sizeof...(SourceArguments) < sizeof...(Arguments) &&
7256
7959
  IsTypePrefix<std::tuple<SourceArguments...>, std::tuple<Arguments...>>::value>>
7257
7960
  CallableObject(const CallableObject<SourceResult(SourceArguments...)>& source)
7258
- : CallableObject(&dropTrailingArguments<SourceResult, SourceArguments...>, packEnvironment(source)) {
7961
+ : CallableObject(recorded<&dropTrailingArguments<SourceResult, SourceArguments...>>(), packEnvironment(source)) {
7259
7962
  shareFunctionObject(source);
7260
7963
  registerSourceAdapter<&dropTrailingArguments<SourceResult, SourceArguments...>, CallableObject<SourceResult(SourceArguments...)>>();
7261
7964
  registerReceiverEntry<&dropTrailingArguments<SourceResult, SourceArguments...>, &dropTrailingArgumentsWithReceiver<SourceResult, SourceArguments...>>();
@@ -7318,7 +8021,7 @@ struct CallableObject<Result(Arguments...)> {
7318
8021
  RestRebaseAdmits<std::tuple<Arguments...>, std::tuple<SourceArguments...>>::value>,
7319
8022
  typename = void>
7320
8023
  CallableObject(const CallableObject<SourceResult(SourceArguments...)>& source)
7321
- : CallableObject(&spreadRestOverLeading<SourceResult, SourceArguments...>, packEnvironment(source)) {
8024
+ : CallableObject(recorded<&spreadRestOverLeading<SourceResult, SourceArguments...>>(), packEnvironment(source)) {
7322
8025
  shareFunctionObject(source);
7323
8026
  registerSourceAdapter<&spreadRestOverLeading<SourceResult, SourceArguments...>, CallableObject<SourceResult(SourceArguments...)>>();
7324
8027
  registerReceiverEntry<&spreadRestOverLeading<SourceResult, SourceArguments...>, &spreadRestOverLeadingWithReceiver<SourceResult, SourceArguments...>>();
@@ -7484,7 +8187,7 @@ struct CallableObject<Result(Arguments...)> {
7484
8187
  typename = std::enable_if_t<std::is_void_v<Result> && !std::is_void_v<SourceResult> && sizeof...(Arguments) != 0>,
7485
8188
  typename = void>
7486
8189
  CallableObject(const CallableObject<SourceResult(Arguments...)>& source)
7487
- : CallableObject(&discardResult<SourceResult>, packEnvironment(source)) {
8190
+ : CallableObject(recorded<&discardResult<SourceResult>>(), packEnvironment(source)) {
7488
8191
  shareFunctionObject(source);
7489
8192
  registerSourceAdapter<&discardResult<SourceResult>, CallableObject<SourceResult(Arguments...)>>();
7490
8193
  registerArgumentFrameAdapter<&discardResult<SourceResult>, CallableObject<SourceResult(Arguments...)>>();
@@ -7524,7 +8227,7 @@ struct CallableObject<Result(Arguments...)> {
7524
8227
  typename = std::enable_if_t<sizeof...(Arguments) != 0 && !std::is_same_v<SourceResult, Result> &&
7525
8228
  ResultWidensIntoArm<SourceResult, Result>::value>>
7526
8229
  CallableObject(const CallableObject<SourceResult()>& source)
7527
- : CallableObject(&dropArgumentsIntoArm<SourceResult>, packEnvironment(source)) {
8230
+ : CallableObject(recorded<&dropArgumentsIntoArm<SourceResult>>(), packEnvironment(source)) {
7528
8231
  shareFunctionObject(source);
7529
8232
  registerSourceAdapter<&dropArgumentsIntoArm<SourceResult>, CallableObject<SourceResult()>>();
7530
8233
  registerReceiverEntry<&dropArgumentsIntoArm<SourceResult>, &dropArgumentsIntoArmWithReceiver<SourceResult>>();
@@ -7587,7 +8290,7 @@ struct CallableObject<Result(Arguments...)> {
7587
8290
  ResultWidensIntoArm<SourceResult, Result>::value>,
7588
8291
  typename = void, typename = void>
7589
8292
  CallableObject(const CallableObject<SourceResult(Arguments...)>& source)
7590
- : CallableObject(&widenResultIntoArm<SourceResult>, packEnvironment(source)) {
8293
+ : CallableObject(recorded<&widenResultIntoArm<SourceResult>>(), packEnvironment(source)) {
7591
8294
  shareFunctionObject(source);
7592
8295
  registerSourceAdapter<&widenResultIntoArm<SourceResult>, CallableObject<SourceResult(Arguments...)>>();
7593
8296
  registerArgumentFrameAdapter<&widenResultIntoArm<SourceResult>, CallableObject<SourceResult(Arguments...)>>();
@@ -7615,8 +8318,25 @@ struct CallableObject<Result(Arguments...)> {
7615
8318
  Result callWithReceiver(const NativeCallReceiver& receiver, Arguments... arguments) const {
7616
8319
  requireCallable();
7617
8320
  const auto keepAlive = environmentOwner;
7618
- for (auto* entry = receiverRegistrations().load(std::memory_order_acquire); entry; entry = entry->next)
7619
- if (entry->entry == invoke) return entry->withReceiver(environment, receiver, std::forward<Arguments>(arguments)...);
8321
+ if (record != nullptr && record->withReceiver != nullptr)
8322
+ return record->withReceiver(environment, receiver, std::forward<Arguments>(arguments)...);
8323
+ return invoke(environment, std::forward<Arguments>(arguments)...);
8324
+ }
8325
+ /**
8326
+ * `callWithReceiver` with the receiver built on demand: only a target that
8327
+ * registered a receiver entry (a method view) reads logical `this`, and every
8328
+ * other target ignores it. three's `depthBuffer.setTest(...)`-style calls on
8329
+ * a state object's function fields built a receiver per call -- a handle
8330
+ * retain and two releases -- for closures that never look at it. The caller
8331
+ * passes a builder only when the receiver is a value it already holds, so
8332
+ * building it later or not at all evaluates nothing the program would see.
8333
+ */
8334
+ template <typename MakeReceiver>
8335
+ Result callWithLazyReceiver(const MakeReceiver& make, Arguments... arguments) const {
8336
+ requireCallable();
8337
+ const auto keepAlive = environmentOwner;
8338
+ if (record != nullptr && record->withReceiver != nullptr)
8339
+ return record->withReceiver(environment, make(), std::forward<Arguments>(arguments)...);
7620
8340
  return invoke(environment, std::forward<Arguments>(arguments)...);
7621
8341
  }
7622
8342
 
@@ -7647,6 +8367,14 @@ struct CallableObject<Result(Arguments...)> {
7647
8367
  // A runtime identity guard exposes one target to the native inliner without
7648
8368
  // assuming a mutable callable field still holds its initializer. Keeping the
7649
8369
  // ordinary frame and environment root preserves replacement and re-entry.
8370
+ //
8371
+ // The one comparison of entry addresses left in this header, and folding
8372
+ // cannot make it wrong: it only chooses between calling `invoke` and calling
8373
+ // `Known` (or the body `Borrowed` that `Known` forwards to), and when a
8374
+ // linker folded `invoke`'s function into `Known`'s, the two have identical
8375
+ // code -- recursively, to every callee, which is what lets the linker fold
8376
+ // them -- so either branch computes the same thing. Nothing about the VALUE
8377
+ // (its receiver entry, frame or facts) is decided here; those are `record`'s.
7650
8378
  template <auto Known>
7651
8379
  [[gnu::always_inline]] Result callKnown(Arguments... arguments) const {
7652
8380
  requireCallable();
@@ -7927,7 +8655,12 @@ struct CallableConstructorObject<Result(Arguments...), Constructed(ConstructArgu
7927
8655
  using Invoke = Result (*)(void*, Arguments...);
7928
8656
  using Construct = Constructed (*)(void*, ConstructArguments...);
7929
8657
 
8658
+ using CallableView = CallableObject<Result(Arguments...)>;
8659
+ using RecordedEntry = typename CallableView::RecordedEntry;
8660
+
7930
8661
  Invoke invoke = nullptr;
8662
+ /** The `[[Call]]` entry's record, as `CallableObject::record`. */
8663
+ const typename CallableView::EntryRecord* record = nullptr;
7931
8664
  Construct construct_ = nullptr;
7932
8665
  void* environment = nullptr;
7933
8666
  Ref<void> environmentOwner;
@@ -7938,16 +8671,22 @@ struct CallableConstructorObject<Result(Arguments...), Constructed(ConstructArgu
7938
8671
  : invoke(invoke_), construct_(construct__), environment(environment_) {}
7939
8672
  CallableConstructorObject(Invoke invoke_, Construct construct__, PackedEnvironment packed)
7940
8673
  : invoke(invoke_), construct_(construct__), environment(packed.pointer), environmentOwner(std::move(packed.owner)) {}
8674
+ CallableConstructorObject(RecordedEntry entry_, Construct construct__, void* environment_)
8675
+ : invoke(entry_.invoke), record(entry_.record), construct_(construct__), environment(environment_) {}
8676
+ CallableConstructorObject(RecordedEntry entry_, Construct construct__, PackedEnvironment packed)
8677
+ : invoke(entry_.invoke), record(entry_.record), construct_(construct__), environment(packed.pointer),
8678
+ environmentOwner(std::move(packed.owner)) {}
7941
8679
  // Shares, never mints, and forced inline -- see `CallableObject`'s copy constructor for both.
7942
8680
  [[gnu::always_inline]] CallableConstructorObject(const CallableConstructorObject& source)
7943
- : invoke(source.invoke), construct_(source.construct_), environment(source.environment), environmentOwner(source.environmentOwner),
7944
- functionObject(source.functionObject) {}
8681
+ : invoke(source.invoke), record(source.record), construct_(source.construct_), environment(source.environment),
8682
+ environmentOwner(source.environmentOwner), functionObject(source.functionObject) {}
7945
8683
  [[gnu::always_inline]] CallableConstructorObject(CallableConstructorObject&& source) noexcept
7946
- : invoke(source.invoke), construct_(source.construct_), environment(source.environment),
8684
+ : invoke(source.invoke), record(source.record), construct_(source.construct_), environment(source.environment),
7947
8685
  environmentOwner(std::move(source.environmentOwner)), functionObject(std::move(source.functionObject)) {}
7948
8686
  [[gnu::always_inline]] CallableConstructorObject& operator=(const CallableConstructorObject& source) {
7949
8687
  if (this == &source) return *this;
7950
8688
  invoke = source.invoke;
8689
+ record = source.record;
7951
8690
  construct_ = source.construct_;
7952
8691
  environment = source.environment;
7953
8692
  environmentOwner = source.environmentOwner;
@@ -7956,6 +8695,7 @@ struct CallableConstructorObject<Result(Arguments...), Constructed(ConstructArgu
7956
8695
  }
7957
8696
  [[gnu::always_inline]] CallableConstructorObject& operator=(CallableConstructorObject&& source) noexcept {
7958
8697
  invoke = source.invoke;
8698
+ record = source.record;
7959
8699
  construct_ = source.construct_;
7960
8700
  environment = source.environment;
7961
8701
  environmentOwner = std::move(source.environmentOwner);
@@ -7976,9 +8716,8 @@ struct CallableConstructorObject<Result(Arguments...), Constructed(ConstructArgu
7976
8716
  }
7977
8717
 
7978
8718
  static constexpr std::size_t physicalArgumentCount = sizeof...(Arguments);
7979
- using CallableView = CallableObject<Result(Arguments...)>;
7980
- NativeCallableFrame argumentFrame() const { return CallableView::argumentFrameFor(invoke, environment); }
7981
- typename CallableView::CallableFacts facts() const { return CallableView::factsFor(invoke, environment); }
8719
+ NativeCallableFrame argumentFrame() const { return CallableView::argumentFrameFor(record, environment); }
8720
+ typename CallableView::CallableFacts facts() const { return CallableView::factsFor(record, environment); }
7982
8721
  std::string_view sourceText() const { return facts().text; }
7983
8722
  std::string_view name() const { return facts().name; }
7984
8723
  std::size_t length() const { return facts().length; }
@@ -7988,7 +8727,7 @@ struct CallableConstructorObject<Result(Arguments...), Constructed(ConstructArgu
7988
8727
  }
7989
8728
 
7990
8729
  Result callWithReceiver(const NativeCallReceiver& receiver, Arguments... arguments) const {
7991
- return CallableView{invoke, PackedEnvironment{environment, environmentOwner, nullptr}}.callWithReceiver(
8730
+ return CallableView{RecordedEntry{invoke, record}, PackedEnvironment{environment, environmentOwner, nullptr}}.callWithReceiver(
7992
8731
  receiver, std::forward<Arguments>(arguments)...);
7993
8732
  }
7994
8733
 
@@ -8060,36 +8799,8 @@ namespace detail {
8060
8799
  /** Defined with the other construction failures below; declared here because the widening above it is where the entry can be missing. */
8061
8800
  [[noreturn]] inline void failUnconstructableFunction(const char* function_, const char* why);
8062
8801
 
8063
- /** One program-wide address per emitted `[[Construct]]` CONVENTION, so a lookup cannot return an entry of a different signature. */
8064
- template <typename Construct>
8065
- struct ConstructEntryTag {
8066
- static constexpr char id = 0;
8067
- };
8068
-
8069
- inline std::map<std::pair<void*, const void*>, void*>& constructEntryTable() {
8070
- using Table = std::map<std::pair<void*, const void*>, void*>;
8071
- GEA_REALM_LOCAL(Table, table, {});
8072
- return table;
8073
- }
8074
8802
  } // namespace detail
8075
8803
 
8076
- /**
8077
- * A declaration's `[[Construct]]` entry, published beside its `[[Call]]` one.
8078
- *
8079
- * Emitted next to the construct thunk (`translation-unit.ts`), keyed by the
8080
- * INVOKE pointer -- the one thing a function object carries that names its
8081
- * declaration -- exactly as `CallableObject::registerSource` publishes the
8082
- * `name`/`length`/source text of that same declaration against the same key.
8083
- * The signature's own tag is part of the key so a lookup asking for a
8084
- * different construct convention finds nothing rather than a bad cast.
8085
- */
8086
- template <typename Invoke, typename Construct>
8087
- inline bool registerConstructEntry(Invoke invoke, Construct construct) {
8088
- detail::constructEntryTable()[{reinterpret_cast<void*>(invoke), &detail::ConstructEntryTag<Construct>::id}] =
8089
- reinterpret_cast<void*>(construct);
8090
- return true;
8091
- }
8092
-
8093
8804
  /**
8094
8805
  * The [[Construct]] entry added to a function object that already exists.
8095
8806
  *
@@ -8102,27 +8813,34 @@ inline bool registerConstructEntry(Invoke invoke, Construct construct) {
8102
8813
  * owner and, above all, its `FunctionObjectIdentity`, so the two views share
8103
8814
  * ONE own-property table and `f === g` is true of them.
8104
8815
  *
8105
- * The construct pointer cannot come from the source value: `CallableObject`
8106
- * stores one entry, and 10.2.2's "create the object, then enter the body with
8107
- * it" is a different convention from `[[Call]]` at both ends. It is looked up
8108
- * by the source's own invoke pointer, so nothing here has to decide WHICH
8109
- * declaration a cell holds -- the value says. A function whose declaration
8110
- * published no construct entry of this signature refuses by name; it never
8111
- * constructs through some other declaration's body.
8816
+ * The construct pointer cannot come from the source value's entry:
8817
+ * `CallableObject` stores one, and 10.2.2's "create the object, then enter the
8818
+ * body with it" is a different convention from `[[Call]]` at both ends. It is
8819
+ * read from the source's own entry record (`entryWithConstruct` published it at
8820
+ * the mint), so nothing here has to decide WHICH declaration a cell holds --
8821
+ * the value says. A function whose declaration published no construct entry of
8822
+ * this signature refuses by name; it never constructs through some other
8823
+ * declaration's body.
8112
8824
  */
8113
8825
  template <typename Constructor, typename Callable>
8114
8826
  inline Constructor withConstructEntry(const Callable& source) {
8115
- const auto& table = detail::constructEntryTable();
8116
- // The entry is published against the declaration's thunk; a value minted
8117
- // with an argument frame carries the frame's forwarding wrapper instead.
8118
- auto invoke = source.invoke;
8119
- if constexpr (requires { Callable::declarationEntryOf(source.invoke); }) invoke = Callable::declarationEntryOf(source.invoke);
8120
- const auto found = table.find({reinterpret_cast<void*>(invoke), &detail::ConstructEntryTag<typename Constructor::Construct>::id});
8121
- if (found == table.end()) {
8827
+ void* found = nullptr;
8828
+ // The entry is published in the declaration's record; a value minted with
8829
+ // an argument frame carries the frame's forwarding wrapper's instead.
8830
+ if constexpr (requires { Callable::declarationRecordOf(source.record); }) {
8831
+ if (const auto* record = Callable::declarationRecordOf(source.record))
8832
+ for (auto* node = record->constructs.load(std::memory_order_acquire); node != nullptr; node = node->next)
8833
+ if (node->convention == &detail::ConstructEntryTag<typename Constructor::Construct>::id) {
8834
+ found = node->construct;
8835
+ break;
8836
+ }
8837
+ }
8838
+ if (found == nullptr) {
8122
8839
  detail::failUnconstructableFunction("an asserted construct signature",
8123
8840
  "the function object's declaration published no [[Construct]] entry of that convention");
8124
8841
  }
8125
- Constructor widened{source.invoke, reinterpret_cast<typename Constructor::Construct>(found->second), source.environment};
8842
+ Constructor widened{source.invoke, reinterpret_cast<typename Constructor::Construct>(found), source.environment};
8843
+ widened.record = source.record;
8126
8844
  widened.environmentOwner = source.environmentOwner;
8127
8845
  widened.functionObject = source.functionObject;
8128
8846
  return widened;
@@ -8313,7 +9031,8 @@ struct ArrayExtension {
8313
9031
 
8314
9032
  template <typename Fields>
8315
9033
  inline const void* arrayExtensionTagOf() {
8316
- static const char tag = 0;
9034
+ // Mutable: its address is the extension's identity (see `PayloadTypeTag`).
9035
+ static char tag = 0;
8317
9036
  return &tag;
8318
9037
  }
8319
9038
 
@@ -9231,12 +9950,48 @@ struct ArrayObject {
9231
9950
  return at(static_cast<size_t>(index));
9232
9951
  }
9233
9952
 
9234
- Element readElementAt(double key) const {
9953
+ // `readElementAtIndex`'s dense case for a double key: ordinary storage, an
9954
+ // integral in-range key (-0 included) and no hole or undefined bookkeeping
9955
+ // answer the cell inline; every other key takes the checked path unchanged.
9956
+ [[gnu::always_inline]] Element readElementAt(double key) const {
9957
+ if (!liveSource && !indexedDescriptors && holes.empty() && undefineds.empty() && key >= 0 &&
9958
+ key < static_cast<double>(cells.size())) [[likely]] {
9959
+ const auto index = static_cast<std::size_t>(key);
9960
+ if (static_cast<double>(index) == key) [[likely]] return cells[index].value;
9961
+ }
9962
+ return readElementAtChecked(key);
9963
+ }
9964
+ [[gnu::noinline]] Element readElementAtChecked(double key) const {
9235
9965
  const std::size_t index = requireIndex(key);
9236
9966
  if (index >= size() || !present(index)) detail::failAbsentElement(key, size());
9237
9967
  if (elementIsUndefined(index)) detail::failUndefinedElement();
9968
+ if (index + 1 == size()) dropSpentFlags();
9238
9969
  return readElement(index);
9239
9970
  }
9971
+ /**
9972
+ * Flags vectors that no longer flag anything. `new Array(n)` (or a `length`
9973
+ * growth, or one undefined store) opens a holes/undefineds vector, and filling
9974
+ * every slot afterwards only zeroes it: the vector itself stays, so every later
9975
+ * read of the array misses the dense fast path for the array's whole life --
9976
+ * three's uniform caches are read this way every draw. A checked read of the
9977
+ * LAST element (a scan reaching its end) drops a vector that is all zero, which
9978
+ * is exactly the state an empty vector states, so each scan pays at most one
9979
+ * pass over the flags. A read inside a parallel region leaves them alone: other
9980
+ * tasks may be reading the same array.
9981
+ */
9982
+ void dropSpentFlags() const {
9983
+ #if defined(GEA_RUNTIME_PARALLEL) && GEA_RUNTIME_PARALLEL
9984
+ if (detail::parallel::activeRegion != nullptr) return;
9985
+ #endif
9986
+ if (liveSource) return;
9987
+ auto* self = const_cast<ArrayObject*>(this);
9988
+ const auto spent = [](const std::vector<std::uint8_t>& flags) {
9989
+ for (const std::uint8_t flag : flags) if (flag != 0) return false;
9990
+ return true;
9991
+ };
9992
+ if (!self->holes.empty() && spent(self->holes)) self->holes.clear();
9993
+ if (!self->undefineds.empty() && spent(self->undefineds)) self->undefineds.clear();
9994
+ }
9240
9995
  // `elementAtIndex`'s dense case first: ordinary storage, in range, no hole or
9241
9996
  // undefined bookkeeping answers the cell after one unsigned compare, so an
9242
9997
  // integer-keyed read keeps the shape the borrowed accessor had.
@@ -9250,6 +10005,7 @@ struct ArrayObject {
9250
10005
  if (index < 0 || static_cast<unsigned long long>(index) >= size() || !present(static_cast<std::size_t>(index)))
9251
10006
  detail::failAbsentElement(static_cast<double>(index), size());
9252
10007
  if (elementIsUndefined(static_cast<std::size_t>(index))) detail::failUndefinedElement();
10008
+ if (static_cast<std::size_t>(index) + 1 == size()) dropSpentFlags();
9253
10009
  return readElement(static_cast<std::size_t>(index));
9254
10010
  }
9255
10011
  void setUndefinedElement(std::size_t index) {
@@ -9575,6 +10331,31 @@ struct ArrayObject {
9575
10331
  }
9576
10332
  }
9577
10333
 
10334
+ /**
10335
+ * `appendRangeConverted` over a source array the caller CONSUMES (a fresh
10336
+ * factory result, a local returned as its last use): each element is moved
10337
+ * out of its cell before it is converted, so one only the source held
10338
+ * reaches `convert` with no other holder -- `gea::emptyArraySentinel`'s
10339
+ * unshared test then makes an inner `[]` its own fresh array, as in JS. A
10340
+ * source with live or descriptor storage is read as `appendRangeConverted`
10341
+ * reads it; nothing reads the consumed source afterwards either way.
10342
+ */
10343
+ template <class Other, class Convert>
10344
+ void appendRangeConvertedReleasing(ArrayObject<Other>& other, std::size_t from, Convert&& convert) {
10345
+ if (!other.hasOrdinaryDenseStorage()) {
10346
+ appendRangeConverted(other, from, std::forward<Convert>(convert));
10347
+ return;
10348
+ }
10349
+ for (std::size_t index = from; index < other.size(); ++index) {
10350
+ if (!other.present(index)) {
10351
+ pushHole();
10352
+ continue;
10353
+ }
10354
+ const Other released = std::move(other.cells[index].value);
10355
+ push(convert(released));
10356
+ }
10357
+ }
10358
+
9578
10359
  /** `Array.prototype.unshift`'s own bulk write, ECMA-262 23.1.3.31 steps 3-8: every element of `other` from index `from` onward, inserted in order AHEAD of this array's existing elements -- `appendRange`'s own hole-preserving contract, at the opposite end. */
9579
10360
  void prependRange(const ArrayObject<Element>& other, size_t from) {
9580
10361
  insertRange(0, other, from);
@@ -9763,6 +10544,25 @@ inline const gea::Ref<ArrayObject<Element>>& emptyArraySentinel() {
9763
10544
 
9764
10545
  class Value;
9765
10546
 
10547
+ // Only a never[] that something else also holds has an identity a program can
10548
+ // observe (tsc's shared `emptyArray`, compared with `===`). An inner `[]` an
10549
+ // unshared rebuild moved out of the array it CONSUMES
10550
+ // (`appendRangeConvertedReleasing`, `Array.from({length}, () => [])`) that
10551
+ // nothing else holds is a fresh array, and in JS every such `[]` is its own:
10552
+ // handing them all the one sentinel would make later pushes land in a single
10553
+ // array shared by every row. Only that rebuild passes `consumedSource`; any
10554
+ // other read -- a binding, even one the emitter spells as its literal
10555
+ // initializer -- keeps the sentinel, so the program's `=== emptyArray` holds.
10556
+ struct ConsumedSource {};
10557
+ inline constexpr ConsumedSource consumedSource{};
10558
+
10559
+ namespace detail {
10560
+ template <typename Source>
10561
+ inline bool consumedEmptyArrayIsUnshared(const gea::Ref<ArrayObject<Source>>& source) {
10562
+ return detail::refCountsOf(source.get())->strong <= 1;
10563
+ }
10564
+ } // namespace detail
10565
+
9766
10566
  template <typename Element, typename Source>
9767
10567
  inline gea::Ref<ArrayObject<Element>> emptyArraySentinel(const gea::Ref<ArrayObject<Source>>& source) {
9768
10568
  // `bigint_detail::fail` is the one thrower declared this early (beside
@@ -9771,13 +10571,52 @@ inline gea::Ref<ArrayObject<Element>> emptyArraySentinel(const gea::Ref<ArrayObj
9771
10571
  return emptyArraySentinel<Element>();
9772
10572
  }
9773
10573
 
10574
+ /** A consumed `never[]` (see above): its own fresh array when nothing else holds it. */
10575
+ template <typename Element, typename Source>
10576
+ inline gea::Ref<ArrayObject<Element>> emptyArraySentinel(const gea::Ref<ArrayObject<Source>>& source, ConsumedSource) {
10577
+ if (source && source->length() != 0) bigint_detail::fail("TypeError", "a never[] value holds elements; its static type lied");
10578
+ if (source && detail::consumedEmptyArrayIsUnshared(source)) return makeRef<ArrayObject<Element>>();
10579
+ return emptyArraySentinel<Element>();
10580
+ }
10581
+
10582
+ /**
10583
+ * `never[]` (or a real `undefined[]`) into `E[]` whose element carrier holds
10584
+ * `undefined` natively (a shared class or record reference): the carrier
10585
+ * cannot tell the two sources apart, exactly as for `any[]`
10586
+ * (`emptyArraySentinelOrBoxed` below), so the answer is decided the same way.
10587
+ * Empty is the sentinel -- or, consumed and held by nothing else, a fresh
10588
+ * array. Populated is a real `undefined[]`, whose every present slot is
10589
+ * `undefined` in `E` too.
10590
+ */
10591
+ template <typename Element, typename Source>
10592
+ inline gea::Ref<ArrayObject<Element>> emptyArraySentinelOrAbsent(const gea::Ref<ArrayObject<Source>>& source, bool consumed = false) {
10593
+ if (!source) return emptyArraySentinel<Element>();
10594
+ if (source->length() == 0)
10595
+ return consumed && detail::consumedEmptyArrayIsUnshared(source) ? makeRef<ArrayObject<Element>>() : emptyArraySentinel<Element>();
10596
+ auto converted = makeRef<ArrayObject<Element>>();
10597
+ converted->reserve(static_cast<std::size_t>(source->length()));
10598
+ for (const auto& slot : source->slots()) {
10599
+ if (slot.present) converted->push(Element::undefined());
10600
+ else converted->pushHole();
10601
+ }
10602
+ return converted;
10603
+ }
10604
+
10605
+ template <typename Element, typename Source>
10606
+ inline gea::Ref<ArrayObject<Element>> emptyArraySentinelOrAbsent(const gea::Ref<ArrayObject<Source>>& source, ConsumedSource) {
10607
+ return emptyArraySentinelOrAbsent<Element>(source, true);
10608
+ }
10609
+
9774
10610
  /** `never[]` (or a real `undefined[]`) into `any[]`: the sentinel when empty, a boxed copy otherwise. */
9775
10611
  // `Boxed` is only ever `Value`; it is a parameter so the return type stays
9776
10612
  // dependent and `ArrayObject<Value>` is instantiated at the use, where `Value`
9777
10613
  // is complete, rather than here, where it is only declared.
9778
10614
  template <typename Source, typename Boxed = Value>
9779
- inline gea::Ref<ArrayObject<Boxed>> emptyArraySentinelOrBoxed(const gea::Ref<ArrayObject<Source>>& source) {
9780
- if (!source || source->length() == 0) return emptyArraySentinel<Boxed>();
10615
+ inline gea::Ref<ArrayObject<Boxed>> emptyArraySentinelOrBoxed(const gea::Ref<ArrayObject<Source>>& source, bool consumed = false) {
10616
+ if (!source) return emptyArraySentinel<Boxed>();
10617
+ // A consumed, unshared `[]` gets its own array, as in `emptyArraySentinel` above.
10618
+ if (source->length() == 0)
10619
+ return consumed && detail::consumedEmptyArrayIsUnshared(source) ? makeRef<ArrayObject<Boxed>>() : emptyArraySentinel<Boxed>();
9781
10620
  auto boxed = makeRef<ArrayObject<Boxed>>();
9782
10621
  boxed->reserve(static_cast<std::size_t>(source->length()));
9783
10622
  // `Value()` is `undefined`; a populated `never[]`/`undefined[]` source
@@ -9789,6 +10628,11 @@ inline gea::Ref<ArrayObject<Boxed>> emptyArraySentinelOrBoxed(const gea::Ref<Arr
9789
10628
  return boxed;
9790
10629
  }
9791
10630
 
10631
+ template <typename Source, typename Boxed = Value>
10632
+ inline gea::Ref<ArrayObject<Boxed>> emptyArraySentinelOrBoxed(const gea::Ref<ArrayObject<Source>>& source, ConsumedSource) {
10633
+ return emptyArraySentinelOrBoxed<Source, Boxed>(source, true);
10634
+ }
10635
+
9792
10636
  namespace detail {
9793
10637
  /**
9794
10638
  * A JS array, presented to a host that takes a contiguous one.
@@ -11886,7 +12730,12 @@ class Optional {
11886
12730
  Optional(U&& value) : state_(State::Present) { new (static_cast<void*>(&value_)) T(T(std::forward<U>(value))); }
11887
12731
 
11888
12732
  Optional& operator=(const Optional&) requires std::is_trivially_copy_assignable_v<T> = default;
11889
- Optional& operator=(const Optional& other) requires (!std::is_trivially_copy_assignable_v<T>) {
12733
+ // Keep the trivial special member, but give the nontrivial implementation
12734
+ // a distinct template identity: prebuilt Clang PCH codegen may emit both
12735
+ // constrained non-template definitions with the same ABI name.
12736
+ template <typename Payload = T>
12737
+ requires (std::is_same_v<Payload, T> && !std::is_trivially_copy_assignable_v<T>)
12738
+ Optional& operator=(const Optional& other) {
11890
12739
  if (this == &other) return *this;
11891
12740
  if (other.constructed()) {
11892
12741
  if (constructed()) detail::assignCopy<T>(value_, other.value_);
@@ -11896,9 +12745,9 @@ class Optional {
11896
12745
  return *this;
11897
12746
  }
11898
12747
  Optional& operator=(Optional&&) requires std::is_trivially_move_assignable_v<T> = default;
11899
- Optional& operator=(Optional&& other) noexcept(std::is_nothrow_move_constructible_v<T> && std::is_nothrow_move_assignable_v<T>)
11900
- requires (!std::is_trivially_move_assignable_v<T>)
11901
- {
12748
+ template <typename Payload = T>
12749
+ requires (std::is_same_v<Payload, T> && !std::is_trivially_move_assignable_v<T>)
12750
+ Optional& operator=(Optional&& other) noexcept(std::is_nothrow_move_constructible_v<T> && std::is_nothrow_move_assignable_v<T>) {
11902
12751
  if (this == &other) return *this;
11903
12752
  if (other.constructed()) {
11904
12753
  if (constructed()) value_ = std::move(other.value_);
@@ -12447,35 +13296,41 @@ struct DefaultUnionArmIndex {
12447
13296
  }();
12448
13297
  };
12449
13298
 
12450
- /** Lifetime dispatch over a closed arm set, by index: a raw byte buffer holds whichever arm is live, so construct/copy/move/destroy need a hand-written vtable-by-recursion in place of what the language generates for a real union of non-trivial arms. */
13299
+ /**
13300
+ * Lifetime dispatch over a closed arm set, by index: a raw byte buffer holds whichever arm is live, so construct/copy/move/destroy need a hand-written vtable in place of what the language generates for a real union of non-trivial arms.
13301
+ *
13302
+ * One flat fold per operation, not a recursion that peels an arm per level: the recursive form was a chain of real calls
13303
+ * (each level its own function, past the inliner's depth), so destroying arm 20 of a uniform-value union walked twenty frames.
13304
+ * The fold is a single compare sequence in one body, which the optimizer turns into a switch. An index past the last arm
13305
+ * matches nothing and does nothing, as the empty recursion base did.
13306
+ */
12451
13307
  template <typename... Arms>
12452
- struct TaggedUnionOps;
12453
-
12454
- template <>
12455
- struct TaggedUnionOps<> {
12456
- static void destroy(std::size_t, void*) {}
12457
- static void copyConstruct(std::size_t, void*, const void*) {}
12458
- static void moveConstruct(std::size_t, void*, void*) {}
12459
- static void defaultConstruct(std::size_t, void*) {}
12460
- };
12461
-
12462
- template <typename Head, typename... Tail>
12463
- struct TaggedUnionOps<Head, Tail...> {
12464
- static void destroy(std::size_t index, void* storage) {
12465
- if (index == 0) static_cast<Head*>(storage)->~Head();
12466
- else TaggedUnionOps<Tail...>::destroy(index - 1, storage);
12467
- }
13308
+ struct TaggedUnionOps {
13309
+ static void destroy(std::size_t index, void* storage) { destroyAt(index, storage, std::index_sequence_for<Arms...>{}); }
12468
13310
  static void copyConstruct(std::size_t index, void* storage, const void* other) {
12469
- if (index == 0) constructCopy<Head>(storage, *static_cast<const Head*>(other));
12470
- else TaggedUnionOps<Tail...>::copyConstruct(index - 1, storage, other);
13311
+ copyConstructAt(index, storage, other, std::index_sequence_for<Arms...>{});
12471
13312
  }
12472
13313
  static void moveConstruct(std::size_t index, void* storage, void* other) {
12473
- if (index == 0) ::new (storage) Head(std::move(*static_cast<Head*>(other)));
12474
- else TaggedUnionOps<Tail...>::moveConstruct(index - 1, storage, other);
13314
+ moveConstructAt(index, storage, other, std::index_sequence_for<Arms...>{});
13315
+ }
13316
+ static void defaultConstruct(std::size_t index, void* storage) { defaultConstructAt(index, storage, std::index_sequence_for<Arms...>{}); }
13317
+
13318
+ private:
13319
+ template <std::size_t... Indices>
13320
+ static void destroyAt(std::size_t index, void* storage, std::index_sequence<Indices...>) {
13321
+ (void)((index == Indices ? (static_cast<Arms*>(storage)->~Arms(), true) : false) || ...);
13322
+ }
13323
+ template <std::size_t... Indices>
13324
+ static void copyConstructAt(std::size_t index, void* storage, const void* other, std::index_sequence<Indices...>) {
13325
+ (void)((index == Indices ? (constructCopy<Arms>(storage, *static_cast<const Arms*>(other)), true) : false) || ...);
12475
13326
  }
12476
- static void defaultConstruct(std::size_t index, void* storage) {
12477
- if (index == 0) ::new (storage) Head();
12478
- else TaggedUnionOps<Tail...>::defaultConstruct(index - 1, storage);
13327
+ template <std::size_t... Indices>
13328
+ static void moveConstructAt(std::size_t index, void* storage, void* other, std::index_sequence<Indices...>) {
13329
+ (void)((index == Indices ? (::new (storage) Arms(std::move(*static_cast<Arms*>(other))), true) : false) || ...);
13330
+ }
13331
+ template <std::size_t... Indices>
13332
+ static void defaultConstructAt(std::size_t index, void* storage, std::index_sequence<Indices...>) {
13333
+ (void)((index == Indices ? (::new (storage) Arms(), true) : false) || ...);
12479
13334
  }
12480
13335
  };
12481
13336
 
@@ -12970,12 +13825,12 @@ class Dictionary {
12970
13825
  if (found != npos) return entries_[found].second;
12971
13826
  enumerableKeys_.reset();
12972
13827
  Entry& entry = entries_.emplace_back(detail::duplicateString(key), V{});
12973
- try {
13828
+ GEA_EH_TRY_ANY(gea_eh_failed) {
12974
13829
  indexInsert(entries_.size() - 1);
12975
- } catch (...) {
13830
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
12976
13831
  entries_.pop_back();
12977
- throw;
12978
- }
13832
+ GEA_EH_RETHROW_ANY(gea_eh_failed);
13833
+ } GEA_EH_END
12979
13834
  if constexpr (aliasable) detail::noteDocumentDataKeyCreated(this, key);
12980
13835
  return entry.second;
12981
13836
  }
@@ -13006,6 +13861,62 @@ class Dictionary {
13006
13861
  const std::size_t found = findPosition(key);
13007
13862
  return found == npos ? V{} : entries_[found].second;
13008
13863
  }
13864
+ /**
13865
+ * `findPosition` for a constant key read at one site, asked first at the
13866
+ * position that site last found it. Keys are unique in `entries_`, so an
13867
+ * entry at the hinted position carrying exactly this key IS the key's entry;
13868
+ * anything else (another table, a moved entry) is a plain lookup that
13869
+ * refreshes the hint. Tables built by one constructor -- three's uniform
13870
+ * tables, cloned from one template per material -- keep a key at one
13871
+ * position, so a hot site stops hashing. The hint is only ever a guess:
13872
+ * relaxed loads and stores suffice, and a stale one costs one compare.
13873
+ */
13874
+ std::size_t hintedPosition(std::string_view key, std::atomic<std::uint32_t>& hint) const {
13875
+ const std::uint32_t at = hint.load(std::memory_order_relaxed);
13876
+ if (at < entries_.size() && entries_[at].first == key) return at;
13877
+ const std::size_t found = findPosition(key);
13878
+ if (found != npos && found < 0xFFFFFFFFu) hint.store(static_cast<std::uint32_t>(found), std::memory_order_relaxed);
13879
+ return found;
13880
+ }
13881
+ /** `read` with a site's position hint; any table that is not a plain own-entry table answers through `read`. */
13882
+ V readHinted(std::string_view key, std::atomic<std::uint32_t>& hint) const {
13883
+ if constexpr (!aliasable) {
13884
+ if (!view_) [[likely]] {
13885
+ if (first_ && first_->first == key) return first_->second;
13886
+ const std::size_t found = hintedPosition(key, hint);
13887
+ return found == npos ? V{} : entries_[found].second;
13888
+ }
13889
+ }
13890
+ return read(key);
13891
+ }
13892
+ /** `readIfPresent` with a site's position hint. */
13893
+ template <typename Carrier>
13894
+ Carrier readIfPresentHinted(std::string_view key, std::atomic<std::uint32_t>& hint) const {
13895
+ if constexpr (!aliasable) {
13896
+ if (!view_) [[likely]] {
13897
+ if (first_ && first_->first == key) return Carrier(first_->second);
13898
+ const std::size_t found = hintedPosition(key, hint);
13899
+ return found == npos ? Carrier() : Carrier(entries_[found].second);
13900
+ }
13901
+ }
13902
+ return readIfPresent<Carrier>(key);
13903
+ }
13904
+ /**
13905
+ * `has(key) ? Carrier(read(key)) : Carrier()` with one lookup for a plain
13906
+ * table: no view and no Document alias or overlay, where `has` and `read`
13907
+ * both answer exactly the own entry. Every other table asks both, as before.
13908
+ */
13909
+ template <typename Carrier>
13910
+ Carrier readIfPresent(std::string_view key) const {
13911
+ if constexpr (!aliasable) {
13912
+ if (!view_) [[likely]] {
13913
+ if (first_ && first_->first == key) return Carrier(first_->second);
13914
+ const std::size_t found = findPosition(key);
13915
+ return found == npos ? Carrier() : Carrier(entries_[found].second);
13916
+ }
13917
+ }
13918
+ return has(key) ? Carrier(read(key)) : Carrier();
13919
+ }
13009
13920
  /**
13010
13921
  * Whether a read of `key` finds a property. For a table of its own entries
13011
13922
  * that is the entry; for a view it is `[[HasProperty]]` on the viewed object,
@@ -13501,12 +14412,12 @@ class Dictionary {
13501
14412
  return;
13502
14413
  }
13503
14414
  entries_.emplace_back(detail::duplicateString(key), std::move(value));
13504
- try {
14415
+ GEA_EH_TRY_ANY(gea_eh_failed) {
13505
14416
  indexInsert(entries_.size() - 1);
13506
- } catch (...) {
14417
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
13507
14418
  entries_.pop_back();
13508
- throw;
13509
- }
14419
+ GEA_EH_RETHROW_ANY(gea_eh_failed);
14420
+ } GEA_EH_END
13510
14421
  }
13511
14422
 
13512
14423
  template <typename V2, typename Convert>
@@ -13701,7 +14612,20 @@ class NumericDictionary {
13701
14612
 
13702
14613
  using Entry = std::pair<const std::string, V>;
13703
14614
 
13704
- static std::string canonicalKey(double key) { return host::detail::toString(key); }
14615
+ // An integral key -- every array-like `Record<number, T>` index, and three's
14616
+ // capability ids -- spells as its decimal digits (`Number::toString` for a
14617
+ // safe integer; -0 spells "0" either way), without the general formatter.
14618
+ static std::string canonicalKey(double key) {
14619
+ if (key >= -9007199254740991.0 && key <= 9007199254740991.0) {
14620
+ const auto whole = static_cast<long long>(key);
14621
+ if (static_cast<double>(whole) == key) {
14622
+ char digits[24];
14623
+ const auto written = std::to_chars(digits, digits + sizeof(digits), whole);
14624
+ return std::string(digits, written.ptr);
14625
+ }
14626
+ }
14627
+ return host::detail::toString(key);
14628
+ }
13705
14629
  V& operator[](double key) { return entries_[canonicalKey(key)]; }
13706
14630
  V& operator[](const std::string& key) { return entries_[key]; }
13707
14631
  /**
@@ -13734,7 +14658,12 @@ class NumericDictionary {
13734
14658
  V read(double key) const {
13735
14659
  char buffer[24];
13736
14660
  const std::string_view digits = integerKeyView(key, buffer);
13737
- if (!digits.empty()) return entries_.read(digits);
14661
+ // An integer key asks the position it was last found at in THIS table
14662
+ // (`Dictionary::readHinted`: one key compare verifies it, a miss is the
14663
+ // ordinary lookup and refreshes it). three's `enabledCapabilities[id]`
14664
+ // per `enable`/`disable` call hashed the capability's digits into a
14665
+ // table of a dozen keys every time.
14666
+ if (!digits.empty()) return entries_.readHinted(digits, integerHints_.slots[static_cast<std::size_t>(key) & 7u]);
13738
14667
  return read(canonicalKey(key));
13739
14668
  }
13740
14669
  V read(const std::string& key) const { return entries_.read(key); }
@@ -13804,6 +14733,16 @@ class NumericDictionary {
13804
14733
 
13805
14734
  private:
13806
14735
  Dictionary<V> entries_;
14736
+ // Position hints for integer keys, by the key's low bits. A hint is only a
14737
+ // guess the entry's own key verifies, so a copied table starts without any,
14738
+ // and racing relaxed stores from parallel readers can only cost a lookup.
14739
+ struct IntegerHints {
14740
+ mutable std::array<std::atomic<std::uint32_t>, 8> slots{};
14741
+ IntegerHints() = default;
14742
+ IntegerHints(const IntegerHints&) noexcept {}
14743
+ IntegerHints& operator=(const IntegerHints&) noexcept { return *this; }
14744
+ };
14745
+ IntegerHints integerHints_;
13807
14746
  };
13808
14747
 
13809
14748
  /**
@@ -13831,12 +14770,12 @@ class SymbolDictionary {
13831
14770
  const auto found = positions_.find(key);
13832
14771
  if (found != positions_.end()) return entries_[found->second].second;
13833
14772
  entries_.emplace_back(key, V{});
13834
- try {
14773
+ GEA_EH_TRY_ANY(gea_eh_failed) {
13835
14774
  positions_.emplace(key, entries_.size() - 1);
13836
- } catch (...) {
14775
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
13837
14776
  entries_.pop_back();
13838
- throw;
13839
- }
14777
+ GEA_EH_RETHROW_ANY(gea_eh_failed);
14778
+ } GEA_EH_END
13840
14779
  return entries_.back().second;
13841
14780
  }
13842
14781
  V read(const Symbol& key) const {
@@ -14126,6 +15065,60 @@ inline void canonicalizeKeyInPlace(Optional<T>& key) {
14126
15065
  if (key.has_value()) canonicalizeKeyInPlace(*key);
14127
15066
  }
14128
15067
 
15068
+ namespace detail {
15069
+ template <typename T>
15070
+ struct MapRefKey : std::false_type {};
15071
+ template <typename T>
15072
+ struct MapRefKey<Ref<T>> : std::bool_constant<!std::is_void_v<T>> {};
15073
+ /**
15074
+ * The identity `operator==` on two handles compares, as one address: the
15075
+ * object, or for a native view the object it views (`nativeIdentity`). An
15076
+ * absent handle is its own key, distinct from null and from every object.
15077
+ */
15078
+ template <typename T>
15079
+ inline const void* mapRefKeyIdentity(const Ref<T>& value) {
15080
+ if (value.isUndefined()) return reinterpret_cast<const void*>(std::uintptr_t{1});
15081
+ if (!value) return nullptr;
15082
+ if constexpr (refStandalone<T>) return static_cast<const void*>(value.get());
15083
+ else {
15084
+ const auto native = refHeaderOf(value.get())->operations->nativeIdentity;
15085
+ return native == nullptr ? static_cast<const void*>(value.get()) : native(value.get());
15086
+ }
15087
+ }
15088
+ /**
15089
+ * Key types `Map` may index by hash (see `Map::Index`): those whose hash below
15090
+ * is consistent with `sameValueZero` -- numbers, strings, and handles, which
15091
+ * hash the identity their equality compares (`mapRefKeyIdentity`). Any other
15092
+ * key (unions, optionals, boxed values) keeps the linear SameValueZero scan,
15093
+ * whose equality those types define in ways a hash would have to repeat.
15094
+ */
15095
+ template <typename K>
15096
+ struct MapKeyIndexable
15097
+ : std::bool_constant<std::is_arithmetic_v<K> || std::is_same_v<K, std::string>
15098
+ || MapRefKey<K>::value
15099
+ > {
15100
+ };
15101
+ struct MapKeyHash {
15102
+ template <typename K>
15103
+ std::size_t operator()(const K& key) const {
15104
+ if constexpr (std::is_floating_point_v<K>) {
15105
+ // SameValueZero: every NaN is one key, and -0 is +0.
15106
+ if (key != key) return static_cast<std::size_t>(0x7ff8000000000000ull);
15107
+ return std::hash<K>{}(key == static_cast<K>(0) ? static_cast<K>(0) : key);
15108
+ } else if constexpr (MapRefKey<K>::value) {
15109
+ return std::hash<const void*>{}(mapRefKeyIdentity(key));
15110
+ } else {
15111
+ return std::hash<K>{}(key);
15112
+ }
15113
+ }
15114
+ };
15115
+ struct MapKeyEqual {
15116
+ template <typename K>
15117
+ bool operator()(const K& left, const K& right) const { return sameValueZero(left, right); }
15118
+ };
15119
+ struct NoMapIndex {};
15120
+ } // namespace detail
15121
+
14129
15122
  /**
14130
15123
  * `Map<K, V>` -- ECMA-262 23.1.
14131
15124
  *
@@ -14233,14 +15226,14 @@ class Map {
14233
15226
  return;
14234
15227
  }
14235
15228
  canonicalizeKeyInPlace(key);
14236
- for (std::pair<K, V>& entry : entries_) {
14237
- if (sameValueZero(entry.first, key)) {
14238
- entry.second = std::move(value);
14239
- return;
14240
- }
15229
+ const std::size_t found = positionOf(key);
15230
+ if (found != notFound) {
15231
+ entries_[found].second = std::move(value);
15232
+ return;
14241
15233
  }
14242
15234
  entries_.emplace_back(std::move(key), std::move(value));
14243
15235
  serials_.push_back(nextSerial_++);
15236
+ indexAppended();
14244
15237
  }
14245
15238
 
14246
15239
  /**
@@ -14252,18 +15245,13 @@ class Map {
14252
15245
  */
14253
15246
  Optional<V> get(const K& key) const {
14254
15247
  if (view_) [[unlikely]] return view_->get(key);
14255
- for (const std::pair<K, V>& entry : entries_) {
14256
- if (sameValueZero(entry.first, key)) return Optional<V>(entry.second);
14257
- }
14258
- return Optional<V>();
15248
+ const std::size_t found = positionOf(key);
15249
+ return found == notFound ? Optional<V>() : Optional<V>(entries_[found].second);
14259
15250
  }
14260
15251
 
14261
15252
  bool has(const K& key) const {
14262
15253
  if (view_) [[unlikely]] return view_->has(key);
14263
- for (const std::pair<K, V>& entry : entries_) {
14264
- if (sameValueZero(entry.first, key)) return true;
14265
- }
14266
- return false;
15254
+ return positionOf(key) != notFound;
14267
15255
  }
14268
15256
 
14269
15257
  /** ECMA-262 23.1.3.3 `delete`: true when an entry was actually removed. */
@@ -14273,13 +15261,12 @@ class Map {
14273
15261
  if (!view_->remove(key, removed)) rejectViewWrite();
14274
15262
  return removed;
14275
15263
  }
14276
- for (std::size_t index = 0; index < entries_.size(); ++index) {
14277
- if (!sameValueZero(entries_[index].first, key)) continue;
14278
- entries_.erase(entries_.begin() + static_cast<std::ptrdiff_t>(index));
14279
- serials_.erase(serials_.begin() + static_cast<std::ptrdiff_t>(index));
14280
- return true;
14281
- }
14282
- return false;
15264
+ const std::size_t index = positionOf(key);
15265
+ if (index == notFound) return false;
15266
+ entries_.erase(entries_.begin() + static_cast<std::ptrdiff_t>(index));
15267
+ serials_.erase(serials_.begin() + static_cast<std::ptrdiff_t>(index));
15268
+ indexRemoved();
15269
+ return true;
14283
15270
  }
14284
15271
 
14285
15272
  void clear() {
@@ -14289,6 +15276,7 @@ class Map {
14289
15276
  }
14290
15277
  entries_.clear();
14291
15278
  serials_.clear();
15279
+ if constexpr (indexable) index_.clear();
14292
15280
  }
14293
15281
 
14294
15282
  /**
@@ -14334,10 +15322,61 @@ class Map {
14334
15322
  gea::host::throwRuntimeError("TypeError", "a Map read through a ReadonlyMap view cannot be written through that view");
14335
15323
  }
14336
15324
 
15325
+ /**
15326
+ * Key -> storage position, kept beside the insertion-ordered storage once the
15327
+ * Map holds `indexFrom` entries, for key types whose hash agrees with
15328
+ * SameValueZero (`detail::MapKeyHash`). A per-draw `map.get(id)` over a few
15329
+ * hundred entries was a scan of all of them. The storage and its serials
15330
+ * stay the authority for order and for iterators (`entryAfter` walks
15331
+ * serials, never positions), so the index changes no observable behaviour.
15332
+ * It is written only by the mutators, never by a read, so concurrent readers
15333
+ * of an unchanging Map (parallel regions) stay read-only.
15334
+ */
15335
+ static constexpr bool indexable = detail::MapKeyIndexable<K>::value;
15336
+ static constexpr std::size_t indexFrom = 8;
15337
+ static constexpr std::size_t notFound = static_cast<std::size_t>(-1);
15338
+ using Index = std::conditional_t<indexable, std::unordered_map<K, std::size_t, detail::MapKeyHash, detail::MapKeyEqual>,
15339
+ detail::NoMapIndex>;
15340
+
15341
+ std::size_t positionOf(const K& key) const {
15342
+ if constexpr (indexable) {
15343
+ if (!index_.empty()) {
15344
+ const auto found = index_.find(key);
15345
+ return found == index_.end() ? notFound : found->second;
15346
+ }
15347
+ }
15348
+ for (std::size_t index = 0; index < entries_.size(); ++index) {
15349
+ if (sameValueZero(entries_[index].first, key)) return index;
15350
+ }
15351
+ return notFound;
15352
+ }
15353
+ void rebuildIndex() {
15354
+ if constexpr (indexable) {
15355
+ index_.clear();
15356
+ if (entries_.size() < indexFrom) return;
15357
+ index_.reserve(entries_.size() * 2);
15358
+ for (std::size_t index = 0; index < entries_.size(); ++index) index_.emplace(entries_[index].first, index);
15359
+ }
15360
+ }
15361
+ void indexAppended() {
15362
+ if constexpr (indexable) {
15363
+ if (!index_.empty()) index_.emplace(entries_.back().first, entries_.size() - 1);
15364
+ else if (entries_.size() >= indexFrom) rebuildIndex();
15365
+ }
15366
+ }
15367
+ // Erasing shifted every later entry down one position (an O(n) move already),
15368
+ // so the index is renumbered by rebuilding it, or dropped below `indexFrom`.
15369
+ void indexRemoved() {
15370
+ if constexpr (indexable) {
15371
+ if (!index_.empty()) rebuildIndex();
15372
+ }
15373
+ }
15374
+
14337
15375
  std::vector<std::pair<K, V>> entries_;
14338
15376
  std::vector<std::uint64_t> serials_;
14339
15377
  std::uint64_t nextSerial_ = 1;
14340
15378
  std::shared_ptr<const detail::MapViewSource<K, V>> view_;
15379
+ Index index_;
14341
15380
  };
14342
15381
 
14343
15382
  namespace detail {
@@ -14638,7 +15677,7 @@ inline bool weakKeySame(const K& left, const K& right) {
14638
15677
  * One weak-collection key after its static object view is erased.
14639
15678
  *
14640
15679
  * The pointer is the ECMAScript object identity used for comparison. The
14641
- * shared holder keeps a typed copy of the original carrier alive, preserving
15680
+ * shared holder keeps a typed copy of ordinary carriers alive, preserving
14642
15681
  * this runtime's documented strong-key behavior without casting one generated
14643
15682
  * struct type to another. This is intentionally independent of WeakMap's K:
14644
15683
  * TypeScript may pass a class instance through a structurally compatible
@@ -14669,12 +15708,30 @@ const void* weakCollectionIdentity(const TaggedUnion<Arms...>& key) {
14669
15708
  struct WeakCollectionKey {
14670
15709
  const void* identity = nullptr;
14671
15710
  std::shared_ptr<const void> owner;
15711
+ std::weak_ptr<const void> nativeOwner;
15712
+ bool nativeWeak = false;
14672
15713
 
14673
15714
  WeakCollectionKey() = default;
14674
15715
 
14675
15716
  template <typename Key>
14676
- explicit WeakCollectionKey(const Key& key)
14677
- : identity(weakCollectionIdentity(key)), owner(std::make_shared<Key>(key)) {}
15717
+ explicit WeakCollectionKey(const Key& key) : identity(weakCollectionIdentity(key)) {
15718
+ // An explicit native carrier contract: the carrier owns its occurrence /
15719
+ // allocation token, while this key observes it without retaining events.
15720
+ // Generic compiler object carriers keep their existing retention policy.
15721
+ if constexpr (requires { std::weak_ptr<const void>(key.weakIdentityOwner()); }) {
15722
+ nativeOwner = key.weakIdentityOwner();
15723
+ nativeWeak = true;
15724
+ } else owner = std::make_shared<Key>(key);
15725
+ }
15726
+
15727
+ template <typename... Arms>
15728
+ explicit WeakCollectionKey(const TaggedUnion<Arms...>& key) {
15729
+ [&]<std::size_t... Indices>(std::index_sequence<Indices...>) {
15730
+ ((key.template is<Indices>() ? (*this = WeakCollectionKey(key.template get<Indices>()), 0) : 0), ...);
15731
+ }(std::index_sequence_for<Arms...>{});
15732
+ }
15733
+
15734
+ bool expired() const { return nativeWeak && nativeOwner.expired(); }
14678
15735
  };
14679
15736
 
14680
15737
  template <typename K, typename V>
@@ -14692,6 +15749,7 @@ class WeakMap {
14692
15749
  virtual void gea_ref_address_anchor() {}
14693
15750
  template <typename Key>
14694
15751
  void set(const Key& key, V value) {
15752
+ pruneExpired();
14695
15753
  const void* identity = weakCollectionIdentity(key);
14696
15754
  const auto found = entries_.find(identity);
14697
15755
  if (found != entries_.end()) {
@@ -14700,23 +15758,34 @@ class WeakMap {
14700
15758
  }
14701
15759
  // The identity index owns the same key holder as before. Updates and
14702
15760
  // lookups neither allocate a holder nor scan unrelated live entries.
14703
- entries_.emplace(identity, std::make_pair(WeakCollectionKey(key), std::move(value)));
15761
+ WeakCollectionKey stored(key);
15762
+ nativeKeys_ = nativeKeys_ || stored.nativeWeak;
15763
+ entries_.emplace(identity, std::make_pair(std::move(stored), std::move(value)));
14704
15764
  }
14705
15765
 
14706
15766
  template <typename Key>
14707
15767
  Optional<V> get(const Key& key) const {
15768
+ pruneExpired();
14708
15769
  const auto found = entries_.find(weakCollectionIdentity(key));
14709
15770
  return found == entries_.end() ? Optional<V>() : Optional<V>(found->second.second);
14710
15771
  }
14711
15772
 
14712
15773
  template <typename Key>
14713
- bool has(const Key& key) const { return entries_.find(weakCollectionIdentity(key)) != entries_.end(); }
15774
+ bool has(const Key& key) const { pruneExpired(); return entries_.find(weakCollectionIdentity(key)) != entries_.end(); }
14714
15775
 
14715
15776
  template <typename Key>
14716
- bool remove(const Key& key) { return entries_.erase(weakCollectionIdentity(key)) != 0; }
15777
+ bool remove(const Key& key) { pruneExpired(); return entries_.erase(weakCollectionIdentity(key)) != 0; }
14717
15778
 
14718
15779
  private:
14719
- std::unordered_map<const void*, std::pair<WeakCollectionKey, V>> entries_;
15780
+ bool nativeKeys_ = false;
15781
+ void pruneExpired() const {
15782
+ if (!nativeKeys_) return;
15783
+ for (auto i = entries_.begin(); i != entries_.end();) {
15784
+ if (i->second.first.expired()) i = entries_.erase(i);
15785
+ else ++i;
15786
+ }
15787
+ }
15788
+ mutable std::unordered_map<const void*, std::pair<WeakCollectionKey, V>> entries_;
14720
15789
  };
14721
15790
 
14722
15791
  /** `WeakSet<K>` -- ECMA-262 24.4. The value-less sibling of `WeakMap`; see that class's comment for what the "weak" here does and does not mean. */
@@ -14735,15 +15804,18 @@ class WeakSet {
14735
15804
  virtual void gea_ref_address_anchor() {}
14736
15805
  template <typename Key>
14737
15806
  void add(const Key& key) {
15807
+ pruneExpired();
14738
15808
  const void* identity = weakCollectionIdentity(key);
14739
15809
  for (const WeakCollectionKey& item : items_) {
14740
15810
  if (item.identity == identity) return;
14741
15811
  }
14742
15812
  items_.emplace_back(key);
15813
+ nativeKeys_ = nativeKeys_ || items_.back().nativeWeak;
14743
15814
  }
14744
15815
 
14745
15816
  template <typename Key>
14746
15817
  bool has(const Key& key) const {
15818
+ pruneExpired();
14747
15819
  const void* identity = weakCollectionIdentity(key);
14748
15820
  for (const WeakCollectionKey& item : items_) {
14749
15821
  if (item.identity == identity) return true;
@@ -14753,6 +15825,7 @@ class WeakSet {
14753
15825
 
14754
15826
  template <typename Key>
14755
15827
  bool remove(const Key& key) {
15828
+ pruneExpired();
14756
15829
  const void* identity = weakCollectionIdentity(key);
14757
15830
  for (std::size_t index = 0; index < items_.size(); ++index) {
14758
15831
  if (items_[index].identity != identity) continue;
@@ -14763,7 +15836,13 @@ class WeakSet {
14763
15836
  }
14764
15837
 
14765
15838
  private:
14766
- std::vector<WeakCollectionKey> items_;
15839
+ bool nativeKeys_ = false;
15840
+ void pruneExpired() const {
15841
+ if (!nativeKeys_) return;
15842
+ items_.erase(std::remove_if(items_.begin(), items_.end(),
15843
+ [](const WeakCollectionKey& key) { return key.expired(); }), items_.end());
15844
+ }
15845
+ mutable std::vector<WeakCollectionKey> items_;
14767
15846
  };
14768
15847
 
14769
15848
  // The weak halves of `mapSet`/`setAdd` above, placed here because a template
@@ -16042,8 +17121,15 @@ inline void setPromiseJobSink(PromiseJobSink sink) { promiseJobSink() = sink; }
16042
17121
  // By rvalue reference: a by-value parameter relocated every job once more (an
16043
17122
  // indirect call and a 32-byte copy) between the awaiter that built it and the
16044
17123
  // host queue that stores it.
17124
+ // Native app retirement may destroy owners whose destructors enqueue work.
17125
+ // Reject that work until both outgoing queues have released their owners.
17126
+ inline bool& microtaskRetirementInProgress() {
17127
+ GEA_REALM_LOCAL(bool, retiring, (false));
17128
+ return retiring;
17129
+ }
17130
+
16045
17131
  inline void queuePromiseJob(PromiseJob&& job) {
16046
- if (!job) return;
17132
+ if (!job || microtaskRetirementInProgress()) return;
16047
17133
  if (PromiseJobSink sink = promiseJobSink()) sink(std::move(job));
16048
17134
  else promiseJobs().push_back(std::move(job));
16049
17135
  }
@@ -16893,12 +17979,12 @@ auto Promise<V>::then(F&& onFulfilled) const {
16893
17979
  result.reject(*state->rejection);
16894
17980
  return;
16895
17981
  }
16896
- try {
17982
+ GEA_EH_TRY_ANY(gea_eh_failed) {
16897
17983
  detail::callSettledHandler(handler, state->value);
16898
17984
  result.resolve();
16899
- } catch (...) {
16900
- result.reject(std::current_exception());
16901
- }
17985
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
17986
+ result.reject(GEA_EH_CURRENT(gea_eh_failed));
17987
+ } GEA_EH_END
16902
17988
  });
16903
17989
  return result;
16904
17990
  } else {
@@ -16909,11 +17995,11 @@ auto Promise<V>::then(F&& onFulfilled) const {
16909
17995
  result.reject(*state->rejection);
16910
17996
  return;
16911
17997
  }
16912
- try {
17998
+ GEA_EH_TRY_ANY(gea_eh_failed) {
16913
17999
  detail::settleThenFromHandled(result, detail::callSettledHandler(handler, state->value));
16914
- } catch (...) {
16915
- result.reject(std::current_exception());
16916
- }
18000
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
18001
+ result.reject(GEA_EH_CURRENT(gea_eh_failed));
18002
+ } GEA_EH_END
16917
18003
  });
16918
18004
  return result;
16919
18005
  }
@@ -16930,12 +18016,12 @@ auto Promise<void>::then(F&& onFulfilled) const {
16930
18016
  result.reject(*state->rejection);
16931
18017
  return;
16932
18018
  }
16933
- try {
18019
+ GEA_EH_TRY_ANY(gea_eh_failed) {
16934
18020
  detail::callSettledHandler(handler, gea::Undefined{});
16935
18021
  result.resolve();
16936
- } catch (...) {
16937
- result.reject(std::current_exception());
16938
- }
18022
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
18023
+ result.reject(GEA_EH_CURRENT(gea_eh_failed));
18024
+ } GEA_EH_END
16939
18025
  });
16940
18026
  return result;
16941
18027
  } else {
@@ -16946,11 +18032,11 @@ auto Promise<void>::then(F&& onFulfilled) const {
16946
18032
  result.reject(*state->rejection);
16947
18033
  return;
16948
18034
  }
16949
- try {
18035
+ GEA_EH_TRY_ANY(gea_eh_failed) {
16950
18036
  detail::settleThenFromHandled(result, detail::callSettledHandler(handler, gea::Undefined{}));
16951
- } catch (...) {
16952
- result.reject(std::current_exception());
16953
- }
18037
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
18038
+ result.reject(GEA_EH_CURRENT(gea_eh_failed));
18039
+ } GEA_EH_END
16954
18040
  });
16955
18041
  return result;
16956
18042
  }
@@ -16969,11 +18055,11 @@ template <typename R, typename V, typename F>
16969
18055
  Promise<R> mapSettledPromise(const Promise<V>& source, F&& mapper) {
16970
18056
  if (source.settled() && !source.rejected()) {
16971
18057
  Promise<R> out;
16972
- try {
18058
+ GEA_EH_TRY_ANY(gea_eh_failed) {
16973
18059
  out.resolve(detail::callSettledHandler(mapper, source.value()));
16974
- } catch (...) {
16975
- out.reject(std::current_exception());
16976
- }
18060
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
18061
+ out.reject(GEA_EH_CURRENT(gea_eh_failed));
18062
+ } GEA_EH_END
16977
18063
  return out;
16978
18064
  }
16979
18065
  return source.then(std::forward<F>(mapper));
@@ -18027,6 +19113,16 @@ class ProxyObject {
18027
19113
  bool revoked() const { return revoked_; }
18028
19114
  void revoke() { revoked_ = true; }
18029
19115
 
19116
+ // These fields still own their references after revocation. Omitting either
19117
+ // edge hides cycles through a native Proxy from the existing collector.
19118
+ template <typename Self>
19119
+ friend void geaTraceRefs(const Self& traced, detail::RefVisitor& visitor)
19120
+ requires (std::derived_from<Self, ProxyObject> && (detail::TraceEdges<Target>::supported || detail::TraceEdges<Handler>::supported)) {
19121
+ const auto& value = static_cast<const ProxyObject&>(traced);
19122
+ detail::traceRefs(value.target_, visitor);
19123
+ detail::traceRefs(value.handler_, visitor);
19124
+ }
19125
+
18030
19126
  private:
18031
19127
  Target target_{};
18032
19128
  Handler handler_{};
@@ -18227,10 +19323,14 @@ inline bool nativeCallReceiverIs(const NativeCallReceiver& receiver) {
18227
19323
  /** One byte per boxed payload type, whose ADDRESS is that type's identity -- `typeid` without RTTI, which embedded targets build without. */
18228
19324
  template <typename T>
18229
19325
  struct PayloadTypeTag {
18230
- static const char id;
19326
+ // Mutable, never written. Every identity tag in this header is: the
19327
+ // address IS the identity, and every tag is the same zero byte, which a
19328
+ // linker may merge as identical read-only data (link.exe's /OPT:ICF does,
19329
+ // whether or not the address is taken). No linker merges writable data.
19330
+ static char id;
18231
19331
  };
18232
19332
  template <typename T>
18233
- const char PayloadTypeTag<T>::id = 0;
19333
+ char PayloadTypeTag<T>::id = 0;
18234
19334
 
18235
19335
  template <typename T>
18236
19336
  const void* payloadTypeTagFor() {
@@ -18240,10 +19340,10 @@ const void* payloadTypeTagFor() {
18240
19340
  /** One program-wide address per emitted source declaration. */
18241
19341
  template <auto Declaration>
18242
19342
  struct CallableDeclarationTag {
18243
- static const char id;
19343
+ static char id; // mutable: see `PayloadTypeTag`
18244
19344
  };
18245
19345
  template <auto Declaration>
18246
- const char CallableDeclarationTag<Declaration>::id = 0;
19346
+ char CallableDeclarationTag<Declaration>::id = 0;
18247
19347
  template <auto Declaration>
18248
19348
  const void* callableDeclarationTagFor() {
18249
19349
  return &CallableDeclarationTag<Declaration>::id;
@@ -20778,6 +21878,8 @@ class NativeHandle<gea_native_protocol_PropertyDescriptor_v1> : public PropertyD
20778
21878
  };
20779
21879
 
20780
21880
  inline Value dynamicArrayPrototypeGet(const PropertyKey&);
21881
+ inline Value dynamicArrayPrototypeGet(const PropertyKey&, const Value&);
21882
+ inline Ref<ArrayObject<Value>> arrayPrototypeObject();
20781
21883
  inline bool dynamicArrayPrototypeHas(const PropertyKey&);
20782
21884
  inline Value dynamicStringPrototypeGet(const PropertyKey&);
20783
21885
  inline Value dynamicFunctionPrototypeGet(const PropertyKey&);
@@ -20880,9 +21982,12 @@ struct NativeClassMethodState {
20880
21982
  * (`constructorOwnProperty`), so a program that never does pays nothing.
20881
21983
  */
20882
21984
  Ref<FunctionObjectIdentity> functionObject;
21985
+ /** Every layout copy of one generic class keeps its static own properties on this one state (`shareConstructorStatics`). */
21986
+ Ref<NativeClassMethodState> staticOwner;
20883
21987
 
20884
21988
  friend void geaTraceRefs(const NativeClassMethodState& value, detail::RefVisitor& visitor) {
20885
21989
  detail::traceRefs(value.functionObject, visitor);
21990
+ detail::traceRefs(value.staticOwner, visitor);
20886
21991
  detail::traceRefs(value.parent, visitor);
20887
21992
  detail::traceRefs(value.prototypeObject, visitor);
20888
21993
  for (const auto& entry : value.methods) detail::traceRefs(entry.second, visitor);
@@ -20892,7 +21997,7 @@ struct NativeClassMethodState {
20892
21997
  };
20893
21998
 
20894
21999
  template <typename NativeClass>
20895
- inline constexpr char nativeClassMethodDeclaration = 0;
22000
+ inline char nativeClassMethodDeclaration = 0; // mutable: its address is the identity (see `detail::PayloadTypeTag`)
20896
22001
 
20897
22002
  inline Ref<NativeClassMethodState> nativeClassMethodStateFromEnvironment(void* environment) {
20898
22003
  return Ref<NativeClassMethodState>::adopt(static_cast<NativeClassMethodState*>(environment), true);
@@ -21124,7 +22229,7 @@ Callable nativeClassMethodValue(const Ref<NativeClassMethodState>& state, Callab
21124
22229
  }
21125
22230
 
21126
22231
  template <typename Callable>
21127
- inline constexpr char nativeClassMethodCarrier = 0;
22232
+ inline char nativeClassMethodCarrier = 0; // mutable: its address is the identity (see `detail::PayloadTypeTag`)
21128
22233
 
21129
22234
  /** Adapt a prototype body once per class evaluation and target convention.
21130
22235
  * Own replacements bypass this immutable original-body cache. Both the typed
@@ -21165,7 +22270,7 @@ Callable nativeClassAdaptedMethodValue(const Ref<NativeClassMethodState>& state,
21165
22270
  * a view's address is never reused by another record.
21166
22271
  */
21167
22272
  template <typename Record>
21168
- inline constexpr char constructorStaticViewTag = 0;
22273
+ inline char constructorStaticViewTag = 0; // mutable: its address is the identity (see `detail::PayloadTypeTag`)
21169
22274
 
21170
22275
  namespace detail {
21171
22276
  inline std::unordered_map<const void*, Ref<NativeClassMethodState>>& constructorStaticViewOwners() {
@@ -21175,17 +22280,38 @@ inline std::unordered_map<const void*, Ref<NativeClassMethodState>>& constructor
21175
22280
  return *owners;
21176
22281
  }
21177
22282
 
22283
+ inline NativeClassMethodState* constructorStaticStateOwner(NativeClassMethodState* state) {
22284
+ while (state != nullptr && state->staticOwner) state = state->staticOwner.get();
22285
+ return state;
22286
+ }
22287
+
21178
22288
  template <typename Record>
21179
22289
  Record* existingConstructorStaticView(NativeClassMethodState* state) {
22290
+ state = constructorStaticStateOwner(state);
22291
+ if (state == nullptr) return nullptr;
21180
22292
  for (const auto& entry : state->staticViews)
21181
22293
  if (entry.first == &constructorStaticViewTag<Record>) return static_cast<Record*>(entry.second.get());
21182
22294
  return nullptr;
21183
22295
  }
21184
22296
  } // namespace detail
21185
22297
 
22298
+ /** The one static side of a generic class whose layout copies are evaluated separately, keyed by its declaration. */
22299
+ inline NativeClassMethodState* sharedConstructorStaticState(const char* owner) {
22300
+ using Owners = std::unordered_map<std::string, Ref<NativeClassMethodState>>;
22301
+ GEA_REALM_LOCAL(Owners, ownerStorage, {});
22302
+ auto& slot = ownerStorage[owner];
22303
+ if (!slot) slot = makeRef<NativeClassMethodState>();
22304
+ return slot.get();
22305
+ }
22306
+
22307
+ inline void shareConstructorStatics(NativeClassMethodState* state, const char* owner) {
22308
+ if (state != nullptr) state->staticOwner = Ref<NativeClassMethodState>::adopt(sharedConstructorStaticState(owner), true);
22309
+ }
22310
+
21186
22311
  template <typename Record>
21187
22312
  Ref<Record> constructorStaticView(NativeClassMethodState* state) {
21188
22313
  if (state == nullptr) detail::refusePayloadMismatch("a class constructor viewed as a record has no class evaluation");
22314
+ state = detail::constructorStaticStateOwner(state);
21189
22315
  if (Record* existing = detail::existingConstructorStaticView<Record>(state)) return Ref<Record>::adopt(existing, true);
21190
22316
  auto view = makeRef<Record>();
21191
22317
  state->staticViews.emplace_back(&constructorStaticViewTag<Record>, view.template staticCast<void>());
@@ -21856,18 +22982,18 @@ inline Value evaluate(ModuleRecord& record, Initializer&& initializer) {
21856
22982
  const auto exportsOf = [](ModuleRecord& current) { return current.moduleObject.getProperty(PropertyKey::string("exports")); };
21857
22983
  if (record.state == ModuleRecord::State::loaded || record.state == ModuleRecord::State::loading) return exportsOf(record);
21858
22984
  record.state = ModuleRecord::State::loading;
21859
- try {
22985
+ GEA_EH_TRY_ANY(gea_eh_failed) {
21860
22986
  Scope scope(record);
21861
22987
  initializer();
21862
22988
  record.state = ModuleRecord::State::loaded;
21863
22989
  return exportsOf(record);
21864
- } catch (...) {
22990
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
21865
22991
  // Node removes a module that failed to evaluate from its cache, so a later
21866
22992
  // require retries rather than observing a permanently poisoned record.
21867
22993
  record.state = ModuleRecord::State::fresh;
21868
22994
  record.resetBindings();
21869
- throw;
21870
- }
22995
+ GEA_EH_RETHROW_ANY(gea_eh_failed);
22996
+ } GEA_EH_END
21871
22997
  }
21872
22998
 
21873
22999
  /**
@@ -21985,6 +23111,34 @@ inline Value installOrdinaryConstructorPrototype(Value ctor) {
21985
23111
  } // namespace host
21986
23112
 
21987
23113
  namespace dictionary {
23114
+ /**
23115
+ * The present-or-absent read of a keyed table (`has(k) ? Carrier(read(k)) :
23116
+ * Carrier()`). A table with a single-lookup `readIfPresent` answers through
23117
+ * it; any other answers through its own `has` and `read`, unchanged.
23118
+ */
23119
+ template <typename Carrier, typename Table, typename Key>
23120
+ inline Carrier readIfPresent(const Table& table, const Key& key) {
23121
+ if constexpr (requires { table.template readIfPresent<Carrier>(std::string_view(key)); })
23122
+ return table.template readIfPresent<Carrier>(std::string_view(key));
23123
+ else
23124
+ return table.has(key) ? Carrier(table.read(key)) : Carrier();
23125
+ }
23126
+ /** `readIfPresent` for a constant key, with the emitting site's position hint (`Dictionary::hintedPosition`). */
23127
+ template <typename Carrier, typename Table, typename Key>
23128
+ inline Carrier readIfPresentHinted(const Table& table, const Key& key, std::atomic<std::uint32_t>& hint) {
23129
+ if constexpr (requires { table.template readIfPresentHinted<Carrier>(std::string_view(key), hint); })
23130
+ return table.template readIfPresentHinted<Carrier>(std::string_view(key), hint);
23131
+ else
23132
+ return readIfPresent<Carrier>(table, key);
23133
+ }
23134
+ /** `table.read(key)` for a constant key, with the emitting site's position hint. */
23135
+ template <typename Table, typename Key>
23136
+ inline auto readHinted(const Table& table, const Key& key, std::atomic<std::uint32_t>& hint) {
23137
+ if constexpr (requires { table.readHinted(std::string_view(key), hint); })
23138
+ return table.readHinted(std::string_view(key), hint);
23139
+ else
23140
+ return table.read(key);
23141
+ }
21988
23142
  inline gea::Ref<gea::Dictionary<gea::Value>> aliasOf(const gea::Value& object);
21989
23143
  template <typename T>
21990
23144
  gea::Ref<gea::Dictionary<gea::Value>> aliasOf(const gea::Ref<T>& object);
@@ -23489,8 +24643,7 @@ struct DynamicCarrier<CallableObject<Result(Arguments...)>> {
23489
24643
  return value.tag() == Value::Tag::Function && value.payloadType() == payloadTypeTagFor<Self>();
23490
24644
  }
23491
24645
  static Self in(const Value& value, std::size_t position) {
23492
- Self::template registerReceiverEntry<&adapt, &adaptLogicalReceiver>();
23493
- return inAs(value, position, false, -1, &adapt);
24646
+ return inAs(value, position, false, -1, Self::template registerReceiverEntry<&adapt, &adaptLogicalReceiver>());
23494
24647
  }
23495
24648
 
23496
24649
  static Self inWithReceiver(const Value& value, std::size_t position) {
@@ -23551,13 +24704,13 @@ struct DynamicCarrier<CallableObject<Result(Arguments...)>> {
23551
24704
  }
23552
24705
  };
23553
24706
 
23554
- static Self inAs(const Value& value, std::size_t position, bool targetReceivesThis, int targetRestFrom, typename Self::Invoke entry, bool targetActualArguments = false) {
24707
+ static Self inAs(const Value& value, std::size_t position, bool targetReceivesThis, int targetRestFrom, typename Self::RecordedEntry entry, bool targetActualArguments = false) {
23555
24708
  return inAsWithEnvironment(value, position, targetReceivesThis, targetRestFrom, entry, value, targetActualArguments);
23556
24709
  }
23557
24710
 
23558
24711
  template <typename Environment>
23559
24712
  static Self inAsWithEnvironment(const Value& value, std::size_t position, bool targetReceivesThis, int targetRestFrom,
23560
- typename Self::Invoke entry, const Environment& environment, bool targetActualArguments = false) {
24713
+ typename Self::RecordedEntry entry, const Environment& environment, bool targetActualArguments = false) {
23561
24714
  static_assert(supported, "a checked dynamic callable adapter requires an exact carrier for every frame position");
23562
24715
  if (value.tag() == Value::Tag::Undefined) refuseMissingCallArgument(position);
23563
24716
  if (value.tag() != Value::Tag::Function) refusePayloadMismatch("a dynamic call argument");
@@ -23943,6 +25096,13 @@ void writeDynamicField(T& field, const Value& value, const char* owner, const ch
23943
25096
  else refuseUnaddressableField(owner, key);
23944
25097
  }
23945
25098
 
25099
+ /** `writeDynamicField`'s conversion alone, for a setter that takes the carrier by value rather than storing it. */
25100
+ template <typename T>
25101
+ T unboxDynamicField(const Value& value, const char* owner, const char* key) {
25102
+ if constexpr (DynamicCarrier<T>::supported) return DynamicCarrier<T>::in(value, 0);
25103
+ else refuseUnaddressableField(owner, key);
25104
+ }
25105
+
23946
25106
  /**
23947
25107
  * Test a dynamic write without instantiating an unavailable carrier API.
23948
25108
  *
@@ -24349,7 +25509,7 @@ gea::Ref<Dictionary<V>> unboxDynamicDictionary(const Value& value, const char* s
24349
25509
  * dynamic object or an open Document -- what `unboxDynamicDictionary` rebuilds
24350
25510
  * -- is told apart by its values instead: the arm whose value carrier admits
24351
25511
  * every enumerable own string-keyed data value, tried after every exact test,
24352
- * in arm order, so an empty object is the first such arm. Hono's static routes
25512
+ * in arm order, so an empty object is the first such arm. A router's static routes
24353
25513
  * store `Object.create(null)` in an `any` tuple slot that is later read as
24354
25514
  * `ParamIndexMap | Params`.
24355
25515
  */
@@ -25886,11 +27046,12 @@ inline void NativeOwnKeyOrderRecycler::operator()(NativeOwnKeyOrder* order) cons
25886
27046
  order->ordinals.layout = nullptr;
25887
27047
  order->ordinals.declared.clear();
25888
27048
  order->next = 0;
25889
- try {
27049
+ GEA_EH_FENCE_OPEN try {
27050
+ GEA_EH_BODY_FENCE
25890
27051
  pool.push_back(order);
25891
27052
  } catch (...) {
25892
27053
  delete order;
25893
- }
27054
+ } GEA_EH_FENCE_CLOSE
25894
27055
  }
25895
27056
  inline NativeOwnKeyOrderPtr makeNativeOwnKeyOrder() {
25896
27057
  std::vector<NativeOwnKeyOrder*>& pool = nativeOwnKeyOrderPool();
@@ -27484,6 +28645,21 @@ struct NativeFieldWrite {
27484
28645
  const void* slot;
27485
28646
  ReadFn readFn;
27486
28647
  bool exactOnly = false;
28648
+ // A store of a key no view route and no source slot names
28649
+ // (`record::writeLiveOpenField`). The pull above is by requested type, and
28650
+ // an extension table has no type of its own to request, so the write site
28651
+ // names the carrier its receipt certified and the Value materializer only a
28652
+ // dynamic observer runs. Every other write leaves it null, and a live view
28653
+ // then never reaches an extension table at all.
28654
+ using ExtendFn = bool (*)(const NativeFieldWrite&, DynamicObject&, const PropertyKey&, const NativeCallReceiver&);
28655
+ ExtendFn extend = nullptr;
28656
+ void (*extendMaterializer)() = nullptr;
28657
+
28658
+ // The table keeps the carrier itself (`setNativeDataWithNativeReceiver`), a
28659
+ // Value included, so `nativeObjectDataReadNative` reads it back typed.
28660
+ template <typename T, typename Policy>
28661
+ static bool extendNative(const NativeFieldWrite& write, DynamicObject& table, const PropertyKey& key,
28662
+ const NativeCallReceiver& receiver);
27487
28663
 
27488
28664
  template <typename S, typename Policy, std::size_t Index = 0>
27489
28665
  static constexpr bool policyComplete() {
@@ -28827,7 +30003,17 @@ bool nativeLiveViewSourceRead(const gea::Ref<Receiver>& source, const PropertyKe
28827
30003
  auto sourceRead = read;
28828
30004
  if (source->gea_readOwnFieldNative(key, sourceRead)) return true;
28829
30005
  if constexpr (NativeExtensions) {
28830
- if (source->gea_matchesOwnField(key)) return false;
30006
+ // A declared slot that is not present is no own property at all: the
30007
+ // language reads on past it (an optional `depth` the original literal
30008
+ // never set). Only a present slot that refused the reader fails.
30009
+ if (source->gea_matchesOwnField(key)) {
30010
+ bool present = true;
30011
+ if constexpr (requires(const Receiver& receiver, bool& out) { receiver.gea_ownFieldPresent(key, out); }) {
30012
+ if (!source->gea_ownFieldPresent(key, present) || present) return false;
30013
+ } else {
30014
+ return false;
30015
+ }
30016
+ }
28831
30017
  return nativeObjectDataReadNative(source, key, read);
28832
30018
  } else {
28833
30019
  return false;
@@ -28838,9 +30024,56 @@ bool nativeLiveViewSourceRead(const gea::Ref<Receiver>& source, const PropertyKe
28838
30024
  }
28839
30025
  }
28840
30026
 
30027
+ template <typename T, typename Policy>
30028
+ bool NativeFieldWrite::extendNative(const NativeFieldWrite& write, DynamicObject& table, const PropertyKey& key,
30029
+ const NativeCallReceiver& receiver) {
30030
+ std::optional<T> value;
30031
+ if (!write.template read<Policy>(value)) return false;
30032
+ const auto materializer = reinterpret_cast<typename NativeDescriptorData::template Materializer<T>>(write.extendMaterializer);
30033
+ return table.template setNativeDataWithNativeReceiver<T, Policy>(key, *value, materializer, receiver);
30034
+ }
30035
+
30036
+ /** [[Set]] of a key the allocation's layout does not declare, carried by an
30037
+ * open-key write (`NativeFieldWrite::extend`): OrdinarySet on the original
30038
+ * allocation's own expando table -- an existing own entry is overwritten in
30039
+ * place, an inherited setter runs, and anything else creates an own data
30040
+ * property, noted in creation order. The value keeps its certified carrier.
30041
+ */
30042
+ template <typename Receiver>
30043
+ bool nativeObjectDataExtend(const gea::Ref<Receiver>& object, const PropertyKey& key, const NativeFieldWrite& write) {
30044
+ if (!object) host::throwRuntimeError("TypeError", "Cannot set native object data on a nullish receiver");
30045
+ if (write.extend == nullptr) host::throwRuntimeError("TypeError", "an open native write has no certified extension carrier");
30046
+ const auto existing = detail::expandoFor(nativePropertyAnchor(object), false);
30047
+ const bool own = existing && existing->ownProperty(key) != nullptr;
30048
+ if (!own && !nativeIsExtensible(object)) return false;
30049
+ const auto table = own ? existing : detail::expandoFor(nativePropertyAnchor(object), true);
30050
+ if (!write.extend(write, *table, key, NativeCallReceiver::object(object))) return false;
30051
+ if (!own && table->ownProperty(key) != nullptr) detail::noteNativeExpandoKeyCreated(object, key);
30052
+ return true;
30053
+ }
30054
+
30055
+ /** A live view's write of a key it does not route, delegated to its immediate
30056
+ * source. A slot the source declares takes it through the source's own-field
30057
+ * protocol. Any other key is the source's extension only for an open-key
30058
+ * write (`NativeFieldWrite::extend`), which names the carrier to keep; a
30059
+ * fixed-key write that reaches here answers false exactly as before. A source
30060
+ * whose undeclared keys live in an index sidecar has no certified extension
30061
+ * route through a view and fails closed.
30062
+ */
28841
30063
  template <typename Receiver>
28842
30064
  bool nativeLiveViewSourceWrite(const gea::Ref<Receiver>& source, const PropertyKey& key, const NativeFieldWrite& write) {
28843
30065
  if constexpr (requires(Receiver& receiver) { receiver.gea_writeOwnFieldNative(key, write, true); }) {
30066
+ if (write.extend != nullptr) {
30067
+ if constexpr (requires(const Receiver& receiver) { receiver.gea_matchesOwnIndex(key); }) {
30068
+ if (source->gea_matchesOwnIndex(key))
30069
+ host::throwRuntimeError("TypeError", "an open native view write reached an index sidecar it has no carrier for");
30070
+ }
30071
+ if constexpr (requires(const Receiver& receiver) { receiver.gea_matchesOwnField(key); }) {
30072
+ if (!source->gea_matchesOwnField(key)) return nativeObjectDataExtend(source, key, write);
30073
+ } else {
30074
+ host::throwRuntimeError("TypeError", "an open native view write reached a source with no own-field predicate");
30075
+ }
30076
+ }
28844
30077
  return source->gea_writeOwnFieldNative(key, write, nativeIsExtensible(source));
28845
30078
  } else {
28846
30079
  std::fputs("gea: a live view write reached a source with no own-field protocol\n", stderr);
@@ -28848,6 +30081,30 @@ bool nativeLiveViewSourceWrite(const gea::Ref<Receiver>& source, const PropertyK
28848
30081
  }
28849
30082
  }
28850
30083
 
30084
+ /** A live view's write of a key it forwards to its immediate source as a
30085
+ * descriptor (`descriptorForward`), where the certified plan proves the
30086
+ * source's layout does not declare it: JavaScript creates the property on
30087
+ * that source. Only a write naming its carrier (`NativeFieldWrite::extend`)
30088
+ * can store it; any other write answers false exactly as the route did
30089
+ * before. A source that does state its own-field predicate is still asked.
30090
+ */
30091
+ template <typename Receiver>
30092
+ bool nativeLiveViewForwardedWrite(const gea::Ref<Receiver>& source, const PropertyKey& key, const NativeFieldWrite& write) {
30093
+ if (write.extend == nullptr) return false;
30094
+ if constexpr (requires(const Receiver& receiver) { receiver.gea_matchesOwnIndex(key); }) {
30095
+ if (source->gea_matchesOwnIndex(key))
30096
+ host::throwRuntimeError("TypeError", "a forwarded native view write reached an index sidecar it has no carrier for");
30097
+ }
30098
+ if constexpr (requires(const Receiver& receiver) { receiver.gea_matchesOwnField(key); }) {
30099
+ if (source->gea_matchesOwnField(key)) {
30100
+ if constexpr (requires(Receiver& receiver) { receiver.gea_writeOwnFieldNative(key, write, true); })
30101
+ return nativeOwnFieldsWritable(source) && source->gea_writeOwnFieldNative(key, write, nativeIsExtensible(source));
30102
+ return false;
30103
+ }
30104
+ }
30105
+ return nativeObjectDataExtend(source, key, write);
30106
+ }
30107
+
28851
30108
  /**
28852
30109
  * CopyDataProperties' store of one key a spread's receiver does not declare:
28853
30110
  * CreateDataProperty on the receiver's expando. `nativeDynamicSet` is the
@@ -29598,7 +30855,8 @@ struct NativeViewOperations {
29598
30855
  trace(object, visitor);
29599
30856
  return walk.probe;
29600
30857
  }
29601
- static inline const detail::RefOperations table{
30858
+ // Mutable for the reason `RefOperationsFor<T>::table` is.
30859
+ static inline constinit detail::RefOperations table{
29602
30860
  &destroy, &release, &drop, &trace, detail::cycleGenerational ? &holdsTracedEdge : nullptr,
29603
30861
  detail::RefOperationsFor<View>::classBase(), detail::inlineKeyOrderOffsetOf<View>(), detail::inlineKeyOrderLayoutOf<View>()
29604
30862
  #if defined(GEA_PROFILE_ALLOCATIONS)
@@ -29624,13 +30882,13 @@ gea::Ref<View> makeViewWithOrigin(const gea::Ref<Source>& source, Arguments&&...
29624
30882
  }
29625
30883
  void* block = Operations::Pool::take();
29626
30884
  auto* object = reinterpret_cast<View*>(static_cast<unsigned char*>(block) + detail::refHeaderStride);
29627
- try {
30885
+ GEA_EH_TRY_ANY(gea_eh_failed) {
29628
30886
  if constexpr (sizeof...(Arguments) == 0 && requires { typename View::gea_default_init; }) ::new (static_cast<void*>(object)) View;
29629
30887
  else ::new (static_cast<void*>(object)) View(static_cast<Arguments&&>(arguments)...);
29630
- } catch (...) {
30888
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
29631
30889
  Operations::release(block);
29632
- throw;
29633
- }
30890
+ GEA_EH_RETHROW_ANY(gea_eh_failed);
30891
+ } GEA_EH_END
29634
30892
  void* originStorage = static_cast<unsigned char*>(static_cast<void*>(object)) + Operations::originOffset;
29635
30893
  ::new (originStorage) NativeViewOrigin{std::move(owner.held), owner.boxObject, held};
29636
30894
  const auto* sourceOrigin = nativeViewRoute(held);
@@ -29757,13 +31015,35 @@ bool defineLiveField(const gea::Ref<Receiver>& receiver, const PropertyKey& key,
29757
31015
  return nativeDynamicDefineProperty(receiver, key, descriptor);
29758
31016
  }
29759
31017
 
29760
- template <typename Result, typename Receiver, typename Adapter, typename Fallback>
31018
+ /** A fixed field name a live-field access spells as a literal: the receipt's
31019
+ * key, materialized as a `PropertyKey` only when the receiver IS a live view.
31020
+ * The plain allocation every frame's reads and writes take never builds one. */
31021
+ struct LiteralFieldKey {
31022
+ const char* text;
31023
+ std::size_t size;
31024
+ };
31025
+ inline const PropertyKey& livePropertyKey(const PropertyKey& key) { return key; }
31026
+ inline PropertyKey livePropertyKey(const LiteralFieldKey& key) { return PropertyKey::string(std::string(key.text, key.size)); }
31027
+
31028
+ /** `hasLiveFieldView` asked of the allocation itself: no `Ref` is copied, so
31029
+ * the plain allocation's answer costs no count traffic. */
31030
+ template <typename Receiver>
31031
+ [[gnu::always_inline]] inline bool isLiveFieldViewReceiver(const gea::Ref<Receiver>& receiver) {
31032
+ void* object = const_cast<void*>(static_cast<const void*>(receiver.get()));
31033
+ const auto slot = detail::refHeaderOf(object)->operations->nativeViewOriginSlot;
31034
+ if (slot == nullptr) return false;
31035
+ const auto* route = static_cast<const NativeViewOrigin*>(slot(object));
31036
+ return route != nullptr && route->read != nullptr;
31037
+ }
31038
+
31039
+ template <typename Result, typename Receiver, typename Key, typename Adapter, typename Fallback>
29761
31040
  Result readLiveField(
29762
- const gea::Ref<Receiver>& receiver, const PropertyKey& key,
31041
+ const gea::Ref<Receiver>& receiver, const Key& fieldKey,
29763
31042
  Adapter&& adapter, NativeFieldRead::AcceptFn accepts, Fallback&& fallback) {
29764
31043
  if (!receiver) host::throwRuntimeError("TypeError", "Cannot read a property of a nullish native view");
31044
+ if (!isLiveFieldViewReceiver(receiver)) return std::forward<Fallback>(fallback)();
29765
31045
  const gea::Ref<void> held(receiver);
29766
- if (!hasLiveFieldView(held)) return std::forward<Fallback>(fallback)();
31046
+ const auto& key = livePropertyKey(fieldKey);
29767
31047
  std::optional<Result> answer;
29768
31048
  struct Context { std::optional<Result>* answer; std::remove_reference_t<Adapter>* adapter; } context{&answer, &adapter};
29769
31049
  NativeFieldRead read(answer, +[](void* slot, const void* type, const void* policy, const void* value) -> bool {
@@ -29776,13 +31056,14 @@ Result readLiveField(
29776
31056
  return std::move(*answer);
29777
31057
  }
29778
31058
 
29779
- template <typename Receiver, typename Source, typename Adapter, typename Fallback>
31059
+ template <typename Receiver, typename Key, typename Source, typename Adapter, typename Fallback>
29780
31060
  bool writeLiveField(
29781
- const gea::Ref<Receiver>& receiver, const PropertyKey& key, const Source& value,
31061
+ const gea::Ref<Receiver>& receiver, const Key& fieldKey, const Source& value,
29782
31062
  Adapter&& adapter, Fallback&& fallback) {
29783
31063
  if (!receiver) host::throwRuntimeError("TypeError", "Cannot assign a property of a nullish native view");
31064
+ if (!isLiveFieldViewReceiver(receiver)) return std::forward<Fallback>(fallback)();
29784
31065
  const gea::Ref<void> held(receiver);
29785
- if (!hasLiveFieldView(held)) return std::forward<Fallback>(fallback)();
31066
+ const auto& key = livePropertyKey(fieldKey);
29786
31067
  auto write = NativeFieldWrite::exact(value);
29787
31068
  write.exactOnly = false;
29788
31069
  write.slot = &adapter;
@@ -29792,6 +31073,31 @@ bool writeLiveField(
29792
31073
  return writeFieldView(held, key, write);
29793
31074
  }
29794
31075
 
31076
+ /** `writeLiveField` for a runtime key outside every route the receipt names
31077
+ * (`NativeFieldViewWrite.openKeys`). The write additionally carries its
31078
+ * certified carrier (`Source` under `Policy`) and Value materializer, so a
31079
+ * view's source that does not declare the key keeps it natively in its
31080
+ * expando (`nativeLiveViewSourceWrite`); a Document view pulls the same
31081
+ * receipt's Value. A plain allocation runs `fallback` with that write.
31082
+ */
31083
+ template <typename Policy, typename Receiver, typename Source, typename Adapter, typename Fallback>
31084
+ bool writeLiveOpenField(
31085
+ const gea::Ref<Receiver>& receiver, const PropertyKey& key, const Source& value, Adapter&& adapter,
31086
+ typename NativeDescriptorData::template Materializer<Source> materializer, Fallback&& fallback) {
31087
+ if (!receiver) host::throwRuntimeError("TypeError", "Cannot assign a property of a nullish native view");
31088
+ auto write = NativeFieldWrite::exact(value);
31089
+ write.exactOnly = false;
31090
+ write.slot = &adapter;
31091
+ write.readFn = +[](const void* slot, const void* type, const void* policy, void* answer) -> bool {
31092
+ return (*static_cast<const std::remove_reference_t<Adapter>*>(slot))(type, policy, answer);
31093
+ };
31094
+ write.extend = &NativeFieldWrite::template extendNative<Source, Policy>;
31095
+ write.extendMaterializer = reinterpret_cast<void (*)()>(materializer);
31096
+ const gea::Ref<void> held(receiver);
31097
+ if (!hasLiveFieldView(held)) return std::forward<Fallback>(fallback)(static_cast<const NativeFieldWrite&>(write));
31098
+ return writeFieldView(held, key, write);
31099
+ }
31100
+
29795
31101
  template <typename View>
29796
31102
  gea::Ref<void> viewOrigin(const gea::Ref<View>& view) {
29797
31103
  return nativeViewOrigin(gea::Ref<void>(view));
@@ -31715,10 +33021,8 @@ inline Value Value::getProperty(const PropertyKey& key, const Value& receiver) c
31715
33021
  std::size_t index = 0;
31716
33022
  if (detail::arrayIndexOfKey(key, index)) {
31717
33023
  Value answer;
31718
- // A hole and an index past the end both read `undefined`, which is what
31719
- // the default-constructed `answer` already is.
31720
- metadata_->elements->element(payload(), index, answer);
31721
- return answer;
33024
+ if (metadata_->elements->element(payload(), index, answer)) return answer;
33025
+ return dynamicArrayPrototypeGet(key, receiver);
31722
33026
  }
31723
33027
  const auto expando = detail::expandoFor(expandoAnchor(), false);
31724
33028
  if (expando && expando->hasProperty(key)) return expando->get(key, receiver);
@@ -32045,9 +33349,13 @@ inline bool Value::hasProperty(const PropertyKey& key) const {
32045
33349
  // `in` DOES tell a hole from a value, which is why this asks `element`
32046
33350
  // rather than comparing the index against `length`.
32047
33351
  if (detail::arrayIndexOfKey(key, index)) {
32048
- if (metadata_->elements->has != nullptr) return metadata_->elements->has(payload(), index);
32049
- Value probe;
32050
- return metadata_->elements->element(payload(), index, probe);
33352
+ if (metadata_->elements->has != nullptr) {
33353
+ if (metadata_->elements->has(payload(), index)) return true;
33354
+ } else {
33355
+ Value probe;
33356
+ if (metadata_->elements->element(payload(), index, probe)) return true;
33357
+ }
33358
+ return dynamicArrayPrototypeHas(key);
32051
33359
  }
32052
33360
  const auto expando = detail::expandoFor(expandoAnchor(), false);
32053
33361
  return (expando && expando->hasProperty(key)) || dynamicArrayPrototypeGet(key).tag() != Tag::Undefined;
@@ -32283,6 +33591,90 @@ inline bool Value::sameValue(const Value& left, const Value& right) {
32283
33591
  * file's own citations); every other String.prototype/Array.prototype member
32284
33592
  * is refused by name at the `[[Get]]`, never boxed and never guessed at.
32285
33593
  */
33594
+ /**
33595
+ * The code unit `std::regex` matches a RegExp in, its string, and its regex.
33596
+ *
33597
+ * The standard libraries supply ECMAScript regex traits for `wchar_t`, not
33598
+ * `char16_t` or `char32_t`. Where `wchar_t` is 32 bits (Linux, macOS) it holds
33599
+ * every UTF-16 code unit and every Unicode scalar alike, so it is the unit.
33600
+ * Windows' `wchar_t` is 16 bits, which would leave a Unicode-mode pattern no
33601
+ * unit for U+10000 and above. The MSVC STL's `std::basic_regex` takes any
33602
+ * traits class, so there the unit is `char32_t` with `RegexUnitTraits`, which
33603
+ * answers the Basic Multilingual Plane exactly as `std::regex_traits<wchar_t>`
33604
+ * does and gives a scalar above it no character class, no case mapping and no
33605
+ * digit value: ECMAScript's `\d`, `\w` and `\s` name only BMP characters, and
33606
+ * a Unicode-mode pattern with `i` is refused before it reaches a matcher.
33607
+ * libstdc++'s regex reads the locale's ctype facet of its unit type, which
33608
+ * exists for `wchar_t` only, so the xtensa ESP toolchains (16-bit `wchar_t`)
33609
+ * keep `wchar_t` and refuse an astral scalar (`unicodeMatcherUnit`).
33610
+ */
33611
+ namespace gea::runtime {
33612
+ #if WCHAR_MAX < 0x10FFFF && defined(_MSVC_STL_VERSION)
33613
+ struct RegexUnitTraits {
33614
+ using char_type = char32_t;
33615
+ using _Uelem = char32_t; // the MSVC STL's matcher reads it from its traits
33616
+ using string_type = std::u32string;
33617
+ using locale_type = std::locale;
33618
+ using char_class_type = std::regex_traits<wchar_t>::char_class_type;
33619
+
33620
+ std::regex_traits<wchar_t> wide;
33621
+
33622
+ static std::size_t length(const char_type *text) { return std::char_traits<char32_t>::length(text); }
33623
+ static bool basicPlane(char_type unit) { return unit <= 0xFFFF; }
33624
+ template <class It>
33625
+ static std::wstring basicPlaneText(It first, It last) {
33626
+ std::wstring out;
33627
+ for (; first != last; ++first) out.push_back(basicPlane(*first) ? static_cast<wchar_t>(*first) : L'\xFFFF');
33628
+ return out;
33629
+ }
33630
+ char_type translate(char_type unit) const { return unit; }
33631
+ char_type translate_nocase(char_type unit) const {
33632
+ return basicPlane(unit) ? static_cast<char_type>(wide.translate_nocase(static_cast<wchar_t>(unit))) : unit;
33633
+ }
33634
+ template <class It>
33635
+ string_type transform(It first, It last) const {
33636
+ return string_type(first, last);
33637
+ }
33638
+ template <class It>
33639
+ string_type transform_primary(It first, It last) const {
33640
+ string_type out;
33641
+ for (; first != last; ++first) out.push_back(translate_nocase(*first));
33642
+ return out;
33643
+ }
33644
+ template <class It>
33645
+ string_type lookup_collatename(It first, It last) const {
33646
+ const std::wstring name = basicPlaneText(first, last);
33647
+ const std::wstring found = wide.lookup_collatename(name.begin(), name.end());
33648
+ return string_type(found.begin(), found.end());
33649
+ }
33650
+ template <class It>
33651
+ char_class_type lookup_classname(It first, It last, bool icase = false) const {
33652
+ const std::wstring name = basicPlaneText(first, last);
33653
+ return wide.lookup_classname(name.begin(), name.end(), icase);
33654
+ }
33655
+ bool isctype(char_type unit, char_class_type mask) const {
33656
+ return basicPlane(unit) && wide.isctype(static_cast<wchar_t>(unit), mask);
33657
+ }
33658
+ int value(char_type unit, int radix) const { return basicPlane(unit) ? wide.value(static_cast<wchar_t>(unit), radix) : -1; }
33659
+ locale_type imbue(locale_type locale) { return wide.imbue(locale); }
33660
+ locale_type getloc() const { return wide.getloc(); }
33661
+ };
33662
+ using RegexUnit = char32_t;
33663
+ using RegexMatcher = std::basic_regex<RegexUnit, RegexUnitTraits>;
33664
+ #else
33665
+ using RegexUnit = wchar_t;
33666
+ using RegexMatcher = std::wregex;
33667
+ #endif
33668
+ using RegexUnits = std::basic_string<RegexUnit>;
33669
+
33670
+ /** An ASCII pattern fragment in matcher units. */
33671
+ inline RegexUnits asciiRegexUnits(const char *text) {
33672
+ RegexUnits out;
33673
+ for (; *text; ++text) out.push_back(static_cast<RegexUnit>(static_cast<unsigned char>(*text)));
33674
+ return out;
33675
+ }
33676
+ } // namespace gea::runtime
33677
+
32286
33678
  namespace gea::runtime::string {
32287
33679
 
32288
33680
  /**
@@ -32399,19 +33791,19 @@ inline std::string stringFromUtf16CodeUnits(const std::u16string &units) {
32399
33791
  return out;
32400
33792
  }
32401
33793
 
32402
- /** libc++ supplies ECMAScript regex traits for wchar_t, not char16_t. */
32403
- inline std::wstring utf16RegexUnits(const std::string &s) {
33794
+ /** UTF-16 code units as matcher units (see `RegexUnit`). */
33795
+ inline RegexUnits utf16RegexUnits(const std::string &s) {
32404
33796
  const std::u16string units = utf16CodeUnits(s);
32405
- std::wstring out;
33797
+ RegexUnits out;
32406
33798
  out.reserve(units.size());
32407
- for (const char16_t unit : units) out.push_back(static_cast<wchar_t>(unit));
33799
+ for (const char16_t unit : units) out.push_back(static_cast<RegexUnit>(unit));
32408
33800
  return out;
32409
33801
  }
32410
33802
 
32411
- inline std::string stringFromUtf16RegexUnits(const std::wstring &units) {
33803
+ inline std::string stringFromUtf16RegexUnits(const RegexUnits &units) {
32412
33804
  std::u16string utf16;
32413
33805
  utf16.reserve(units.size());
32414
- for (const wchar_t unit : units) {
33806
+ for (const RegexUnit unit : units) {
32415
33807
  // Every string/pattern reaches this projection from UTF-16. A matcher
32416
33808
  // cannot manufacture a scalar outside that domain; reject instead of
32417
33809
  // truncating one if a platform regex implementation violates it.
@@ -34566,6 +35958,198 @@ inline std::string translateDotAll(const std::string &src) {
34566
35958
  return out;
34567
35959
  }
34568
35960
 
35961
+ /**
35962
+ * Whether this standard library's `^` and `$` can match at a line terminator
35963
+ * in a pattern compiled WITHOUT LWG 2503's `multiline`.
35964
+ *
35965
+ * A library without that flag -- the VS 2022 STL, 14.44 and earlier -- has
35966
+ * only ever matched multiline: `^` after a `\n` and `$` before one. The VS 18
35967
+ * STL keeps the same behaviour under `_REGEX_LEGACY_MULTILINE_MODE=1`. A
35968
+ * pattern with `m` is right there, but `/^a/.test("x\na")` answered true where
35969
+ * ES 22.2.2.6 answers false, so a pattern without `m` takes the anchor rewrite
35970
+ * below instead of the library's own `^`/`$`.
35971
+ *
35972
+ * `GEA_REGEX_SIMULATE_LEGACY_MULTILINE` is test-only: on a library that HAS
35973
+ * the flag it compiles every pattern multiline, which is the legacy matcher's
35974
+ * behaviour, so the rewrite is exercised where the legacy library is absent.
35975
+ * On a library without the flag the legacy matcher is already the one in use,
35976
+ * and the macro adds nothing.
35977
+ */
35978
+ #if defined(GEA_REGEX_SIMULATE_LEGACY_MULTILINE) || \
35979
+ !(defined(_LIBCPP_VERSION) || defined(__GLIBCXX__) || (defined(_REGEX_LEGACY_MULTILINE_MODE) && !_REGEX_LEGACY_MULTILINE_MODE))
35980
+ #define GEA_REGEX_LEGACY_ANCHORS 1
35981
+ #endif
35982
+
35983
+ #ifdef GEA_REGEX_LEGACY_ANCHORS
35984
+ /**
35985
+ * A pattern without `m`, rewritten so a multiline-only matcher answers as ES
35986
+ * does. Neither form contains a `^` or `$` the library could match at a line
35987
+ * terminator, so which line terminators that library recognizes (the VS 2022
35988
+ * STL knows only `\n`) does not matter.
35989
+ *
35990
+ * `$` is end of input, which needs no lookbehind: `(?![\s\S])` holds exactly
35991
+ * where no code unit follows, and every search here ends at the end of input.
35992
+ *
35993
+ * `^` is position 0, which a lookahead cannot see, so the search is split by
35994
+ * start position. `later` serves every start after 0 and never matches a `^`.
35995
+ * `atStart` serves the one attempt at position 0 (`match_continuous`, no
35996
+ * previous character): there a `^` reached before anything is consumed is
35997
+ * always at position 0, and the library's own `^` answers it. A `^` that can
35998
+ * be reached after consuming -- `/a\n^b/`, or inside a quantified group --
35999
+ * instead checks that nothing was consumed: a leading lookahead captures the
36000
+ * whole input into group 1, and `(?=\1)` can then only match at position 0,
36001
+ * because anywhere later fewer code units remain than the capture holds. The
36002
+ * program's own groups move up by one in that form, so its back-references
36003
+ * are renumbered and its matches carry one extra group (`startCapture`).
36004
+ *
36005
+ * An anchor followed by a quantifier is left alone: ES rejects `^*`, and so
36006
+ * does std::regex, at the same place it did before.
36007
+ */
36008
+ struct LegacyAnchorRewrite {
36009
+ bool needed = false;
36010
+ bool anchoredStart = false;
36011
+ bool startCapture = false;
36012
+ RegexUnits atStart;
36013
+ RegexUnits later;
36014
+ };
36015
+
36016
+ inline LegacyAnchorRewrite rewriteLegacyAnchors(const RegexUnits &source) {
36017
+ struct Anchor {
36018
+ std::size_t at;
36019
+ bool leading;
36020
+ };
36021
+ struct Frame {
36022
+ bool lookahead;
36023
+ bool leading;
36024
+ std::size_t firstAnchor;
36025
+ };
36026
+ const auto quantifierAt = [&](std::size_t at) {
36027
+ return at < source.size() && (source[at] == L'*' || source[at] == L'+' || source[at] == L'?' || source[at] == L'{');
36028
+ };
36029
+ std::vector<Anchor> anchors;
36030
+ std::vector<Frame> frames;
36031
+ // Whether nothing can have been consumed since the match started, on every
36032
+ // path to here. Conservative: a `^` wrongly called non-leading only costs
36033
+ // the capture, while one wrongly called leading would be matched loosely.
36034
+ bool leading = true;
36035
+ bool topAlternativeStart = true;
36036
+ bool everyAlternativeAnchored = true;
36037
+ for (std::size_t i = 0; i < source.size();) {
36038
+ const RegexUnit c = source[i];
36039
+ if (frames.empty() && topAlternativeStart) {
36040
+ topAlternativeStart = false;
36041
+ if (c != L'^' || quantifierAt(i + 1)) everyAlternativeAnchored = false;
36042
+ }
36043
+ if (c == L'\\') {
36044
+ const RegexUnit escape = i + 1 < source.size() ? source[i + 1] : L'\0';
36045
+ i += 2;
36046
+ if (escape == L'b' || escape == L'B') continue;
36047
+ while (escape >= L'1' && escape <= L'9' && i < source.size() && source[i] >= L'0' && source[i] <= L'9') ++i;
36048
+ leading = false;
36049
+ continue;
36050
+ }
36051
+ if (c == L'[') {
36052
+ // The first unescaped `]` closes the class, `[]` included -- the same
36053
+ // reading `escapeLiteralBracesForStd` and `translateDotAll` use.
36054
+ ++i;
36055
+ while (i < source.size() && source[i] != L']') i += source[i] == L'\\' ? 2 : 1;
36056
+ ++i;
36057
+ leading = false;
36058
+ continue;
36059
+ }
36060
+ if (c == L'(') {
36061
+ const bool special = i + 1 < source.size() && source[i + 1] == L'?';
36062
+ const bool lookahead = special && i + 2 < source.size() && (source[i + 2] == L'=' || source[i + 2] == L'!');
36063
+ frames.push_back(Frame{lookahead, leading, anchors.size()});
36064
+ i += special ? 3 : 1;
36065
+ continue;
36066
+ }
36067
+ if (c == L')') {
36068
+ ++i;
36069
+ if (frames.empty()) {
36070
+ leading = false;
36071
+ continue;
36072
+ }
36073
+ const Frame frame = frames.back();
36074
+ frames.pop_back();
36075
+ // A repeated group enters its body again after consuming.
36076
+ if (quantifierAt(i)) {
36077
+ for (std::size_t k = frame.firstAnchor; k < anchors.size(); ++k) anchors[k].leading = false;
36078
+ }
36079
+ leading = frame.lookahead && frame.leading;
36080
+ continue;
36081
+ }
36082
+ if (c == L'|') {
36083
+ ++i;
36084
+ leading = frames.empty() || frames.back().leading;
36085
+ if (frames.empty()) topAlternativeStart = true;
36086
+ continue;
36087
+ }
36088
+ if (c == L'^' || c == L'$') {
36089
+ if (!quantifierAt(i + 1)) anchors.push_back(Anchor{i, leading});
36090
+ ++i;
36091
+ continue;
36092
+ }
36093
+ ++i;
36094
+ leading = false;
36095
+ }
36096
+ LegacyAnchorRewrite out;
36097
+ if (anchors.empty()) return out;
36098
+ out.needed = true;
36099
+ out.anchoredStart = everyAlternativeAnchored && !topAlternativeStart;
36100
+ for (const Anchor &anchor : anchors) {
36101
+ if (source[anchor.at] == L'^' && !anchor.leading) out.startCapture = true;
36102
+ }
36103
+ out.atStart.reserve(source.size() + 32);
36104
+ out.later.reserve(source.size() + 32);
36105
+ if (out.startCapture) out.atStart += asciiRegexUnits("(?=([\\s\\S]*))");
36106
+ std::size_t nextAnchor = 0;
36107
+ bool inClass = false;
36108
+ for (std::size_t i = 0; i < source.size();) {
36109
+ const RegexUnit c = source[i];
36110
+ if (c == L'\\' && i + 1 < source.size()) {
36111
+ std::size_t end = i + 2;
36112
+ if (!inClass && out.startCapture && source[i + 1] >= L'1' && source[i + 1] <= L'9') {
36113
+ while (end < source.size() && source[end] >= L'0' && source[end] <= L'9') ++end;
36114
+ // Decimal increment on the digits themselves, so no width can overflow.
36115
+ RegexUnits reference(source, i + 1, end - i - 1);
36116
+ std::size_t digit = reference.size();
36117
+ while (digit > 0 && reference[digit - 1] == L'9') reference[--digit] = L'0';
36118
+ if (digit == 0) reference.insert(reference.begin(), L'1');
36119
+ else ++reference[digit - 1];
36120
+ out.atStart += L'\\';
36121
+ out.atStart += reference;
36122
+ } else {
36123
+ out.atStart.append(source, i, 2);
36124
+ }
36125
+ out.later.append(source, i, end - i);
36126
+ i = end;
36127
+ continue;
36128
+ }
36129
+ if (inClass) {
36130
+ if (c == L']') inClass = false;
36131
+ } else if (c == L'[') {
36132
+ inClass = true;
36133
+ } else if (nextAnchor < anchors.size() && anchors[nextAnchor].at == i) {
36134
+ const Anchor &anchor = anchors[nextAnchor++];
36135
+ if (c == L'$') {
36136
+ out.atStart += asciiRegexUnits("(?![\\s\\S])");
36137
+ out.later += asciiRegexUnits("(?![\\s\\S])");
36138
+ } else {
36139
+ out.atStart += anchor.leading ? asciiRegexUnits("^") : asciiRegexUnits("(?=\\1)");
36140
+ out.later += asciiRegexUnits("[^\\s\\S]");
36141
+ }
36142
+ ++i;
36143
+ continue;
36144
+ }
36145
+ out.atStart.push_back(c);
36146
+ out.later.push_back(c);
36147
+ ++i;
36148
+ }
36149
+ return out;
36150
+ }
36151
+ #endif
36152
+
34569
36153
  [[noreturn]] inline void throwTypeError(const std::string &message);
34570
36154
 
34571
36155
  /**
@@ -34573,7 +36157,7 @@ inline std::string translateDotAll(const std::string &src) {
34573
36157
  *
34574
36158
  * Unicode mode decodes the pattern and the input to code points so dot,
34575
36159
  * classes and quantifiers see an astral character whole, and std::regex then
34576
- * matches them as `wchar_t`. That is exact where `wchar_t` is 32 bits and
36160
+ * matches them as `RegexUnit`s. That is exact where the unit is 32 bits and
34577
36161
  * impossible where it is 16 -- the xtensa ESP toolchain reports
34578
36162
  * `sizeof(wchar_t) == 2` -- because U+10000 and above do not fit, and
34579
36163
  * libstdc++ has no `regex_traits<char32_t>` to widen to. A `static_assert`
@@ -34583,21 +36167,21 @@ inline std::string translateDotAll(const std::string &src) {
34583
36167
  * and unicodeSets refusals below are: a TypeError at the site, never a silent
34584
36168
  * split into surrogate halves.
34585
36169
  */
34586
- inline wchar_t unicodeMatcherUnit(std::uint32_t scalar) {
34587
- if constexpr (sizeof(wchar_t) < 4) {
36170
+ inline RegexUnit unicodeMatcherUnit(std::uint32_t scalar) {
36171
+ if constexpr (sizeof(RegexUnit) < 4) {
34588
36172
  if (scalar > 0xFFFF) {
34589
36173
  throwTypeError("Unicode RegExp matching of code points above U+FFFF needs a 32-bit wchar_t matcher, which this platform's toolchain does not provide");
34590
36174
  }
34591
36175
  }
34592
- return static_cast<wchar_t>(scalar);
36176
+ return static_cast<RegexUnit>(scalar);
34593
36177
  }
34594
36178
 
34595
36179
  /** Decode into scalars while preserving one exact UTF-16 matcher boundary. */
34596
- inline std::wstring unicodeRegexUnits(
36180
+ inline RegexUnits unicodeRegexUnits(
34597
36181
  const std::string &text,
34598
36182
  std::size_t exactBoundary = std::numeric_limits<std::size_t>::max()) {
34599
36183
  const std::u16string units = gea::runtime::string::utf16CodeUnits(text);
34600
- std::wstring out;
36184
+ RegexUnits out;
34601
36185
  out.reserve(units.size());
34602
36186
  for (std::size_t index = 0; index < units.size(); ++index) {
34603
36187
  const std::uint32_t first = units[index];
@@ -34609,15 +36193,15 @@ inline std::wstring unicodeRegexUnits(
34609
36193
  continue;
34610
36194
  }
34611
36195
  }
34612
- out.push_back(static_cast<wchar_t>(first));
36196
+ out.push_back(static_cast<RegexUnit>(first));
34613
36197
  }
34614
36198
  return out;
34615
36199
  }
34616
36200
 
34617
- inline std::string stringFromUnicodeRegexUnits(const std::wstring &units) {
36201
+ inline std::string stringFromUnicodeRegexUnits(const RegexUnits &units) {
34618
36202
  std::string out;
34619
36203
  out.reserve(units.size() * 2);
34620
- for (const wchar_t unit : units) gea::runtime::string::appendUtf8CodePoint(out, static_cast<double>(unit));
36204
+ for (const RegexUnit unit : units) gea::runtime::string::appendUtf8CodePoint(out, static_cast<double>(unit));
34621
36205
  return out;
34622
36206
  }
34623
36207
 
@@ -34673,7 +36257,7 @@ inline bool decodeUnicodeEscapeAt(
34673
36257
  return true;
34674
36258
  }
34675
36259
 
34676
- inline void appendUnicodeRegexLiteral(std::wstring &out, std::uint32_t value) {
36260
+ inline void appendUnicodeRegexLiteral(RegexUnits &out, std::uint32_t value) {
34677
36261
  // A value reached through CharacterEscape is an atom, even when it happens
34678
36262
  // to spell a regex metacharacter. Escape it again for std::regex's parser.
34679
36263
  if (value <= 0x7F) {
@@ -34695,7 +36279,7 @@ inline void appendUnicodeRegexLiteral(std::wstring &out, std::uint32_t value) {
34695
36279
  * every raw source character is decoded to one wide scalar so dot, classes,
34696
36280
  * ranges and quantifiers operate on code points rather than surrogate halves.
34697
36281
  */
34698
- inline bool unicodeRegexSource(const std::string &source, std::wstring &out) {
36282
+ inline bool unicodeRegexSource(const std::string &source, RegexUnits &out) {
34699
36283
  out.clear();
34700
36284
  out.reserve(source.size());
34701
36285
  for (std::size_t index = 0; index < source.size();) {
@@ -34727,7 +36311,7 @@ inline bool unicodeRegexSource(const std::string &source, std::wstring &out) {
34727
36311
  if ((escape == 'p' || escape == 'P') && index + 2 < source.size() && source[index + 2] == '{') return false;
34728
36312
  if (escape == 'k' && index + 2 < source.size() && source[index + 2] == '<') return false;
34729
36313
  out.push_back(L'\\');
34730
- out.push_back(static_cast<wchar_t>(static_cast<unsigned char>(escape)));
36314
+ out.push_back(static_cast<RegexUnit>(static_cast<unsigned char>(escape)));
34731
36315
  index += 2;
34732
36316
  }
34733
36317
  return true;
@@ -35090,7 +36674,7 @@ inline bool validatePatternSource(const std::string &source, bool unicode = fals
35090
36674
  }
35091
36675
  if (parenDepth != 0) return false;
35092
36676
  if (!unicode) return true;
35093
- std::wstring translated;
36677
+ RegexUnits translated;
35094
36678
  return unicodeRegexSource(source, translated);
35095
36679
  }
35096
36680
 
@@ -35189,7 +36773,7 @@ struct MatchSlice {
35189
36773
  * write -- `/^[a-z0-9._-]+(?::\d{3,4})?$/`, `/\/\.\.?(?:[/?#]|$)/` -- run on
35190
36774
  * the UTF-8 bytes directly.
35191
36775
  *
35192
- * `std::regex` over a transcoded `std::wstring` costs a conversion and an
36776
+ * `std::regex` over a transcoded `RegexUnits` costs a conversion and an
35193
36777
  * allocation per call before matching starts, which dominates a `test` on a
35194
36778
  * short string. This answers `test` without either.
35195
36779
  *
@@ -35662,7 +37246,7 @@ struct Pattern {
35662
37246
  // shapes the libc++/libstdc++ ECMAScript parser understands. When no
35663
37247
  // translation applies the two strings are identical.
35664
37248
  std::string compiledSource;
35665
- std::wstring unicodeCompiledSource;
37249
+ RegexUnits unicodeCompiledSource;
35666
37250
 
35667
37251
  // v1: `Pattern::group_names` / `Pattern::has_named_groups`.
35668
37252
  //
@@ -35678,11 +37262,11 @@ struct Pattern {
35678
37262
 
35679
37263
  // The compiled `std::regex` for this pattern, resolved once. `compiledRegex`
35680
37264
  // used to re-transcode `compiledSource` to UTF-16 and look the result up in
35681
- // the process-wide cache -- a wstring key built and compared -- on EVERY
37265
+ // the process-wide cache -- a matcher-unit key built and compared -- on EVERY
35682
37266
  // `test`/`exec`. The map's nodes are never erased, so the pointer is good
35683
37267
  // for the process. `source` and the flags are fixed at construction (there
35684
37268
  // is no `compile()` mutation in this runtime), so nothing invalidates it.
35685
- mutable const std::wregex* compiledCache = nullptr;
37269
+ mutable const RegexMatcher* compiledCache = nullptr;
35686
37270
  // A pattern that is one literal string -- a `/\x00/` key check, a
35687
37271
  // `/,/` split -- is a substring search, not a `std::regex_search` over a
35688
37272
  // transcoded copy of the input: libc++'s ECMAScript matcher was 8% of a
@@ -36025,7 +37609,13 @@ struct Pattern {
36025
37609
  std::regex::flag_type stdFlags() const {
36026
37610
  auto value = std::regex::ECMAScript;
36027
37611
  if (ignoreCase) value |= std::regex::icase;
37612
+ // LWG 2503's `multiline` is not in every standard library.
37613
+ #if defined(GEA_REGEX_SIMULATE_LEGACY_MULTILINE) && \
37614
+ (defined(_LIBCPP_VERSION) || defined(__GLIBCXX__) || defined(_REGEX_LEGACY_MULTILINE_MODE))
37615
+ value |= std::regex_constants::multiline;
37616
+ #elif defined(_LIBCPP_VERSION) || defined(__GLIBCXX__) || defined(_REGEX_LEGACY_MULTILINE_MODE)
36028
37617
  if (multiline) value |= std::regex_constants::multiline;
37618
+ #endif
36029
37619
  return value;
36030
37620
  }
36031
37621
 
@@ -36036,13 +37626,13 @@ struct Pattern {
36036
37626
  * on every evaluation of a regex literal inside a loop, so the process-wide
36037
37627
  * cache keyed by (flags, source) is kept.
36038
37628
  */
36039
- using Utf16Regex = std::wregex;
36040
- using Utf16Match = std::match_results<std::wstring::const_iterator>;
37629
+ using Utf16Regex = RegexMatcher;
37630
+ using Utf16Match = std::match_results<RegexUnits::const_iterator>;
36041
37631
 
36042
- static const Utf16Regex &cachedStdRegex(const std::wstring &source, std::regex::flag_type flags) {
36043
- using Cache = std::map<std::pair<std::wstring, unsigned>, Utf16Regex>;
37632
+ static const Utf16Regex &cachedStdRegex(const RegexUnits &source, std::regex::flag_type flags) {
37633
+ using Cache = std::map<std::pair<RegexUnits, unsigned>, Utf16Regex>;
36044
37634
  GEA_REALM_LOCAL(Cache, cache, {});
36045
- const std::pair<std::wstring, unsigned> key(source, static_cast<unsigned>(flags));
37635
+ const std::pair<RegexUnits, unsigned> key(source, static_cast<unsigned>(flags));
36046
37636
  auto found = cache.find(key);
36047
37637
  if (found != cache.end()) return found->second;
36048
37638
  // A pattern `std::regex` cannot compile is a **SyntaxError**, not a
@@ -36052,20 +37642,34 @@ struct Pattern {
36052
37642
  // kill the process. The source validator deliberately covers only the
36053
37643
  // syntax this runtime rewrites itself; this catch remains the fail-closed
36054
37644
  // boundary for an incompatibility in the platform regex implementation.
37645
+ #if GEA_EH_FENCED
37646
+ std::optional<std::regex_error> failure;
37647
+ {
37648
+ ::gea::EhFence gea_eh_fence;
37649
+ try {
37650
+ ::gea::EhFence gea_eh_body;
37651
+ return cache.emplace(key, Utf16Regex(source, flags)).first->second;
37652
+ } catch (const std::regex_error &error) {
37653
+ ::gea::detail::recordThrown(failure, error);
37654
+ }
37655
+ }
37656
+ throwSyntaxErrorLate(std::string("Invalid regular expression: ") + failure->what());
37657
+ #else
36055
37658
  try {
36056
37659
  return cache.emplace(key, Utf16Regex(source, flags)).first->second;
36057
37660
  } catch (const std::regex_error &error) {
36058
37661
  throwSyntaxErrorLate(std::string("Invalid regular expression: ") + error.what());
36059
37662
  }
37663
+ #endif
36060
37664
  }
36061
37665
 
36062
37666
  static const Utf16Regex &cachedStdRegex(const std::string &source, std::regex::flag_type flags) {
36063
37667
  return cachedStdRegex(gea::runtime::string::utf16RegexUnits(source), flags);
36064
37668
  }
36065
37669
 
36066
- const std::wstring &matcherSource() const {
37670
+ const RegexUnits &matcherSource() const {
36067
37671
  if (unicode) return unicodeCompiledSource;
36068
- static thread_local std::wstring source;
37672
+ static thread_local RegexUnits source;
36069
37673
  source = gea::runtime::string::utf16RegexUnits(compiledSource);
36070
37674
  return source;
36071
37675
  }
@@ -36075,13 +37679,62 @@ struct Pattern {
36075
37679
  return *compiledCache;
36076
37680
  }
36077
37681
 
36078
- std::wstring matcherInput(
37682
+ #ifdef GEA_REGEX_LEGACY_ANCHORS
37683
+ // `rewriteLegacyAnchors`' two forms, resolved on first search: 0 unknown,
37684
+ // 1 rewritten, -1 nothing to rewrite (`m`, or no anchor outside a class).
37685
+ mutable signed char legacyAnchorState = 0;
37686
+ mutable const Utf16Regex *legacyAtStart = nullptr;
37687
+ // Null when every alternative opens with `^`: no later start can match.
37688
+ mutable const Utf16Regex *legacyLater = nullptr;
37689
+ mutable std::size_t legacyAtStartGroupOffset = 0;
37690
+
37691
+ /**
37692
+ * The leftmost match starting at or after `startUnits`, as
37693
+ * `std::regex_search` from there would find it on a library whose `^`/`$`
37694
+ * respect `multiline`. Positions in `match` are absolute in `input`; capture
37695
+ * group `n` is `match[n + groupOffset]`.
37696
+ */
37697
+ bool searchMatcher(const RegexUnits &input, std::size_t startUnits, Utf16Match &match, std::size_t &groupOffset) const {
37698
+ groupOffset = 0;
37699
+ // The pattern as written is compiled first, so a pattern std::regex
37700
+ // rejects raises the SyntaxError it always raised.
37701
+ const Utf16Regex &compiled = compiledRegex();
37702
+ if (legacyAnchorState == 0) {
37703
+ const LegacyAnchorRewrite rewrite = multiline ? LegacyAnchorRewrite{} : rewriteLegacyAnchors(matcherSource());
37704
+ if (rewrite.needed) {
37705
+ // Settled only once both forms compiled: a throw here must not leave
37706
+ // the library's loose anchors answering the next call.
37707
+ legacyAtStart = &cachedStdRegex(rewrite.atStart, stdFlags());
37708
+ if (!rewrite.anchoredStart) legacyLater = &cachedStdRegex(rewrite.later, stdFlags());
37709
+ legacyAtStartGroupOffset = rewrite.startCapture ? 1 : 0;
37710
+ }
37711
+ legacyAnchorState = rewrite.needed ? 1 : -1;
37712
+ }
37713
+ if (legacyAnchorState < 0) {
37714
+ auto flags = std::regex_constants::match_default;
37715
+ if (startUnits > 0) flags |= std::regex_constants::match_prev_avail;
37716
+ return std::regex_search(input.cbegin() + static_cast<std::ptrdiff_t>(startUnits), input.cend(), match, compiled, flags);
37717
+ }
37718
+ if (startUnits == 0) {
37719
+ if (std::regex_search(input.cbegin(), input.cend(), match, *legacyAtStart, std::regex_constants::match_continuous)) {
37720
+ groupOffset = legacyAtStartGroupOffset;
37721
+ return true;
37722
+ }
37723
+ startUnits = 1;
37724
+ }
37725
+ if (legacyLater == nullptr || startUnits > input.size()) return false;
37726
+ return std::regex_search(
37727
+ input.cbegin() + static_cast<std::ptrdiff_t>(startUnits), input.cend(), match, *legacyLater, std::regex_constants::match_prev_avail);
37728
+ }
37729
+ #endif
37730
+
37731
+ RegexUnits matcherInput(
36079
37732
  const std::string &input,
36080
37733
  std::size_t exactBoundary = std::numeric_limits<std::size_t>::max()) const {
36081
37734
  return unicode ? unicodeRegexUnits(input, exactBoundary) : gea::runtime::string::utf16RegexUnits(input);
36082
37735
  }
36083
37736
 
36084
- std::size_t matcherIndexFromUtf16(const std::wstring &input, std::size_t units) const {
37737
+ std::size_t matcherIndexFromUtf16(const RegexUnits &input, std::size_t units) const {
36085
37738
  if (!unicode) return units;
36086
37739
  std::size_t seen = 0;
36087
37740
  for (std::size_t index = 0; index < input.size(); ++index) {
@@ -36093,7 +37746,7 @@ struct Pattern {
36093
37746
  return input.size();
36094
37747
  }
36095
37748
 
36096
- std::size_t utf16IndexFromMatcher(const std::wstring &input, std::size_t index) const {
37749
+ std::size_t utf16IndexFromMatcher(const RegexUnits &input, std::size_t index) const {
36097
37750
  if (!unicode) return index;
36098
37751
  std::size_t units = 0;
36099
37752
  for (std::size_t at = 0; at < std::min(index, input.size()); ++at) {
@@ -36102,7 +37755,7 @@ struct Pattern {
36102
37755
  return units;
36103
37756
  }
36104
37757
 
36105
- std::string captureFromMatcher(const std::wstring &capture) const {
37758
+ std::string captureFromMatcher(const RegexUnits &capture) const {
36106
37759
  return unicode ? stringFromUnicodeRegexUnits(capture) : gea::runtime::string::stringFromUtf16RegexUnits(capture);
36107
37760
  }
36108
37761
 
@@ -36127,8 +37780,17 @@ struct Pattern {
36127
37780
  // Unicode mode CodePointAt sees the trailing surrogate there as a lone
36128
37781
  // code point; preserving this exact boundary keeps sticky/global matching
36129
37782
  // at that index instead of snapping backward to the pair's high surrogate.
36130
- const std::wstring inputUnits = matcherInput(input, stateful ? startPublicUnits : std::numeric_limits<std::size_t>::max());
37783
+ const RegexUnits inputUnits = matcherInput(input, stateful ? startPublicUnits : std::numeric_limits<std::size_t>::max());
36131
37784
  const std::size_t startUnits = matcherIndexFromUtf16(inputUnits, startPublicUnits);
37785
+ #ifdef GEA_REGEX_LEGACY_ANCHORS
37786
+ Utf16Match match;
37787
+ std::size_t groupOffset = 0;
37788
+ if (!searchMatcher(inputUnits, startUnits, match, groupOffset)) {
37789
+ if (stateful) resetLastIndex();
37790
+ return MatchSlice{};
37791
+ }
37792
+ const std::size_t matchStartUnits = static_cast<std::size_t>(match[0].first - inputUnits.cbegin());
37793
+ #else
36132
37794
  const Utf16Regex &compiled = compiledRegex();
36133
37795
  Utf16Match match;
36134
37796
  auto searchBegin = inputUnits.cbegin() + static_cast<std::ptrdiff_t>(startUnits);
@@ -36139,6 +37801,7 @@ struct Pattern {
36139
37801
  return MatchSlice{};
36140
37802
  }
36141
37803
  const std::size_t matchStartUnits = startUnits + static_cast<std::size_t>(match.position(0));
37804
+ #endif
36142
37805
  if (sticky && matchStartUnits != startUnits) {
36143
37806
  resetLastIndex();
36144
37807
  return MatchSlice{};
@@ -36154,6 +37817,9 @@ struct Pattern {
36154
37817
  out.length = matchEndPublicUnits - matchStartPublicUnits;
36155
37818
  out.captures.reserve(match.size());
36156
37819
  for (std::size_t i = 0; i < match.size(); ++i) {
37820
+ #ifdef GEA_REGEX_LEGACY_ANCHORS
37821
+ if (i > 0 && i <= groupOffset) continue;
37822
+ #endif
36157
37823
  // An unmatched group is ABSENT, not the empty string: ES 22.2.7.2 step
36158
37824
  // 28.b stores `undefined` for it, and a program that tests
36159
37825
  // `m[2] === undefined` must be able to tell the two apart.
@@ -36179,8 +37845,14 @@ struct Pattern {
36179
37845
  if (found >= 0) return found == 1;
36180
37846
  }
36181
37847
  }
36182
- const std::wstring inputUnits = matcherInput(input);
37848
+ const RegexUnits inputUnits = matcherInput(input);
37849
+ #ifdef GEA_REGEX_LEGACY_ANCHORS
37850
+ Utf16Match match;
37851
+ std::size_t groupOffset = 0;
37852
+ return searchMatcher(inputUnits, 0, match, groupOffset);
37853
+ #else
36183
37854
  return std::regex_search(inputUnits, compiledRegex());
37855
+ #endif
36184
37856
  }
36185
37857
  };
36186
37858
 
@@ -36921,6 +38593,30 @@ template <typename T>
36921
38593
  * the question asked first where the mismatch must be a catchable `TypeError`
36922
38594
  * (`rebuildDynamicArray`).
36923
38595
  */
38596
+ template <typename Target>
38597
+ bool boxedClassRefAdmits(const Value& value);
38598
+
38599
+ /**
38600
+ * A boxed (`any`) argument a callable adapter frame hands to a body that
38601
+ * declares a class parameter (`emit-narrowing.ts`'s `assertedUnionText`,
38602
+ * `FRAME_ARGUMENT_UNION_MATERIALIZER`): the function was stored into a slot
38603
+ * whose frame also admits `any`. An instance of the class (or of a
38604
+ * descendant) is that object; anything else -- `null` included, which the
38605
+ * class parameter cannot hold -- is a catchable `TypeError`.
38606
+ */
38607
+ template <typename Target>
38608
+ gea::Ref<Target> frameArgumentClassRef(const Value& value) {
38609
+ const auto* target = &gea::detail::RefOperationsFor<Target>::table;
38610
+ if (value.tag() != Value::Tag::Object || !value.classObject() ||
38611
+ (!gea::detail::classIdentityExtends(value.classIdentity(), target) &&
38612
+ value.classIdentity() != &gea::detail::PlainObjectOperationsFor<Target>::table)) {
38613
+ throwRuntimeError("TypeError",
38614
+ "a function stored into a slot whose frame also admits `any` was passed an argument that is not an "
38615
+ "instance of the class its parameter declares");
38616
+ }
38617
+ return value.classObject().template staticCast<Target>();
38618
+ }
38619
+
36924
38620
  template <typename Target>
36925
38621
  bool boxedClassRefAdmits(const Value& value) {
36926
38622
  if (value.tag() == Value::Tag::Null) return true;
@@ -37003,24 +38699,37 @@ inline gea::Ref<gea::ArrayObject<std::string>> splitByPattern(
37003
38699
  const std::string &input,
37004
38700
  const gea::runtime::regex::Pattern &pattern) {
37005
38701
  auto out = gea::makeRef<gea::ArrayObject<std::string>>();
38702
+ #ifndef GEA_REGEX_LEGACY_ANCHORS
37006
38703
  const gea::runtime::regex::Pattern::Utf16Regex &compiled = pattern.compiledRegex();
37007
- const std::wstring inputUnits = pattern.matcherInput(input);
38704
+ #endif
38705
+ const RegexUnits inputUnits = pattern.matcherInput(input);
37008
38706
  // Step 14: an empty input either yields one empty string or nothing at all,
37009
38707
  // decided by whether the separator matches it.
37010
38708
  if (input.empty()) {
37011
38709
  gea::runtime::regex::Pattern::Utf16Match probe;
38710
+ #ifdef GEA_REGEX_LEGACY_ANCHORS
38711
+ std::size_t probeGroupOffset = 0;
38712
+ if (!pattern.searchMatcher(inputUnits, 0, probe, probeGroupOffset)) out->push(input);
38713
+ #else
37012
38714
  if (!std::regex_search(inputUnits, probe, compiled)) out->push(input);
38715
+ #endif
37013
38716
  return out;
37014
38717
  }
37015
38718
  std::size_t chunkStartUnits = 0;
37016
38719
  std::size_t cursorMatcherUnits = 0;
37017
38720
  while (cursorMatcherUnits < inputUnits.size()) {
37018
38721
  gea::runtime::regex::Pattern::Utf16Match match;
38722
+ #ifdef GEA_REGEX_LEGACY_ANCHORS
38723
+ std::size_t groupOffset = 0;
38724
+ if (!pattern.searchMatcher(inputUnits, cursorMatcherUnits, match, groupOffset)) break;
38725
+ const std::size_t positionMatcherUnits = static_cast<std::size_t>(match[0].first - inputUnits.cbegin());
38726
+ #else
37019
38727
  auto begin = inputUnits.cbegin() + static_cast<std::ptrdiff_t>(cursorMatcherUnits);
37020
38728
  auto flags = std::regex_constants::match_default;
37021
38729
  if (cursorMatcherUnits > 0) flags |= std::regex_constants::match_prev_avail;
37022
38730
  if (!std::regex_search(begin, inputUnits.cend(), match, compiled, flags)) break;
37023
38731
  const std::size_t positionMatcherUnits = cursorMatcherUnits + static_cast<std::size_t>(match.position(0));
38732
+ #endif
37024
38733
  const std::size_t endMatcherUnits = positionMatcherUnits + static_cast<std::size_t>(match.length(0));
37025
38734
  const std::size_t positionUnits = pattern.utf16IndexFromMatcher(inputUnits, positionMatcherUnits);
37026
38735
  const std::size_t endUnits = pattern.utf16IndexFromMatcher(inputUnits, endMatcherUnits);
@@ -37038,7 +38747,11 @@ inline gea::Ref<gea::ArrayObject<std::string>> splitByPattern(
37038
38747
  // order. An unmatched group appends `undefined` in the spec; the declared
37039
38748
  // element type here is `string`, so it appends the empty string -- the
37040
38749
  // same divergence `ExecResult::capture` states, for the same reason.
38750
+ #ifdef GEA_REGEX_LEGACY_ANCHORS
38751
+ for (std::size_t group = 1 + groupOffset; group < match.size(); ++group) {
38752
+ #else
37041
38753
  for (std::size_t group = 1; group < match.size(); ++group) {
38754
+ #endif
37042
38755
  out->push(match[group].matched ? pattern.captureFromMatcher(match.str(group)) : std::string());
37043
38756
  }
37044
38757
  chunkStartUnits = endUnits;
@@ -37626,15 +39339,15 @@ auto fromIterator(gea::Iterator<E> source, const Callable& fn) {
37626
39339
  // generator source before the throw propagates. A throw out of that
37627
39340
  // `return()` is discarded -- the mapper's completion is the one that
37628
39341
  // escapes (IteratorClose step 5). A native cursor has nothing to close.
37629
- try {
39342
+ GEA_EH_TRY_ANY(gea_eh_failed) {
37630
39343
  if constexpr (std::is_void_v<Produced>) { fromCall(fn, value, index); result->push(Undefined{}); }
37631
39344
  else result->push(fromCall(fn, value, index));
37632
- } catch (...) {
39345
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
37633
39346
  if (source.isGeneratorFrame()) {
37634
- try { (void)source.resumeReturn({}); } catch (...) {}
39347
+ GEA_EH_FENCE_OPEN try { GEA_EH_BODY_FENCE (void)source.resumeReturn({}); } catch (...) {} GEA_EH_FENCE_CLOSE
37635
39348
  }
37636
- throw;
37637
- }
39349
+ GEA_EH_RETHROW_ANY(gea_eh_failed);
39350
+ } GEA_EH_END
37638
39351
  index += 1;
37639
39352
  }
37640
39353
  return result;
@@ -38740,6 +40453,10 @@ inline double toNumber(double value) { return value; }
38740
40453
  // ECMAScript ToNumber(boolean): true -> 1, false -> 0.
38741
40454
  inline double toNumber(bool value) { return value ? 1.0 : 0.0; }
38742
40455
 
40456
+ // ECMAScript ToNumber of a boxed value (`Number` itself handed over as a callback
40457
+ // whose convention states `any`: `text.split(',').map(Number)`).
40458
+ inline double toNumber(const Value& value) { return gea::dynamicToNumber(value); }
40459
+
38743
40460
  // ECMAScript ToNumber(null) = 0. See the top-of-file note: v1 has no
38744
40461
  // standalone carrier for null, only an arm of a union visitor.
38745
40462
  inline double toNumberNull() { return 0.0; }
@@ -42620,11 +44337,12 @@ inline gea::Ref<ErrorRecord> create(const gea::Optional<std::string>& message) {
42620
44337
  namespace PromiseConstructor {
42621
44338
 
42622
44339
  inline std::exception_ptr rejectionReason(const gea::Value& reason) {
42623
- try {
44340
+ GEA_EH_TRY_ANY(gea_eh_failed) {
42624
44341
  throw reason;
42625
- } catch (...) {
42626
- return std::current_exception();
42627
- }
44342
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
44343
+ return GEA_EH_CURRENT(gea_eh_failed);
44344
+ } GEA_EH_END
44345
+ GEA_EH_UNREACHABLE
42628
44346
  }
42629
44347
 
42630
44348
  /**
@@ -42724,11 +44442,11 @@ struct RejecterFactory;
42724
44442
  template <typename Reason, typename V>
42725
44443
  struct RejecterFactory<gea::CallableObject<void(Reason)>, V> {
42726
44444
  static void invoke(void* environment, Reason reason) {
42727
- try {
44445
+ GEA_EH_TRY_ANY(gea_eh_failed) {
42728
44446
  throw gea::detail::DynamicCarrier<Reason>::out(reason);
42729
- } catch (...) {
42730
- static_cast<gea::Promise<V>*>(environment)->reject(std::current_exception());
42731
- }
44447
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
44448
+ static_cast<gea::Promise<V>*>(environment)->reject(GEA_EH_CURRENT(gea_eh_failed));
44449
+ } GEA_EH_END
42732
44450
  }
42733
44451
 
42734
44452
  static gea::CallableObject<void(Reason)> make(const gea::Promise<V>& promise) {
@@ -42800,22 +44518,22 @@ struct VoidExecutorRunner<gea::CallableObject<Completion(Resolver, Rejecter)>> {
42800
44518
  template <typename V, typename Executor>
42801
44519
  inline gea::Promise<V> construct(const Executor& executor) {
42802
44520
  gea::Promise<V> result;
42803
- try {
44521
+ GEA_EH_TRY_ANY(gea_eh_failed) {
42804
44522
  ExecutorRunner<Executor, V>::run(executor, result);
42805
- } catch (...) {
42806
- result.reject(std::current_exception());
42807
- }
44523
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
44524
+ result.reject(GEA_EH_CURRENT(gea_eh_failed));
44525
+ } GEA_EH_END
42808
44526
  return result;
42809
44527
  }
42810
44528
 
42811
44529
  template <typename Executor>
42812
44530
  inline gea::Promise<void> constructVoid(const Executor& executor) {
42813
44531
  gea::Promise<void> result;
42814
- try {
44532
+ GEA_EH_TRY_ANY(gea_eh_failed) {
42815
44533
  VoidExecutorRunner<Executor>::run(executor, result);
42816
- } catch (...) {
42817
- result.reject(std::current_exception());
42818
- }
44534
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
44535
+ result.reject(GEA_EH_CURRENT(gea_eh_failed));
44536
+ } GEA_EH_END
42819
44537
  return result;
42820
44538
  }
42821
44539
 
@@ -42828,20 +44546,20 @@ inline gea::Promise<void> constructVoid(const Executor& executor) {
42828
44546
  */
42829
44547
  template <typename V, typename Executor>
42830
44548
  inline void initialize(gea::Promise<V>& target, const Executor& executor) {
42831
- try {
44549
+ GEA_EH_TRY_ANY(gea_eh_failed) {
42832
44550
  ExecutorRunner<Executor, V>::run(executor, target);
42833
- } catch (...) {
42834
- target.reject(std::current_exception());
42835
- }
44551
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
44552
+ target.reject(GEA_EH_CURRENT(gea_eh_failed));
44553
+ } GEA_EH_END
42836
44554
  }
42837
44555
 
42838
44556
  template <typename Executor>
42839
44557
  inline void initializeVoid(gea::Promise<void>& target, const Executor& executor) {
42840
- try {
44558
+ GEA_EH_TRY_ANY(gea_eh_failed) {
42841
44559
  VoidExecutorRunner<Executor>::run(executor, target);
42842
- } catch (...) {
42843
- target.reject(std::current_exception());
42844
- }
44560
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
44561
+ target.reject(GEA_EH_CURRENT(gea_eh_failed));
44562
+ } GEA_EH_END
42845
44563
  }
42846
44564
 
42847
44565
  template <typename V>
@@ -43151,12 +44869,12 @@ struct ThenableSettlement {
43151
44869
  */
43152
44870
  inline bool adoptThenable(gea::Promise<gea::Value>& target, const gea::Value& thenable) {
43153
44871
  gea::Value then;
43154
- try {
44872
+ GEA_EH_TRY_ANY(gea_eh_failed) {
43155
44873
  then = thenable.getProperty(gea::PropertyKey::string("then"));
43156
- } catch (...) {
43157
- target.reject(std::current_exception());
44874
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
44875
+ target.reject(GEA_EH_CURRENT(gea_eh_failed));
43158
44876
  return true;
43159
- }
44877
+ } GEA_EH_END
43160
44878
  if (then.tag() != gea::Value::Tag::Function) return false;
43161
44879
  gea::Promise<gea::Value> adopting = target;
43162
44880
  queuePromiseJob([adopting, thenable, then]() mutable {
@@ -43183,13 +44901,13 @@ inline bool adoptThenable(gea::Promise<gea::Value>& target, const gea::Value& th
43183
44901
  gea::Value::Tag::Function,
43184
44902
  gea::CallableObject<gea::Value(gea::Value)>(invoke, packEnvironment(ThenableSettlement{adopting, settled, rejecting})));
43185
44903
  };
43186
- try {
44904
+ GEA_EH_TRY_ANY(gea_eh_failed) {
43187
44905
  then.callWithReceiver(thenable, {function(false), function(true)});
43188
- } catch (...) {
44906
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
43189
44907
  if (*settled) return;
43190
44908
  *settled = true;
43191
- adopting.reject(std::current_exception());
43192
- }
44909
+ adopting.reject(GEA_EH_CURRENT(gea_eh_failed));
44910
+ } GEA_EH_END
43193
44911
  });
43194
44912
  return true;
43195
44913
  }
@@ -43216,11 +44934,12 @@ inline bool boxedPromiseMethod(const gea::Value& self, const gea::PropertyKey& k
43216
44934
  }
43217
44935
 
43218
44936
  inline std::exception_ptr boxedRejection(const gea::Value& reason) {
43219
- try {
44937
+ GEA_EH_TRY_ANY(gea_eh_failed) {
43220
44938
  throw reason;
43221
- } catch (...) {
43222
- return std::current_exception();
43223
- }
44939
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
44940
+ return GEA_EH_CURRENT(gea_eh_failed);
44941
+ } GEA_EH_END
44942
+ GEA_EH_UNREACHABLE
43224
44943
  }
43225
44944
 
43226
44945
  /** Settles `result` with what `handler` makes of `argument`; a non-callable handler passes the argument through. */
@@ -43230,11 +44949,11 @@ inline void settleThroughHandler(gea::Promise<gea::Value>& result, const gea::Va
43230
44949
  else result.resolve(argument);
43231
44950
  return;
43232
44951
  }
43233
- try {
44952
+ GEA_EH_TRY_ANY(gea_eh_failed) {
43234
44953
  result.resolve(handler.callWithReceiver(gea::Value(), {argument}));
43235
- } catch (...) {
43236
- result.reject(std::current_exception());
43237
- }
44954
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
44955
+ result.reject(GEA_EH_CURRENT(gea_eh_failed));
44956
+ } GEA_EH_END
43238
44957
  }
43239
44958
 
43240
44959
  template <typename V>
@@ -43259,11 +44978,11 @@ gea::Promise<V> promiseFromDynamic(const gea::Value& value, Unbox unbox) {
43259
44978
  gea::Promise<V> result;
43260
44979
  boxed.observe(
43261
44980
  [result, unbox](const gea::Value& settled) mutable {
43262
- try {
44981
+ GEA_EH_TRY_ANY(gea_eh_failed) {
43263
44982
  result.resolve(unbox(settled));
43264
- } catch (...) {
43265
- result.reject(std::current_exception());
43266
- }
44983
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
44984
+ result.reject(GEA_EH_CURRENT(gea_eh_failed));
44985
+ } GEA_EH_END
43267
44986
  },
43268
44987
  [result](std::exception_ptr reason) mutable { result.reject(reason); });
43269
44988
  return result;
@@ -43311,11 +45030,11 @@ BoxedPromiseOps boxedPromiseOpsFor() {
43311
45030
  using Settle = std::function<void(const gea::Value&)>;
43312
45031
  static const auto observe = [](const P& source, Settle fulfilled, Settle rejected) {
43313
45032
  auto onRejected = [rejected](std::exception_ptr reason) {
43314
- try {
45033
+ GEA_EH_TRY_VALUE(gea_eh_caught) {
43315
45034
  std::rethrow_exception(reason);
43316
- } catch (const gea::Value& thrown) {
45035
+ } GEA_EH_CATCH_VALUE(gea_eh_caught, thrown) {
43317
45036
  rejected(thrown);
43318
- }
45037
+ } GEA_EH_END
43319
45038
  };
43320
45039
  if constexpr (std::is_void_v<V>) {
43321
45040
  source.observe([fulfilled]() { fulfilled(gea::Value()); }, onRejected);
@@ -43492,22 +45211,24 @@ inline void validateCloseResult(const gea::Value& value) {
43492
45211
 
43493
45212
  /** IteratorClose with an already-throwing completion preserves that original throw. */
43494
45213
  inline void closePreservingThrow(const gea::Value& iterator) {
43495
- try {
45214
+ GEA_EH_FENCE_OPEN try {
45215
+ GEA_EH_BODY_FENCE
43496
45216
  close(iterator);
43497
45217
  } catch (const gea::Value&) {
43498
45218
  // ECMA-262 IteratorClose gives an existing throw completion precedence
43499
45219
  // over GetMethod/Call/result-validation failures from `return`.
43500
- }
45220
+ } GEA_EH_FENCE_CLOSE
43501
45221
  }
43502
45222
 
43503
45223
  /** A failing IteratorNext/IteratorComplete/IteratorValue is an abrupt completion that closes the iterator. */
43504
45224
  inline Step stepClosing(const gea::Value& iterator) {
43505
- try {
45225
+ GEA_EH_TRY_VALUE(gea_eh_caught) {
43506
45226
  return step(iterator);
43507
- } catch (const gea::Value&) {
45227
+ } GEA_EH_CATCH_VALUE_UNNAMED(gea_eh_caught) {
43508
45228
  closePreservingThrow(iterator);
43509
- throw;
43510
- }
45229
+ GEA_EH_RETHROW_VALUE(gea_eh_caught);
45230
+ } GEA_EH_END
45231
+ GEA_EH_UNREACHABLE
43511
45232
  }
43512
45233
 
43513
45234
  /**
@@ -43611,10 +45332,11 @@ class CompletionGuard {
43611
45332
  if (closed_) return;
43612
45333
  if (std::uncaught_exceptions() > uncaughtOnEntry_) {
43613
45334
  closed_ = true;
43614
- try {
45335
+ GEA_EH_FENCE_OPEN try {
45336
+ GEA_EH_BODY_FENCE
43615
45337
  action_();
43616
45338
  } catch (...) {
43617
- }
45339
+ } GEA_EH_FENCE_CLOSE
43618
45340
  return;
43619
45341
  }
43620
45342
  close();
@@ -43797,32 +45519,24 @@ decltype(auto) eventFields(Event& event) {
43797
45519
  // Event handler attributes accept null to remove the callback. Do not create a
43798
45520
  // new callback-table entry when an already closed socket is being cleaned up.
43799
45521
  inline void setWebSocketOnOpen(const gea::host::WebSocket& socket, std::nullptr_t) {
43800
- auto& callbacks = gea::host::websocket::callbackTable();
43801
- auto found = callbacks.find(socket.nativeHandle);
43802
- if (found != callbacks.end()) found->second.on_open = nullptr;
45522
+ gea::host::websocket::set_open_callback(socket.nativeHandle, {});
43803
45523
  }
43804
45524
 
43805
45525
  inline void setWebSocketOnMessage(const gea::host::WebSocket& socket, std::nullptr_t) {
43806
- auto& callbacks = gea::host::websocket::callbackTable();
43807
- auto found = callbacks.find(socket.nativeHandle);
43808
- if (found != callbacks.end()) found->second.on_message = nullptr;
45526
+ gea::host::websocket::set_message_callback(socket.nativeHandle, {});
43809
45527
  }
43810
45528
 
43811
45529
  inline void setWebSocketOnClose(const gea::host::WebSocket& socket, std::nullptr_t) {
43812
- auto& callbacks = gea::host::websocket::callbackTable();
43813
- auto found = callbacks.find(socket.nativeHandle);
43814
- if (found != callbacks.end()) found->second.on_close = nullptr;
45530
+ gea::host::websocket::set_close_callback(socket.nativeHandle, {});
43815
45531
  }
43816
45532
 
43817
45533
  inline void setWebSocketOnError(const gea::host::WebSocket& socket, std::nullptr_t) {
43818
- auto& callbacks = gea::host::websocket::callbackTable();
43819
- auto found = callbacks.find(socket.nativeHandle);
43820
- if (found != callbacks.end()) found->second.on_error = nullptr;
45534
+ gea::host::websocket::set_error_callback(socket.nativeHandle, {});
43821
45535
  }
43822
45536
 
43823
45537
  template <typename Result>
43824
45538
  void setWebSocketOnOpen(const gea::host::WebSocket& socket, const gea::CallableObject<Result()>& handler) {
43825
- gea::host::websocket::callbackTable()[socket.nativeHandle].on_open = [handler]() { handler.call(); };
45539
+ gea::host::websocket::set_open_callback(socket.nativeHandle, [handler]() { handler.call(); });
43826
45540
  }
43827
45541
 
43828
45542
  /**
@@ -43844,31 +45558,31 @@ void setWebSocketOnOpen(const gea::host::WebSocket& socket, const gea::CallableO
43844
45558
  */
43845
45559
  template <typename Result>
43846
45560
  void setWebSocketOnMessage(const gea::host::WebSocket& socket, const gea::CallableObject<Result()>& handler) {
43847
- gea::host::websocket::callbackTable()[socket.nativeHandle].on_message = [handler](const std::string&) { handler.call(); };
45561
+ gea::host::websocket::set_message_callback(socket.nativeHandle, [handler](const std::string&) { handler.call(); });
43848
45562
  }
43849
45563
 
43850
45564
  template <typename Result>
43851
45565
  void setWebSocketOnClose(const gea::host::WebSocket& socket, const gea::CallableObject<Result()>& handler) {
43852
- gea::host::websocket::callbackTable()[socket.nativeHandle].on_close = [handler](int, const std::string&) { handler.call(); };
45566
+ gea::host::websocket::set_close_callback(socket.nativeHandle, [handler](int, const std::string&) { handler.call(); });
43853
45567
  }
43854
45568
 
43855
45569
  template <typename Result>
43856
45570
  void setWebSocketOnError(const gea::host::WebSocket& socket, const gea::CallableObject<Result()>& handler) {
43857
- gea::host::websocket::callbackTable()[socket.nativeHandle].on_error = [handler](const std::string&) { handler.call(); };
45571
+ gea::host::websocket::set_error_callback(socket.nativeHandle, [handler](const std::string&) { handler.call(); });
43858
45572
  }
43859
45573
 
43860
45574
  template <typename Result, typename Event>
43861
45575
  void setWebSocketOnMessage(const gea::host::WebSocket& socket, const gea::CallableObject<Result(Event)>& handler) {
43862
- gea::host::websocket::callbackTable()[socket.nativeHandle].on_message = [handler](const std::string& data) {
45576
+ gea::host::websocket::set_message_callback(socket.nativeHandle, [handler](const std::string& data) {
43863
45577
  Event event = makeEvent<Event>();
43864
45578
  assign(eventFields(event).data, data);
43865
45579
  handler.call(event);
43866
- };
45580
+ });
43867
45581
  }
43868
45582
 
43869
45583
  template <typename Result, typename Event>
43870
45584
  void setWebSocketOnClose(const gea::host::WebSocket& socket, const gea::CallableObject<Result(Event)>& handler) {
43871
- gea::host::websocket::callbackTable()[socket.nativeHandle].on_close = [handler](int code, const std::string& reason) {
45585
+ gea::host::websocket::set_close_callback(socket.nativeHandle, [handler](int code, const std::string& reason) {
43872
45586
  Event event = makeEvent<Event>();
43873
45587
  assign(eventFields(event).code, static_cast<double>(code));
43874
45588
  assign(eventFields(event).reason, reason);
@@ -43878,16 +45592,16 @@ void setWebSocketOnClose(const gea::host::WebSocket& socket, const gea::Callable
43878
45592
  // error.
43879
45593
  assign(eventFields(event).wasClean, true);
43880
45594
  handler.call(event);
43881
- };
45595
+ });
43882
45596
  }
43883
45597
 
43884
45598
  template <typename Result, typename Event>
43885
45599
  void setWebSocketOnError(const gea::host::WebSocket& socket, const gea::CallableObject<Result(Event)>& handler) {
43886
- gea::host::websocket::callbackTable()[socket.nativeHandle].on_error = [handler](const std::string& message) {
45600
+ gea::host::websocket::set_error_callback(socket.nativeHandle, [handler](const std::string& message) {
43887
45601
  Event event = makeEvent<Event>();
43888
45602
  assign(eventFields(event).message, message);
43889
45603
  handler.call(event);
43890
- };
45604
+ });
43891
45605
  }
43892
45606
 
43893
45607
  /**
@@ -44411,12 +46125,13 @@ gea::Promise<void> addIceCandidate(const gea::host::RTCPeerConnection& peer, con
44411
46125
  namespace gea::runtime::hostaudio {
44412
46126
  template<class MediaElement>
44413
46127
  inline gea::Promise<void> play(const MediaElement& element) {
44414
- try {
46128
+ GEA_EH_TRY_ANY(gea_eh_failed) {
44415
46129
  if (element.play()) return gea::Promise<void>::settled_value();
44416
46130
  return gea::Promise<void>::rejected_with(std::make_exception_ptr(std::runtime_error("Media playback could not start")));
44417
- } catch (...) {
44418
- return gea::Promise<void>::rejected_with(std::current_exception());
44419
- }
46131
+ } GEA_EH_CATCH_ANY(gea_eh_failed) {
46132
+ return gea::Promise<void>::rejected_with(GEA_EH_CURRENT(gea_eh_failed));
46133
+ } GEA_EH_END
46134
+ GEA_EH_UNREACHABLE
44420
46135
  }
44421
46136
  }
44422
46137
 
@@ -44772,6 +46487,16 @@ void setNodeAttribute(Node& node, const std::string& name, const std::string& va
44772
46487
  node.setAttribute(name, value);
44773
46488
  }
44774
46489
 
46490
+ template <typename Node>
46491
+ void setBooleanNodeAttribute(Node& node, const std::string& name, bool value) {
46492
+ if (name == "disabled") {
46493
+ if (value) node.setAttribute(name, "");
46494
+ else node.removeAttribute(name);
46495
+ return;
46496
+ }
46497
+ setNodeAttribute(node, name, value ? "true" : "false");
46498
+ }
46499
+
44775
46500
  template <typename Node>
44776
46501
  void setNodeStyle(Node& node, const std::string& property, const std::string& value) {
44777
46502
  node.style().setProperty(property, value);
@@ -44795,65 +46520,54 @@ inline void recordNodeSubscription(int nodeId, std::function<void()> release);
44795
46520
  template <typename Node>
44796
46521
  gea::Ref<bool> nodeLiveToken(const Node& node);
44797
46522
 
44798
- /**
44799
- * Whether the engine dispatches `name` off-tree. `rotary` (the encoder dial)
44800
- * always: it has no element target, the runtime hands each detent to the one
44801
- * document-level listener chain (`dispatchDocumentRotary`), and
44802
- * `Tree::setEventListener` drops "rotary" as a type it never walks the tree
44803
- * for -- so an `onRotary` delegated to the body was registered nowhere and the
44804
- * dial did nothing, silently. `keydown` and `keyup` are off-tree on anything but an
44805
- * `<input>`: the runtime hands a key to the focused input's own listener (which
44806
- * bubbles to the body) and then to the document-level chain. The same rule the
44807
- * gea plugin's `cpp-mounted-lowering.ts` applies to its direct-root listeners.
44808
- */
46523
+ /** Rotary remains an off-tree compatibility notification; keys use the native root's node path. */
44809
46524
  template <typename Node>
44810
- bool isDocumentLevelEvent(const Node& node, const std::string& name) {
44811
- if (name == "rotary") return true;
44812
- if (name != "keydown" && name != "keyup") return false;
44813
- const char* tag = node.tagName();
44814
- if (!tag) return true;
44815
- std::string lowered(tag);
44816
- for (char& character : lowered) character = static_cast<char>(std::tolower(static_cast<unsigned char>(character)));
44817
- return lowered != "input";
46525
+ bool isDocumentLevelEvent(const Node&, const std::string& name) {
46526
+ return name == "rotary";
44818
46527
  }
44819
46528
 
44820
46529
  /**
44821
- * Register `invoke` for `name` on behalf of `node`: the one place both engine
44822
- * `addNodeListener` overloads bind through.
44823
- *
44824
- * A document-level event goes straight to `Document::addEventListener`, which
44825
- * chains it onto the off-tree singleton: no `containsNode` gate, since there is
44826
- * no target to contain. The chain has no per-listener removal, so the handler
44827
- * is gated on the node's live token instead -- a rebuilt subtree leaves an
44828
- * inert closure behind rather than a second generation of the handler.
44829
- *
44830
- * Everything else is delegated to the BODY and gated by `containsNode`; see
44831
- * the no-argument `addNodeListener` for why, and `recordNodeSubscription` for
44832
- * how it is released with the node.
46530
+ * Restores an event's currentTarget/phase after a node handler runs. It lives at
46531
+ * namespace scope: clang leaves a local class's inline destructor inside a
46532
+ * generic lambda of a function template uninstantiated, and the link fails.
44833
46533
  */
46534
+ struct CurrentTargetRestore {
46535
+ gea::framework::events::PointerEvent& event;
46536
+ gea::framework::events::EventTarget target;
46537
+ int targetId;
46538
+ gea::framework::events::EventPhase phase;
46539
+ ~CurrentTargetRestore() {
46540
+ event.currentTarget = target;
46541
+ event.currentTargetId = targetId;
46542
+ event.eventPhase = phase;
46543
+ }
46544
+ };
46545
+
46546
+ /** Bind native node handlers to their allocation and retain the compiler's early-disposal fence. */
44834
46547
  template <typename Node, typename Invoke>
44835
46548
  void bindNodeListener(Node& node, const std::string& name, Invoke invoke) {
44836
46549
  const auto target = node;
44837
- auto run = [target, invoke](gea::framework::events::PointerEvent& event) mutable {
44838
- const auto previousTarget = event.currentTarget;
44839
- const auto previousTargetId = event.currentTargetId;
44840
- const auto previousPhase = event.eventPhase;
46550
+ auto alive = nodeLiveToken(node);
46551
+ auto run = gea::framework::events::explicitEventCallback([](auto& target, auto& alive, auto& invoke, gea::framework::events::PointerEvent& event) {
46552
+ if (!*alive || !target.valid() || !target.isConnected()) return;
46553
+ CurrentTargetRestore restore{event, event.currentTarget, event.currentTargetId, event.eventPhase};
44841
46554
  event.currentTarget = gea::framework::events::EventTarget(target.id());
44842
46555
  event.currentTargetId = target.id();
44843
46556
  event.eventPhase = event.targetId == target.id() ? gea::framework::events::EventPhase::AtTarget
44844
46557
  : gea::framework::events::EventPhase::Bubbling;
44845
46558
  invoke(event);
44846
- event.currentTarget = previousTarget;
44847
- event.currentTargetId = previousTargetId;
44848
- event.eventPhase = previousPhase;
44849
- };
46559
+ }, target, alive, std::move(invoke));
44850
46560
  if (isDocumentLevelEvent(node, name)) {
44851
- auto alive = nodeLiveToken(node);
44852
- gea::embedded::ui::Document::instance().addEventListener(
44853
- name.c_str(), [alive, run](gea::framework::events::PointerEvent& event) mutable {
44854
- if (!*alive) return;
44855
- run(event);
44856
- });
46561
+ gea::embedded::ui::Document::instance().addEventListener(name.c_str(), std::move(run));
46562
+ return;
46563
+ }
46564
+ if (name == "keydown" || name == "keyup") {
46565
+ // The native root dispatcher now walks the real allocation-bound node
46566
+ // path. Document delegation bypassed that path and outlived raw removal.
46567
+ const auto listenerId = target.addEventListener(name.c_str(), std::move(run));
46568
+ recordNodeSubscription(target.id(), [target, name, listenerId]() {
46569
+ target.removeEventListener(name.c_str(), listenerId);
46570
+ });
44857
46571
  return;
44858
46572
  }
44859
46573
  #if defined(GEA_JSX_NODE_LISTENER_HOOK)
@@ -44863,10 +46577,10 @@ void bindNodeListener(Node& node, const std::string& name, Invoke invoke) {
44863
46577
  GEA_JSX_NODE_LISTENER_HOOK(target.id(), name.c_str());
44864
46578
  #endif
44865
46579
  const auto listenerId = gea::embedded::ui::Document::instance().body().addEventListener(
44866
- name.c_str(), [target, run](gea::framework::events::PointerEvent& event) mutable {
46580
+ name.c_str(), gea::framework::events::explicitEventCallback([](auto& target, auto& run, gea::framework::events::PointerEvent& event) {
44867
46581
  if (!gea::embedded::ui::Tree::instance().containsNode(target.id(), event.targetId)) return;
44868
46582
  run(event);
44869
- });
46583
+ }, target, std::move(run)));
44870
46584
  recordNodeSubscription(target.id(), [name, listenerId]() {
44871
46585
  gea::embedded::ui::Document::instance().body().removeEventListener(name.c_str(), listenerId);
44872
46586
  });
@@ -44887,72 +46601,34 @@ void bindNodeListener(Node& node, const std::string& name, Invoke invoke) {
44887
46601
 
44888
46602
  template <typename Node, typename Result>
44889
46603
  void addNodeListener(Node& node, const std::string& type, const gea::CallableObject<Result()>& handler) {
44890
- // Registered on the BODY, not on `node`, and gated by `containsNode`.
44891
- //
44892
- // The engine dispatches a pointer event to the node the hit test named and
44893
- // to nothing else -- it does not walk ancestors. So `onClick` on a `<div>`
44894
- // whose only child is a `<span>` never ran: the hit landed on the span, the
44895
- // listener sat on the div, and the app rendered perfectly and did nothing.
44896
- //
44897
- // Bubbling is the caller's job, and v1 does it exactly this way -- see any
44898
- // `mount_*` in the gea plugin's mounted-renderer output (all 12 of a JSX
44899
- // todo list's click listeners are on the body, none on a node): an early
44900
- // return unless `Tree::containsNode(root, event.targetId)`, then
44901
- // `currentTarget`/`currentTargetId`/`eventPhase` set for the duration of the
44902
- // handler and restored after, so a nested handler sees its own target and
44903
- // the outer one is not left holding the inner one's.
44904
- //
44905
- // OWNED BY `node`, and released when `node` is taken down -- see
44906
- // `recordNodeSubscription` below. The listener lives on the body, but the body
44907
- // is never removed, so nothing else would ever take it off: a conditional
44908
- // branch or a list row that is rebuilt leaves its handler on the body forever,
44909
- // and `Tree::createNode` hands the freed node ids straight back to the
44910
- // subtree that replaces it. Every generation's handler then matches the same
44911
- // `containsNode` gate and they ALL run on one click. An idempotent handler
44912
- // (`setActive(id)`, `managing = 1`) survives that; a TOGGLE does not -- a
44913
- // toggle button ran `toggle()` once per generation, so after one rebuild a click
44914
- // flipped the state twice and the whole UI stayed where it was, with nothing
44915
- // logged and every node still rendering correctly.
46604
+ // Keys are owned by the real node and follow the native root's ancestor
46605
+ // path. Pointer handlers retain the existing body-delegation compatibility
46606
+ // path, gated by containment. Both record early JSX disposal; native node
46607
+ // removal additionally releases the node-owned keyboard listener itself.
44916
46608
  const gea::CallableObject<Result()> held = handler;
44917
- bindNodeListener(node, eventTypeOf(type), [held](gea::framework::events::PointerEvent&) mutable { held.call(); });
46609
+ bindNodeListener(node, eventTypeOf(type), gea::framework::events::explicitEventCallback([](auto& held, gea::framework::events::PointerEvent&) { held.call(); }, held));
44918
46610
  }
44919
46611
 
44920
46612
  /**
44921
- * A handler that DOES declare the event -- `onTouchMove={e => pan(e.clientX,
44922
- * e.clientY)}`.
44923
- *
44924
- * Delegated to the BODY and gated by `containsNode`, for the same reason and by
44925
- * the same rule as the no-argument overload above: the engine dispatches to the
44926
- * node the hit test named and does not walk ancestors, so a listener sitting on
44927
- * the node it was written on never fires when the hit lands on a child. This
44928
- * overload previously registered on the node -- which is why a `<div>` wrapping
44929
- * the whole app received nothing at all, and the refusal it was supposed to
44930
- * print never even ran. A drag that does nothing, silently.
44931
- *
44932
- * The event is passed through as the engine's own `PointerEvent` whenever the
44933
- * declared parameter has a carrier for it (the gea plugin package maps
44934
- * `PointerEvent`/`TouchEvent`/`RotaryEvent` onto `gea::framework::events::
44935
- * PointerEvent` in `nativeTypes`, so `e.clientX` is a native member read, not a
44936
- * boxed property). `currentTarget`/`currentTargetId`/`eventPhase` are set for
44937
- * the duration of the call and restored after, so the handler observes the node
44938
- * it was written on rather than the descendant that was hit.
44939
- *
44940
- * A parameter type with no such carrier still refuses at the moment it fires,
44941
- * rather than being handed a value-initialized event whose every field reads
44942
- * zero -- naming it is the honest answer, and a silent 0 would be a miscompile.
46613
+ * A declared event parameter uses the engine's own native PointerEvent carrier.
46614
+ * Keyboard handlers bind to the allocation-owned node; pointer compatibility
46615
+ * handlers remain delegated to the body. bindNodeListener scopes currentTarget
46616
+ * and eventPhase for either route, including exceptional and nested callbacks.
46617
+ * A parameter with no native carrier refuses when invoked rather than receiving
46618
+ * a fabricated default event.
44943
46619
  */
44944
46620
  template <typename Node, typename Result, typename Argument>
44945
46621
  void addNodeListener(Node& node, const std::string& type, const gea::CallableObject<Result(Argument)>& handler) {
44946
46622
  const gea::CallableObject<Result(Argument)> held = handler;
44947
46623
  const std::string name = eventTypeOf(type);
44948
- bindNodeListener(node, name, [held, name](gea::framework::events::PointerEvent& event) mutable {
46624
+ bindNodeListener(node, name, gea::framework::events::explicitEventCallback([](auto& held, auto& name, gea::framework::events::PointerEvent& event) {
44949
46625
  if constexpr (std::is_constructible_v<std::decay_t<Argument>, const gea::framework::events::PointerEvent&>) {
44950
46626
  held.call(static_cast<std::decay_t<Argument>>(event));
44951
46627
  } else {
44952
46628
  std::fprintf(stderr, "gea: the handler for \"%s\" declares an event parameter, which no host table states a carrier for\n", name.c_str());
44953
46629
  gea::detail::abortAfterFlush();
44954
46630
  }
44955
- });
46631
+ }, held, name));
44956
46632
  }
44957
46633
 
44958
46634
  template <typename Node, typename Result, typename... Arguments, typename = std::enable_if_t<(sizeof...(Arguments) > 1)>>
@@ -44989,6 +46665,16 @@ void setNodeAttribute(Node& node, const std::string& name, const std::string& va
44989
46665
  JsxDocument::instance().setAttribute(node.id(), name, value);
44990
46666
  }
44991
46667
 
46668
+ template <typename Node>
46669
+ void setBooleanNodeAttribute(Node& node, const std::string& name, bool value) {
46670
+ if (name == "disabled") {
46671
+ if (value) JsxDocument::instance().setAttribute(node.id(), name, "");
46672
+ else JsxDocument::instance().removeAttribute(node.id(), name);
46673
+ return;
46674
+ }
46675
+ setNodeAttribute(node, name, value ? "true" : "false");
46676
+ }
46677
+
44992
46678
  template <typename Node>
44993
46679
  void setNodeStyle(Node& node, const std::string& property, const std::string& value) {
44994
46680
  JsxDocument::instance().setStyleProperty(node.id(), property, value);
@@ -45119,7 +46805,7 @@ void prop(Node& node, const std::string& name, const V& value) {
45119
46805
  node.style().imageId(value.id);
45120
46806
  #endif
45121
46807
  } else if constexpr (std::is_same_v<V, bool>) {
45122
- detail::setNodeAttribute(node, name, value ? "true" : "false");
46808
+ detail::setBooleanNodeAttribute(node, name, value);
45123
46809
  } else if constexpr (std::is_convertible_v<V, std::string>) {
45124
46810
  detail::setNodeAttribute(node, name, static_cast<std::string>(value));
45125
46811
  } else if constexpr (std::is_arithmetic_v<V>) {
@@ -45756,6 +47442,7 @@ inline void recordNodeSubscription(int nodeId, std::function<void()> release) {
45756
47442
  /** Run and forget every release `nodeId` owns, in the order they were recorded. */
45757
47443
  inline void releaseNodeSubscriptions(int nodeId) {
45758
47444
  auto& owned = nodeSubscriptions();
47445
+ std::exception_ptr failure;
45759
47446
  #if defined(GEA_RUNTIME_COMPACT_CODE) && GEA_RUNTIME_COMPACT_CODE
45760
47447
  // Unlinked before any runs: a release may record another node's
45761
47448
  // subscription, which appends to the list under the walk.
@@ -45780,16 +47467,33 @@ inline void releaseNodeSubscriptions(int nodeId) {
45780
47467
  NodeSubscription* entry = releasing;
45781
47468
  releasing = entry->next;
45782
47469
  if (entry->alive) *entry->alive = false;
45783
- if (entry->release) entry->release();
47470
+ try {
47471
+ if (entry->release) entry->release();
47472
+ } catch (...) {
47473
+ if (!failure) failure = std::current_exception();
47474
+ }
45784
47475
  delete entry;
45785
47476
  }
45786
47477
  #else
45787
47478
  const auto found = owned.find(nodeId);
45788
47479
  if (found != owned.end()) {
45789
- for (auto& release : found->second) release();
47480
+ std::vector<std::function<void()>> releasing;
47481
+ releasing.swap(found->second);
45790
47482
  owned.erase(found);
47483
+ // No map/vector iterator survives user cleanup or capture destruction.
47484
+ // Reentrant registration for the same node owns a fresh list.
47485
+ for (auto& release : releasing) {
47486
+ try {
47487
+ release();
47488
+ } catch (...) {
47489
+ if (!failure) failure = std::current_exception();
47490
+ }
47491
+ }
45791
47492
  }
45792
47493
  #endif
47494
+ // Both retired batches and their captures are gone before the first error
47495
+ // escapes. Reentrant registrations belong to the fresh table, not this batch.
47496
+ if (failure) std::rethrow_exception(failure);
45793
47497
  }
45794
47498
 
45795
47499
  /**
@@ -45894,12 +47598,22 @@ inline void drainMicrotasks() {
45894
47598
  }
45895
47599
 
45896
47600
  inline void queueMicrotask(std::function<void()> task) {
45897
- if (!task) return;
47601
+ if (!task || gea::detail::microtaskRetirementInProgress()) return;
45898
47602
  microtaskQueue().push_back(std::move(task));
45899
47603
  }
45900
47604
 
45901
47605
  inline void clearMicrotasks() {
45902
- microtaskQueue().clear();
47606
+ struct RetirementScope {
47607
+ bool previous = gea::detail::microtaskRetirementInProgress();
47608
+ RetirementScope() { gea::detail::microtaskRetirementInProgress() = true; }
47609
+ ~RetirementScope() { gea::detail::microtaskRetirementInProgress() = previous; }
47610
+ } scope;
47611
+ // Swap before destruction: releasing native captures can reenter scheduling
47612
+ // or retirement. Neither queue may be mutated while its owners are released.
47613
+ std::vector<std::function<void()>> retiredReactive;
47614
+ retiredReactive.swap(microtaskQueue());
47615
+ std::deque<gea::detail::PromiseJob> retiredPromises;
47616
+ retiredPromises.swap(gea::detail::promiseJobs());
45903
47617
  }
45904
47618
 
45905
47619
  /**
@@ -46435,6 +48149,15 @@ inline void domSetAttribute(const Node& node, const std::string& name, const std
46435
48149
  node.setAttribute(name, value);
46436
48150
  }
46437
48151
 
48152
+ // Emitted string literals are const char arrays. Without this exact string
48153
+ // boundary C++ prefers their standard pointer-to-bool conversion over the
48154
+ // std::string constructor, silently storing "true" for an id/class/value.
48155
+ template <typename Node>
48156
+ inline void domSetAttribute(const Node& node, const std::string& name, const char* value) {
48157
+ if (!value) throw std::invalid_argument("domSetAttribute requires a non-null native string");
48158
+ node.setAttribute(name, std::string(value));
48159
+ }
48160
+
46438
48161
  template <typename Node>
46439
48162
  inline void domSetAttribute(const Node& node, const std::string& name, double value) {
46440
48163
  node.setAttribute(name, gea::host::detail::toString(value));