@geastack/compiler 1.0.43 → 1.0.45

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 (35) hide show
  1. package/dist/cli.js +8 -2
  2. package/dist/ir/callable-class-flow.js +87 -29
  3. package/dist/ir/construction-only-fields.d.ts +1 -1
  4. package/dist/ir/construction-only-fields.js +3 -1
  5. package/dist/ir/lower-operands.js +6 -1
  6. package/dist/ir/native-callable-data-owner.js +13 -1
  7. package/dist/ir/native-callable-data-write.d.ts +0 -4
  8. package/dist/ir/native-callable-data-write.js +9 -0
  9. package/dist/ir/shake.js +21 -0
  10. package/dist/semantics/frontend.js +18 -14
  11. package/dist/semantics/normalize/field-bindings.d.ts +2 -0
  12. package/dist/semantics/normalize/field-bindings.js +669 -13
  13. package/dist/semantics/normalize/flow/component-solver.js +37 -2
  14. package/dist/semantics/normalize/flow/source-value-session.d.ts +3 -0
  15. package/dist/semantics/normalize/flow/source-value-session.js +343 -138
  16. package/dist/semantics/normalize/global-host-mutations.js +14 -6
  17. package/dist/semantics/normalize/implicit-arguments-tuple.d.ts +11 -10
  18. package/dist/semantics/normalize/implicit-arguments-tuple.js +15 -3
  19. package/dist/semantics/normalize/parameter-bindings.js +18 -0
  20. package/dist/semantics/normalize/producers/object-assignment.js +7 -1
  21. package/dist/semantics/normalize/stated-dynamic-value.d.ts +11 -0
  22. package/dist/semantics/normalize/stated-dynamic-value.js +36 -0
  23. package/dist/semantics/normalize/structural-mutable-method.js +88 -2
  24. package/dist/targets/cpp/borrowed-call-entry.d.ts +41 -2
  25. package/dist/targets/cpp/borrowed-call-entry.js +91 -6
  26. package/dist/targets/cpp/emit-callable.js +62 -29
  27. package/dist/targets/cpp/emit.js +106 -10
  28. package/dist/targets/cpp/host/emit-host-object.js +69 -2
  29. package/dist/targets/cpp/records.d.ts +1 -0
  30. package/dist/targets/cpp/records.js +1 -1
  31. package/dist/targets/cpp/translation-unit.js +59 -22
  32. package/dist/targets/cpp/virtual-methods.js +9 -4
  33. package/package.json +1 -1
  34. package/src/targets/cpp/runtime/gea_dynamic_proxy.h +121 -0
  35. package/src/targets/cpp/runtime/gea_runtime.h +218 -28
@@ -5,7 +5,7 @@ import { prototypeSetterValue, virtualConversionOwnerOf } from '../../ir/program
5
5
  import { extendsClass, virtualDispatchKey, virtualMethodFamiliesOf } from '../../projection/dispatch.js';
6
6
  export { extendsClass, virtualDispatchKey, virtualMethodFamiliesOf };
7
7
  import { cppFormalName } from './emit-context.js';
8
- import { nativeFieldPolicyType, wellKnownSymbolEnumNameOf } from './records.js';
8
+ import { nativeFieldPolicyType, switchedByKeyLength, wellKnownSymbolEnumNameOf } from './records.js';
9
9
  import { cppAbiParameterType, cppBodyName, cppCallableDeclarationTagName, cppClassName, cppRecordFieldKeyIsSymbol, cppRecordFieldName, cppResultTypeOf, cppStringLiteral, cppTypeOf, cppUndefinedIn } from './types.js';
10
10
  import { programConversionText, dynamicCarrierBoxText } from './emit-narrowing.js';
11
11
  /**
@@ -515,7 +515,7 @@ export const prototypeReadHooks = (classes, abiOf, capturesNothing, readDynamica
515
515
  : [
516
516
  `(!gea_key.isSymbol() && (${keys
517
517
  .filter((key) => !cppRecordFieldKeyIsSymbol(key))
518
- .map((key) => `gea_key.text() == ${cppStringLiteral(key)}`)
518
+ .map((key) => `std::string_view{gea_key.text()} == ${cppStringLiteral(key)}`)
519
519
  .join(' || ')}))`
520
520
  ]),
521
521
  ...(keys?.some(cppRecordFieldKeyIsSymbol)
@@ -531,8 +531,13 @@ export const prototypeReadHooks = (classes, abiOf, capturesNothing, readDynamica
531
531
  ? []
532
532
  : [
533
533
  ' if (!gea_key.isSymbol()) {',
534
- ' const std::string& gea_name = gea_key.text();',
535
- ...texts.map((getter) => ` if (gea_name == ${cppStringLiteral(getter.key)}) { gea_out = ${getter.text}; return true; }`),
534
+ // A `string_view` under a switch on the length, as the
535
+ // record field dispatchers do (`switchedByKeyLength`): a
536
+ // class with seventy methods answered a read of a name it
537
+ // does not have -- an optional member probed on an object
538
+ // of a sibling class -- with seventy `strlen`+`memcmp`s.
539
+ ' const std::string_view gea_name = gea_key.text();',
540
+ ...switchedByKeyLength(texts.map((getter) => ` if (gea_name == ${cppStringLiteral(getter.key)}) { gea_out = ${getter.text}; return true; }`)),
536
541
  ' }'
537
542
  ]),
538
543
  ...(symbols.length === 0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.43",
3
+ "version": "1.0.45",
4
4
  "description": "The geastack TypeScript-to-C++ compiler: one semantic spine, no source-shaped authority, no boxing of statically typed values.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -213,6 +213,57 @@ inline Value dynamicAdd(const Value& left, const Value& right) {
213
213
  return Value::box(Value::Tag::Number, dynamicToNumber(a) + dynamicToNumber(b));
214
214
  }
215
215
 
216
+ /**
217
+ * ECMA-262 7.2.13 IsLessThan over two dynamic values: 1 for true, 0 for false
218
+ * and -1 for undefined (a NaN on either side), which each relational operator
219
+ * reads its own way. ToPrimitive with hint Number runs in source order -- the
220
+ * left operand first unless the operator swapped them (`>`, `<=`). Two
221
+ * strings compare by code unit, as the typed string path compares them.
222
+ */
223
+ inline int dynamicIsLessThan(const Value& x, const Value& y, bool leftFirst) {
224
+ Value px;
225
+ Value py;
226
+ if (leftFirst) {
227
+ px = dynamicToPrimitive(x, ToPrimitiveHint::Number);
228
+ py = dynamicToPrimitive(y, ToPrimitiveHint::Number);
229
+ } else {
230
+ py = dynamicToPrimitive(y, ToPrimitiveHint::Number);
231
+ px = dynamicToPrimitive(x, ToPrimitiveHint::Number);
232
+ }
233
+ if (px.tag() == Value::Tag::String && py.tag() == Value::Tag::String) return px.as<std::string>() < py.as<std::string>() ? 1 : 0;
234
+ if (px.tag() == Value::Tag::BigInt && py.tag() == Value::Tag::BigInt) return px.as<BigInt>() < py.as<BigInt>() ? 1 : 0;
235
+ if (px.tag() == Value::Tag::BigInt || py.tag() == Value::Tag::BigInt)
236
+ host::throwRuntimeError("TypeError", "comparing a BigInt with another type is not supported through dynamic values");
237
+ const double nx = dynamicToNumber(px);
238
+ const double ny = dynamicToNumber(py);
239
+ if (std::isnan(nx) || std::isnan(ny)) return -1;
240
+ return nx < ny ? 1 : 0;
241
+ }
242
+
243
+ /**
244
+ * ECMA-262 7.2.14 IsLooselyEqual over two dynamic values. Same-type operands
245
+ * compare strictly; `null` and `undefined` equal each other and nothing
246
+ * else; a string meets a number as a number, a boolean as a number, and an
247
+ * object meets a primitive through ToPrimitive. A BigInt meeting another type
248
+ * is refused by name rather than approximated.
249
+ */
250
+ inline bool dynamicLooselyEquals(const Value& x, const Value& y) {
251
+ if (x.tag() == y.tag()) return Value::strictEquals(x, y);
252
+ const auto nullish = [](const Value& value) { return value.tag() == Value::Tag::Null || value.tag() == Value::Tag::Undefined; };
253
+ if (nullish(x) || nullish(y)) return nullish(x) && nullish(y);
254
+ if (x.tag() == Value::Tag::Number && y.tag() == Value::Tag::String) return x.as<double>() == host::detail::toNumber(y.as<std::string>());
255
+ if (x.tag() == Value::Tag::String && y.tag() == Value::Tag::Number) return host::detail::toNumber(x.as<std::string>()) == y.as<double>();
256
+ if (x.tag() == Value::Tag::Boolean) return dynamicLooselyEquals(Value::box(Value::Tag::Number, x.as<bool>() ? 1.0 : 0.0), y);
257
+ if (y.tag() == Value::Tag::Boolean) return dynamicLooselyEquals(x, Value::box(Value::Tag::Number, y.as<bool>() ? 1.0 : 0.0));
258
+ const bool xObject = isObjectValue(x);
259
+ const bool yObject = isObjectValue(y);
260
+ if (xObject && !yObject) return dynamicLooselyEquals(dynamicToPrimitive(x), y);
261
+ if (yObject && !xObject) return dynamicLooselyEquals(x, dynamicToPrimitive(y));
262
+ if (x.tag() == Value::Tag::BigInt || y.tag() == Value::Tag::BigInt)
263
+ host::throwRuntimeError("TypeError", "loose equality between a BigInt and another type is not supported through dynamic values");
264
+ return false;
265
+ }
266
+
216
267
  inline bool dynamicArrayPrototypeHas(const PropertyKey& key) {
217
268
  if (key.isSymbol()) return false;
218
269
  std::size_t index = 0;
@@ -414,6 +465,76 @@ inline Value dynamicStringPrototypeGet(const PropertyKey& key) {
414
465
  return found == methods.end() ? Value() : found->second;
415
466
  }
416
467
 
468
+ /**
469
+ * `Number.prototype`'s methods read off a number the program holds as a
470
+ * dynamic value (`value.toFixed(3)` where `value` came out of a parsed
471
+ * document). Each is the native function the typed path already calls
472
+ * (`toFixed`, `toPrecision`, `toExponential`, `toStringRadix`), reached
473
+ * through the boxed receiver. A method not listed reads `undefined`, so
474
+ * calling it is the language's own TypeError rather than an answer this
475
+ * table invented.
476
+ */
477
+ inline Value dynamicNumberPrototypeGet(const PropertyKey& key) {
478
+ if (key.isSymbol()) return Value();
479
+ using Args = gea::Ref<ArrayObject<Value>>;
480
+ using Method = CallableObject<Value(Value, Args)>;
481
+ static const std::map<std::string, Value> methods = [] {
482
+ std::map<std::string, Value> result;
483
+ for (const char* name : {"toFixed", "toPrecision", "toExponential", "toString", "valueOf"}) {
484
+ auto callable = Method(+[](void* environment, Value receiver, Args args) -> Value {
485
+ alignas(void*) unsigned char slot[sizeof(void*)];
486
+ const std::string& method = *gea::unpackEnvironment<std::string>(environment, slot);
487
+ if (receiver.tag() != Value::Tag::Number)
488
+ host::throwRuntimeError("TypeError", "Number.prototype." + method + " requires that 'this' be a Number");
489
+ const double number = detail::unboxAs<double>(receiver, Value::Tag::Number, "Number.prototype method receiver");
490
+ const Value first = args->size() ? args->readElement(0) : Value();
491
+ const bool given = first.tag() != Value::Tag::Undefined;
492
+ const auto string = [](std::string value) { return Value::box(Value::Tag::String, std::move(value)); };
493
+ if (method == "valueOf") return Value::box(Value::Tag::Number, number);
494
+ if (method == "toString") return string(given ? host::detail::toStringRadix(number, dynamicToNumber(first)) : host::detail::toString(number));
495
+ // ECMA-262 21.1.3.5 step 2: an undefined precision is ToString(x).
496
+ if (method == "toPrecision") return string(given ? host::detail::toPrecision(number, dynamicToNumber(first)) : host::detail::toString(number));
497
+ // ECMA-262 21.1.3.3: an undefined fractionDigits is ToIntegerOrInfinity(undefined), 0.
498
+ const double digits = given ? dynamicToNumber(first) : 0.0;
499
+ if (method == "toFixed") return string(host::detail::toFixed(number, std::isnan(digits) ? 0.0 : digits));
500
+ // ECMA-262 21.1.3.2: an undefined fractionDigits means as many digits
501
+ // as the value needs, a form the typed path does not spell either.
502
+ if (!given) host::throwRuntimeError("TypeError", "Number.prototype.toExponential without fractionDigits is not supported through a dynamic receiver");
503
+ return string(host::detail::toExponential(number, std::isnan(digits) ? 0.0 : digits));
504
+ }, gea::packEnvironment<std::string>(std::string(name)));
505
+ result.emplace(name, Value::boxMethod<1>(callable));
506
+ }
507
+ return result;
508
+ }();
509
+ const auto found = methods.find(key.text());
510
+ return found == methods.end() ? Value() : found->second;
511
+ }
512
+
513
+ /** `Boolean.prototype`'s two methods read off a boolean held as a dynamic value. */
514
+ inline Value dynamicBooleanPrototypeGet(const PropertyKey& key) {
515
+ if (key.isSymbol()) return Value();
516
+ using Args = gea::Ref<ArrayObject<Value>>;
517
+ using Method = CallableObject<Value(Value, Args)>;
518
+ static const std::map<std::string, Value> methods = [] {
519
+ std::map<std::string, Value> result;
520
+ for (const char* name : {"toString", "valueOf"}) {
521
+ auto callable = Method(+[](void* environment, Value receiver, Args) -> Value {
522
+ alignas(void*) unsigned char slot[sizeof(void*)];
523
+ const std::string& method = *gea::unpackEnvironment<std::string>(environment, slot);
524
+ if (receiver.tag() != Value::Tag::Boolean)
525
+ host::throwRuntimeError("TypeError", "Boolean.prototype." + method + " requires that 'this' be a Boolean");
526
+ const bool value = detail::unboxAs<bool>(receiver, Value::Tag::Boolean, "Boolean.prototype method receiver");
527
+ if (method == "valueOf") return Value::box(Value::Tag::Boolean, value);
528
+ return Value::box(Value::Tag::String, std::string(value ? "true" : "false"));
529
+ }, gea::packEnvironment<std::string>(std::string(name)));
530
+ result.emplace(name, Value::boxMethod<1>(callable));
531
+ }
532
+ return result;
533
+ }();
534
+ const auto found = methods.find(key.text());
535
+ return found == methods.end() ? Value() : found->second;
536
+ }
537
+
417
538
  // The intrinsic is one ordinary native array with its own method properties.
418
539
  // Identity sidecars already carry descriptors on arrays; a new representation
419
540
  // or a boxed array would lose that existing native ownership for no reason.
@@ -3188,6 +3188,13 @@ struct CycleState {
3188
3188
  // fullCollectionEvery` candidates per full sweep is exactly what the
3189
3189
  // collection count meant when every young collection was a full buffer.
3190
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;
3191
3198
  // Young-collection survivors whose "live" verdict rested on a clipped edge
3192
3199
  // (`Node::hadClippedEdge`). They are not re-entered into `candidates`: a
3193
3200
  // young pass can never decide them (the clipped edge is invisible to it by
@@ -3318,16 +3325,49 @@ inline bool& cycleSafepointArmed() {
3318
3325
  #endif
3319
3326
  }
3320
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
+
3321
3349
  /** The deferred list normally waits for the cadence-driven full collection,
3322
3350
  * which needs young candidates to keep arriving. A program whose only
3323
3351
  * releases are of permanent objects would otherwise never reach one, so the
3324
- * list itself becomes the trigger once it holds what `fullCollectionEvery`
3325
- * young collections' worth of candidates would have: the same bound the
3326
- * cadence gives an all-mature garbage cycle, derived from the policy rather
3327
- * than a third knob. Entries are unique objects (`cycleBuffered` keeps each
3328
- * 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. */
3329
3369
  inline bool deferredOverdue(const CycleState& state) {
3330
- return state.deferred.size() >= state.candidateThreshold * state.fullCollectionEvery;
3370
+ return state.deferred.size() >= state.candidateThreshold * state.fullCollectionEvery + state.survivorsOfLastFullCollection;
3331
3371
  }
3332
3372
 
3333
3373
  /**
@@ -3857,7 +3897,7 @@ inline void filterBufferedCandidates(CycleState& state) {
3857
3897
  * collection (`full == true`) ignores the mature bit and traces everything
3858
3898
  * reachable from the candidates, then re-marks every survivor mature; this is
3859
3899
  * what `gea::collectCycles()` runs, and what the automatic path promotes to
3860
- * every `fullCollectionEvery` young collections (see `CycleState`).
3900
+ * once young collections have examined `fullCollectionBudget` candidates.
3861
3901
  *
3862
3902
  * Correctness of the young path -- why it can only OVER-retain, never
3863
3903
  * under-collect a live object:
@@ -3908,7 +3948,7 @@ inline void filterBufferedCandidates(CycleState& state) {
3908
3948
  * way, the entry candidate is never lost after a false retain: it sits
3909
3949
  * buffered, reachable from `state.candidates`, until the next FULL
3910
3950
  * collection traces it without the mature filter, finds the true
3911
- * incoming count, and frees it -- bounded by `fullCollectionEvery`, never
3951
+ * incoming count, and frees it -- bounded by `fullCollectionBudget`, never
3912
3952
  * indefinite, and never dependent on some unrelated later release
3913
3953
  * happening to touch it again.
3914
3954
  * - `restorePins`'s `restoreWeakCounts` replays `savedWeak` -- captured
@@ -3933,7 +3973,7 @@ GEA_EH_NOINLINE inline void collectReferenceCycles(bool full = false) {
3933
3973
  // ordinary (young) collection to full on the configured cadence, and on
3934
3974
  // the very first collection (nothing is mature yet, so this costs nothing
3935
3975
  // and establishes the baseline for the counter).
3936
- 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;
3937
3977
  // A full collection also owes the deferred survivors an answer (see
3938
3978
  // `CycleState::deferred`), so it runs for them even with no fresh candidate.
3939
3979
  if (state.candidates.empty() && !(full && !state.deferred.empty())) return;
@@ -4325,6 +4365,7 @@ GEA_EH_NOINLINE inline void collectReferenceCycles(bool full = false) {
4325
4365
  if (trace.runs % 32 == 0 && gea_heap_trace_print) gea_heap_trace_print();
4326
4366
  }
4327
4367
  #endif
4368
+ if (full) state.survivorsOfLastFullCollection = graph.live.size();
4328
4369
  graph.clear();
4329
4370
  state.collecting = false;
4330
4371
  state.allocationPressure = 0;
@@ -13887,6 +13928,7 @@ class Dictionary {
13887
13928
  if (first_ && first_->first == key) return first_->second;
13888
13929
  if (!first_ && entries_.empty()) {
13889
13930
  enumerableKeys_.reset();
13931
+ noteKey(key);
13890
13932
  first_.emplace(detail::duplicateString(key), V{});
13891
13933
  if constexpr (aliasable) detail::noteDocumentDataKeyCreated(this, key);
13892
13934
  return first_->second;
@@ -13894,6 +13936,7 @@ class Dictionary {
13894
13936
  const std::size_t found = findPosition(key);
13895
13937
  if (found != npos) return entries_[found].second;
13896
13938
  enumerableKeys_.reset();
13939
+ noteKey(key);
13897
13940
  Entry& entry = entries_.emplace_back(detail::duplicateString(key), V{});
13898
13941
  GEA_EH_TRY_ANY(gea_eh_failed) {
13899
13942
  indexInsert(entries_.size() - 1);
@@ -13952,6 +13995,7 @@ class Dictionary {
13952
13995
  V readHinted(std::string_view key, std::atomic<std::uint32_t>& hint) const {
13953
13996
  if constexpr (!aliasable) {
13954
13997
  if (!view_) [[likely]] {
13998
+ if (!mayHoldKey(key)) return V{};
13955
13999
  if (first_ && first_->first == key) return first_->second;
13956
14000
  const std::size_t found = hintedPosition(key, hint);
13957
14001
  return found == npos ? V{} : entries_[found].second;
@@ -13964,6 +14008,7 @@ class Dictionary {
13964
14008
  Carrier readIfPresentHinted(std::string_view key, std::atomic<std::uint32_t>& hint) const {
13965
14009
  if constexpr (!aliasable) {
13966
14010
  if (!view_) [[likely]] {
14011
+ if (!mayHoldKey(key)) return Carrier();
13967
14012
  if (first_ && first_->first == key) return Carrier(first_->second);
13968
14013
  const std::size_t found = hintedPosition(key, hint);
13969
14014
  return found == npos ? Carrier() : Carrier(entries_[found].second);
@@ -14477,6 +14522,7 @@ class Dictionary {
14477
14522
  void appendAbsent(const std::string& key, V value) {
14478
14523
  if (view_) [[unlikely]] detail::refuseAliasedDictionaryStore();
14479
14524
  enumerableKeys_.reset();
14525
+ noteKey(key);
14480
14526
  if (!first_ && entries_.empty()) {
14481
14527
  first_.emplace(detail::duplicateString(key), std::move(value));
14482
14528
  return;
@@ -14592,6 +14638,28 @@ class Dictionary {
14592
14638
  // `std::map` that cost one node allocation per key.
14593
14639
  static constexpr std::size_t kScanLimit = 8;
14594
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; }
14595
14663
  static constexpr std::uint32_t kEmptySlot = static_cast<std::uint32_t>(-1);
14596
14664
  std::vector<std::uint32_t> index_;
14597
14665
  std::size_t findPosition(std::string_view key) const {
@@ -15347,6 +15415,10 @@ class Map {
15347
15415
  entries_.clear();
15348
15416
  serials_.clear();
15349
15417
  if constexpr (indexable) index_.clear();
15418
+ if constexpr (directable) {
15419
+ direct_.clear();
15420
+ directOk_ = true;
15421
+ }
15350
15422
  }
15351
15423
 
15352
15424
  /**
@@ -15403,12 +15475,49 @@ class Map {
15403
15475
  * of an unchanging Map (parallel regions) stay read-only.
15404
15476
  */
15405
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
+ }
15406
15506
  static constexpr std::size_t indexFrom = 8;
15407
15507
  static constexpr std::size_t notFound = static_cast<std::size_t>(-1);
15408
15508
  using Index = std::conditional_t<indexable, std::unordered_map<K, std::size_t, detail::MapKeyHash, detail::MapKeyEqual>,
15409
15509
  detail::NoMapIndex>;
15410
15510
 
15411
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
+ }
15412
15521
  if constexpr (indexable) {
15413
15522
  if (!index_.empty()) {
15414
15523
  const auto found = index_.find(key);
@@ -15429,6 +15538,26 @@ class Map {
15429
15538
  }
15430
15539
  }
15431
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
+ }
15432
15561
  if constexpr (indexable) {
15433
15562
  if (!index_.empty()) index_.emplace(entries_.back().first, entries_.size() - 1);
15434
15563
  else if (entries_.size() >= indexFrom) rebuildIndex();
@@ -15437,6 +15566,18 @@ class Map {
15437
15566
  // Erasing shifted every later entry down one position (an O(n) move already),
15438
15567
  // so the index is renumbered by rebuilding it, or dropped below `indexFrom`.
15439
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
+ }
15440
15581
  if constexpr (indexable) {
15441
15582
  if (!index_.empty()) rebuildIndex();
15442
15583
  }
@@ -15447,6 +15588,8 @@ class Map {
15447
15588
  std::uint64_t nextSerial_ = 1;
15448
15589
  std::shared_ptr<const detail::MapViewSource<K, V>> view_;
15449
15590
  Index index_;
15591
+ std::vector<std::uint32_t> direct_;
15592
+ bool directOk_ = true;
15450
15593
  };
15451
15594
 
15452
15595
  namespace detail {
@@ -19687,7 +19830,19 @@ namespace detail {
19687
19830
  struct LiteralReadCache {
19688
19831
  std::atomic<const ValueMetadata*> absentOn[4]{};
19689
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};
19690
19842
  std::atomic<std::int8_t> stringAbsent{-1};
19843
+ // The same fact for a number and for a boolean: their prototype tables hold nothing under this key.
19844
+ std::atomic<std::int8_t> numberAbsent{-1};
19845
+ std::atomic<std::int8_t> booleanAbsent{-1};
19691
19846
  // The same fact for an Array: this key is neither `length` nor an index and the Array prototype table holds nothing under it.
19692
19847
  std::atomic<std::int8_t> arrayAbsent{-1};
19693
19848
  };
@@ -21963,8 +22118,12 @@ inline Value dynamicArrayPrototypeGet(const PropertyKey&, const Value&);
21963
22118
  inline Ref<ArrayObject<Value>> arrayPrototypeObject();
21964
22119
  inline bool dynamicArrayPrototypeHas(const PropertyKey&);
21965
22120
  inline Value dynamicStringPrototypeGet(const PropertyKey&);
22121
+ inline Value dynamicNumberPrototypeGet(const PropertyKey&);
22122
+ inline Value dynamicBooleanPrototypeGet(const PropertyKey&);
21966
22123
  inline Value dynamicFunctionPrototypeGet(const PropertyKey&);
21967
22124
  inline double dynamicToNumber(const Value&);
22125
+ inline int dynamicIsLessThan(const Value&, const Value&, bool);
22126
+ inline bool dynamicLooselyEquals(const Value&, const Value&);
21968
22127
  inline std::string dynamicToString(const Value&);
21969
22128
  namespace detail {
21970
22129
  [[noreturn]] inline void refusePayloadMismatch(const char* site);
@@ -33216,10 +33375,14 @@ inline Value Value::getProperty(const PropertyKey& key, const Value& receiver) c
33216
33375
  }
33217
33376
  }
33218
33377
  if (tag_ == Tag::Object || tag_ == Tag::Function) detail::refuseOpaquePropertyAccess("a property read", key);
33219
- // Every remaining box is a primitive, whose properties all live on a
33220
- // prototype this runtime does not model. `undefined` is what the language
33221
- // answers for a key no prototype in the chain holds, and this runtime's
33222
- // chain for a primitive is empty.
33378
+ // Every remaining box is a primitive, whose properties live on its
33379
+ // prototype: `Number.prototype` and `Boolean.prototype` answer from their
33380
+ // method tables, and a key no table holds reads `undefined`, as the
33381
+ // language answers for a key no prototype in the chain holds.
33382
+ if (metadata_->fields == nullptr && metadata_->elements == nullptr) {
33383
+ if (tag_ == Tag::Number) return dynamicNumberPrototypeGet(key);
33384
+ if (tag_ == Tag::Boolean) return dynamicBooleanPrototypeGet(key);
33385
+ }
33223
33386
  return Value();
33224
33387
  }
33225
33388
 
@@ -33235,9 +33398,15 @@ inline bool Value::readDeclaredField(const PropertyKey& key, Value& out) const {
33235
33398
  }
33236
33399
 
33237
33400
  inline Value Value::getLiteralProperty(const PropertyKey& key, detail::LiteralReadCache& cache) const {
33401
+ constexpr auto relaxed = std::memory_order_relaxed;
33402
+ // A type this site has already seen answer from its declared fields: the
33403
+ // ladder below and `getProperty`'s own would only reach the same table.
33404
+ if (!proxy_ && !dynamic_ && tag_ == Tag::Object && (cache.fieldOn[0].load(relaxed) == metadata_ || cache.fieldOn[1].load(relaxed) == metadata_)) {
33405
+ Value answer;
33406
+ if (metadata_->fields->read(payload(), key, answer)) return answer;
33407
+ }
33238
33408
  Value viewed;
33239
33409
  if (nativeViewValue(viewed)) return viewed.getLiteralProperty(key, cache);
33240
- constexpr auto relaxed = std::memory_order_relaxed;
33241
33410
  if (!proxy_ && !dynamic_ && tag_ == Tag::Object) {
33242
33411
  // 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
33243
33412
  // views a native object, from that object's cached read) and an Array from its prototype table, neither needing `getProperty`'s ladder.
@@ -33265,11 +33434,22 @@ inline Value Value::getLiteralProperty(const PropertyKey& key, detail::LiteralRe
33265
33434
  }
33266
33435
  }
33267
33436
  if (!proxy_ && !dynamic_) {
33268
- // A literal-keyed read of a primitive: a number, boolean or bigint reads every key
33269
- // as `undefined` (`getProperty` falls through to its closing return for
33270
- // them), and a serializer may ask each value it visits for a hook method.
33271
- if ((tag_ == Tag::Number || tag_ == Tag::Boolean || tag_ == Tag::BigInt) && metadata_->fields == nullptr && metadata_->elements == nullptr)
33272
- return Value();
33437
+ // A literal-keyed read of a primitive. A number or boolean answers from
33438
+ // its prototype's method table, and the miss -- which is what a
33439
+ // serializer asking each value it visits for a hook method sees -- is
33440
+ // remembered per key, as a string's is. A bigint reads every key as
33441
+ // `undefined` (`getProperty`'s closing return).
33442
+ if ((tag_ == Tag::Number || tag_ == Tag::Boolean) && metadata_->fields == nullptr && metadata_->elements == nullptr) {
33443
+ const bool number = tag_ == Tag::Number;
33444
+ std::atomic<std::int8_t>& slot = number ? cache.numberAbsent : cache.booleanAbsent;
33445
+ std::int8_t absent = slot.load(relaxed);
33446
+ if (absent < 0) {
33447
+ absent = (number ? dynamicNumberPrototypeGet(key) : dynamicBooleanPrototypeGet(key)).tag() == Tag::Undefined ? 1 : 0;
33448
+ slot.store(absent, relaxed);
33449
+ }
33450
+ return absent == 1 ? Value() : number ? dynamicNumberPrototypeGet(key) : dynamicBooleanPrototypeGet(key);
33451
+ }
33452
+ if (tag_ == Tag::BigInt && metadata_->fields == nullptr && metadata_->elements == nullptr) return Value();
33273
33453
  if (tag_ == Tag::String) {
33274
33454
  std::int8_t absent = cache.stringAbsent.load(relaxed);
33275
33455
  if (absent < 0) {
@@ -33284,12 +33464,6 @@ inline Value Value::getLiteralProperty(const PropertyKey& key, detail::LiteralRe
33284
33464
  cache.stringAbsent.store(absent, relaxed);
33285
33465
  }
33286
33466
  if (absent == 1) return Value();
33287
- } else if ((tag_ == Tag::Number || tag_ == Tag::Boolean) && metadata_->fields == nullptr && metadata_->elements == nullptr) {
33288
- // `getProperty`'s own tail for a bare number or boolean: no field table,
33289
- // no elements, no prototype this runtime models, so every key reads
33290
- // `undefined`. A serializer may ask each number and boolean it visits for
33291
- // a hook method, and the ten branches before that tail were the whole cost.
33292
- return Value();
33293
33467
  } else if (tag_ == Tag::Object && metadata_->fields != nullptr && metadata_->elements == nullptr) {
33294
33468
  for (const auto& entry : cache.absentOn) {
33295
33469
  if (entry.load(relaxed) != metadata_) continue;
@@ -33307,6 +33481,18 @@ inline Value Value::getLiteralProperty(const PropertyKey& key, detail::LiteralRe
33307
33481
  }
33308
33482
  }
33309
33483
  }
33484
+ // The conditions under which `getProperty` asks the declared field table
33485
+ // before anything else (`readDeclaredField`): no view hook on the type, no
33486
+ // proxy or dynamic object, not a Document, not a tuple. A hit there is
33487
+ // remembered for the type, so the next box of it skips straight to it.
33488
+ if (!proxy_ && !dynamic_ && tag_ == Tag::Object && metadata_->nativeViewValue == nullptr && metadata_->fields != nullptr &&
33489
+ metadata_->elements == nullptr && metadata_->payloadType != detail::payloadTypeTagFor<gea::Ref<gea::Dictionary<gea::Value>>>()) {
33490
+ Value declared;
33491
+ if (metadata_->fields->read(payload(), key, declared)) {
33492
+ cache.fieldOn[cache.nextField.fetch_add(1, relaxed) % 2].store(metadata_, relaxed);
33493
+ return declared;
33494
+ }
33495
+ }
33310
33496
  Value answer = getProperty(key, *this);
33311
33497
  // Learned only from a miss the type itself proves: a key its declared names
33312
33498
  // do not include, on a layout with no elements or prototype hook, so the
@@ -46918,9 +47104,13 @@ void bindNodeListener(Node& node, const std::string& name, Invoke invoke) {
46918
47104
  gea::embedded::ui::Document::instance().addEventListener(name.c_str(), std::move(run));
46919
47105
  return;
46920
47106
  }
46921
- if (name == "keydown" || name == "keyup") {
47107
+ if (name == "keydown" || name == "keyup" || name == "scroll") {
46922
47108
  // The native root dispatcher now walks the real allocation-bound node
46923
47109
  // path. Document delegation bypassed that path and outlived raw removal.
47110
+ // Scroll never reached the body at all: the engine stops a non-bubbling
47111
+ // dispatch at its target, so a <virtual-list> scrolled by the watch Crown
47112
+ // or hardware Up/Down buttons left its recycled rows where the last touch
47113
+ // put them.
46924
47114
  const auto listenerId = target.addEventListener(name.c_str(), std::move(run));
46925
47115
  recordNodeSubscription(target.id(), [target, name, listenerId]() {
46926
47116
  target.removeEventListener(name.c_str(), listenerId);
@@ -46958,8 +47148,8 @@ void bindNodeListener(Node& node, const std::string& name, Invoke invoke) {
46958
47148
 
46959
47149
  template <typename Node, typename Result>
46960
47150
  void addNodeListener(Node& node, const std::string& type, const gea::CallableObject<Result()>& handler) {
46961
- // Keys are owned by the real node and follow the native root's ancestor
46962
- // path. Pointer handlers retain the existing body-delegation compatibility
47151
+ // Keys and scroll are owned by the real node and follow the native root's
47152
+ // ancestor path. Pointer handlers retain the existing body-delegation compatibility
46963
47153
  // path, gated by containment. Both record early JSX disposal; native node
46964
47154
  // removal additionally releases the node-owned keyboard listener itself.
46965
47155
  const gea::CallableObject<Result()> held = handler;