@geastack/compiler 1.0.42 → 1.0.44

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 (58) hide show
  1. package/dist/cli.js +8 -2
  2. package/dist/conversion/nodes.js +5 -2
  3. package/dist/ir/callable-class-flow.js +48 -13
  4. package/dist/ir/certify.js +1 -1
  5. package/dist/ir/host-template-conversions.d.ts +2 -2
  6. package/dist/ir/host-template-conversions.js +73 -2
  7. package/dist/ir/lower-destructuring.js +22 -3
  8. package/dist/ir/lower-operands.js +30 -1
  9. package/dist/ir/native-field-view-facts.d.ts +8 -1
  10. package/dist/ir/native-field-view-facts.js +13 -3
  11. package/dist/ir/operation-conversions.js +1 -1
  12. package/dist/ir/program-conversions.d.ts +1 -1
  13. package/dist/ir/program-conversions.js +68 -1
  14. package/dist/ir/property-read-conversions.js +7 -1
  15. package/dist/ir/publish-native-field-view-facts.js +4 -0
  16. package/dist/ir/reflection-demand.js +29 -3
  17. package/dist/ir/shake.js +21 -0
  18. package/dist/projection/dispatch.d.ts +19 -1
  19. package/dist/projection/dispatch.js +34 -0
  20. package/dist/representation/value-records.js +182 -13
  21. package/dist/semantics/frontend.js +18 -14
  22. package/dist/semantics/normalize/collection-bindings.d.ts +7 -0
  23. package/dist/semantics/normalize/collection-bindings.js +35 -1
  24. package/dist/semantics/normalize/derived-expression-type.js +49 -0
  25. package/dist/semantics/normalize/field-bindings.js +6 -1
  26. package/dist/semantics/normalize/flow/component-solver.js +37 -2
  27. package/dist/semantics/normalize/flow/source-value-session.d.ts +12 -2
  28. package/dist/semantics/normalize/flow/source-value-session.js +861 -212
  29. package/dist/semantics/normalize/global-host-mutations.js +14 -6
  30. package/dist/semantics/normalize/implicit-arguments-tuple.d.ts +11 -10
  31. package/dist/semantics/normalize/implicit-arguments-tuple.js +15 -3
  32. package/dist/semantics/normalize/local-bindings.js +23 -1
  33. package/dist/semantics/normalize/producers/references.js +26 -18
  34. package/dist/semantics/normalize/structural-array-element.d.ts +7 -0
  35. package/dist/semantics/normalize/structural-array-element.js +24 -1
  36. package/dist/semantics/normalize/structural-layout-type.js +5 -1
  37. package/dist/semantics/normalize/structural-mutable-method.js +88 -2
  38. package/dist/semantics/normalize/structural-parts.js +13 -8
  39. package/dist/semantics/normalize/structural.js +25 -1
  40. package/dist/targets/cpp/borrowed-call-entry.d.ts +41 -2
  41. package/dist/targets/cpp/borrowed-call-entry.js +91 -6
  42. package/dist/targets/cpp/class-properties/emit-class-properties.js +5 -1
  43. package/dist/targets/cpp/emit-callable.js +81 -39
  44. package/dist/targets/cpp/emit-native-field-view.d.ts +2 -0
  45. package/dist/targets/cpp/emit-native-field-view.js +1 -1
  46. package/dist/targets/cpp/emit-properties.js +114 -12
  47. package/dist/targets/cpp/host/emit-host-invoke.js +16 -2
  48. package/dist/targets/cpp/host/emit-host-object.js +69 -2
  49. package/dist/targets/cpp/host/host-members.js +4 -0
  50. package/dist/targets/cpp/prototype/emit-prototype-array.d.ts +42 -0
  51. package/dist/targets/cpp/prototype/emit-prototype-array.js +31 -9
  52. package/dist/targets/cpp/records.d.ts +1 -0
  53. package/dist/targets/cpp/records.js +40 -17
  54. package/dist/targets/cpp/translation-unit.js +82 -24
  55. package/dist/targets/cpp/virtual-methods.js +9 -4
  56. package/package.json +1 -1
  57. package/src/targets/cpp/runtime/gea_dynamic_proxy.h +17 -1
  58. package/src/targets/cpp/runtime/gea_runtime.h +485 -64
@@ -166,6 +166,17 @@ namespace gea {
166
166
  return value;
167
167
  }
168
168
 
169
+ /** `float32Product`'s pin for a double product: `Math.hypot` squares and sums
170
+ * in one expression, and Clang's default fuses that pair into one rounding. */
171
+ [[gnu::always_inline]] inline double float64Product(double value) {
172
+ #if defined(__aarch64__)
173
+ __asm__("" : "+w"(value));
174
+ #elif (defined(__x86_64__) || defined(__i386__)) && defined(__SSE2__)
175
+ __asm__("" : "+x"(value));
176
+ #endif
177
+ return value;
178
+ }
179
+
169
180
  namespace detail {
170
181
 
171
182
  inline void collectReferenceCycles(bool full);
@@ -3177,6 +3188,13 @@ struct CycleState {
3177
3188
  // fullCollectionEvery` candidates per full sweep is exactly what the
3178
3189
  // collection count meant when every young collection was a full buffer.
3179
3190
  std::size_t candidatesSinceFullCollection = 0;
3191
+ // How many objects the last full collection found live: the size of the
3192
+ // traced heap a full collection pays for. Both full-collection triggers
3193
+ // (`fullCollectionBudget`, `deferredOverdue`) scale with it, so a program
3194
+ // that keeps a large, stable graph and touches much of it every frame pays
3195
+ // for a full trace in proportion to the work done since the last one rather
3196
+ // than once per frame.
3197
+ std::size_t survivorsOfLastFullCollection = 0;
3180
3198
  // Young-collection survivors whose "live" verdict rested on a clipped edge
3181
3199
  // (`Node::hadClippedEdge`). They are not re-entered into `candidates`: a
3182
3200
  // young pass can never decide them (the clipped edge is invisible to it by
@@ -3307,16 +3325,49 @@ inline bool& cycleSafepointArmed() {
3307
3325
  #endif
3308
3326
  }
3309
3327
 
3328
+ /**
3329
+ * How many young candidates a run of young collections examines before the
3330
+ * next automatic collection is promoted to full: `fullCollectionEvery`
3331
+ * buffers' worth, or the heap the last full collection found live, whichever
3332
+ * is larger.
3333
+ *
3334
+ * A full collection traces everything reachable from its roots, so its cost
3335
+ * is the surviving heap, not the candidate count. With a fixed budget, a
3336
+ * program holding a large graph paid that whole trace every `candidateThreshold
3337
+ * * fullCollectionEvery` candidates however large the graph was; scaling the
3338
+ * budget with the survivors makes the full trace's cost, amortized over the
3339
+ * candidates that paid for it, a constant -- the rule a generational
3340
+ * collector uses to size its old generation's collections. What it costs is
3341
+ * latency: a garbage cycle only a full collection can free (one made of
3342
+ * mature objects) waits until that much young work has been done, which is
3343
+ * bounded by the heap, not by time.
3344
+ */
3345
+ inline std::size_t fullCollectionBudget(const CycleState& state) {
3346
+ return std::max(state.candidateThreshold * state.fullCollectionEvery, state.survivorsOfLastFullCollection);
3347
+ }
3348
+
3310
3349
  /** The deferred list normally waits for the cadence-driven full collection,
3311
3350
  * which needs young candidates to keep arriving. A program whose only
3312
3351
  * releases are of permanent objects would otherwise never reach one, so the
3313
- * list itself becomes the trigger once it holds what `fullCollectionEvery`
3314
- * young collections' worth of candidates would have: the same bound the
3315
- * cadence gives an all-mature garbage cycle, derived from the policy rather
3316
- * than a third knob. Entries are unique objects (`cycleBuffered` keeps each
3317
- * out twice), so a server's steady state cannot reach it by traffic alone. */
3352
+ * list itself becomes the trigger once it is large against the heap.
3353
+ *
3354
+ * Entries are unique objects (`cycleBuffered` keeps each out twice), so the
3355
+ * list never holds more than the permanent objects that dipped since the last
3356
+ * full collection. A render loop re-touches thousands of long-lived objects
3357
+ * every frame -- every node, attribute and uniform of a scene -- so against a
3358
+ * fixed bound (`fullCollectionEvery` buffers' worth) the list refilled past it
3359
+ * in a frame and every frame ended in a full trace of the whole scene. The
3360
+ * bound is therefore that fixed allowance ON TOP of the heap the last full
3361
+ * collection kept: re-touching that heap, however much of it, can never reach
3362
+ * it; only that many objects beyond it can -- permanent objects allocated
3363
+ * since, which is the heap growing. Soundness: a garbage structure only a
3364
+ * full collection can free has a member in this list (the release that made
3365
+ * it garbage dipped it), and the full collection this bound or the candidate
3366
+ * cadence (`fullCollectionBudget`) eventually forces frees it; until then the
3367
+ * garbage is made of objects the last full collection kept or of objects
3368
+ * promoted since, which the two bounds cap in proportion to that heap. */
3318
3369
  inline bool deferredOverdue(const CycleState& state) {
3319
- return state.deferred.size() >= state.candidateThreshold * state.fullCollectionEvery;
3370
+ return state.deferred.size() >= state.candidateThreshold * state.fullCollectionEvery + state.survivorsOfLastFullCollection;
3320
3371
  }
3321
3372
 
3322
3373
  /**
@@ -3846,7 +3897,7 @@ inline void filterBufferedCandidates(CycleState& state) {
3846
3897
  * collection (`full == true`) ignores the mature bit and traces everything
3847
3898
  * reachable from the candidates, then re-marks every survivor mature; this is
3848
3899
  * what `gea::collectCycles()` runs, and what the automatic path promotes to
3849
- * every `fullCollectionEvery` young collections (see `CycleState`).
3900
+ * once young collections have examined `fullCollectionBudget` candidates.
3850
3901
  *
3851
3902
  * Correctness of the young path -- why it can only OVER-retain, never
3852
3903
  * under-collect a live object:
@@ -3897,7 +3948,7 @@ inline void filterBufferedCandidates(CycleState& state) {
3897
3948
  * way, the entry candidate is never lost after a false retain: it sits
3898
3949
  * buffered, reachable from `state.candidates`, until the next FULL
3899
3950
  * collection traces it without the mature filter, finds the true
3900
- * incoming count, and frees it -- bounded by `fullCollectionEvery`, never
3951
+ * incoming count, and frees it -- bounded by `fullCollectionBudget`, never
3901
3952
  * indefinite, and never dependent on some unrelated later release
3902
3953
  * happening to touch it again.
3903
3954
  * - `restorePins`'s `restoreWeakCounts` replays `savedWeak` -- captured
@@ -3922,7 +3973,7 @@ GEA_EH_NOINLINE inline void collectReferenceCycles(bool full = false) {
3922
3973
  // ordinary (young) collection to full on the configured cadence, and on
3923
3974
  // the very first collection (nothing is mature yet, so this costs nothing
3924
3975
  // and establishes the baseline for the counter).
3925
- if (!full && (state.collections == 0 || state.candidatesSinceFullCollection >= state.candidateThreshold * state.fullCollectionEvery)) full = true;
3976
+ if (!full && (state.collections == 0 || state.candidatesSinceFullCollection >= fullCollectionBudget(state))) full = true;
3926
3977
  // A full collection also owes the deferred survivors an answer (see
3927
3978
  // `CycleState::deferred`), so it runs for them even with no fresh candidate.
3928
3979
  if (state.candidates.empty() && !(full && !state.deferred.empty())) return;
@@ -4314,6 +4365,7 @@ GEA_EH_NOINLINE inline void collectReferenceCycles(bool full = false) {
4314
4365
  if (trace.runs % 32 == 0 && gea_heap_trace_print) gea_heap_trace_print();
4315
4366
  }
4316
4367
  #endif
4368
+ if (full) state.survivorsOfLastFullCollection = graph.live.size();
4317
4369
  graph.clear();
4318
4370
  state.collecting = false;
4319
4371
  state.allocationPressure = 0;
@@ -13876,6 +13928,7 @@ class Dictionary {
13876
13928
  if (first_ && first_->first == key) return first_->second;
13877
13929
  if (!first_ && entries_.empty()) {
13878
13930
  enumerableKeys_.reset();
13931
+ noteKey(key);
13879
13932
  first_.emplace(detail::duplicateString(key), V{});
13880
13933
  if constexpr (aliasable) detail::noteDocumentDataKeyCreated(this, key);
13881
13934
  return first_->second;
@@ -13883,6 +13936,7 @@ class Dictionary {
13883
13936
  const std::size_t found = findPosition(key);
13884
13937
  if (found != npos) return entries_[found].second;
13885
13938
  enumerableKeys_.reset();
13939
+ noteKey(key);
13886
13940
  Entry& entry = entries_.emplace_back(detail::duplicateString(key), V{});
13887
13941
  GEA_EH_TRY_ANY(gea_eh_failed) {
13888
13942
  indexInsert(entries_.size() - 1);
@@ -13941,6 +13995,7 @@ class Dictionary {
13941
13995
  V readHinted(std::string_view key, std::atomic<std::uint32_t>& hint) const {
13942
13996
  if constexpr (!aliasable) {
13943
13997
  if (!view_) [[likely]] {
13998
+ if (!mayHoldKey(key)) return V{};
13944
13999
  if (first_ && first_->first == key) return first_->second;
13945
14000
  const std::size_t found = hintedPosition(key, hint);
13946
14001
  return found == npos ? V{} : entries_[found].second;
@@ -13953,6 +14008,7 @@ class Dictionary {
13953
14008
  Carrier readIfPresentHinted(std::string_view key, std::atomic<std::uint32_t>& hint) const {
13954
14009
  if constexpr (!aliasable) {
13955
14010
  if (!view_) [[likely]] {
14011
+ if (!mayHoldKey(key)) return Carrier();
13956
14012
  if (first_ && first_->first == key) return Carrier(first_->second);
13957
14013
  const std::size_t found = hintedPosition(key, hint);
13958
14014
  return found == npos ? Carrier() : Carrier(entries_[found].second);
@@ -14466,6 +14522,7 @@ class Dictionary {
14466
14522
  void appendAbsent(const std::string& key, V value) {
14467
14523
  if (view_) [[unlikely]] detail::refuseAliasedDictionaryStore();
14468
14524
  enumerableKeys_.reset();
14525
+ noteKey(key);
14469
14526
  if (!first_ && entries_.empty()) {
14470
14527
  first_.emplace(detail::duplicateString(key), std::move(value));
14471
14528
  return;
@@ -14581,6 +14638,28 @@ class Dictionary {
14581
14638
  // `std::map` that cost one node allocation per key.
14582
14639
  static constexpr std::size_t kScanLimit = 8;
14583
14640
  static constexpr std::size_t npos = static_cast<std::size_t>(-1);
14641
+ /**
14642
+ * One bit per key this table has ever stored, chosen from the key's length
14643
+ * and its first and last bytes (`keyBit`), so a read of a key whose bit is
14644
+ * clear is answered "absent" without touching an entry.
14645
+ *
14646
+ * A renderer probes every geometry for entries it rarely has -- a color or
14647
+ * tangent attribute, morph targets -- once per draw, each a different table,
14648
+ * so a miss walked every entry's key and no per-site hint could remember it.
14649
+ * The bit is set by every insertion and never cleared: a deleted key leaves
14650
+ * it set, and two keys may share one, which only sends the read on to the
14651
+ * lookup it always made. A clear bit is proof, because nothing stores a key
14652
+ * without setting it. Only the plain own-entry reads consult it; a view or
14653
+ * an alias holds no entries of its own here.
14654
+ */
14655
+ std::uint64_t keyMask_ = 0;
14656
+ static constexpr unsigned keyBit(std::string_view key) {
14657
+ const std::size_t size = key.size();
14658
+ const unsigned edges = size == 0 ? 0u : static_cast<unsigned>(static_cast<unsigned char>(key[0])) * 3u + static_cast<unsigned char>(key[size - 1]);
14659
+ return static_cast<unsigned>(size * 7u + edges) & 63u;
14660
+ }
14661
+ void noteKey(std::string_view key) { keyMask_ |= std::uint64_t{1} << keyBit(key); }
14662
+ bool mayHoldKey(std::string_view key) const { return (keyMask_ & (std::uint64_t{1} << keyBit(key))) != 0; }
14584
14663
  static constexpr std::uint32_t kEmptySlot = static_cast<std::uint32_t>(-1);
14585
14664
  std::vector<std::uint32_t> index_;
14586
14665
  std::size_t findPosition(std::string_view key) const {
@@ -15336,6 +15415,10 @@ class Map {
15336
15415
  entries_.clear();
15337
15416
  serials_.clear();
15338
15417
  if constexpr (indexable) index_.clear();
15418
+ if constexpr (directable) {
15419
+ direct_.clear();
15420
+ directOk_ = true;
15421
+ }
15339
15422
  }
15340
15423
 
15341
15424
  /**
@@ -15392,12 +15475,49 @@ class Map {
15392
15475
  * of an unchanging Map (parallel regions) stay read-only.
15393
15476
  */
15394
15477
  static constexpr bool indexable = detail::MapKeyIndexable<K>::value;
15478
+ /**
15479
+ * Key -> position + 1 for a Map whose every key is a small non-negative
15480
+ * integer Number -- object ids, slot numbers -- held in a plain array the
15481
+ * key indexes. Such a Map is typically read per frame per object (a
15482
+ * renderer's per-geometry and per-program state tables): below `indexFrom`
15483
+ * a read compared the key against every entry, and above it hashed into a
15484
+ * node-based table, where one array load answers either.
15485
+ *
15486
+ * It is kept while every key so far qualifies and the array stays within
15487
+ * a constant factor of the entry count; the first key that does not
15488
+ * (fractional, negative, NaN, or far past the others) drops it for good and
15489
+ * the Map falls back to `index_` and the scan. Like `index_`, it is only a
15490
+ * position cache: storage order, serials and iteration are untouched.
15491
+ */
15492
+ static constexpr bool directable = std::is_same_v<K, double>;
15493
+ static constexpr std::uint32_t directSlotLimit = std::uint32_t{1} << 20;
15494
+ /** Whether `key` is an integer in [0, directSlotLimit), and which slot it names. -0 is 0, as SameValueZero says. */
15495
+ static bool directSlotOf(const K& key, std::uint32_t& slot) {
15496
+ if constexpr (directable) {
15497
+ if (!(key >= 0.0 && key < static_cast<double>(directSlotLimit))) return false;
15498
+ slot = static_cast<std::uint32_t>(key);
15499
+ return static_cast<double>(slot) == key;
15500
+ } else {
15501
+ (void)key;
15502
+ (void)slot;
15503
+ return false;
15504
+ }
15505
+ }
15395
15506
  static constexpr std::size_t indexFrom = 8;
15396
15507
  static constexpr std::size_t notFound = static_cast<std::size_t>(-1);
15397
15508
  using Index = std::conditional_t<indexable, std::unordered_map<K, std::size_t, detail::MapKeyHash, detail::MapKeyEqual>,
15398
15509
  detail::NoMapIndex>;
15399
15510
 
15400
15511
  std::size_t positionOf(const K& key) const {
15512
+ if constexpr (directable) {
15513
+ // Every key is a small non-negative integer (`direct_`), so a key that
15514
+ // is not one is absent, and one that is names its slot.
15515
+ if (directOk_) {
15516
+ std::uint32_t slot = 0;
15517
+ if (!directSlotOf(key, slot) || slot >= direct_.size()) return notFound;
15518
+ return static_cast<std::size_t>(direct_[slot]) - 1;
15519
+ }
15520
+ }
15401
15521
  if constexpr (indexable) {
15402
15522
  if (!index_.empty()) {
15403
15523
  const auto found = index_.find(key);
@@ -15418,6 +15538,26 @@ class Map {
15418
15538
  }
15419
15539
  }
15420
15540
  void indexAppended() {
15541
+ if constexpr (directable) {
15542
+ if (directOk_) {
15543
+ std::uint32_t slot = 0;
15544
+ const std::size_t count = entries_.size();
15545
+ if (directSlotOf(entries_.back().first, slot) && slot < directSlotLimit && slot < 64 + 16 * count) {
15546
+ if (slot >= direct_.size()) direct_.resize(static_cast<std::size_t>(slot) + 1, 0);
15547
+ direct_[slot] = static_cast<std::uint32_t>(count);
15548
+ return;
15549
+ }
15550
+ // A key outside the direct table's domain: the Map answers through
15551
+ // the scan and the hashed index from here on, as it always did.
15552
+ directOk_ = false;
15553
+ direct_.clear();
15554
+ direct_.shrink_to_fit();
15555
+ if constexpr (indexable) {
15556
+ if (entries_.size() >= indexFrom) rebuildIndex();
15557
+ }
15558
+ return;
15559
+ }
15560
+ }
15421
15561
  if constexpr (indexable) {
15422
15562
  if (!index_.empty()) index_.emplace(entries_.back().first, entries_.size() - 1);
15423
15563
  else if (entries_.size() >= indexFrom) rebuildIndex();
@@ -15426,6 +15566,18 @@ class Map {
15426
15566
  // Erasing shifted every later entry down one position (an O(n) move already),
15427
15567
  // so the index is renumbered by rebuilding it, or dropped below `indexFrom`.
15428
15568
  void indexRemoved() {
15569
+ if constexpr (directable) {
15570
+ if (directOk_) {
15571
+ // Erasing shifted every later entry down one position: renumber.
15572
+ std::fill(direct_.begin(), direct_.end(), 0u);
15573
+ for (std::size_t index = 0; index < entries_.size(); ++index) {
15574
+ std::uint32_t slot = 0;
15575
+ directSlotOf(entries_[index].first, slot);
15576
+ direct_[slot] = static_cast<std::uint32_t>(index + 1);
15577
+ }
15578
+ return;
15579
+ }
15580
+ }
15429
15581
  if constexpr (indexable) {
15430
15582
  if (!index_.empty()) rebuildIndex();
15431
15583
  }
@@ -15436,6 +15588,8 @@ class Map {
15436
15588
  std::uint64_t nextSerial_ = 1;
15437
15589
  std::shared_ptr<const detail::MapViewSource<K, V>> view_;
15438
15590
  Index index_;
15591
+ std::vector<std::uint32_t> direct_;
15592
+ bool directOk_ = true;
15439
15593
  };
15440
15594
 
15441
15595
  namespace detail {
@@ -15970,6 +16124,15 @@ struct ArrayObjectElementOf<ArrayObject<Element>> {
15970
16124
  using type = Element;
15971
16125
  };
15972
16126
 
16127
+ namespace detail {
16128
+ template <typename Element>
16129
+ ArrayObject<Element> arrayObjectBaseProbe(const ArrayObject<Element>&);
16130
+ template <typename T>
16131
+ using ArrayObjectBaseOf = decltype(arrayObjectBaseProbe(std::declval<const T&>()));
16132
+ template <typename T>
16133
+ concept DerivedArrayObject = !IsArrayObjectStruct<T>::value && requires { typename ArrayObjectBaseOf<T>; };
16134
+ }
16135
+
15973
16136
  namespace detail {
15974
16137
  template <typename T>
15975
16138
  struct DynamicCarrier;
@@ -19667,6 +19830,15 @@ namespace detail {
19667
19830
  struct LiteralReadCache {
19668
19831
  std::atomic<const ValueMetadata*> absentOn[4]{};
19669
19832
  std::atomic<std::uint8_t> next{0};
19833
+ /**
19834
+ * Types whose declared field table answered this key here (see
19835
+ * `Value::getLiteralProperty`): for a box of one of them the read goes to
19836
+ * that table first, as `getProperty` itself would after its ladder of
19837
+ * checks, and only a miss -- a field this instance has deleted -- walks the
19838
+ * ladder. Two, for a site that sees two types (a 3- and a 4-vector).
19839
+ */
19840
+ std::atomic<const ValueMetadata*> fieldOn[2]{};
19841
+ std::atomic<std::uint8_t> nextField{0};
19670
19842
  std::atomic<std::int8_t> stringAbsent{-1};
19671
19843
  // The same fact for an Array: this key is neither `length` nor an index and the Array prototype table holds nothing under it.
19672
19844
  std::atomic<std::int8_t> arrayAbsent{-1};
@@ -20236,6 +20408,8 @@ struct Error;
20236
20408
  namespace host {
20237
20409
  inline gea::Ref<gea::runtime::Error> createRuntimeError(const char* kind, const gea::Optional<std::string>& message);
20238
20410
  inline bool isRuntimeError(const gea::Value& value);
20411
+ inline gea::Ref<gea::runtime::Error> runtimeErrorOf(const gea::Value& value);
20412
+ inline bool isErrorValue(const gea::Value& value);
20239
20413
  inline bool instanceOfRuntimeError(const gea::Value& value, const char* kind);
20240
20414
  inline std::string runtimeErrorString(const gea::Value& value);
20241
20415
  [[noreturn]] inline void throwRuntimeError(const char* kind, const std::string& message);
@@ -24448,6 +24622,20 @@ struct DynamicCallableCarrier<Optional<T>> {
24448
24622
  }
24449
24623
  };
24450
24624
 
24625
+ /**
24626
+ * The compiler's certified live view of a dynamic object as record `T`, for a
24627
+ * record a boxed callable's frame names (`program-conversions.ts`'s
24628
+ * `dynamic-call-argument`). The generated program specializes it for exactly
24629
+ * the records it published that recipe for; every other `T` has none.
24630
+ */
24631
+ template <typename T>
24632
+ struct DynamicArgumentView {
24633
+ static constexpr bool installed = false;
24634
+ };
24635
+
24636
+ template <typename Element>
24637
+ gea::Ref<ArrayObject<Element>> dynamicArgumentArrayView(const Value& value);
24638
+
24451
24639
  template <typename T>
24452
24640
  struct DynamicCarrier<gea::Ref<T>> {
24453
24641
  static constexpr bool supported = true;
@@ -24459,6 +24647,19 @@ struct DynamicCarrier<gea::Ref<T>> {
24459
24647
  }
24460
24648
  static gea::Ref<T> in(const Value& value, std::size_t position) {
24461
24649
  if (value.tag() == Value::Tag::Undefined) refuseMissingCallArgument(position);
24650
+ // A caller hands the callee its own object, whatever layout the caller
24651
+ // gave it: `pts.map(([r, y]) => ...)` over `number[]` rows, an options
24652
+ // literal into an `o = {}` parameter. Another layout is read through a
24653
+ // live view of that same object, so the callee's writes reach the caller.
24654
+ if (value.tag() == Value::Tag::Object && !accepts(value)) {
24655
+ if constexpr (IsArrayObjectStruct<T>::value) {
24656
+ using Element = typename ArrayObjectElementOf<T>::type;
24657
+ if constexpr (DynamicCarrier<Element>::supported)
24658
+ if (value.isArrayPayload()) return dynamicArgumentArrayView<Element>(value);
24659
+ } else if constexpr (DynamicArgumentView<T>::installed) {
24660
+ return DynamicArgumentView<T>::in(value);
24661
+ }
24662
+ }
24462
24663
  return unboxClassRef<T>(value, "a dynamic call argument");
24463
24664
  }
24464
24665
  };
@@ -29421,6 +29622,14 @@ using ::gea::checkedNativeArrayView;
29421
29622
  using ::gea::nativeArrayViewAccepts;
29422
29623
  using ::gea::nativeArrayViewAcceptsExact;
29423
29624
  using ::gea::nativeArrayViewElementsAccept;
29625
+
29626
+ /** Each element crosses by the frame's own rule for its carrier, in both directions. */
29627
+ template <typename Element>
29628
+ gea::Ref<ArrayObject<Element>> dynamicArgumentArrayView(const Value& value) {
29629
+ return checkedNativeArrayView<Element, NativeFieldLeafPolicy>(
29630
+ value, "a dynamic call argument", [](const Value& entry) -> Element { return DynamicCarrier<Element>::in(entry, 0); },
29631
+ [](const Element& entry) -> Value { return DynamicCarrier<Element>::out(entry); });
29632
+ }
29424
29633
  }
29425
29634
 
29426
29635
  /** A descriptor query creates a new ordinary object. Its copied native
@@ -29831,20 +30040,30 @@ bool nativeDynamicRead(const gea::Ref<T>& object, const PropertyKey& key, Value&
29831
30040
  }
29832
30041
  if (const auto read = record::readDocumentView(Ref<void>(object), key, answer)) return *read;
29833
30042
  if (const auto read = record::readNativeViewValue(Ref<void>(object), key, answer)) return *read;
30043
+ // OrdinaryGet continues from every own miss to the prototype, exactly as the
30044
+ // boxed twin `Value::getProperty` does: a class's accessors and methods are
30045
+ // answered by its generated prototype hook, never by instance storage.
30046
+ const auto inherited = [&]() -> bool {
30047
+ if constexpr (requires(const T& reader) { reader.gea_readPrototypeProperty(key, answer); })
30048
+ return object->gea_readPrototypeProperty(key, answer);
30049
+ else
30050
+ return false;
30051
+ };
29834
30052
  if constexpr (requires(const T& reader) { reader.gea_readOwnField(key, answer); }) {
29835
30053
  if (object->gea_readOwnField(key, answer)) return true;
29836
30054
  if constexpr (detail::NativeOwnFieldPredicate<T>) {
29837
30055
  // A deleted fixed slot is still the layout's slot. Do not let an index
29838
30056
  // sidecar or expando shadow it merely because its presence bit is false.
29839
- if (object->gea_matchesOwnField(key)) return false;
30057
+ if (object->gea_matchesOwnField(key)) return inherited();
29840
30058
  }
29841
30059
  }
29842
30060
  if constexpr (requires(const T& reader) { reader.gea_readOwnIndex(key, answer); reader.gea_matchesOwnIndex(key); }) {
29843
30061
  if (object->gea_readOwnIndex(key, answer)) return true;
29844
- if (object->gea_matchesOwnIndex(key)) return false;
30062
+ if (object->gea_matchesOwnIndex(key)) return inherited();
29845
30063
  }
29846
30064
  const gea::Ref<DynamicObject> expando = detail::expandoFor(nativePropertyAnchor(object), false);
29847
- return expando && expando->readWithReceiver(key, [&] { return Value::box(Value::Tag::Object, object); }, answer);
30065
+ if (expando && expando->readWithReceiver(key, [&] { return Value::box(Value::Tag::Object, object); }, answer)) return true;
30066
+ return inherited();
29848
30067
  }
29849
30068
 
29850
30069
  // A certified missing property still evaluates its receiver/key and throws on
@@ -32583,6 +32802,26 @@ bool assignOwnPropertiesUnorderedWith(const gea::Ref<T>& source, const gea::Ref<
32583
32802
  }
32584
32803
 
32585
32804
  /** Array exotic own enumerable string keys, followed by enumerable expandos. */
32805
+ template <typename Element>
32806
+ std::vector<std::string> arrayOwnEnumerableKeys(const gea::Ref<ArrayObject<Element>>& array);
32807
+ template <typename Element>
32808
+ bool arrayHasOwnEnumerableKey(const gea::Ref<ArrayObject<Element>>& array, const std::string& key);
32809
+ template <typename Element>
32810
+ std::vector<std::string> arrayOwnPropertyNames(const gea::Ref<ArrayObject<Element>>& array);
32811
+
32812
+ template <detail::DerivedArrayObject Array>
32813
+ std::vector<std::string> arrayOwnEnumerableKeys(const gea::Ref<Array>& array) {
32814
+ return arrayOwnEnumerableKeys(gea::Ref<detail::ArrayObjectBaseOf<Array>>(array));
32815
+ }
32816
+ template <detail::DerivedArrayObject Array>
32817
+ bool arrayHasOwnEnumerableKey(const gea::Ref<Array>& array, const std::string& key) {
32818
+ return arrayHasOwnEnumerableKey(gea::Ref<detail::ArrayObjectBaseOf<Array>>(array), key);
32819
+ }
32820
+ template <detail::DerivedArrayObject Array>
32821
+ std::vector<std::string> arrayOwnPropertyNames(const gea::Ref<Array>& array) {
32822
+ return arrayOwnPropertyNames(gea::Ref<detail::ArrayObjectBaseOf<Array>>(array));
32823
+ }
32824
+
32586
32825
  template <typename Element>
32587
32826
  std::vector<std::string> arrayOwnEnumerableKeys(const gea::Ref<ArrayObject<Element>>& array) {
32588
32827
  std::vector<std::string> keys;
@@ -33148,9 +33387,15 @@ inline bool Value::readDeclaredField(const PropertyKey& key, Value& out) const {
33148
33387
  }
33149
33388
 
33150
33389
  inline Value Value::getLiteralProperty(const PropertyKey& key, detail::LiteralReadCache& cache) const {
33390
+ constexpr auto relaxed = std::memory_order_relaxed;
33391
+ // A type this site has already seen answer from its declared fields: the
33392
+ // ladder below and `getProperty`'s own would only reach the same table.
33393
+ if (!proxy_ && !dynamic_ && tag_ == Tag::Object && (cache.fieldOn[0].load(relaxed) == metadata_ || cache.fieldOn[1].load(relaxed) == metadata_)) {
33394
+ Value answer;
33395
+ if (metadata_->fields->read(payload(), key, answer)) return answer;
33396
+ }
33151
33397
  Value viewed;
33152
33398
  if (nativeViewValue(viewed)) return viewed.getLiteralProperty(key, cache);
33153
- constexpr auto relaxed = std::memory_order_relaxed;
33154
33399
  if (!proxy_ && !dynamic_ && tag_ == Tag::Object) {
33155
33400
  // A serializer may ask every value it visits for a hook method, a type-tag key and @@toStringTag. A Document answers from its own table (or, when it
33156
33401
  // views a native object, from that object's cached read) and an Array from its prototype table, neither needing `getProperty`'s ladder.
@@ -33220,6 +33465,18 @@ inline Value Value::getLiteralProperty(const PropertyKey& key, detail::LiteralRe
33220
33465
  }
33221
33466
  }
33222
33467
  }
33468
+ // The conditions under which `getProperty` asks the declared field table
33469
+ // before anything else (`readDeclaredField`): no view hook on the type, no
33470
+ // proxy or dynamic object, not a Document, not a tuple. A hit there is
33471
+ // remembered for the type, so the next box of it skips straight to it.
33472
+ if (!proxy_ && !dynamic_ && tag_ == Tag::Object && metadata_->nativeViewValue == nullptr && metadata_->fields != nullptr &&
33473
+ metadata_->elements == nullptr && metadata_->payloadType != detail::payloadTypeTagFor<gea::Ref<gea::Dictionary<gea::Value>>>()) {
33474
+ Value declared;
33475
+ if (metadata_->fields->read(payload(), key, declared)) {
33476
+ cache.fieldOn[cache.nextField.fetch_add(1, relaxed) % 2].store(metadata_, relaxed);
33477
+ return declared;
33478
+ }
33479
+ }
33223
33480
  Value answer = getProperty(key, *this);
33224
33481
  // Learned only from a miss the type itself proves: a key its declared names
33225
33482
  // do not include, on a layout with no elements or prototype hook, so the
@@ -33965,6 +34222,26 @@ inline bool isShortBasicLatin(const std::string &s) {
33965
34222
  return size == 0 || (static_cast<unsigned char>(s[0]) & 0x80u) == 0;
33966
34223
  }
33967
34224
 
34225
+ // The UTF-8 walks below take eight ASCII bytes (eight code units) per step
34226
+ // with this. A per-byte walk past a string's first non-ASCII byte made every
34227
+ // `length`/`charAt`/`slice` on a long, mostly-ASCII string -- a shader chunk
34228
+ // with one accented comment -- a full byte loop, and three.js's include
34229
+ // resolver calls them once per character.
34230
+ inline bool isAsciiWord(const unsigned char *bytes) {
34231
+ std::uint64_t word;
34232
+ std::memcpy(&word, bytes, 8);
34233
+ return (word & 0x8080808080808080ull) == 0;
34234
+ }
34235
+
34236
+ /** How many of the first `limit` bytes (at most `s.size()`) lead `s` as ASCII. */
34237
+ inline std::size_t asciiPrefixLength(const std::string &s, std::size_t limit) {
34238
+ const unsigned char *d = reinterpret_cast<const unsigned char *>(s.data());
34239
+ std::size_t i = 0;
34240
+ while (i + 8 <= limit && isAsciiWord(d + i)) i += 8;
34241
+ while (i < limit && !(d[i] & 0x80)) ++i;
34242
+ return i;
34243
+ }
34244
+
33968
34245
  inline Utf16Metadata utf16Metadata(const std::string &s) {
33969
34246
  // A short name answers from two loads; `OnDemandDocument.isElementName`
33970
34247
  // takes the metadata of the name it compares once per element.
@@ -33989,12 +34266,17 @@ inline Utf16Metadata utf16Metadata(const std::string &s) {
33989
34266
  std::size_t n = len;
33990
34267
  if (!basicLatin) {
33991
34268
  n = i; // ASCII prefix: one unit per byte so far
33992
- for (; i < len; ++i) {
33993
- unsigned char byte = d[i];
33994
- if ((byte & 0xC0) == 0x80) continue;
34269
+ const auto count = [&](unsigned char byte) {
34270
+ if ((byte & 0xC0) == 0x80) return;
33995
34271
  if ((byte & 0xF8) == 0xF0) n += 2;
33996
34272
  else n += 1;
34273
+ };
34274
+ // Each byte counts on its own, so whole words can be classified at once.
34275
+ for (; i + 8 <= len; i += 8) {
34276
+ if (isAsciiWord(d + i)) n += 8;
34277
+ else for (std::size_t k = 0; k < 8; ++k) count(d[i + k]);
33997
34278
  }
34279
+ for (; i < len; ++i) count(d[i]);
33998
34280
  }
33999
34281
  return {n, basicLatin, {}};
34000
34282
  }
@@ -34038,9 +34320,15 @@ inline std::uint32_t decodeCodePointAt(const std::string &s, std::size_t i, std:
34038
34320
  /** Map a JavaScript UTF-16 code-unit offset onto this runtime's UTF-8 storage. */
34039
34321
  inline std::size_t byteOffsetFromUtf16(const std::string &s, std::size_t target) {
34040
34322
  if (isShortBasicLatin(s)) return std::min(target, s.size());
34323
+ const unsigned char *d = reinterpret_cast<const unsigned char *>(s.data());
34041
34324
  std::size_t byte = 0;
34042
34325
  std::size_t units = 0;
34043
34326
  while (byte < s.size() && units < target) {
34327
+ if (units + 8 <= target && byte + 8 <= s.size() && isAsciiWord(d + byte)) {
34328
+ byte += 8;
34329
+ units += 8;
34330
+ continue;
34331
+ }
34044
34332
  std::size_t width = 1;
34045
34333
  const std::uint32_t codePoint = decodeCodePointAt(s, byte, width);
34046
34334
  byte += width;
@@ -34052,10 +34340,16 @@ inline std::size_t byteOffsetFromUtf16(const std::string &s, std::size_t target)
34052
34340
  /** Map a matcher byte boundary back to the UTF-16 index ECMAScript exposes. */
34053
34341
  inline std::size_t utf16OffsetFromByte(const std::string &s, std::size_t target) {
34054
34342
  if (isShortBasicLatin(s)) return std::min(target, s.size());
34343
+ const unsigned char *d = reinterpret_cast<const unsigned char *>(s.data());
34055
34344
  std::size_t byte = 0;
34056
34345
  std::size_t units = 0;
34057
34346
  const std::size_t stop = std::min(target, s.size());
34058
34347
  while (byte < stop) {
34348
+ if (byte + 8 <= stop && isAsciiWord(d + byte)) {
34349
+ byte += 8;
34350
+ units += 8;
34351
+ continue;
34352
+ }
34059
34353
  std::size_t width = 1;
34060
34354
  const std::uint32_t codePoint = decodeCodePointAt(s, byte, width);
34061
34355
  byte += width;
@@ -34163,24 +34457,28 @@ inline std::string substringUtf16(const std::string &s, std::size_t startUnit, s
34163
34457
  // ASCII fast path: if every byte up to `endUnit` is ASCII, UTF-16 indices
34164
34458
  // equal byte indices, so the slice is a plain byte substr -- no
34165
34459
  // per-code-point surrogate accounting and no quadratic walk.
34166
- {
34167
- const unsigned char *d = reinterpret_cast<const unsigned char *>(s.data());
34168
- const std::size_t size = s.size();
34169
- const std::size_t scanLimit = endUnit < size ? endUnit : size;
34170
- std::size_t i = 0;
34171
- while (i < scanLimit && !(d[i] & 0x80)) ++i;
34172
- if (i == scanLimit) {
34173
- const std::size_t b0 = startUnit < size ? startUnit : size;
34174
- const std::size_t b1 = endUnit < size ? endUnit : size;
34175
- if (b0 >= b1) return std::string();
34176
- return s.substr(b0, b1 - b0);
34177
- }
34460
+ const std::size_t scanLimit = endUnit < s.size() ? endUnit : s.size();
34461
+ const std::size_t asciiPrefix = asciiPrefixLength(s, scanLimit);
34462
+ if (asciiPrefix == scanLimit) {
34463
+ const std::size_t b0 = startUnit < s.size() ? startUnit : s.size();
34464
+ if (b0 >= scanLimit) return std::string();
34465
+ return s.substr(b0, scanLimit - b0);
34178
34466
  }
34467
+ const unsigned char *d = reinterpret_cast<const unsigned char *>(s.data());
34179
34468
  std::string out;
34180
34469
  out.reserve((endUnit - startUnit) * 2);
34181
- std::size_t unitPosition = 0;
34182
- std::size_t i = 0;
34470
+ // The prefix just scanned is one unit per byte: resume the walk there.
34471
+ std::size_t unitPosition = asciiPrefix < startUnit ? asciiPrefix : startUnit;
34472
+ std::size_t i = unitPosition;
34183
34473
  while (i < s.size() && unitPosition < endUnit) {
34474
+ // An ASCII word is eight units: counted wholly before the range, copied wholly inside it.
34475
+ if (i + 8 <= s.size() && (unitPosition + 8 <= startUnit || (unitPosition >= startUnit && unitPosition + 8 <= endUnit)) &&
34476
+ isAsciiWord(d + i)) {
34477
+ if (unitPosition >= startUnit) out.append(s, i, 8);
34478
+ i += 8;
34479
+ unitPosition += 8;
34480
+ continue;
34481
+ }
34184
34482
  unsigned char b = static_cast<unsigned char>(s[i]);
34185
34483
  std::size_t length;
34186
34484
  bool astral = false;
@@ -34388,6 +34686,11 @@ inline std::string charAt(const std::string &s, double position) {
34388
34686
  position = integerPosition(position);
34389
34687
  // The first unit of a string whose first byte is ASCII is that byte, without scanning for its UTF-16 length.
34390
34688
  if (position == 0.0 && !s.empty() && static_cast<unsigned char>(s[0]) < 0x80) return std::string(1, s[0]);
34689
+ // So is any unit inside the ASCII prefix: a scan to it, not the whole string's length.
34690
+ if (position > 0.0 && position < static_cast<double>(s.size())) {
34691
+ const std::size_t index = static_cast<std::size_t>(position);
34692
+ if (asciiPrefixLength(s, index + 1) > index) return std::string(1, s[index]);
34693
+ }
34391
34694
  const std::size_t length = utf16Length(s);
34392
34695
  if (!std::isfinite(position) || position < 0.0 || position >= static_cast<double>(length)) return std::string();
34393
34696
  const std::size_t index = static_cast<std::size_t>(position);
@@ -37337,6 +37640,44 @@ struct Pattern {
37337
37640
  // `test`: 0 unknown, 1 compiled, -1 outside the subset.
37338
37641
  mutable signed char simpleState = 0;
37339
37642
  mutable std::shared_ptr<const simple::Program> simpleProgram;
37643
+ // The unit every match must open with, for `matchAt`'s search: -1 unknown,
37644
+ // 0 none.
37645
+ mutable int leadingUnitState = -1;
37646
+
37647
+ /**
37648
+ * The ASCII character a match of `compiledSource` must begin with: its
37649
+ * first atom, when that is a plain character no quantifier can skip and no
37650
+ * top-level `|` routes around -- `/#pragma unroll_loop_start\s+…/`. 0 when
37651
+ * the pattern does not pin one.
37652
+ */
37653
+ int leadingUnit() const {
37654
+ if (leadingUnitState >= 0) return leadingUnitState;
37655
+ leadingUnitState = 0;
37656
+ const std::string &text = compiledSource;
37657
+ if (ignoreCase || unicode || text.empty()) return 0;
37658
+ const unsigned char first = static_cast<unsigned char>(text[0]);
37659
+ if (first == 0 || first >= 0x80 || std::string_view("\\^$.|?*+()[]{}").find(static_cast<char>(first)) != std::string_view::npos) return 0;
37660
+ if (text.size() > 1 && std::string_view("*?{").find(text[1]) != std::string_view::npos) return 0;
37661
+ int depth = 0;
37662
+ bool inClass = false;
37663
+ for (std::size_t i = 0; i < text.size(); ++i) {
37664
+ const char c = text[i];
37665
+ if (c == '\\') {
37666
+ ++i;
37667
+ } else if (inClass) {
37668
+ if (c == ']') inClass = false;
37669
+ } else if (c == '[') {
37670
+ inClass = true;
37671
+ } else if (c == '(') {
37672
+ ++depth;
37673
+ } else if (c == ')') {
37674
+ --depth;
37675
+ } else if (c == '|' && depth == 0) {
37676
+ return 0;
37677
+ }
37678
+ }
37679
+ return leadingUnitState = first;
37680
+ }
37340
37681
 
37341
37682
  const simple::Program *simplePattern() const {
37342
37683
  if (simpleState == 0) {
@@ -37897,6 +38238,28 @@ struct Pattern {
37897
38238
  if (stateful) resetLastIndex();
37898
38239
  return MatchSlice{};
37899
38240
  }
38241
+ // An ASCII literal (`/NUM_DIR_LIGHTS/g`) is a byte search, as in `test`:
38242
+ // no byte of a multi-byte sequence is ASCII, so the bytes match exactly
38243
+ // where the code units do, and a start inside a surrogate pair cannot
38244
+ // begin a match. Transcoding the whole input for `std::regex` on every
38245
+ // match made each `replace` of three.js's shader constants O(n) per match
38246
+ // on top of libc++'s matcher. Sticky stays below: it must not slide off a
38247
+ // half pair.
38248
+ if (!sticky && !unicode && literalPattern() && !literalUtf8.empty() && gea::runtime::string::asciiOnly(literalUtf8)) {
38249
+ const std::size_t from = gea::runtime::string::byteOffsetFromUtf16(input, startPublicUnits);
38250
+ const std::size_t at = input.find(literalUtf8, from);
38251
+ if (at == std::string::npos) {
38252
+ if (stateful) resetLastIndex();
38253
+ return MatchSlice{};
38254
+ }
38255
+ MatchSlice out;
38256
+ out.matched = true;
38257
+ out.position = gea::runtime::string::utf16OffsetFromByte(input, at);
38258
+ out.length = literalUtf8.size();
38259
+ if (stateful) setLastIndexUnits(out.position + out.length);
38260
+ out.captures.push_back(gea::Optional<std::string>(literalUtf8));
38261
+ return out;
38262
+ }
37900
38263
  // A caller may write lastIndex into the middle of a surrogate pair. In
37901
38264
  // Unicode mode CodePointAt sees the trailing surrogate there as a lone
37902
38265
  // code point; preserving this exact boundary keeps sticky/global matching
@@ -37915,11 +38278,30 @@ struct Pattern {
37915
38278
  const Utf16Regex &compiled = compiledRegex();
37916
38279
  Utf16Match match;
37917
38280
  auto searchBegin = inputUnits.cbegin() + static_cast<std::ptrdiff_t>(startUnits);
37918
- if (!std::regex_search(searchBegin, inputUnits.cend(), match, compiled, searchFlagsFrom(inputUnits, startUnits))) {
38281
+ bool found = false;
38282
+ if (const int lead = sticky ? 0 : leadingUnit()) {
38283
+ // libc++ allocates and frees its matcher state at every start it tries,
38284
+ // which made one walk over a shader source (`#pragma unroll_loop_start`)
38285
+ // cost milliseconds. A match can only start at `lead`: try only there,
38286
+ // in order, so the first success is still the leftmost match.
38287
+ for (auto at = searchBegin; (at = std::find(at, inputUnits.cend(), static_cast<RegexUnit>(lead))) != inputUnits.cend(); ++at) {
38288
+ const auto flags =
38289
+ searchFlagsFrom(inputUnits, static_cast<std::size_t>(at - inputUnits.cbegin())) | std::regex_constants::match_continuous;
38290
+ if (std::regex_search(at, inputUnits.cend(), match, compiled, flags)) {
38291
+ searchBegin = at;
38292
+ found = true;
38293
+ break;
38294
+ }
38295
+ }
38296
+ } else {
38297
+ found = std::regex_search(searchBegin, inputUnits.cend(), match, compiled, searchFlagsFrom(inputUnits, startUnits));
38298
+ }
38299
+ if (!found) {
37919
38300
  if (stateful) resetLastIndex();
37920
38301
  return MatchSlice{};
37921
38302
  }
37922
- const std::size_t matchStartUnits = startUnits + static_cast<std::size_t>(match.position(0));
38303
+ const std::size_t matchStartUnits =
38304
+ static_cast<std::size_t>(searchBegin - inputUnits.cbegin()) + static_cast<std::size_t>(match.position(0));
37923
38305
  #endif
37924
38306
  if (sticky && matchStartUnits != startUnits) {
37925
38307
  resetLastIndex();
@@ -43065,7 +43447,7 @@ inline std::string typeOf(const gea::Value &value) {
43065
43447
  // without that dynamic boundary still refuses by name inside `dynamicToString`:
43066
43448
  // manufacturing "[object Object]" would bypass a possible native `toString`.
43067
43449
  inline std::string toString(const gea::Value &value) {
43068
- if (gea::host::isRuntimeError(value)) return gea::host::runtimeErrorString(value);
43450
+ if (gea::host::isErrorValue(value)) return gea::host::runtimeErrorString(value);
43069
43451
  switch (value.tag()) {
43070
43452
  case gea::Value::Tag::Undefined:
43071
43453
  return toStringUndefined();
@@ -43324,9 +43706,15 @@ inline double min_invoke(void*, gea::Ref<gea::ArrayObject<double>> values) {
43324
43706
  * another argument is NaN*; any NaN with no infinity makes it NaN; no
43325
43707
  * arguments at all is +0. And squaring before summing overflows to +Infinity
43326
43708
  * for magnitudes above ~1.34e154 whose true hypotenuse is finite, and flushes
43327
- * to +0 below ~1.5e-162. Scaling every term by the largest magnitude first --
43328
- * the standard formulation, and the one V8 uses -- removes both, and is exact
43329
- * on the cases that should be exact (hypot(3, 4) is 5).
43709
+ * to +0 below ~1.5e-162. Scaling every term by the largest magnitude first
43710
+ * removes both, and is exact on the cases that should be exact (hypot(3, 4)
43711
+ * is 5).
43712
+ *
43713
+ * The sum is V8's: Kahan-compensated, in argument order, then
43714
+ * `sqrt(sum) * largest`, each square rounded on its own. ECMA-262 lets the
43715
+ * result be approximated, so this is for parity with the browser: a plain sum
43716
+ * differs from V8 on about 6% of three-operand calls, and a fused
43717
+ * square-and-add on about 1% of two-operand calls.
43330
43718
  */
43331
43719
  inline double hypot_invoke(void*, gea::Ref<gea::ArrayObject<double>> values) {
43332
43720
  bool sawNaN = false;
@@ -43343,13 +43731,17 @@ inline double hypot_invoke(void*, gea::Ref<gea::ArrayObject<double>> values) {
43343
43731
  }
43344
43732
  if (sawNaN) return std::numeric_limits<double>::quiet_NaN();
43345
43733
  if (largest == 0.0) return 0.0;
43346
- double sumOfSquares = 0.0;
43734
+ double sum = 0.0;
43735
+ double compensation = 0.0;
43347
43736
  for (const auto& slot : values->slots()) {
43348
43737
  if (!slot.present) continue;
43349
- const double scaled = slot.value / largest;
43350
- sumOfSquares += scaled * scaled;
43738
+ const double scaled = std::fabs(slot.value) / largest;
43739
+ const double summand = gea::float64Product(scaled * scaled) - compensation;
43740
+ const double preliminary = sum + summand;
43741
+ compensation = (preliminary - sum) - summand;
43742
+ sum = preliminary;
43351
43743
  }
43352
- return largest * std::sqrt(sumOfSquares);
43744
+ return std::sqrt(sum) * largest;
43353
43745
  }
43354
43746
 
43355
43747
  // ---------------------------------------------------------------------------
@@ -44009,7 +44401,7 @@ inline void registerErrorRecordType(const char* name) {
44009
44401
  */
44010
44402
  inline bool instanceOfError(const gea::Value& value, const char* name) {
44011
44403
  if (value.tag() != gea::Value::Tag::Object) return false;
44012
- if (gea::host::isRuntimeError(value)) return gea::host::instanceOfRuntimeError(value, name);
44404
+ if (gea::host::isErrorValue(value)) return gea::host::instanceOfRuntimeError(value, name);
44013
44405
  const auto found = detail::errorPayloadTypes().find(name);
44014
44406
  if (found == detail::errorPayloadTypes().end()) return false;
44015
44407
  const void* payload = value.payloadType();
@@ -44829,7 +45221,7 @@ inline void log(const std::string& text) {
44829
45221
  std::fputc('\n', stdout);
44830
45222
  }
44831
45223
 
44832
- /** Node routes both `console.warn` and `console.error` to stderr; only `error` has a real call site in the corpus, so only it is implemented. */
45224
+ /** Node routes both `console.warn` and `console.error` to stderr; `warn` below delegates here. */
44833
45225
  inline void error(const std::string& text) {
44834
45226
  std::fputs(text.c_str(), stderr);
44835
45227
  std::fputc('\n', stderr);
@@ -44955,6 +45347,23 @@ inline void info(const std::vector<gea::Value>& values) { log(values); }
44955
45347
 
44956
45348
  inline void info(const gea::Ref<gea::ArrayObject<gea::Value>>& values) { log(values); }
44957
45349
 
45350
+ /**
45351
+ * `console.warn` -- stderr, byte for byte what `console.error` writes.
45352
+ *
45353
+ * Node's `warn` and `error` (`lib/internal/console/constructor.js`) both write
45354
+ * `kFormatForStderr(args)` to `kUseStderr`; they differ only in which
45355
+ * diagnostics channel they publish to, which this runtime does not have. So
45356
+ * `warn` delegates to `error`, as `info` delegates to `log` above, and restates
45357
+ * the same four overloads for the same reason: the arity shape picks the one.
45358
+ */
45359
+ inline void warn(const std::string& text) { error(text); }
45360
+
45361
+ inline void warn(const gea::Value& first, const std::vector<gea::Value>& rest) { error(first, rest); }
45362
+
45363
+ inline void warn(const std::vector<gea::Value>& values) { error(values); }
45364
+
45365
+ inline void warn(const gea::Ref<gea::ArrayObject<gea::Value>>& values) { error(values); }
45366
+
44958
45367
  } // namespace console
44959
45368
 
44960
45369
  } // namespace gea::host
@@ -46679,9 +47088,13 @@ void bindNodeListener(Node& node, const std::string& name, Invoke invoke) {
46679
47088
  gea::embedded::ui::Document::instance().addEventListener(name.c_str(), std::move(run));
46680
47089
  return;
46681
47090
  }
46682
- if (name == "keydown" || name == "keyup") {
47091
+ if (name == "keydown" || name == "keyup" || name == "scroll") {
46683
47092
  // The native root dispatcher now walks the real allocation-bound node
46684
47093
  // path. Document delegation bypassed that path and outlived raw removal.
47094
+ // Scroll never reached the body at all: the engine stops a non-bubbling
47095
+ // dispatch at its target, so a <virtual-list> scrolled by the watch Crown
47096
+ // or hardware Up/Down buttons left its recycled rows where the last touch
47097
+ // put them.
46685
47098
  const auto listenerId = target.addEventListener(name.c_str(), std::move(run));
46686
47099
  recordNodeSubscription(target.id(), [target, name, listenerId]() {
46687
47100
  target.removeEventListener(name.c_str(), listenerId);
@@ -46719,8 +47132,8 @@ void bindNodeListener(Node& node, const std::string& name, Invoke invoke) {
46719
47132
 
46720
47133
  template <typename Node, typename Result>
46721
47134
  void addNodeListener(Node& node, const std::string& type, const gea::CallableObject<Result()>& handler) {
46722
- // Keys are owned by the real node and follow the native root's ancestor
46723
- // path. Pointer handlers retain the existing body-delegation compatibility
47135
+ // Keys and scroll are owned by the real node and follow the native root's
47136
+ // ancestor path. Pointer handlers retain the existing body-delegation compatibility
46724
47137
  // path, gated by containment. Both record early JSX disposal; native node
46725
47138
  // removal additionally releases the node-owned keyboard listener itself.
46726
47139
  const gea::CallableObject<Result()> held = handler;
@@ -50529,17 +50942,13 @@ inline void gea_json_read(gea::json::Reader& reader, gea::embedded::ui::Signal<T
50529
50942
  // and `new TextDecoder(label)` for a label this implementation does not
50530
50943
  // support (`RangeError`).
50531
50944
  //
50532
- // v1 raises those through `gea_cpp_reject(gea_cpp_value::error(...))`, which
50533
- // needs its boxed error carrier. This runtime has no such carrier: a thrown
50534
- // value here is a program-generated error struct (`ErrorConstructor::create`
50535
- // is a template over one, declared *after* this header), so a library
50536
- // function in this header cannot construct one. So each of the four aborts BY
50537
- // NAME with the specification's own message and clause, exactly as
50538
- // `detail::typedArrayLengthIndex`, `gea::runtime::array::reduce`'s empty-array
50539
- // TypeError and `detail::refuseOmittedArgument` already do for the same
50540
- // reason. That is a real difference from ECMAScript -- a `try { atob(x) }
50541
- // catch {}` cannot recover -- and it is stated here rather than papered over
50542
- // with a plausible empty string.
50945
+ // `decodeURI`/`decodeURIComponent` throw a catchable `URIError` through
50946
+ // `gea::host::throwRuntimeError`, the runtime-owned Error carrier. `btoa`,
50947
+ // `atob` and the TextDecoder label check still abort BY NAME with the
50948
+ // specification's message: they predate that carrier and have not been moved
50949
+ // onto it, so a `try { atob(x) } catch {}` cannot recover yet. That is a real
50950
+ // difference from ECMAScript, stated here rather than papered over with a
50951
+ // plausible empty string.
50543
50952
  // ===========================================================================
50544
50953
 
50545
50954
  namespace gea::runtime::text {
@@ -50855,11 +51264,7 @@ inline void appendPercentU(std::string& out, std::uint32_t codeUnit) {
50855
51264
  out.push_back(hexDigit(codeUnit & 0x0F));
50856
51265
  }
50857
51266
 
50858
- /** v1: `gea::uri::uri_error` (uri.cpp), re-typed to this runtime's named abort -- see this family's header comment for why. */
50859
- [[noreturn]] inline void refuseMalformedUri() {
50860
- std::fprintf(stderr, "gea: URIError: URI malformed (ECMA-262 19.2.6.5 Decode, step 4.b / 19.2.6.4 Encode, step 4.b)\n");
50861
- gea::detail::abortAfterFlush();
50862
- }
51267
+ [[noreturn]] inline void refuseMalformedUri() { gea::host::throwRuntimeError("URIError", "URI malformed"); }
50863
51268
 
50864
51269
  /** v1: `gea::uri::is_unescaped` (uri.cpp). ECMA-262 19.2.6.1.1's `uriUnescaped` = `uriAlpha` + DecimalDigit + `uriMark`. */
50865
51270
  inline bool isUnescaped(std::uint32_t codePoint) {
@@ -51096,15 +51501,19 @@ inline std::string unescapeImpl(const std::string& input) {
51096
51501
  * than through a second copy.
51097
51502
  */
51098
51503
  inline std::string encodeUri(const std::string& value) { return encodeImpl(value, false); }
51504
+ inline std::string encodeUri(const char* value) { return encodeUri(std::string(value)); }
51099
51505
  inline std::string encodeUri(double value) { return encodeImpl(gea::host::detail::toString(value), false); }
51100
51506
  inline std::string encodeUri(bool value) { return encodeImpl(gea::host::detail::toString(value), false); }
51101
51507
  inline std::string encodeUriComponent(const std::string& value) { return encodeImpl(value, true); }
51508
+ inline std::string encodeUriComponent(const char* value) { return encodeUriComponent(std::string(value)); }
51102
51509
  inline std::string encodeUriComponent(double value) { return encodeImpl(gea::host::detail::toString(value), true); }
51103
51510
  inline std::string encodeUriComponent(bool value) { return encodeImpl(gea::host::detail::toString(value), true); }
51104
51511
  inline std::string decodeUri(const std::string& value) { return decodeImpl(value, false); }
51512
+ inline std::string decodeUri(const char* value) { return decodeUri(std::string(value)); }
51105
51513
  inline std::string decodeUri(double value) { return decodeImpl(gea::host::detail::toString(value), false); }
51106
51514
  inline std::string decodeUri(bool value) { return decodeImpl(gea::host::detail::toString(value), false); }
51107
51515
  inline std::string decodeUriComponent(const std::string& value) { return decodeImpl(value, true); }
51516
+ inline std::string decodeUriComponent(const char* value) { return decodeUriComponent(std::string(value)); }
51108
51517
  inline std::string decodeUriComponent(double value) { return decodeImpl(gea::host::detail::toString(value), true); }
51109
51518
  inline std::string decodeUriComponent(bool value) { return decodeImpl(gea::host::detail::toString(value), true); }
51110
51519
 
@@ -51707,11 +52116,23 @@ inline bool isRuntimeError(const gea::Value& value) {
51707
52116
  return value.tag() == gea::Value::Tag::Object &&
51708
52117
  value.payloadType() == gea::detail::payloadTypeTagFor<gea::Ref<gea::runtime::Error>>();
51709
52118
  }
52119
+ inline gea::Ref<gea::runtime::Error> runtimeErrorOf(const gea::Value& value) {
52120
+ if (value.tag() != gea::Value::Tag::Object) return {};
52121
+ if (value.payloadType() == gea::detail::payloadTypeTagFor<gea::Ref<gea::runtime::Error>>()) return value.as<gea::Ref<gea::runtime::Error>>();
52122
+ if (value.classObject() && gea::detail::classIdentityExtends(value.classIdentity(), &gea::detail::RefOperationsFor<gea::runtime::Error>::table))
52123
+ return value.classObject().template staticCast<gea::runtime::Error>();
52124
+ return {};
52125
+ }
52126
+ inline bool isErrorValue(const gea::Value& value) { return static_cast<bool>(runtimeErrorOf(value)); }
51710
52127
  inline bool instanceOfRuntimeError(const gea::Value& value, const char* kind) {
51711
- return isRuntimeError(value) && value.as<gea::Ref<gea::runtime::Error>>()->instanceOf(kind);
52128
+ const auto error = runtimeErrorOf(value);
52129
+ return error && error->instanceOf(kind);
51712
52130
  }
51713
52131
  inline std::string runtimeErrorString(const gea::Value& value) {
51714
- return gea::detail::unboxAs<gea::Ref<gea::runtime::Error>>(value, gea::Value::Tag::Object, "Error ToString")->toString();
52132
+ const auto error = runtimeErrorOf(value);
52133
+ if (!error) return gea::detail::unboxAs<gea::Ref<gea::runtime::Error>>(value, gea::Value::Tag::Object, "Error ToString")->toString();
52134
+ if (value.classObject() && value.getProperty(gea::PropertyKey::string("toString")).tag() == gea::Value::Tag::Function) return gea::dynamicToString(value);
52135
+ return error->toString();
51715
52136
  }
51716
52137
  [[noreturn]] inline void throwRuntimeError(const char* kind, const std::string& message) {
51717
52138
  #if defined(GEA_RUNTIME_THROW_ENDS_PROGRAM) && GEA_RUNTIME_THROW_ENDS_PROGRAM
@@ -51736,7 +52157,7 @@ inline const bool uncaughtDescriberInstalled = [] {
51736
52157
  std::rethrow_exception(current);
51737
52158
  } catch (const gea::Value& value) {
51738
52159
  try {
51739
- text = gea::host::isRuntimeError(value) ? gea::host::runtimeErrorString(value) : gea::dynamicToString(value);
52160
+ text = gea::host::isErrorValue(value) ? gea::host::runtimeErrorString(value) : gea::dynamicToString(value);
51740
52161
  } catch (...) {
51741
52162
  text = "<a value whose ToString threw>";
51742
52163
  }