@geastack/compiler 1.0.43 → 1.0.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -246,6 +246,16 @@ const valuesOfView = (ctx, operation, view) => {
246
246
  throw createCppEmitBlockedError('host-member-call:Object.values', `"Object.values" of a known shape mints an array, and this call's result carries ` +
247
247
  `"${result === undefined ? 'nothing' : representationKey(result)}"`);
248
248
  }
249
+ if (!classOwnKeysAreStatic(ctx, view.representation)) {
250
+ const walked = creationOrderedOwnCopyText(ctx, view, 'values', (_key, value, walkCtx) => {
251
+ const converted = alignedValueText(walkCtx, 'host/emit-host-object.ts:values-of-class-instance', dynamicCarrier, result.element, value);
252
+ return converted === null ? null : `__gea_values.push_back(${converted});`;
253
+ }, null, true);
254
+ if (walked === null)
255
+ return refuseClassInstanceWalk('values', view.representation);
256
+ return (`([&]() { ${classWalkProtocolAssertion(view)} std::vector<${cppTypeOf(result.element)}> __gea_values; ${walked}; ` +
257
+ `return gea::detail::hostArrayResult(std::move(__gea_values)); })()`);
258
+ }
249
259
  const element = representationKey(result.element);
250
260
  const ordered = ownKeyFields(view);
251
261
  // A field whose carrier differs from the element (`{ on: true, none: 'none' }`
@@ -448,6 +458,16 @@ const entriesOfView = (ctx, operation, view) => {
448
458
  return (`gea::host::ObjectConstructor::entriesOf<${cppTypeOf(entry.element)}>(${view.receiver}, ` +
449
459
  `[](std::string __gea_key, ${cppTypeOf(view.value)} __gea_value) { ${entryText(entry, '__gea_key', value)} })`);
450
460
  }
461
+ if (!classOwnKeysAreStatic(ctx, view.representation)) {
462
+ const walked = creationOrderedOwnCopyText(ctx, view, 'entries', (key, value, walkCtx) => {
463
+ const converted = alignedValueText(walkCtx, 'host/emit-host-object.ts:entries-of-class-instance', dynamicCarrier, entry.value, value);
464
+ return converted === null ? null : `__gea_entries.push_back([&]() { ${entryText(entry, key, converted)} }());`;
465
+ }, null, true);
466
+ if (walked === null)
467
+ return refuseClassInstanceWalk('entries', view.representation);
468
+ return (`([&]() { ${classWalkProtocolAssertion(view)} std::vector<${cppTypeOf(entry.element)}> __gea_entries; ${walked}; ` +
469
+ `return gea::detail::hostArrayResult(std::move(__gea_entries)); })()`);
470
+ }
451
471
  const ordered = ownKeyFields(view);
452
472
  const entryOf = (field) => {
453
473
  const read = getOwnValue(ctx, view, field);
@@ -476,7 +496,54 @@ const entriesOfView = (ctx, operation, view) => {
476
496
  return (`([&]() { std::vector<${cppTypeOf(entry.element)}> __gea_entries; ${walked} ` +
477
497
  `return gea::detail::hostArrayResult(std::move(__gea_entries)); })()`);
478
498
  };
479
- const creationOrderedOwnCopyText = (ctx, view, destination, each, assigned = null) => {
499
+ /**
500
+ * Whether a class instance's own keys are exactly the field list its carrier's
501
+ * shape names, in that order, so the static arms of `values` and `entries`
502
+ * may list them.
503
+ *
504
+ * A `class-ref` names the class its handle is DECLARED at, and the object
505
+ * behind it can be any subclass: a `Material`-typed handle holding a
506
+ * `DashedMaterial` owns `dashSize`, which no struct the handle can name has.
507
+ * Its carrier's shape need not even be the class's own -- the struct is
508
+ * rendered from the class's instance shape, a use site's handle may carry a
509
+ * wider one (`model.ts`'s `class-ref`), and listing that shape's fields
510
+ * read members the struct does not have. And with a base class, the base's
511
+ * fields are created first while the shape lists the derived class's own
512
+ * first. Each of those is a run-time or chain-order fact the struct's own
513
+ * field dispatcher already answers (`nativeEnumerableStringKeys`), which is
514
+ * how `keys` enumerates every shared object, so only a class with no base,
515
+ * no subclass and its own instance shape keeps the static list.
516
+ */
517
+ const classOwnKeysAreStatic = (ctx, representation) => {
518
+ if (representation.kind !== 'class-ref')
519
+ return true;
520
+ if (representation.ancestors.length > 0 || representation.nativeBase !== undefined)
521
+ return false;
522
+ const layout = ctx.classes.get(representation.declaration);
523
+ const instance = layout?.instance;
524
+ if (layout === undefined || layout.base !== null || instance === null || instance === undefined)
525
+ return false;
526
+ if (!('shapeId' in instance) || instance.shapeId !== representation.shapeId)
527
+ return false;
528
+ for (const other of ctx.classes.values())
529
+ if (other.base === representation.declaration)
530
+ return false;
531
+ return true;
532
+ };
533
+ /**
534
+ * The runtime walk is the only arm a class instance gets, and without the
535
+ * struct's property protocol it answers false and copies nothing -- an empty
536
+ * array where the instance has keys. Stated to the C++ compiler, so that case
537
+ * cannot build at all.
538
+ */
539
+ const classWalkProtocolAssertion = (view) => `static_assert(gea::detail::NativeFieldTable<typename std::remove_cvref_t<decltype(${view.receiver})>::element_type>, ` +
540
+ '"the own properties of a class instance are walked through its property protocol");';
541
+ const refuseClassInstanceWalk = (member, representation) => {
542
+ throw createCppEmitBlockedError(`host-member-call:Object.${member}`, `"Object.${member}" of a "${representationKey(representation)}" handle enumerates whatever class the instance really is, ` +
543
+ "which only the runtime's creation-order walk can see, and no conversion from its dynamic values into this call's " +
544
+ 'result was admitted for that walk');
545
+ };
546
+ const creationOrderedOwnCopyText = (ctx, view, destination, each, assigned = null, always = false) => {
480
547
  const indexed = indexedRecordViewOf(ctx.deriver, view.representation);
481
548
  const ownership = indexed !== null ? indexed.ownership : ownershipOfGeneratedCarrier(view.representation);
482
549
  if (ownership !== 'shared-refcount')
@@ -506,7 +573,7 @@ const creationOrderedOwnCopyText = (ctx, view, destination, each, assigned = nul
506
573
  return (`gea::${assigned.orderless === true ? 'assignOwnPropertiesUnorderedWith' : 'assignOwnPropertiesInCreationOrderWith'}(${view.receiver}, ${assigned.target}, ` +
507
574
  `[&](const std::string& __gea_ordered_key, const gea::Value& __gea_ordered_value) { ${body} }, ${assigned.staticCopy})`);
508
575
  return (`gea::copyOwnPropertiesInCreationOrder(${view.receiver}, ` +
509
- `[&](const std::string& __gea_ordered_key, const gea::Value& __gea_ordered_value) { ${body} }${indexed !== null ? ', true' : ''})`);
576
+ `[&](const std::string& __gea_ordered_key, const gea::Value& __gea_ordered_value) { ${body} }${indexed !== null || always ? ', true' : ''})`);
510
577
  };
511
578
  /**
512
579
  * A property key argument, as `gea::PropertyKey`.
@@ -256,6 +256,7 @@ export declare const enumerationOrdered: <T>(entries: readonly T[], keyOf: (entr
256
256
  * this file did not name is left exactly as written.
257
257
  */
258
258
  export declare const withUnreadParametersUnnamed: (declaration: string, body: readonly string[]) => string;
259
+ export declare const switchedByKeyLength: (body: readonly string[]) => readonly string[];
259
260
  /**
260
261
  * The C++ storage one field of this struct occupies.
261
262
  *
@@ -1444,7 +1444,7 @@ const keyByteLengthOfBranch = (line) => {
1444
1444
  * it skips.
1445
1445
  */
1446
1446
  const switchedKeyBranches = 6;
1447
- const switchedByKeyLength = (body) => {
1447
+ export const switchedByKeyLength = (body) => {
1448
1448
  const out = [];
1449
1449
  let run = [];
1450
1450
  const flush = () => {
@@ -15,7 +15,7 @@ import { nativePromiseBaseInitializeStatements } from './native-promise-base.js'
15
15
  import { classFieldStorageOwnerOf, classMemberOf, classMethodOverrideOf } from '../../projection/fields.js';
16
16
  import { balanceCppUnits, chunkCppItems, cppChunkFileName, cppUnitByteBudget } from './balanced-units.js';
17
17
  import { readonlyBorrowFormalsOf } from '../../ir/borrowed-call-arguments.js';
18
- import { stableBorrowEntryOf } from './borrowed-call-entry.js';
18
+ import { borrowForwardedArgumentsOf, stableBorrowEntryOf, withoutDyingArguments } from './borrowed-call-entry.js';
19
19
  import { programFactsOf } from '../../ir/program-facts.js';
20
20
  import { integrityRestrictionsOf } from '../../ir/integrity-restrictions.js';
21
21
  import { keyOrderObservationOf, nothingProvenUnobserved } from '../../ir/key-order-observation.js';
@@ -752,7 +752,7 @@ const signatureOf = (body, captures, narrowed = new Set(), narrowedResult = fals
752
752
  const formals = bodyFormalsOf(cppEnvironmentStructOf(captures, body.sourceOwner), effectiveAbi, admission, narrowed, borrowsReceiver(body), borrowed, isCoroutineBody(body));
753
753
  return `${result} ${name}(${formals.join(', ')})`;
754
754
  };
755
- const thunkOf = (body, captures, narrowed, narrowedResult, linkage, taskResult = false) => {
755
+ const thunkOf = (body, captures, narrowed, narrowedResult, linkage, taskResult = false, stableEntry = undefined) => {
756
756
  if (!body.abi)
757
757
  return null;
758
758
  const abi = body.abi;
@@ -783,7 +783,12 @@ const thunkOf = (body, captures, narrowed, narrowedResult, linkage, taskResult =
783
783
  : admission.kind === 'ok' && admission.layout.receiver !== null
784
784
  ? [`${cppEnvironmentLocalName}->${cppCaptureReceiverFieldName}`]
785
785
  : [];
786
- const call = `${cppBodyName(body.sourceOwner)}(${[
786
+ // The thunk's by-value formals are slots of its own frame that nothing else
787
+ // can name, so they are stable actuals for the borrowed entry: entering it
788
+ // directly binds them in place, where the owning entry moved each one into a
789
+ // formal of its own and released the emptied shell on the way out.
790
+ const borrowedEntry = stableEntry !== undefined && !hasEnvironment && !isCoroutineBody(body) ? stableEntry : undefined;
791
+ const call = `${borrowedEntry?.name ?? cppBodyName(body.sourceOwner)}(${[
787
792
  ...(hasEnvironment ? [isCoroutineBody(body) ? `*${cppEnvironmentLocalName}` : cppEnvironmentLocalName] : []),
788
793
  ...receiverActual,
789
794
  // The thunk's own formals stay the ABI's, so the carrier's function-pointer
@@ -791,7 +796,9 @@ const thunkOf = (body, captures, narrowed, narrowedResult, linkage, taskResult =
791
796
  // boundary where the two spellings meet.
792
797
  ...abi.parameters.map((parameter, ordinal) => narrowed.has(ordinal)
793
798
  ? `static_cast<${cppNarrowedIntegerType}>(${cppFormalName(ordinal)})`
794
- : `std::forward<${cppAbiParameterType(parameter)}>(${cppFormalName(ordinal)})`)
799
+ : borrowedEntry?.formals.has(ordinal)
800
+ ? cppFormalName(ordinal)
801
+ : `std::forward<${cppAbiParameterType(parameter)}>(${cppFormalName(ordinal)})`)
795
802
  ].join(', ')})`;
796
803
  // The thunk's own result stays the ABI's, so the carrier's function-pointer
797
804
  // type is unchanged; a narrowed body result converts back here.
@@ -1938,22 +1945,45 @@ const renderTranslationUnitSession = (input) => {
1938
1945
  const physicalCounts = new Map();
1939
1946
  for (const body of input.bodies)
1940
1947
  physicalCounts.set(String(body.sourceOwner), (physicalCounts.get(String(body.sourceOwner)) ?? 0) + 1);
1948
+ const stableEntryOf = (body, dying) => isRegionId(body.sourceOwner) || constructorBodies.has(String(body.sourceOwner))
1949
+ ? null
1950
+ : stableBorrowEntryOf(body, body.sourceOwner, (declaration) => {
1951
+ const placement = input.placements.get(declaration);
1952
+ return placement?.storage.kind === 'local' && placement.storage.owner === body.sourceOwner && !captures.isBoxed(declaration)
1953
+ ? placement.representation
1954
+ : null;
1955
+ }, formalsBorrowedIn(body.sourceOwner), dying, {
1956
+ captureFree: captures.of(body.sourceOwner).kind === 'none',
1957
+ synchronous: !isCoroutineBody(body),
1958
+ singleBody: physicalCounts.get(String(body.sourceOwner)) === 1,
1959
+ narrowedNumericAbi: formalsNarrowedIn(body.sourceOwner).size > 0 || resultNarrowedIn(body.sourceOwner)
1960
+ });
1961
+ // A formal handed on as the last use of its cell is "dying", and a dying
1962
+ // read keeps its formal owning so the read can move. Into a position the
1963
+ // callee's own borrowed entry takes by reference, nothing moves: the entry
1964
+ // binds the slot in place. So such reads stop counting as dying, which can
1965
+ // admit the caller's formal to its own entry, which can in turn release the
1966
+ // read that forwards IT -- a fixed point, growing until no entry gains a
1967
+ // formal. A chain of setters forwarding one union or handle down to a
1968
+ // read-only leaf then passes it by reference at every level instead of
1969
+ // moving it once per level.
1970
+ let borrowDying = dyingArguments;
1971
+ for (;;) {
1972
+ const entries = new Map();
1973
+ for (const body of input.bodies) {
1974
+ const entry = stableEntryOf(body, borrowDying);
1975
+ if (entry)
1976
+ entries.set(cppBodyName(body.sourceOwner), entry);
1977
+ }
1978
+ const forwarded = borrowForwardedArgumentsOf(input.bodies, entries, dyingArguments);
1979
+ if ([...forwarded].every((value) => !borrowDying.has(value)))
1980
+ break;
1981
+ borrowDying = withoutDyingArguments(dyingArguments, forwarded);
1982
+ }
1941
1983
  for (const body of input.bodies) {
1942
1984
  if (isRegionId(body.sourceOwner))
1943
1985
  continue;
1944
- const entry = constructorBodies.has(String(body.sourceOwner))
1945
- ? null
1946
- : stableBorrowEntryOf(body, body.sourceOwner, (declaration) => {
1947
- const placement = input.placements.get(declaration);
1948
- return placement?.storage.kind === 'local' && placement.storage.owner === body.sourceOwner && !captures.isBoxed(declaration)
1949
- ? placement.representation
1950
- : null;
1951
- }, formalsBorrowedIn(body.sourceOwner), dyingArguments, {
1952
- captureFree: captures.of(body.sourceOwner).kind === 'none',
1953
- synchronous: !isCoroutineBody(body),
1954
- singleBody: physicalCounts.get(String(body.sourceOwner)) === 1,
1955
- unchangedNumericAbi: formalsNarrowedIn(body.sourceOwner).size === 0 && !resultNarrowedIn(body.sourceOwner)
1956
- });
1986
+ const entry = stableEntryOf(body, borrowDying);
1957
1987
  if (entry)
1958
1988
  stableBorrowEntries.set(cppBodyName(body.sourceOwner), entry);
1959
1989
  if (process.env.GEA_BORROW_DEBUG) {
@@ -1965,7 +1995,7 @@ const renderTranslationUnitSession = (input) => {
1965
1995
  return placement?.storage.kind === 'local' && placement.storage.owner === body.sourceOwner && !captures.isBoxed(declaration)
1966
1996
  ? placement.representation
1967
1997
  : null;
1968
- }, dyingArguments).size
1998
+ }, borrowDying).size
1969
1999
  : 0;
1970
2000
  const flags = [
1971
2001
  `entry=${entry ? 'yes' : 'no'}`,
@@ -1988,13 +2018,18 @@ const renderTranslationUnitSession = (input) => {
1988
2018
  const signatures = input.bodies.flatMap((body) => {
1989
2019
  const original = `${signatureOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), formalsBorrowedIn(body.sourceOwner), cppBodyName(body.sourceOwner), taskResultOf(body))};`;
1990
2020
  const entry = stableBorrowEntries.get(cppBodyName(body.sourceOwner));
1991
- return entry === undefined ? [original] : [original, `${signatureOf(body, captures, new Set(), false, entry.formals, entry.name)};`];
2021
+ return entry === undefined
2022
+ ? [original]
2023
+ : [
2024
+ original,
2025
+ `${signatureOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), entry.formals, entry.name)};`
2026
+ ];
1992
2027
  });
1993
2028
  const thunks = new Map();
1994
2029
  // The functions whose minted values publish a `[[Construct]]` entry.
1995
2030
  const constructEntries = new Set();
1996
2031
  for (const body of input.bodies) {
1997
- const thunk = thunkOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), linkage, taskResultOf(body));
2032
+ const thunk = thunkOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), linkage, taskResultOf(body), isRegionId(body.sourceOwner) ? undefined : stableBorrowEntries.get(cppBodyName(body.sourceOwner)));
1998
2033
  if (thunk)
1999
2034
  thunks.set(body, thunk);
2000
2035
  if (thunk?.publishesConstruct && !isRegionId(body.sourceOwner))
@@ -2074,7 +2109,7 @@ const renderTranslationUnitSession = (input) => {
2074
2109
  // The formals this body's signature takes by reference: their objects
2075
2110
  // outlive the call, which `emit.ts`'s stable field reads rely on.
2076
2111
  const borrowed = stableEntry?.formals ?? formalsBorrowedIn(body.sourceOwner);
2077
- const sections = emitBody(promiseView ?? body, input.placements, input.classes, hosts, deriver, input.wellKnownSymbols, captures, symbolKeys, templateObjects, directCallables, virtuals.dispatched, narrowedStorage.factsOf(body.sourceOwner), formalsNarrowedIn(body.sourceOwner), repeatedConstructors, dyingArguments, instantiation, (callable) => abiByBody.get(String(callable)) ?? null, functionFacts, constructEntries, hostMethodAliases, callableMemberCandidates, callableFlowCandidates.get(body.owner) ?? new Map(), borrowableMemberBodies, stableBorrowEntries, printerDrift, input.conversions, selectionHelpers, callableIdentityDemand, nativeIntegrityRestricted, fixedFieldStateConstant, definitionCells, constructionOnlyFields, keyOrderUnobserved, debugSource, borrowed, asyncResults.taskResults, programSite.conversionIsCertified, input.programConversionRecipes, structs.classIndexProtocols);
2112
+ const sections = emitBody(promiseView ?? body, input.placements, input.classes, hosts, deriver, input.wellKnownSymbols, captures, symbolKeys, templateObjects, directCallables, virtuals.dispatched, narrowedStorage.factsOf(body.sourceOwner), formalsNarrowedIn(body.sourceOwner), repeatedConstructors, borrowDying, instantiation, (callable) => abiByBody.get(String(callable)) ?? null, functionFacts, constructEntries, hostMethodAliases, callableMemberCandidates, callableFlowCandidates.get(body.owner) ?? new Map(), borrowableMemberBodies, stableBorrowEntries, printerDrift, input.conversions, selectionHelpers, callableIdentityDemand, nativeIntegrityRestricted, fixedFieldStateConstant, definitionCells, constructionOnlyFields, keyOrderUnobserved, debugSource, borrowed, asyncResults.taskResults, programSite.conversionIsCertified, input.programConversionRecipes, structs.classIndexProtocols);
2078
2113
  const commonJsScope = [
2079
2114
  ...coroutineEnvironmentPrologueOf(promiseView ?? body, captures),
2080
2115
  ...(commonJsOwner === null || commonJsOwner.nativeRecord
@@ -2098,7 +2133,9 @@ const renderTranslationUnitSession = (input) => {
2098
2133
  ...(stableEntry === undefined
2099
2134
  ? []
2100
2135
  : [
2101
- plain(`${signatureOf(body, captures, new Set(), false, formalsBorrowedIn(body.sourceOwner))} {`),
2136
+ // The wrapper keeps the declared signature's narrowed integer formals and
2137
+ // result, so it forwards them to the entry without a conversion.
2138
+ plain(`${signatureOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), formalsBorrowedIn(body.sourceOwner))} {`),
2102
2139
  plain(
2103
2140
  // The stable entry's own signature always states `gea_this`
2104
2141
  // first when the body has a receiver (`formalsOf` spells it
@@ -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.44",
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": {