@geastack/compiler 1.0.29 → 1.0.30

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 (48) hide show
  1. package/dist/conversion/dictionary-view.js +18 -0
  2. package/dist/conversion/dynamic-wrapper.d.ts +5 -0
  3. package/dist/conversion/dynamic-wrapper.js +4 -1
  4. package/dist/conversion/structural-plan.js +8 -1
  5. package/dist/ir/absent-class-arm.d.ts +4 -0
  6. package/dist/ir/absent-class-arm.js +50 -2
  7. package/dist/ir/call-entry.js +9 -0
  8. package/dist/ir/callable-class-flow.js +1 -1
  9. package/dist/ir/certify.js +12 -1
  10. package/dist/ir/class-allocation-domain.js +64 -17
  11. package/dist/ir/key-order-observation.js +3 -0
  12. package/dist/ir/native-array-transport.js +37 -3
  13. package/dist/ir/native-field-view-domains.d.ts +7 -0
  14. package/dist/ir/native-field-view-domains.js +29 -4
  15. package/dist/ir/native-field-view-facts.js +17 -4
  16. package/dist/ir/native-key-query.js +5 -2
  17. package/dist/ir/operation-conversions.js +6 -0
  18. package/dist/ir/program-conversions.js +8 -0
  19. package/dist/ir/reflection-demand.js +249 -36
  20. package/dist/ir/shake.js +15 -1
  21. package/dist/representation/host-templates.d.ts +1 -1
  22. package/dist/representation/host-templates.js +5 -3
  23. package/dist/semantics/normalize/any-cast-member-call.d.ts +36 -0
  24. package/dist/semantics/normalize/any-cast-member-call.js +55 -0
  25. package/dist/semantics/normalize/derived-expression-type.js +40 -0
  26. package/dist/semantics/normalize/flow/callable-reach.js +56 -23
  27. package/dist/semantics/normalize/fresh-dictionary-storage.d.ts +2 -0
  28. package/dist/semantics/normalize/fresh-dictionary-storage.js +115 -8
  29. package/dist/semantics/normalize/local-bindings.js +8 -1
  30. package/dist/semantics/normalize/producers/boundary.js +3 -22
  31. package/dist/semantics/normalize/producers/cited-value-type.d.ts +19 -0
  32. package/dist/semantics/normalize/producers/cited-value-type.js +38 -0
  33. package/dist/semantics/normalize/producers/computations.js +32 -11
  34. package/dist/semantics/normalize/producers/invocations.js +10 -0
  35. package/dist/semantics/normalize/return-bindings.js +47 -1
  36. package/dist/semantics/normalize/structural-any-binding-consumer.d.ts +34 -0
  37. package/dist/semantics/normalize/structural-any-binding-consumer.js +208 -0
  38. package/dist/semantics/normalize/structural-declarations.js +10 -1
  39. package/dist/semantics/normalize/structural.d.ts +2 -0
  40. package/dist/semantics/normalize/structural.js +42 -2
  41. package/dist/targets/cpp/conversions.js +21 -1
  42. package/dist/targets/cpp/emit-narrowing.js +22 -1
  43. package/dist/targets/cpp/emit-native-field-view.d.ts +1 -1
  44. package/dist/targets/cpp/emit-native-field-view.js +25 -7
  45. package/dist/targets/cpp/emit-union-properties.js +10 -3
  46. package/dist/targets/cpp/host/emit-host-object.js +1 -1
  47. package/package.json +1 -1
  48. package/src/targets/cpp/runtime/gea_runtime.h +37 -0
@@ -0,0 +1,208 @@
1
+ import ts from 'typescript';
2
+ import { containsUnstatedPosition } from './derived-expression-type.js';
3
+ const isReturnOwner = (node) => ts.isFunctionDeclaration(node) ||
4
+ ts.isFunctionExpression(node) ||
5
+ ts.isArrowFunction(node) ||
6
+ ts.isMethodDeclaration(node) ||
7
+ ts.isGetAccessorDeclaration(node);
8
+ const isAsyncOrGenerator = (owner) => ((ts.canHaveModifiers(owner) ? ts.getModifiers(owner) : undefined)?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) ??
9
+ false) ||
10
+ ('asteriskToken' in owner && owner.asteriskToken !== undefined);
11
+ const isFreshDictionary = (node) => ts.isCallExpression(node) &&
12
+ ts.isPropertyAccessExpression(node.expression) &&
13
+ ts.isIdentifier(node.expression.expression) &&
14
+ node.expression.expression.text === 'Object' &&
15
+ node.expression.name.text === 'create' &&
16
+ node.arguments.length === 1 &&
17
+ node.arguments[0]?.kind === ts.SyntaxKind.NullKeyword;
18
+ const isFresh = (node) => ts.isArrayLiteralExpression(node) || ts.isObjectLiteralExpression(node) || isFreshDictionary(node);
19
+ /**
20
+ * The binding whose layout a node takes, and where in it the node sits: the
21
+ * binding's name or a read of it (no steps), or a fresh literal inside its
22
+ * initializer (`[/^$/, [], Object.create(null)]` and each fresh value it
23
+ * holds). A fresh value IS part of the binding's one object, so it is built at
24
+ * the binding's layout rather than converted into it; anything else written
25
+ * there (a read of another cell) keeps its own storage and is converted as
26
+ * usual.
27
+ */
28
+ const positionOf = (checker, node) => {
29
+ if (ts.isVariableDeclaration(node))
30
+ return { declaration: node, steps: [] };
31
+ if (ts.isIdentifier(node)) {
32
+ const declaration = checker.getSymbolAtLocation(node)?.valueDeclaration;
33
+ return declaration ? { declaration, steps: [] } : null;
34
+ }
35
+ if (!isFresh(node))
36
+ return null;
37
+ const steps = [];
38
+ let current = node;
39
+ for (;;) {
40
+ const parent = current.parent;
41
+ if (ts.isVariableDeclaration(parent))
42
+ return parent.initializer === current ? { declaration: parent, steps: steps.reverse() } : null;
43
+ if (ts.isArrayLiteralExpression(parent)) {
44
+ if (ts.isSpreadElement(current))
45
+ return null;
46
+ steps.push(parent.elements.indexOf(current));
47
+ current = parent;
48
+ continue;
49
+ }
50
+ if (ts.isPropertyAssignment(parent) && parent.initializer === current && ts.isObjectLiteralExpression(parent.parent)) {
51
+ const name = parent.name;
52
+ if (!ts.isIdentifier(name) && !ts.isStringLiteral(name))
53
+ return null;
54
+ steps.push(name.text);
55
+ current = parent.parent;
56
+ continue;
57
+ }
58
+ return null;
59
+ }
60
+ };
61
+ /** A `const` binding with a stated type and an initializer, the only kind this rule lays out. */
62
+ const statedBinding = (declaration) => {
63
+ if (!ts.isVariableDeclaration(declaration) || !ts.isIdentifier(declaration.name))
64
+ return null;
65
+ if (!declaration.type || !declaration.initializer)
66
+ return null;
67
+ const list = declaration.parent;
68
+ if (!ts.isVariableDeclarationList(list) || (list.flags & ts.NodeFlags.Const) === 0)
69
+ return null;
70
+ return declaration;
71
+ };
72
+ /** The type at `steps` inside `type`: a tuple element or a property's declared type. */
73
+ const typeAtSteps = (checker, type, steps) => {
74
+ let current = type;
75
+ for (const step of steps) {
76
+ if (current === null)
77
+ return null;
78
+ if (typeof step === 'number') {
79
+ if (!checker.isTupleType(current))
80
+ return null;
81
+ current = checker.getTypeArguments(current)[step] ?? null;
82
+ }
83
+ else {
84
+ const property = current.getProperty(step);
85
+ current = property ? checker.getTypeOfSymbol(property) : null;
86
+ }
87
+ }
88
+ return current;
89
+ };
90
+ /** The function whose stated return a read is handed to whole, or `null` for any other use. */
91
+ const returnConsumerOf = (reference) => {
92
+ const statement = reference.parent;
93
+ if (!ts.isReturnStatement(statement) || statement.expression !== reference)
94
+ return null;
95
+ let owner = statement.parent;
96
+ while (owner && !ts.isFunctionLike(owner))
97
+ owner = owner.parent;
98
+ if (!owner || !isReturnOwner(owner) || isAsyncOrGenerator(owner) || !owner.type)
99
+ return null;
100
+ return owner;
101
+ };
102
+ /**
103
+ * Every specialization path the census walks `node` under: the same fork
104
+ * `census.ts`'s `visit` performs, one copy per admitted instantiation of each
105
+ * enclosing generic, outermost first.
106
+ */
107
+ const pathsOf = (inputs, node) => {
108
+ const ancestors = [];
109
+ for (let current = node; current && !ts.isSourceFile(current); current = current.parent)
110
+ ancestors.unshift(current);
111
+ let paths = [[]];
112
+ for (const ancestor of ancestors) {
113
+ const next = [];
114
+ for (const path of paths) {
115
+ const holder = path[path.length - 1];
116
+ if (holder !== undefined && holder.owner === ancestor) {
117
+ next.push(path);
118
+ continue;
119
+ }
120
+ const subject = inputs.identities.genericSubjectOf(ancestor);
121
+ const copies = inputs.specializations.specializationsOf(subject);
122
+ if (copies.length === 0) {
123
+ if (!inputs.specializations.isGeneric(subject))
124
+ next.push(path);
125
+ continue;
126
+ }
127
+ for (const copy of copies)
128
+ if (inputs.specializations.admittedUnder(subject, copy, path))
129
+ next.push([...path, { owner: subject, ordinal: copy.ordinal }]);
130
+ }
131
+ paths = next;
132
+ }
133
+ return paths;
134
+ };
135
+ export const createAnyBindingConsumerLayout = (inputs) => {
136
+ /** Every (copy, wanted type) a binding is handed to, or `null` when it does not qualify. */
137
+ const consumers = new Map();
138
+ const consumersOf = (declaration) => {
139
+ const { checker, flow } = inputs;
140
+ if (!flow || !declaration.type || !ts.isIdentifier(declaration.name))
141
+ return null;
142
+ const stated = checker.getTypeFromTypeNode(declaration.type);
143
+ if (!containsUnstatedPosition(checker, declaration, stated))
144
+ return null;
145
+ const symbol = checker.getSymbolAtLocation(declaration.name);
146
+ if (!symbol)
147
+ return null;
148
+ const references = flow.referencesToSymbol(symbol).filter((reference) => reference !== declaration.name);
149
+ if (references.length === 0)
150
+ return null;
151
+ const found = [];
152
+ for (const reference of references) {
153
+ const owner = returnConsumerOf(reference);
154
+ if (owner === null || owner.type === undefined)
155
+ return null;
156
+ const wanted = checker.getTypeFromTypeNode(owner.type);
157
+ if (!checker.isTypeAssignableTo(wanted, stated))
158
+ return null;
159
+ // A consumer that wants the very type the binding states fills no open
160
+ // position: `AsyncGenerator<string>`'s defaulted `any` is the same
161
+ // `any` on both sides. Laying such a binding out "at its consumer" only
162
+ // re-homed an object literal into the async generator's native carrier.
163
+ if (wanted === stated)
164
+ return null;
165
+ for (const path of pathsOf(inputs, owner))
166
+ found.push({ path, wanted });
167
+ }
168
+ return found.length === 0 ? null : found;
169
+ };
170
+ const settled = new Map();
171
+ const layoutOf = (declaration, steps) => {
172
+ if (!consumers.has(declaration)) {
173
+ // A cycle back into this binding while its consumers are read answers
174
+ // the stated layout, which is what the binding had before this rule.
175
+ consumers.set(declaration, null);
176
+ consumers.set(declaration, consumersOf(declaration));
177
+ }
178
+ const found = consumers.get(declaration);
179
+ if (!found)
180
+ return null;
181
+ let agreed = null;
182
+ for (const { path, wanted } of found) {
183
+ const position = typeAtSteps(inputs.checker, wanted, steps);
184
+ if (position === null)
185
+ return null;
186
+ const layout = inputs.layoutAt(path, position);
187
+ if (agreed !== null && agreed !== layout)
188
+ return null;
189
+ agreed = layout;
190
+ }
191
+ return agreed;
192
+ };
193
+ return (node) => {
194
+ const position = positionOf(inputs.checker, node);
195
+ if (position === null)
196
+ return null;
197
+ const declaration = statedBinding(position.declaration);
198
+ if (declaration === null)
199
+ return null;
200
+ const key = `${declaration.pos}:${declaration.getSourceFile().fileName}|${position.steps.join('/')}`;
201
+ if (settled.has(key))
202
+ return settled.get(key) ?? null;
203
+ settled.set(key, null);
204
+ const layout = layoutOf(declaration, position.steps);
205
+ settled.set(key, layout);
206
+ return layout;
207
+ };
208
+ };
@@ -350,7 +350,16 @@ export const physicalInitializerTypeOf = (checker, declaration, declared, parame
350
350
  // shared authority; a function/arrow literal is rarely `any`-degraded, so
351
351
  // this mostly falls straight through to the checker exactly as before,
352
352
  // but stays uniform with every other "what does this hold" question.
353
- const physical = censusedTypeAt(checker, parameters, initializer);
353
+ //
354
+ // Except that for a function LITERAL the composed census answers its
355
+ // RETURN (`structural.ts` rebuilds the callable shape from the literal's
356
+ // own signature for exactly that reason, and `signatureOf` reads the bound
357
+ // return through it). Taking that answer as the literal's type made a
358
+ // member whose arrow had a settled return -- hono's `this[method] = (...)
359
+ // => { ...; return this as any }` -- look non-callable, and the member fell
360
+ // back to its overload set's `callable-identity`.
361
+ const censused = censusedTypeAt(checker, parameters, initializer);
362
+ const physical = censused.getCallSignatures().length > 0 ? censused : checker.getTypeAtLocation(initializer);
354
363
  if (physical.getCallSignatures().length !== 1)
355
364
  return null;
356
365
  if (declaredSignatures.length >= 2)
@@ -92,6 +92,8 @@ export interface StructuralMapper {
92
92
  readonly typeAt: (node: ts.Node) => StructuralTypeId;
93
93
  /** A source-keyed closed fresh allocation channel, shared by bindings and native frames. */
94
94
  readonly indexedStorageTypeAt: (node: ts.Node) => StructuralTypeId | null;
95
+ /** A fresh value inside a stated-`any` binding laid out at its one consumer's type (`structural-any-binding-consumer.ts`). */
96
+ readonly statedAnyBindingLayoutAt: (node: ts.Node) => StructuralTypeId | null;
95
97
  readonly indexedStorageResultAt: (node: ts.Node) => StructuralTypeId | null;
96
98
  readonly mutableMethodStorageTypeAt: (node: ts.MethodDeclaration) => StructuralTypeId | null;
97
99
  readonly mutableMethodReadTypeAt: (node: ts.Node) => StructuralTypeId | null;
@@ -14,6 +14,8 @@ import { emptyRecordLinkFamilyCensus } from './record-link-families.js';
14
14
  import { bivariantSlotArrayAliasTypeOf, bivariantSlotBindingTypeOf, bivariantSlotElementTypeOf, bivariantSlotParameterTypeOf, bivariantSlotReadTypeOf } from './bivariant-slot-parameter.js';
15
15
  import { emptyDeclaredMemberCensus } from './structural-declarations.js';
16
16
  import { createLocalUnionResolver } from './structural-local-union.js';
17
+ import { createAnyBindingConsumerLayout } from './structural-any-binding-consumer.js';
18
+ import { anyCastMemberCallOf } from './any-cast-member-call.js';
17
19
  import { createMutableMethodResolver } from './structural-mutable-method.js';
18
20
  import { createMutableFieldResolver } from './structural-mutable-field.js';
19
21
  import { structuralArrayReadAt } from './structural-array-read.js';
@@ -38,7 +40,7 @@ import { emptyCollectionBindingCensus } from './collection-bindings.js';
38
40
  import { bagShapeOfType, bagShapeTypeAt, emptyObjectBagCensus } from './object-bag-bindings.js';
39
41
  import { indexedAccessMemberTypes } from './structural-indexed-access.js';
40
42
  import { joinedCallableOf } from './structural-joins.js';
41
- import { censusFreshDictionaryStorage, dictionaryArmIndexOf } from './fresh-dictionary-storage.js';
43
+ import { censusFreshDictionaryStorage, isNullPrototypeCreate, dictionaryArmIndexOf } from './fresh-dictionary-storage.js';
42
44
  import { creationOrderOf, creationOrderedProperties } from './structural-creation-order.js';
43
45
  import { collectionMemberResultTypeAt, contextualArrayConstructTypeAt, inferredArrayElementAt, statedCollectionTypeAt, inferredCollectionTypeArgumentsAt, unstatedNeverArray } from './structural-array-element.js';
44
46
  import { createDeclaredBodyResolver } from './structural-declared-body.js';
@@ -502,7 +504,7 @@ const buildMapper = (checker, identities, table, instantiations, specializations
502
504
  const fact = freshDictionaries.storageAt(node);
503
505
  if (fact === null)
504
506
  return null;
505
- if (ts.isObjectLiteralExpression(node))
507
+ if (ts.isObjectLiteralExpression(node) || (ts.isCallExpression(node) && isNullPrototypeCreate(checker, node)))
506
508
  return dictionaryStorageType(fact);
507
509
  return replaceDictionaryArms(checker.getTypeAtLocation(node), fact);
508
510
  };
@@ -2937,6 +2939,13 @@ const buildMapper = (checker, identities, table, instantiations, specializations
2937
2939
  * constructor ends up carried as one of its own instances.
2938
2940
  */
2939
2941
  const ordinaryOwnCallableInvocationAt = createStructuralOwnCallableInvocationResolver(checker, table, flow, signatureOf, ordinaryOwnCallableSourceAt);
2942
+ const anyBindingConsumerLayoutAt = createAnyBindingConsumerLayout({
2943
+ checker,
2944
+ identities,
2945
+ specializations,
2946
+ flow,
2947
+ layoutAt: (copy, type) => mapperFor(copy).typeOf(type)
2948
+ });
2940
2949
  const localUnionAt = createLocalUnionResolver(checker, table, parameters, flow, (node) => mapper.typeAt(node), (node) => (ts.isExpression(node) ? objectDescriptorReturnTypeAt(unwrapErasedExpression(node)) : null), (node) => (ts.isExpression(node) ? (ordinaryOwnCallableInvocationAt(unwrapErasedExpression(node))?.observedResult ?? null) : null));
2941
2950
  const callResultAt = createStructuralCallResultResolver(checker, table, (node) => mapper.typeAt(node), ordinaryOwnCallableInvocationAt);
2942
2951
  const constructResultAt = createStructuralConstructResultResolver(table, (node) => mapper.typeAt(node));
@@ -4424,6 +4433,17 @@ const buildMapper = (checker, identities, table, instantiations, specializations
4424
4433
  };
4425
4434
  const mutableMethods = createMutableMethodResolver(checker, table, flow, signatureOf, (node) => mapper.typeAt(node), (node) => mapper.rawTypeAt(node));
4426
4435
  const structuralRules = [
4436
+ {
4437
+ name: 'stated-any-binding-at-consumer-layout',
4438
+ forms: [
4439
+ ts.SyntaxKind.VariableDeclaration,
4440
+ ts.SyntaxKind.Identifier,
4441
+ ts.SyntaxKind.ArrayLiteralExpression,
4442
+ ts.SyntaxKind.ObjectLiteralExpression,
4443
+ ts.SyntaxKind.CallExpression
4444
+ ],
4445
+ resolve: (node) => anyBindingConsumerLayoutAt(node)
4446
+ },
4427
4447
  {
4428
4448
  name: 'mutable-field-storage',
4429
4449
  forms: [ts.SyntaxKind.PropertyAccessExpression, ts.SyntaxKind.ElementAccessExpression],
@@ -4470,6 +4490,25 @@ const buildMapper = (checker, identities, table, instantiations, specializations
4470
4490
  : table.intern({ kind: 'union', members: [typeOf(standIn), ...recordIds] });
4471
4491
  }
4472
4492
  },
4493
+ {
4494
+ // `(this as any).buildAllMatchers()` into a stated slot: see `any-cast-member-call.ts`.
4495
+ name: 'any-cast-member-call',
4496
+ forms: [ts.SyntaxKind.PropertyAccessExpression, ts.SyntaxKind.CallExpression],
4497
+ resolve: (node) => {
4498
+ const found = anyCastMemberCallOf(checker, node);
4499
+ if (found === null)
4500
+ return null;
4501
+ const result = typeOf(found.stated);
4502
+ if (ts.isCallExpression(node))
4503
+ return result;
4504
+ const callable = table.intern({
4505
+ kind: 'signature',
4506
+ call: [{ parameters: [], minimumArity: 0, thisParameter: mapper.typeAt(found.receiver), result }],
4507
+ construct: []
4508
+ });
4509
+ return table.intern({ kind: 'union', members: [callable, typeOf(checker.getUndefinedType())] });
4510
+ }
4511
+ },
4473
4512
  {
4474
4513
  // `buf.equals && buf.equals(x)`: see `isHostMethodPresenceTest`.
4475
4514
  name: 'host-method-presence-test',
@@ -5662,6 +5701,7 @@ const buildMapper = (checker, identities, table, instantiations, specializations
5662
5701
  typeAt,
5663
5702
  indexedStorageTypeAt,
5664
5703
  indexedStorageResultAt,
5704
+ statedAnyBindingLayoutAt: anyBindingConsumerLayoutAt,
5665
5705
  mutableMethodStorageTypeAt: mutableMethods.storageTypeAt,
5666
5706
  mutableMethodReadTypeAt: mutableMethods.readTypeAt,
5667
5707
  mutableFieldStorageTypeOf: mutableFields.storageTypeOf,
@@ -2700,6 +2700,13 @@ const cppConversionTables = (layouts, nativeNarrowing, nativeWrappedPayload) =>
2700
2700
  if (proxyArmWithoutHome(source, target))
2701
2701
  return null;
2702
2702
  const recipe = conversionRecipeOf(source, target);
2703
+ // An element the chain converts inline (`convertedValueText`) is
2704
+ // spelled by the chain's own recipe for that pair: a `narrowed-load`
2705
+ // out of a sum is the native arm read (`.get<N>()`) whose contract
2706
+ // `nativeNarrowing` states, anything else the wrapped-payload claim.
2707
+ const elementPairUnused = (from, to) => conversionRecipeOf(from, to)?.id === 'narrowed-load' && (from.kind === 'optional' || from.kind === 'tagged-union')
2708
+ ? nativeNarrowing(from, to).nativeFieldProtocol === 'unused'
2709
+ : heldPairUnusedOf(nativeWrappedPayload)(from, to);
2703
2710
  if (recipe !== null && recipe.renders) {
2704
2711
  // `unreachable-value` spells either `unreachableValue<T>()` (a throw that
2705
2712
  // reads nothing) or a discard into `undefined`: no field is read and no
@@ -2723,7 +2730,20 @@ const cppConversionTables = (layouts, nativeNarrowing, nativeWrappedPayload) =>
2723
2730
  // the same shape around the payload's own conversion.
2724
2731
  recipe.id === 'optional-payload-convert' && source.kind === 'optional' && target.kind === 'optional'
2725
2732
  ? nativeWrappedPayload(source.payload, target.payload)
2726
- : {};
2733
+ : // `array-to-tuple` reads each position by index
2734
+ // (`readElement`) and `array-copy-recast` copies by
2735
+ // `appendRangeConverted`; neither touches a field
2736
+ // table, so each reads one exactly when its element
2737
+ // conversions do.
2738
+ recipe.id === 'array-to-tuple' && source.kind === 'array-object' && target.kind === 'record'
2739
+ ? target.fields.every((field) => elementPairUnused(source.element, field.value))
2740
+ ? { nativeFieldProtocol: 'unused' }
2741
+ : {}
2742
+ : recipe.id === 'array-copy-recast' && source.kind === 'array-object' && target.kind === 'array-object'
2743
+ ? elementPairUnused(source.element, target.element)
2744
+ ? { nativeFieldProtocol: 'unused' }
2745
+ : {}
2746
+ : {};
2727
2747
  return {
2728
2748
  id: `chain:${recipe.id}`,
2729
2749
  domain: `static:${recipe.id}`,
@@ -3771,6 +3771,16 @@ const unboxedLoadTextAt = (target, text, receiverFactory, freshObject = false) =
3771
3771
  const refused = `([]() -> ${targetType} { gea::detail::refusePayloadMismatch("a dynamic value admitted by no union arm"); }())`;
3772
3772
  const typed = target.arms.map((_, index) => index).filter((index) => index !== catchAll);
3773
3773
  let result = catchAll >= 0 ? armText(catchAll) : refused;
3774
+ // A string-keyed dictionary arm also admits an ordinary dynamic object by
3775
+ // its values (`dynamicDictionaryEntriesAccept`), after every exact test --
3776
+ // the same rebuild `unboxDynamicDictionary` performs for a lone dictionary.
3777
+ if (catchAll < 0)
3778
+ for (let position = typed.length - 1; position >= 0; position--) {
3779
+ const arm = target.arms[typed[position]].value;
3780
+ if (arm.kind !== 'dictionary' || arm.key !== 'string' || arm.value.kind === 'dynamic')
3781
+ continue;
3782
+ result = `(gea::detail::dynamicDictionaryEntriesAccept<${cppTypeOf(arm.value)}>(${text}) ? ${armText(typed[position])} : ${result})`;
3783
+ }
3774
3784
  for (let position = typed.length - 1; position >= 0; position--) {
3775
3785
  const index = typed[position];
3776
3786
  result =
@@ -5008,7 +5018,8 @@ const dynamicWrapperText = (ctx, plan, node, text) => {
5008
5018
  // arm admits is the TypeError a program may catch, never an abort.
5009
5019
  const shaped = plan.arms.filter((entry) => entry.byShape);
5010
5020
  const elementwise = plan.arms.filter((entry) => entry.byElements);
5011
- let result = shaped.length === 0 && elementwise.length === 0
5021
+ const entrywise = plan.arms.filter((entry) => entry.byEntries);
5022
+ let result = shaped.length === 0 && elementwise.length === 0 && entrywise.length === 0
5012
5023
  ? `([]() -> ${targetType} { gea::detail::refusePayloadMismatch("a dynamic value admitted by no union arm"); }())`
5013
5024
  : `([]() -> ${targetType} { gea::host::throwRuntimeError("TypeError", ${cppStringLiteral("a dynamic value is none of the union's object arms")}); }())`;
5014
5025
  for (let index = shaped.length - 1; index >= 0; index--) {
@@ -5044,6 +5055,16 @@ const dynamicWrapperText = (ctx, plan, node, text) => {
5044
5055
  `(gea::detail::nativeArrayViewElementsAccept<${cppTypeOf(element)}, ${nativeFieldPolicyType(element)}>(${text}) ? ` +
5045
5056
  `${targetType}::ofArm<${entry.index}>(${payload}) : ${result})`;
5046
5057
  }
5058
+ for (let index = entrywise.length - 1; index >= 0; index--) {
5059
+ const entry = entrywise[index];
5060
+ const value = plan.target.arms[entry.index].value;
5061
+ if (value.kind !== 'dictionary')
5062
+ return null;
5063
+ const payload = recipeText(ctx, entry.conversion, text);
5064
+ if (payload === null)
5065
+ return null;
5066
+ result = `(gea::detail::dynamicDictionaryEntriesAccept<${cppTypeOf(value.value)}>(${text}) ? ${targetType}::ofArm<${entry.index}>(${payload}) : ${result})`;
5067
+ }
5047
5068
  for (let index = plan.arms.length - 1; index >= 0; index--) {
5048
5069
  const arm = branch(plan.arms[index]);
5049
5070
  if (arm === null)
@@ -3,7 +3,7 @@ import type { NativeFieldViewRead } from '../../ir/native-field-view-facts.js';
3
3
  import { type Representation } from '../../representation/model.js';
4
4
  import { type EmitContext } from './emit-context.js';
5
5
  /** Carrier wrappers select a native allocation; the route itself is never inferred from its copied fields. */
6
- export declare const withFieldReceiver: (value: Representation, text: string, emit: (carrier: Representation) => string, dynamic?: (carrier: Representation, text: string) => string) => string;
6
+ export declare const withFieldReceiver: (value: Representation, text: string, emit: (carrier: Representation) => string, dynamic?: (carrier: Representation, text: string) => string, nativeData?: (carrier: Representation, text: string) => string) => string;
7
7
  /** Bind deferred operands once before either the live route or an ordinary allocation is observed. */
8
8
  export declare const nativeFieldViewOperandContext: (ctx: EmitContext, operation: GetOperation | SetOperation) => EmitContext;
9
9
  export declare const nativeFieldViewReadForText: (ctx: EmitContext, receiver: IrOperand, target: Representation, receipt: NativeFieldViewRead, ordinaryReadOf: (carrier: Representation, key: string) => {
@@ -5,6 +5,8 @@ import { nativeFieldPolicyType, staticKeyOrderText } from './records.js';
5
5
  import { tracksKeyOrder } from './key-order-tracking.js';
6
6
  import { cppTypeOf, cppStringLiteral, cppRecordFieldKeyIsSymbol, fieldPropertyKeyText } from './types.js';
7
7
  import { propertyKeyText } from './emit-dynamic-properties.js';
8
+ import { nativeDataPropertyText } from './emit-buffers.js';
9
+ import { nativeDataPropertyOf } from '../../representation/native-data-properties.js';
8
10
  const tokenOf = (type) => `gea::detail::payloadTypeTagFor<${type}>()`;
9
11
  const routeTokenOf = (value) => `gea_type == ${tokenOf(cppTypeOf(value))} && gea_policy == ${tokenOf(nativeFieldPolicyType(value))}`;
10
12
  /** A static symbol member reaches the IR as its `sym(decl|...)` key text, never as a string property. */
@@ -17,20 +19,23 @@ const renderedLeaf = (ctx, id, text) => {
17
19
  return rendered;
18
20
  };
19
21
  /** Carrier wrappers select a native allocation; the route itself is never inferred from its copied fields. */
20
- export const withFieldReceiver = (value, text, emit, dynamic) => {
22
+ export const withFieldReceiver = (value, text, emit, dynamic, nativeData) => {
21
23
  if (value.kind === 'borrowed-ref')
22
- return withFieldReceiver(value.referent, text, emit, dynamic);
24
+ return withFieldReceiver(value.referent, text, emit, dynamic, nativeData);
23
25
  if (value.kind === 'optional')
24
26
  return (`if (!${text}.has_value()) gea::host::throwRuntimeError("TypeError", "Cannot access a nullish native view"); ` +
25
- withFieldReceiver(value.payload, `(*${text})`, emit, dynamic));
27
+ withFieldReceiver(value.payload, `(*${text})`, emit, dynamic, nativeData));
26
28
  // A `dynamic` arm is a `gea::Value` already; its own [[Get]] is the read.
27
29
  if (value.kind === 'dynamic' && dynamic !== undefined)
28
30
  return dynamic(value, text);
31
+ // A binary-view arm reads its own internal slot (`nativeData` routes).
32
+ if ((value.kind === 'typed-array' || value.kind === 'data-view' || value.kind === 'array-buffer') && nativeData !== undefined)
33
+ return nativeData(value, text);
29
34
  if (value.kind === 'tagged-union')
30
35
  return (value.arms
31
36
  // `text` is a generic lambda's `const auto&` parameter, so its member
32
37
  // templates are dependent names.
33
- .map((arm, index) => `if (${text}.template is<${index}>()) { ${withFieldReceiver(arm.value, `${text}.template get<${index}>()`, emit, dynamic)} }`)
38
+ .map((arm, index) => `if (${text}.template is<${index}>()) { ${withFieldReceiver(arm.value, `${text}.template get<${index}>()`, emit, dynamic, nativeData)} }`)
34
39
  .join(' ') + ' gea::host::throwRuntimeError("TypeError", "No native field-view receiver arm");');
35
40
  if ((value.kind === 'record' || value.kind === 'record-with-index' || value.kind === 'class-ref' || value.kind === 'native-record-ref') &&
36
41
  value.ownership === 'shared-refcount')
@@ -73,15 +78,28 @@ export const nativeFieldViewReadForText = (ctx, receiver, target, receipt, ordin
73
78
  ? 'gea::host::throwRuntimeError("TypeError", "Cannot access a non-object native view receiver");'
74
79
  : `return ${renderedLeaf(ctx, route.conversion, `${text}.getProperty(${viewKeyText(key)})`)};`;
75
80
  };
81
+ const nativeDataRead = (key) => (carrier, text) => {
82
+ const property = nativeDataPropertyOf(carrier, key);
83
+ const route = property && receipt.sources.find((entry) => representationKey(entry.source) === representationKey(property.result));
84
+ const read = property && route ? nativeDataPropertyText(text, carrier, property) : null;
85
+ return read === null || !route
86
+ ? 'gea::host::throwRuntimeError("TypeError", "a binary view arm has no certified native data route");'
87
+ : `return ${renderedLeaf(ctx, route.conversion, read)};`;
88
+ };
76
89
  const forKey = (key) => withFieldReceiver(receiver.representation, 'gea_field_input', (carrier) => {
77
90
  const actual = ordinaryReadOf(carrier, key);
78
91
  const ordinary = actual && receipt.sources.find((entry) => representationKey(entry.source) === representationKey(actual.source));
79
92
  // A getter is the plain allocation's whole answer: there is no own
80
93
  // field for the native route to find, and a live view still answers
81
94
  // first through `readLiveField`.
82
- const getterAnswer = ordinary && actual?.accessor === true ? `return ${renderedLeaf(ctx, ordinary.conversion, actual.text)};` : null;
95
+ // `gea_field_receiver` is a generic lambda's parameter, so its member
96
+ // is a dependent expression, and a recipe spelling a union's
97
+ // `.is<N>()` on it does not parse. Read through the source's own
98
+ // carrier type and the recipe sees a concrete value.
99
+ const concrete = actual ? `static_cast<const ${cppTypeOf(actual.source)}&>(${actual.text})` : '';
100
+ const getterAnswer = ordinary && actual?.accessor === true ? `return ${renderedLeaf(ctx, ordinary.conversion, concrete)};` : null;
83
101
  const plain = ordinary && actual && actual.source.kind === 'optional'
84
- ? `return ${renderedLeaf(ctx, ordinary.conversion, actual.text)};`
102
+ ? `return ${renderedLeaf(ctx, ordinary.conversion, concrete)};`
85
103
  : 'gea::host::throwRuntimeError("TypeError", "a native view receiver has no admitted plain allocation");';
86
104
  const property = `${viewKeyText(key)}`;
87
105
  const native = `std::optional<${result}> gea_plain_answer; auto gea_plain_adapter = ${adapter}; ` +
@@ -103,7 +121,7 @@ export const nativeFieldViewReadForText = (ctx, receiver, target, receipt, ordin
103
121
  'gea::host::throwRuntimeError("TypeError", "a native allocation read has no certified carrier route"); ';
104
122
  return (`return gea::record::readLiveField<${result}>(gea_field_receiver, ${property}, ` +
105
123
  `${adapter}, ${accepted}, [&]() -> ${result} { ${getterAnswer ?? `${native}${plain}`} });`);
106
- }, dynamicRead(key));
124
+ }, dynamicRead(key), nativeDataRead(key));
107
125
  // The receiver is the statement-lambda's ARGUMENT, not a local bound inside
108
126
  // it: a withheld receiver can be `(*presentOrThrow(<element read>))`, a
109
127
  // reference into a temporary `Optional`. A local `const auto&` outlives that
@@ -98,12 +98,19 @@ const nativePrototypeAnswers = nativeInheritedMemberOf;
98
98
  * read. Missing class members likewise proceed to the runtime-property path
99
99
  * instead of acquiring meaning from an unrelated physical slot.
100
100
  */
101
- const armFieldSite = (ctx, arm, armExprText, key) => {
101
+ const armFieldSite = (ctx, arm, armExprText, key, write = false) => {
102
102
  if (!addressableArmKind(arm.kind))
103
103
  return null;
104
104
  if (arm.kind === 'class-ref') {
105
105
  const member = classMemberOf(ctx.classes, arm.declaration, key);
106
- if (member?.kind !== 'field' && (member !== null || !nativeBaseFieldOf(ctx.deriver, arm, key, ctx.classes)))
106
+ // A method some write shadows with an own property (hono's routers'
107
+ // `this.match = match`) has a physical override slot, and a STORE lands in
108
+ // it: that slot is the field `declaredRecordFieldOf` answers, the one the
109
+ // IR certified the store's conversion against, and a lone class receiver
110
+ // writes it the same way. A read is not a slot read -- the slot is absent
111
+ // until that store runs, and the prototype method answers until then.
112
+ const overridden = write && member?.kind === 'method' && classMethodOverrideOf(ctx.classes, arm.declaration, key) !== null;
113
+ if (member?.kind !== 'field' && !overridden && (member !== null || !nativeBaseFieldOf(ctx.deriver, arm, key, ctx.classes)))
107
114
  return null;
108
115
  }
109
116
  const declared = declaredFieldRepresentationOf(ctx.deriver, arm, key, ctx.classes);
@@ -1139,7 +1146,7 @@ const unionLeafSetText = (ctx, operation, leaf, key, rawValueText) => {
1139
1146
  if (leaf.representation.kind === 'null' || leaf.representation.kind === 'undefined') {
1140
1147
  return `gea::host::throwGetPropertyOfNullish<void>("${leaf.representation.kind}", "set");`;
1141
1148
  }
1142
- const site = armFieldSite(ctx, leaf.representation, leaf.text, key);
1149
+ const site = armFieldSite(ctx, leaf.representation, leaf.text, key, true);
1143
1150
  if (site !== null) {
1144
1151
  const converted = alignedValueText(ctx, 'emit-union-properties.ts:820', operation.value.representation, site.representation, rawValueText);
1145
1152
  if (converted === null) {
@@ -3025,7 +3025,7 @@ export const objectMemberText = (ctx, member, operation) => {
3025
3025
  return assignText(ctx, operation);
3026
3026
  if (member === 'fromEntries')
3027
3027
  return fromEntriesText(ctx, operation);
3028
- if (member === 'create')
3028
+ if (hostMemberTemplateOf('ObjectConstructor', member) === 'object-create')
3029
3029
  return createText(operation);
3030
3030
  if (member === 'defineProperty')
3031
3031
  return definePropertyText(ctx, operation);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.29",
3
+ "version": "1.0.30",
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": {
@@ -24286,6 +24286,43 @@ gea::Ref<Dictionary<V>> unboxDynamicDictionary(const Value& value, const char* s
24286
24286
  }
24287
24287
  }
24288
24288
 
24289
+ /**
24290
+ * Dictionary arms of one union, read out of a dynamic value. A native table of
24291
+ * an arm's own carrier is that arm (its exact payload test). An ordinary
24292
+ * dynamic object or an open Document -- what `unboxDynamicDictionary` rebuilds
24293
+ * -- is told apart by its values instead: the arm whose value carrier admits
24294
+ * every enumerable own string-keyed data value, tried after every exact test,
24295
+ * in arm order, so an empty object is the first such arm. Hono's static routes
24296
+ * store `Object.create(null)` in an `any` tuple slot that is later read as
24297
+ * `ParamIndexMap | Params`.
24298
+ */
24299
+ template <typename V>
24300
+ bool dynamicDictionaryEntriesAccept(const Value& value) {
24301
+ if constexpr (std::is_same_v<V, Value> || !requires { DynamicCarrier<V>::accepts(std::declval<const Value&>()); }) {
24302
+ return false;
24303
+ } else {
24304
+ if (value.tag() != Value::Tag::Object) return false;
24305
+ if (value.payloadType() == payloadTypeTagFor<gea::Ref<Dictionary<Value>>>()) {
24306
+ const auto& source = value.as<gea::Ref<Dictionary<Value>>>();
24307
+ if (!source) return false;
24308
+ bool accepted = true;
24309
+ auto scratch = gea::makeRef<Dictionary<bool>>();
24310
+ source->copyInto(*scratch, [&](const Value& entry) {
24311
+ accepted = accepted && DynamicCarrier<V>::accepts(entry);
24312
+ return true;
24313
+ });
24314
+ return accepted;
24315
+ }
24316
+ const gea::Ref<DynamicObject> table = value.asDynamicObject();
24317
+ if (!table) return false;
24318
+ for (const auto& property : table->properties()) {
24319
+ if (property.key.isSymbol() || !property.descriptor.enumerable) continue;
24320
+ if (property.descriptor.isAccessor() || !DynamicCarrier<V>::accepts(property.descriptor.dataValue())) return false;
24321
+ }
24322
+ return true;
24323
+ }
24324
+ }
24325
+
24289
24326
  /**
24290
24327
  * A `Map<K, U>` read as `Map<unknown, unknown>`: the same map, every key and
24291
24328
  * value boxed as it leaves and checked as it enters.