@geastack/compiler 1.0.44 → 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.
@@ -16,6 +16,7 @@ import { callbackContractParameterType, inlineJsxCallbackParameterType, callback
16
16
  import { declaredClosedTupleRestElementsOf, impliedPatternElementOfArms, impliedPatternPositionPresentEverywhere } from './parameter-slot.js';
17
17
  import { iteratorYieldTypesOf } from './producers/iteration-yield.js';
18
18
  import { annotationStatesNothing, exactEmptyObjectLiteralType, isNullishType, containsUnstatedPosition, derivedExpressionType, indexAliasEvidence, indexedTypeOf, explicitThisCallReturnType, overloadInvariantReturnTypeAt, arrayFromCopyTypeAt, indexNamedCallables, isStandardInterfaceType, isBindingOnlyReference, isCalleeOf, isTrackedCallable, isUnusableEvidence as statesNoStorage, carriesNoEvidence, disjointUnionMembersOf, disjointUnionTypeOf, joinOfWrites, jsDocTypeStatesNothing, literalMemberNameOf, narrowsOnlyUnstatedPositions, isStructuralConstructorType, narrowsStructuralConstructorToClasses, narrowsArrayBufferViewToViews, statesAnArrayBufferView, isLibArrayBufferViewType, withoutUndefinedMember, memberTypeOf, objectAssignTargetType, nameOfCallable, synthesizedUnionArmsAt, readsWholeSynthesizedCell, widestOf, impliedPatternElementRootOf, impliedPatternParameterOf } from './derived-expression-type.js';
19
+ import { readsStatedDynamicValue } from './stated-dynamic-value.js';
19
20
  import { isUnreducedTypeForm } from './unreduced-type-form.js';
20
21
  import { noHostProvidedNames, valueSymbolAt } from './unresolvable-names.js';
21
22
  import { isHomelessRecordArm, recordArmUnionStatementOf, recordHomeArmsAtRead } from './record-home-arms.js';
@@ -1573,6 +1574,10 @@ hostProvided = noHostProvidedNames) => {
1573
1574
  return cached;
1574
1575
  if (resolving.has(node))
1575
1576
  return null;
1577
+ if (readsStatedDynamicValue(upstream.statedTypeAt, node)) {
1578
+ memo.set(node, null);
1579
+ return null;
1580
+ }
1576
1581
  resolving.add(node);
1577
1582
  const answer = compute(node);
1578
1583
  resolving.delete(node);
@@ -1603,6 +1608,11 @@ hostProvided = noHostProvidedNames) => {
1603
1608
  const argument = implicitArgumentsReadTypeAt(checker, node, (owner) => upstream.implicitArgumentsTupleAt?.(owner) ?? null);
1604
1609
  if (argument)
1605
1610
  return argument;
1611
+ // A read of a field the prior round widened to `any` (and of anything
1612
+ // read off it) is typed by the checker from the field's narrow inference;
1613
+ // it carries whatever the field holds, exactly as an `any` read does.
1614
+ if (readsStatedDynamicValue(upstream.statedTypeAt, node))
1615
+ return null;
1606
1616
  const type = (node.kind === ts.SyntaxKind.ThisKeyword ? concreteThisTypeOf(node) : null) ??
1607
1617
  objectAssignTargetType(checker, node) ??
1608
1618
  checker.getTypeAtLocation(node);
@@ -2384,6 +2394,14 @@ hostProvided = noHostProvidedNames) => {
2384
2394
  record(argument);
2385
2395
  continue;
2386
2396
  }
2397
+ // A read of a field the prior round widened supplies whatever the
2398
+ // field holds, although the checker still types it from the field's
2399
+ // narrow inference.
2400
+ if (skipSilentSites && !resolved && readsStatedDynamicValue(upstream.statedTypeAt, argument)) {
2401
+ passed.push(checker.getAnyType());
2402
+ record(argument);
2403
+ continue;
2404
+ }
2387
2405
  if (skipSilentSites && !resolved && isSuppliedDynamic(argument)) {
2388
2406
  passed.push(supplied);
2389
2407
  record(argument);
@@ -98,7 +98,13 @@ export const contributeObjectAssignmentElement = (context, candidate, node) => {
98
98
  const rawMember = memberTypeOf(context.checker, rawSource, key, node) ?? context.checker.getIndexTypeOfType(rawSource, ts.IndexKind.String);
99
99
  // The extracted property's type belongs to the source, not to the target
100
100
  // slot. A real conversion between those two is audited at the store.
101
- const extractedType = context.types.typeOf(rawMember ?? ((rawSource.flags & ts.TypeFlags.Any) !== 0 ? rawSource : context.checker.getUndefinedType()));
101
+ // A member the source DECLARES but the checker types `any` -- a JavaScript
102
+ // field assigned from an unannotated parameter -- is unusable evidence to
103
+ // `memberTypeOf`, never an absent one: reading it as `undefined` made the
104
+ // store's value a dead `unreachableValue` that threw on the first run.
105
+ // It reads as the dynamic value it is, and the store converts it.
106
+ const declared = (rawSource.flags & ts.TypeFlags.Any) !== 0 || context.checker.getPropertyOfType(rawSource, key) !== undefined;
107
+ const extractedType = context.types.typeOf(rawMember ?? (declared ? context.checker.getAnyType() : context.checker.getUndefinedType()));
102
108
  const sourceResult = semanticResultId(operationId(context.identities.nodeIdOf(pattern), 'destructuring', 0), 'value');
103
109
  const getId = mintOperationId(context.ordinals, candidate.id, 'destructuring');
104
110
  const get = {
@@ -0,0 +1,11 @@
1
+ import ts from '#typescript';
2
+ /**
3
+ * Whether `node` evaluates to a value a census STATED dynamic although the
4
+ * checker types it -- a read of a field widened by `widenDynamicallyWrittenFields`,
5
+ * a cell holding one, or a member read or method result off one. The checker
6
+ * still answers such a node from the field's narrow inference, so every
7
+ * consumer that asks the checker first must ask this beside it, or it lays out
8
+ * a typed slot for the boxed value and converts it through the same checked
9
+ * unbox the widening removed from the field.
10
+ */
11
+ export declare const readsStatedDynamicValue: (statedTypeAt: (node: ts.Node) => ts.Type | null, node: ts.Node, depth?: number) => boolean;
@@ -0,0 +1,36 @@
1
+ import ts from '#typescript';
2
+ /**
3
+ * Whether `node` evaluates to a value a census STATED dynamic although the
4
+ * checker types it -- a read of a field widened by `widenDynamicallyWrittenFields`,
5
+ * a cell holding one, or a member read or method result off one. The checker
6
+ * still answers such a node from the field's narrow inference, so every
7
+ * consumer that asks the checker first must ask this beside it, or it lays out
8
+ * a typed slot for the boxed value and converts it through the same checked
9
+ * unbox the widening removed from the field.
10
+ */
11
+ export const readsStatedDynamicValue = (statedTypeAt, node, depth = 0) => {
12
+ if (depth > 16)
13
+ return false;
14
+ const stated = statedTypeAt(node);
15
+ if (stated)
16
+ return (stated.flags & ts.TypeFlags.Any) !== 0;
17
+ if (ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node))
18
+ return readsStatedDynamicValue(statedTypeAt, node.expression, depth + 1);
19
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
20
+ return readsStatedDynamicValue(statedTypeAt, node.expression, depth + 1);
21
+ if (ts.isCallExpression(node))
22
+ return ((ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression)) &&
23
+ readsStatedDynamicValue(statedTypeAt, node.expression.expression, depth + 1));
24
+ if (ts.isConditionalExpression(node))
25
+ return (readsStatedDynamicValue(statedTypeAt, node.whenTrue, depth + 1) || readsStatedDynamicValue(statedTypeAt, node.whenFalse, depth + 1));
26
+ if (ts.isBinaryExpression(node)) {
27
+ const operator = node.operatorToken.kind;
28
+ if (operator === ts.SyntaxKind.QuestionQuestionToken ||
29
+ operator === ts.SyntaxKind.BarBarToken ||
30
+ operator === ts.SyntaxKind.AmpersandAmpersandToken ||
31
+ // `+` over a dynamic operand is a string or a number, decided at run time.
32
+ operator === ts.SyntaxKind.PlusToken)
33
+ return readsStatedDynamicValue(statedTypeAt, node.left, depth + 1) || readsStatedDynamicValue(statedTypeAt, node.right, depth + 1);
34
+ }
35
+ return false;
36
+ };
@@ -263,9 +263,11 @@ const referenceIdentityOperators = new Map([
263
263
  ['!=', { kind: 'infix', text: '!=' }]
264
264
  ]);
265
265
  /**
266
- * `-`, `*`, `/`, `%` and `**` over two genuinely dynamic operands (a JS
267
- * library's `this.pages.length * this.pageSize`, both read off an untyped
268
- * `opts`), where the checker typed the result `number`.
266
+ * `-`, `*`, `/`, `%`, `**` and the bitwise and shift operators over two
267
+ * genuinely dynamic operands (a JS library's `this.pages.length *
268
+ * this.pageSize`, both read off an untyped `opts`). Each yields a Number, so
269
+ * the result is that double, converted into whatever carrier the result
270
+ * holds (a field widened to `any` holds it boxed).
269
271
  *
270
272
  * 13.15.3 ApplyStringOrNumericBinaryOperator: ToNumeric the LEFT operand, then
271
273
  * the RIGHT -- in that order, since either may run user code (ToPrimitive) --
@@ -275,25 +277,100 @@ const referenceIdentityOperators = new Map([
275
277
  * BigInt: that aborts by name instead of producing a Number the language
276
278
  * never would.
277
279
  */
278
- const dynamicArithmeticOperators = new Set(['-', '*', '/', '%', '**']);
280
+ const dynamicArithmeticOperators = new Set(['-', '*', '/', '%', '**', '&', '|', '^', '<<', '>>', '>>>']);
279
281
  const dynamicArithmeticText = (ctx, operation, first, second) => {
280
282
  if (!dynamicArithmeticOperators.has(operation.operator))
281
283
  return null;
282
284
  if (first.representation.kind !== 'dynamic' || second.representation.kind !== 'dynamic')
283
285
  return null;
284
286
  const result = operation.result.representation;
285
- if (result.kind !== 'scalar' || result.domain !== 'number')
286
- return null;
287
287
  const numberCarrier = { kind: 'scalar', domain: 'number' };
288
288
  const spelling = binaryOperatorFor(operation.operator, numberCarrier);
289
289
  if (spelling === null)
290
290
  return null;
291
291
  const applied = spelling.kind === 'infix' ? `gea_left_number ${spelling.text} gea_right_number` : `${spelling.text}(gea_left_number, gea_right_number)`;
292
- return (`([&]() -> double { const gea::Value& gea_left = ${operandText(ctx, first)}; const gea::Value& gea_right = ${operandText(ctx, second)}; ` +
292
+ const number = `([&]() -> double { const gea::Value& gea_left = ${operandText(ctx, first)}; const gea::Value& gea_right = ${operandText(ctx, second)}; ` +
293
293
  'if (gea_left.tag() == gea::Value::Tag::BigInt && gea_right.tag() == gea::Value::Tag::BigInt) ' +
294
294
  `gea::detail::refusePayloadMismatch("BigInt ${operation.operator} BigInt is a BigInt, and this cell was typed number"); ` +
295
295
  'const double gea_left_number = gea::dynamicToNumber(gea_left); const double gea_right_number = gea::dynamicToNumber(gea_right); ' +
296
- `return ${applied}; }())`);
296
+ `return ${applied}; }())`;
297
+ if (result.kind === 'scalar' && result.domain === 'number')
298
+ return number;
299
+ // A dynamic result holds the Number boxed: the box is the value itself, not
300
+ // a conversion of a carrier the program wrote.
301
+ if (result.kind === 'dynamic')
302
+ return `gea::Value::box(gea::Value::Tag::Number, ${number})`;
303
+ return alignedValueText(ctx, 'emit.ts:dynamic-arithmetic', numberCarrier, result, number);
304
+ };
305
+ /**
306
+ * The relational and equality operators over a genuinely dynamic operand:
307
+ * ECMA-262's IsLessThan (7.2.13) and IsLooselyEqual (7.2.14) as the runtime
308
+ * implements them over boxes, and IsStrictlyEqual as `Value::strictEquals`.
309
+ * A typed other side is boxed for the comparison -- the box is that value,
310
+ * so no coercion is invented -- and the census names none that would bring
311
+ * a dynamic side to it. Each yields a Boolean, held boxed when the result is
312
+ * dynamic.
313
+ */
314
+ const dynamicComparisonOperators = new Set(['<', '>', '<=', '>=', '===', '!==', '==', '!=']);
315
+ const dynamicComparisonText = (ctx, operation, first, second) => {
316
+ const firstDynamic = first.representation.kind === 'dynamic';
317
+ const secondDynamic = second.representation.kind === 'dynamic';
318
+ if (!firstDynamic && !secondDynamic)
319
+ return null;
320
+ if (!dynamicComparisonOperators.has(operation.operator))
321
+ return null;
322
+ const left = firstDynamic ? operandText(ctx, first) : boxedValueText(ctx, first, 'dynamic comparison');
323
+ const right = secondDynamic ? operandText(ctx, second) : boxedValueText(ctx, second, 'dynamic comparison');
324
+ const condition = (() => {
325
+ switch (operation.operator) {
326
+ case '<':
327
+ return `gea::dynamicIsLessThan(${left}, ${right}, true) == 1`;
328
+ case '>':
329
+ return `gea::dynamicIsLessThan(${right}, ${left}, false) == 1`;
330
+ case '<=':
331
+ return `gea::dynamicIsLessThan(${right}, ${left}, false) == 0`;
332
+ case '>=':
333
+ return `gea::dynamicIsLessThan(${left}, ${right}, true) == 0`;
334
+ case '===':
335
+ return `gea::Value::strictEquals(${left}, ${right})`;
336
+ case '!==':
337
+ return `!gea::Value::strictEquals(${left}, ${right})`;
338
+ case '==':
339
+ return `gea::dynamicLooselyEquals(${left}, ${right})`;
340
+ case '!=':
341
+ return `!gea::dynamicLooselyEquals(${left}, ${right})`;
342
+ default:
343
+ return null;
344
+ }
345
+ })();
346
+ if (condition === null)
347
+ return null;
348
+ const result = operation.result.representation;
349
+ if (result.kind === 'scalar' && result.domain === 'boolean')
350
+ return `(${condition})`;
351
+ if (result.kind === 'dynamic')
352
+ return `gea::Value::box(gea::Value::Tag::Boolean, static_cast<bool>(${condition}))`;
353
+ return alignedValueText(ctx, 'emit.ts:dynamic-comparison', { kind: 'scalar', domain: 'boolean' }, result, `(${condition})`);
354
+ };
355
+ const dynamicUnaryText = (ctx, operation, operand) => {
356
+ if (operand.representation.kind !== 'dynamic')
357
+ return null;
358
+ const number = `gea::dynamicToNumber(${operandText(ctx, operand)})`;
359
+ const applied = operation.operator === '-'
360
+ ? `(-${number})`
361
+ : operation.operator === '+'
362
+ ? number
363
+ : operation.operator === '~'
364
+ ? `gea::bitwiseNot(${number})`
365
+ : null;
366
+ if (applied === null)
367
+ return null;
368
+ const result = operation.result.representation;
369
+ if (result.kind === 'scalar' && result.domain === 'number')
370
+ return applied;
371
+ if (result.kind === 'dynamic')
372
+ return `gea::Value::box(gea::Value::Tag::Number, ${applied})`;
373
+ return alignedValueText(ctx, 'emit.ts:dynamic-unary', { kind: 'scalar', domain: 'number' }, result, applied);
297
374
  };
298
375
  const binaryOperatorFor = (operator, carrier) => {
299
376
  if (carrier.kind === 'string')
@@ -525,6 +602,13 @@ const emitCompute = (ctx, lines, operation) => {
525
602
  }
526
603
  if (operation.operator === 'ToNumeric')
527
604
  return emitToNumericCoercion(ctx, lines, first, operation.result);
605
+ // `-x`, `+x` and `~x` over a dynamic operand: ToNumber (ToPrimitive
606
+ // first) and the Number operator, as the binary operators above do.
607
+ const dynamicUnary = dynamicUnaryText(ctx, operation, first);
608
+ if (dynamicUnary !== null) {
609
+ lines.push(`${defineValue(ctx, operation.result)} = ${dynamicUnary};`);
610
+ return;
611
+ }
528
612
  const spelling = unaryOperatorFor(operation.operator, first.representation);
529
613
  if (!spelling) {
530
614
  throw createCppEmitBlockedError(`runtime-helper:computation:unary:${operation.operator}:${first.representation.kind}`, `unary "${operation.operator}" on a "${first.representation.kind}" carrier has no C++ spelling in this emitter`);
@@ -768,7 +852,11 @@ const emitCompute = (ctx, lines, operation) => {
768
852
  // flag: it is the one case left that boxes an operand this backend could
769
853
  // otherwise have kept native (the `firstDynamic !== secondDynamic` branch
770
854
  // just above, when it applies).
771
- if (ctx.deriver.dynamicFallback &&
855
+ // Two dynamic operands have no native carrier to keep, so the full
856
+ // dispatch is the only spelling there is and needs no opt-in: a field
857
+ // widened to `any` added to another (`x + x` over a dynamic `x`).
858
+ const bothDynamic = first.representation.kind === 'dynamic' && second.representation.kind === 'dynamic';
859
+ if ((ctx.deriver.dynamicFallback || bothDynamic) &&
772
860
  operation.operator === '+' &&
773
861
  (first.representation.kind === 'dynamic' ||
774
862
  second.representation.kind === 'dynamic' ||
@@ -776,7 +864,10 @@ const emitCompute = (ctx, lines, operation) => {
776
864
  second.representation.kind === 'tagged-union')) {
777
865
  const left = boxedValueText(ctx, first, 'dynamic addition');
778
866
  const right = boxedValueText(ctx, second, 'dynamic addition');
779
- const dynamic = { kind: 'dynamic', reason: 'opt-in-fallback' };
867
+ // `gea::dynamicAdd` answers a box, which IS a dynamic result's carrier.
868
+ const dynamic = operation.result.representation.kind === 'dynamic' && !ctx.deriver.dynamicFallback
869
+ ? operation.result.representation
870
+ : { kind: 'dynamic', reason: 'opt-in-fallback' };
780
871
  const text = alignedValueText(ctx, 'emit.ts:738', dynamic, operation.result.representation, `gea::dynamicAdd(${left}, ${right})`);
781
872
  if (text === null)
782
873
  throw createCppEmitBlockedError(`conversion:dynamic->${representationKey(operation.result.representation)}`, 'dynamic addition result has no checked conversion');
@@ -862,6 +953,11 @@ const emitCompute = (ctx, lines, operation) => {
862
953
  return;
863
954
  }
864
955
  }
956
+ const dynamicComparison = dynamicComparisonText(ctx, operation, first, second);
957
+ if (dynamicComparison !== null) {
958
+ lines.push(`${defineValue(ctx, operation.result)} = ${dynamicComparison};`);
959
+ return;
960
+ }
865
961
  if (representationKey(first.representation) !== representationKey(second.representation)) {
866
962
  throw createCppEmitBlockedError(`conversion:${representationKey(first.representation)}->${representationKey(second.representation)}`, `binary "${operation.operator}" mixes a "${first.representation.kind}" and a "${second.representation.kind}" carrier, ` +
867
963
  'and the census names no coercion that brings them together');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.44",
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.
@@ -19840,6 +19840,9 @@ struct LiteralReadCache {
19840
19840
  std::atomic<const ValueMetadata*> fieldOn[2]{};
19841
19841
  std::atomic<std::uint8_t> nextField{0};
19842
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};
19843
19846
  // The same fact for an Array: this key is neither `length` nor an index and the Array prototype table holds nothing under it.
19844
19847
  std::atomic<std::int8_t> arrayAbsent{-1};
19845
19848
  };
@@ -22115,8 +22118,12 @@ inline Value dynamicArrayPrototypeGet(const PropertyKey&, const Value&);
22115
22118
  inline Ref<ArrayObject<Value>> arrayPrototypeObject();
22116
22119
  inline bool dynamicArrayPrototypeHas(const PropertyKey&);
22117
22120
  inline Value dynamicStringPrototypeGet(const PropertyKey&);
22121
+ inline Value dynamicNumberPrototypeGet(const PropertyKey&);
22122
+ inline Value dynamicBooleanPrototypeGet(const PropertyKey&);
22118
22123
  inline Value dynamicFunctionPrototypeGet(const PropertyKey&);
22119
22124
  inline double dynamicToNumber(const Value&);
22125
+ inline int dynamicIsLessThan(const Value&, const Value&, bool);
22126
+ inline bool dynamicLooselyEquals(const Value&, const Value&);
22120
22127
  inline std::string dynamicToString(const Value&);
22121
22128
  namespace detail {
22122
22129
  [[noreturn]] inline void refusePayloadMismatch(const char* site);
@@ -33368,10 +33375,14 @@ inline Value Value::getProperty(const PropertyKey& key, const Value& receiver) c
33368
33375
  }
33369
33376
  }
33370
33377
  if (tag_ == Tag::Object || tag_ == Tag::Function) detail::refuseOpaquePropertyAccess("a property read", key);
33371
- // Every remaining box is a primitive, whose properties all live on a
33372
- // prototype this runtime does not model. `undefined` is what the language
33373
- // answers for a key no prototype in the chain holds, and this runtime's
33374
- // 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
+ }
33375
33386
  return Value();
33376
33387
  }
33377
33388
 
@@ -33423,11 +33434,22 @@ inline Value Value::getLiteralProperty(const PropertyKey& key, detail::LiteralRe
33423
33434
  }
33424
33435
  }
33425
33436
  if (!proxy_ && !dynamic_) {
33426
- // A literal-keyed read of a primitive: a number, boolean or bigint reads every key
33427
- // as `undefined` (`getProperty` falls through to its closing return for
33428
- // them), and a serializer may ask each value it visits for a hook method.
33429
- if ((tag_ == Tag::Number || tag_ == Tag::Boolean || tag_ == Tag::BigInt) && metadata_->fields == nullptr && metadata_->elements == nullptr)
33430
- 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();
33431
33453
  if (tag_ == Tag::String) {
33432
33454
  std::int8_t absent = cache.stringAbsent.load(relaxed);
33433
33455
  if (absent < 0) {
@@ -33442,12 +33464,6 @@ inline Value Value::getLiteralProperty(const PropertyKey& key, detail::LiteralRe
33442
33464
  cache.stringAbsent.store(absent, relaxed);
33443
33465
  }
33444
33466
  if (absent == 1) return Value();
33445
- } else if ((tag_ == Tag::Number || tag_ == Tag::Boolean) && metadata_->fields == nullptr && metadata_->elements == nullptr) {
33446
- // `getProperty`'s own tail for a bare number or boolean: no field table,
33447
- // no elements, no prototype this runtime models, so every key reads
33448
- // `undefined`. A serializer may ask each number and boolean it visits for
33449
- // a hook method, and the ten branches before that tail were the whole cost.
33450
- return Value();
33451
33467
  } else if (tag_ == Tag::Object && metadata_->fields != nullptr && metadata_->elements == nullptr) {
33452
33468
  for (const auto& entry : cache.absentOn) {
33453
33469
  if (entry.load(relaxed) != metadata_) continue;