@geastack/compiler 1.0.23 → 1.0.25

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.
@@ -0,0 +1,182 @@
1
+ import ts from 'typescript';
2
+ import { forEachReachableStatement } from './reachability.js';
3
+ export const emptyAssertedArgumentArmCensus = { armsOf: () => null };
4
+ const presentMembersOf = (type) => (type.isUnion() ? type.types : [type]).filter((member) => (member.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null)) === 0);
5
+ const containsTypeParameter = (checker, type, depth = 0) => {
6
+ if (depth > 4)
7
+ return true;
8
+ if (type.flags & ts.TypeFlags.TypeParameter)
9
+ return true;
10
+ if (type.isUnionOrIntersection())
11
+ return type.types.some((member) => containsTypeParameter(checker, member, depth + 1));
12
+ if ((type.flags & ts.TypeFlags.Object) !== 0 && (type.objectFlags & ts.ObjectFlags.Reference) !== 0)
13
+ return checker.getTypeArguments(type).some((argument) => containsTypeParameter(checker, argument, depth + 1));
14
+ return false;
15
+ };
16
+ const unwrapParens = (node) => (ts.isParenthesizedExpression(node) ? unwrapParens(node.expression) : node);
17
+ /**
18
+ * A plain record: an object type with no call or construct signature that is
19
+ * not a class instance, an array, or a tuple. A class arm is nominal, so a
20
+ * record beside it would be a second layout the class's methods never see.
21
+ */
22
+ const isPlainRecord = (checker, type) => (type.flags & ts.TypeFlags.Object) !== 0 &&
23
+ ((type.getSymbol()?.flags ?? 0) & ts.SymbolFlags.Class) === 0 &&
24
+ type.getCallSignatures().length === 0 &&
25
+ type.getConstructSignatures().length === 0 &&
26
+ !checker.isArrayType(type) &&
27
+ !checker.isTupleType(type);
28
+ /** Whether a narrowing condition reads `node` -- the walk `record-stand-in-arms.ts` states. */
29
+ const narrows = (node) => {
30
+ let current = node;
31
+ for (;;) {
32
+ const parent = current.parent;
33
+ if (!parent)
34
+ return false;
35
+ if (ts.isParenthesizedExpression(parent) ||
36
+ ts.isTypeOfExpression(parent) ||
37
+ ts.isNonNullExpression(parent) ||
38
+ (ts.isPrefixUnaryExpression(parent) && parent.operator === ts.SyntaxKind.ExclamationToken) ||
39
+ (ts.isPropertyAccessExpression(parent) && parent.expression === current) ||
40
+ (ts.isElementAccessExpression(parent) && parent.expression === current)) {
41
+ current = parent;
42
+ continue;
43
+ }
44
+ if (ts.isBinaryExpression(parent)) {
45
+ switch (parent.operatorToken.kind) {
46
+ case ts.SyntaxKind.AmpersandAmpersandToken:
47
+ case ts.SyntaxKind.BarBarToken:
48
+ case ts.SyntaxKind.QuestionQuestionToken:
49
+ case ts.SyntaxKind.EqualsEqualsEqualsToken:
50
+ case ts.SyntaxKind.ExclamationEqualsEqualsToken:
51
+ case ts.SyntaxKind.EqualsEqualsToken:
52
+ case ts.SyntaxKind.ExclamationEqualsToken:
53
+ case ts.SyntaxKind.InstanceOfKeyword:
54
+ case ts.SyntaxKind.InKeyword:
55
+ current = parent;
56
+ continue;
57
+ default:
58
+ return false;
59
+ }
60
+ }
61
+ if (ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent))
62
+ return parent.expression === current;
63
+ if (ts.isForStatement(parent))
64
+ return parent.condition === current;
65
+ if (ts.isConditionalExpression(parent))
66
+ return parent.condition === current;
67
+ if (ts.isSwitchStatement(parent))
68
+ return parent.expression === current;
69
+ if (ts.isCaseClause(parent))
70
+ return parent.expression === current;
71
+ return false;
72
+ }
73
+ };
74
+ export const censusAssertedArgumentArms = (checker, files, reachable) => {
75
+ /** The seed one call argument states, when it is `record as unknown as Union` landing where the union is the parameter. */
76
+ const seedOf = (argument) => {
77
+ const outer = unwrapParens(argument);
78
+ if (!ts.isAsExpression(outer) && !ts.isTypeAssertionExpression(outer))
79
+ return null;
80
+ const inner = unwrapParens(outer.expression);
81
+ if (!ts.isAsExpression(inner) && !ts.isTypeAssertionExpression(inner))
82
+ return null;
83
+ if ((checker.getTypeFromTypeNode(inner.type).flags & ts.TypeFlags.Unknown) === 0)
84
+ return null;
85
+ const union = checker.getTypeFromTypeNode(outer.type);
86
+ const record = checker.getTypeAtLocation(unwrapParens(inner.expression));
87
+ if (!union.isUnion() || containsTypeParameter(checker, union) || containsTypeParameter(checker, record))
88
+ return null;
89
+ const homes = presentMembersOf(union);
90
+ if (homes.length < 2 || !homes.every((home) => isPlainRecord(checker, home)))
91
+ return null;
92
+ if (!isPlainRecord(checker, record) || homes.includes(record) || checker.isTypeAssignableTo(record, union))
93
+ return null;
94
+ return { union, record };
95
+ };
96
+ const seeds = [];
97
+ for (const file of files) {
98
+ if (file.isDeclarationFile)
99
+ continue;
100
+ const visit = (node) => {
101
+ if (reachable.memberIsPruned(node))
102
+ return;
103
+ if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
104
+ const argumentsList = node.arguments ?? [];
105
+ const signature = checker.getResolvedSignature(node);
106
+ argumentsList.forEach((argument, index) => {
107
+ if (argumentsList.slice(0, index + 1).some(ts.isSpreadElement))
108
+ return;
109
+ const seed = seedOf(argument);
110
+ const parameter = signature?.getParameters()[index];
111
+ if (!seed || !parameter || checker.getTypeOfSymbol(parameter) !== seed.union)
112
+ return;
113
+ seeds.push(seed);
114
+ });
115
+ }
116
+ ts.forEachChild(node, visit);
117
+ };
118
+ forEachReachableStatement(reachable, file, visit);
119
+ }
120
+ if (seeds.length === 0)
121
+ return emptyAssertedArgumentArmCensus;
122
+ const records = new Map();
123
+ for (const seed of seeds) {
124
+ const held = records.get(seed.union);
125
+ if (!held)
126
+ records.set(seed.union, [seed.record]);
127
+ else if (!held.includes(seed.record))
128
+ held.push(seed.record);
129
+ }
130
+ /**
131
+ * Whether a narrowing test on a value of `union` can tell its arms apart.
132
+ * Truthiness and nullishness of the value itself cannot -- every arm is an
133
+ * object -- and neither can a member every arm states with a non-unit type.
134
+ */
135
+ const discriminates = (use, union) => {
136
+ const parent = use.parent;
137
+ if (!parent)
138
+ return true;
139
+ if (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) {
140
+ const key = ts.isPropertyAccessExpression(parent)
141
+ ? parent.name.text
142
+ : ts.isStringLiteralLike(parent.argumentExpression)
143
+ ? parent.argumentExpression.text
144
+ : null;
145
+ if (key === null)
146
+ return true;
147
+ return [...presentMembersOf(union), ...(records.get(union) ?? [])].some((arm) => {
148
+ const property = arm.getProperty(key);
149
+ return !property || (checker.getTypeOfSymbol(property).flags & ts.TypeFlags.Unit) !== 0;
150
+ });
151
+ }
152
+ if (ts.isBinaryExpression(parent)) {
153
+ const operator = parent.operatorToken.kind;
154
+ return operator === ts.SyntaxKind.InstanceOfKeyword || operator === ts.SyntaxKind.InKeyword;
155
+ }
156
+ return ts.isTypeOfExpression(parent);
157
+ };
158
+ const withdrawn = new Set();
159
+ for (const file of files) {
160
+ if (file.isDeclarationFile)
161
+ continue;
162
+ const visit = (node) => {
163
+ if (reachable.memberIsPruned(node) || ts.isTypeNode(node))
164
+ return;
165
+ if ((ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && narrows(node)) {
166
+ const type = checker.getTypeAtLocation(node);
167
+ if (records.has(type) && discriminates(node, type))
168
+ withdrawn.add(type);
169
+ }
170
+ ts.forEachChild(node, visit);
171
+ };
172
+ forEachReachableStatement(reachable, file, visit);
173
+ }
174
+ for (const union of withdrawn)
175
+ records.delete(union);
176
+ if (process.env['GEA_BINDING_DEBUG'])
177
+ for (const seed of seeds)
178
+ console.error(`[ASSERTED-ARGUMENT-ARM] ${checker.typeToString(seed.record)} into ${checker.typeToString(seed.union)}${withdrawn.has(seed.union) ? ' :: withdrawn' : ''}`);
179
+ if (records.size === 0)
180
+ return emptyAssertedArgumentArmCensus;
181
+ return { armsOf: (union) => records.get(union) ?? null };
182
+ };
@@ -4,6 +4,7 @@ import type { ValueFlowIndex } from './flow/model.js';
4
4
  import { type SloppyAbsenceCensus } from './sloppy-absence.js';
5
5
  import { type SuppressedWriteArmCensus } from './suppressed-write-arms.js';
6
6
  import { type RecordStandInArmCensus } from './record-stand-in-arms.js';
7
+ import { type AssertedArgumentArmCensus } from './asserted-argument-arms.js';
7
8
  import { type RecordLinkFamilyCensus } from './record-link-families.js';
8
9
  import { type DeclaredMemberCensus } from './structural-declarations.js';
9
10
  import type { DeclarationId, StructuralTypeId } from '../../identity/ids.js';
@@ -203,7 +204,7 @@ export interface StructuralMapper {
203
204
  */
204
205
  readonly classCopies: () => ReadonlyMap<DeclarationId, readonly ClassCopyKey[]>;
205
206
  }
206
- export declare const createStructuralMapper: (checker: ts.TypeChecker, identities: IdentityTable, table: StructuralTypeTable, instantiations?: InstantiationCensus, specializations?: SpecializationCensus, parameters?: ParameterBindingCensus, absent?: AbsentGlobalCensus, collections?: CollectionBindingCensus, bags?: ObjectBagCensus, flow?: ValueFlowIndex, families?: InterfaceFamilyCensus, moduleRecords?: CommonJsModuleRecordCensus, declaredMembers?: DeclaredMemberCensus, isIntrinsicDescriptorCall?: (call: ts.CallExpression) => boolean, standIns?: RecordStandInArmCensus, linkFamilies?: RecordLinkFamilyCensus, sloppyAbsence?: SloppyAbsenceCensus, suppressedWrites?: SuppressedWriteArmCensus) => StructuralMapper;
207
+ export declare const createStructuralMapper: (checker: ts.TypeChecker, identities: IdentityTable, table: StructuralTypeTable, instantiations?: InstantiationCensus, specializations?: SpecializationCensus, parameters?: ParameterBindingCensus, absent?: AbsentGlobalCensus, collections?: CollectionBindingCensus, bags?: ObjectBagCensus, flow?: ValueFlowIndex, families?: InterfaceFamilyCensus, moduleRecords?: CommonJsModuleRecordCensus, declaredMembers?: DeclaredMemberCensus, isIntrinsicDescriptorCall?: (call: ts.CallExpression) => boolean, standIns?: RecordStandInArmCensus, linkFamilies?: RecordLinkFamilyCensus, sloppyAbsence?: SloppyAbsenceCensus, suppressedWrites?: SuppressedWriteArmCensus, assertedArguments?: AssertedArgumentArmCensus) => StructuralMapper;
207
208
  /**
208
209
  * `JSON.stringify(value)` from the default lib over a value that may have no
209
210
  * JSON form, so the call may return `undefined` although the lib declares
@@ -6,6 +6,7 @@ import { noSloppyAbsence, withAbsences } from './sloppy-absence.js';
6
6
  import { emptySuppressedWriteArmCensus } from './suppressed-write-arms.js';
7
7
  import { recordStorageFamilies } from './record-storage-families.js';
8
8
  import { emptyRecordStandInArmCensus } from './record-stand-in-arms.js';
9
+ import { emptyAssertedArgumentArmCensus } from './asserted-argument-arms.js';
9
10
  import { emptyRecordLinkFamilyCensus } from './record-link-families.js';
10
11
  import { bivariantSlotArrayAliasTypeOf, bivariantSlotBindingTypeOf, bivariantSlotElementTypeOf, bivariantSlotParameterTypeOf, bivariantSlotReadTypeOf } from './bivariant-slot-parameter.js';
11
12
  import { emptyDeclaredMemberCensus } from './structural-declarations.js';
@@ -100,7 +101,7 @@ const nativeErrorNames = new Set([
100
101
  'TypeError',
101
102
  'URIError'
102
103
  ]);
103
- export const createStructuralMapper = (checker, identities, table, instantiations = emptyInstantiationCensus, specializations = emptySpecializationCensus, parameters = emptyParameterBindingCensus, absent = emptyAbsentGlobalCensus, collections = emptyCollectionBindingCensus, bags = emptyObjectBagCensus, flow, families = emptyInterfaceFamilyCensus, moduleRecords = emptyCommonJsModuleRecordCensus, declaredMembers = emptyDeclaredMemberCensus, isIntrinsicDescriptorCall = () => false, standIns = emptyRecordStandInArmCensus, linkFamilies = emptyRecordLinkFamilyCensus, sloppyAbsence = noSloppyAbsence, suppressedWrites = emptySuppressedWriteArmCensus) => {
104
+ export const createStructuralMapper = (checker, identities, table, instantiations = emptyInstantiationCensus, specializations = emptySpecializationCensus, parameters = emptyParameterBindingCensus, absent = emptyAbsentGlobalCensus, collections = emptyCollectionBindingCensus, bags = emptyObjectBagCensus, flow, families = emptyInterfaceFamilyCensus, moduleRecords = emptyCommonJsModuleRecordCensus, declaredMembers = emptyDeclaredMemberCensus, isIntrinsicDescriptorCall = () => false, standIns = emptyRecordStandInArmCensus, linkFamilies = emptyRecordLinkFamilyCensus, sloppyAbsence = noSloppyAbsence, suppressedWrites = emptySuppressedWriteArmCensus, assertedArguments = emptyAssertedArgumentArmCensus) => {
104
105
  const storageTypeOf = recordStorageFamilies(checker, flow, parameters);
105
106
  // One disagreement list for the WHOLE mapper, for the same reason the caches
106
107
  // below are shared: two rules answering for one node is a fact about the rule
@@ -133,13 +134,13 @@ export const createStructuralMapper = (checker, identities, table, instantiation
133
134
  const cached = views.get(key);
134
135
  if (cached)
135
136
  return cached;
136
- const built = buildMapper(checker, identities.forSpecialization(path), table, instantiations, specializations, path, bindingPath, mapperFor, parameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, standIns, linkFamilies, aliasRecurrence, instantiatedMembersFor(bindingPath), viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements, sloppyAbsence, suppressedWrites);
137
+ const built = buildMapper(checker, identities.forSpecialization(path), table, instantiations, specializations, path, bindingPath, mapperFor, parameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, standIns, linkFamilies, aliasRecurrence, instantiatedMembersFor(bindingPath), viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements, sloppyAbsence, suppressedWrites, assertedArguments);
137
138
  views.set(key, built);
138
139
  return built;
139
140
  };
140
141
  return mapperFor(rootSpecialization);
141
142
  };
142
- const buildMapper = (checker, identities, table, instantiations, specializations, path, bindingPath, mapperFor, programParameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, standIns, linkFamilies, aliasRecurrence, instantiatedMembers, viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements, sloppyAbsence, suppressedWrites) => {
143
+ const buildMapper = (checker, identities, table, instantiations, specializations, path, bindingPath, mapperFor, programParameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, standIns, linkFamilies, aliasRecurrence, instantiatedMembers, viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements, sloppyAbsence, suppressedWrites, assertedArguments) => {
143
144
  const { boundByPath, bindingOf: censusBindingOf, substituteTypeParameter } = createTypeParameterSubstitution(identities, instantiations, specializations, bindingPath);
144
145
  // What a parameter holds is a fact about the COPY this view describes: a
145
146
  // generic body's copies are called with different carriers. Scoped once,
@@ -2246,6 +2247,12 @@ const buildMapper = (checker, identities, table, instantiations, specializations
2246
2247
  const standInArms = standInArmIdsOf(standIns.armsOf(type));
2247
2248
  if (standInArms)
2248
2249
  return remember(type, table.intern({ kind: 'union', members: [...present.map(typeOf), ...standInArms] }));
2250
+ // A record an argument hands this union through `as unknown as` is the
2251
+ // same object in the callee -- `asserted-argument-arms.ts` -- so it is
2252
+ // its own carrier's arm, never a stand-in copy of another shape.
2253
+ const assertedArms = assertedArguments.armsOf(type);
2254
+ if (assertedArms)
2255
+ return remember(type, table.intern({ kind: 'union', members: [...present.map(typeOf), ...assertedArms.map(typeOf)] }));
2249
2256
  // A union of pure INDEX-SIGNATURE objects is one table whose values are
2250
2257
  // the union. `Record<string, string> | Record<string, string[]>` (hono's
2251
2258
  // `_getQueryParam`, `utils/url.ts:255`) describes one object either way:
@@ -1040,8 +1040,8 @@ export const emitDenseSetup = (ctx, lines, blockId) => {
1040
1040
  // modulus is bounded by itself instead, and nothing ties that number to
1041
1041
  // this array, so the length has to cover it: `table[i % 16]` is a
1042
1042
  // window exactly when the table holds sixteen elements or more.
1043
- const reach = array.modulus === null ? `${cells}.size() > 0` : `${cells}.size() >= ${array.modulus}`;
1044
- said.push(...holder.guard, `${holder.text}->holes.empty()`, reach, ...writable);
1043
+ const reach = array.modulus === null ? `${size} > 0` : `${size} >= ${array.modulus}`;
1044
+ said.push(...holder.guard, ...shape, reach, ...writable);
1045
1045
  // The divisor of every index in this window, read here rather than on
1046
1046
  // every turn. Nothing in the loop resizes the array -- that is what the
1047
1047
  // window's own admission proved -- but only this hoist tells the
@@ -931,6 +931,26 @@ export const emitCall = (ctx, lines, operation) => {
931
931
  lines.push(`${expression};`);
932
932
  return;
933
933
  }
934
+ const unary = ctx.numericCalls.get(operation);
935
+ if (unary === 'abs' || unary === 'clz32') {
936
+ const argument = operation.arguments[0];
937
+ const text = operandText(ctx, argument);
938
+ const integerArgument = isIntegerStorageValue(ctx, argument.value);
939
+ const integerResult = operation.result !== null && isIntegerStorageValue(ctx, operation.result.id);
940
+ // `abs` of an integer argument is the integer one (`ir/integers.ts`);
941
+ // otherwise it is the double the host computes, NaN and -0 included.
942
+ // `clz32` is an integer whatever it is given, through ToUint32.
943
+ const expression = unary === 'abs'
944
+ ? integerResult && integerArgument
945
+ ? `gea::integerAbs(static_cast<long long>(${text}))`
946
+ : `std::fabs(static_cast<double>(${text}))`
947
+ : `gea::integerClz32(${integerArgument ? `static_cast<std::uint32_t>(static_cast<long long>(${text}))` : `gea::toUint32(${text})`})`;
948
+ if (operation.result && !ctx.unreadValues.has(operation.result.id))
949
+ lines.push(`${defineValue(ctx, operation.result)} = ${expression};`);
950
+ else
951
+ lines.push(`${expression};`);
952
+ return;
953
+ }
934
954
  if (ctx.numericCalls.get(operation) === 'imul') {
935
955
  const args = operation.arguments.map((argument) => {
936
956
  const text = operandText(ctx, argument);
@@ -394,10 +394,23 @@ const denseCellText = (ctx, operation) => {
394
394
  // could run: measured on `bench/comparison/fixtures/object_create.ts`,
395
395
  // 9.05ms without the hint and 8.49ms with it, for the same instructions in a
396
396
  // better order.
397
+ //
398
+ // A remainder index (`DenseAccess.signed`) carries the dividend's sign, and
399
+ // an un-narrowed one its fraction too: `t[-3 % 16]` and `t[1.5 % 16]` are
400
+ // both `undefined` in JS, and as a `size_t` they are an out-of-bounds read
401
+ // and `t[1]`. The test rides on the flag, so the cold half answers them.
402
+ const key = ctx.denseIndices.get(operation.key.value) ?? operandText(ctx, operation.key);
403
+ const flag = cppDenseFlagName(access.flag);
404
+ const integral = ctx.denseIndices.has(operation.key.value) || ctx.integerValues.has(operation.key.value);
405
+ const guarded = !access.signed
406
+ ? flag
407
+ : integral
408
+ ? `${flag} && (${key}) >= 0`
409
+ : `${flag} && (${key}) >= 0 && static_cast<double>(static_cast<long long>(${key})) == (${key})`;
397
410
  return {
398
411
  pointer: cppDensePointerName(access.array),
399
- index: `static_cast<std::size_t>(${ctx.denseIndices.get(operation.key.value) ?? operandText(ctx, operation.key)})`,
400
- flag: `GEA_LIKELY(${cppDenseFlagName(access.flag)})`,
412
+ index: `static_cast<std::size_t>(${key})`,
413
+ flag: `GEA_LIKELY(${guarded})`,
401
414
  text: `${cppDensePointerName(access.array)}[static_cast<std::size_t>(${ctx.denseIndices.get(operation.key.value) ?? operandText(ctx, operation.key)})]${operation.receiver.representation.kind === 'typed-array' ? '' : '.value'}`
402
415
  };
403
416
  };
@@ -17,31 +17,5 @@ import type { IntegerStorageFacts } from '../../ir/integers.js';
17
17
  import { type InstantiationFacts } from '../../ir/instantiation.js';
18
18
  import { type CallableIdentityDemand } from '../../ir/callable-identity-demand.js';
19
19
  import type { HostMethodAlias } from './host/host-method-aliases.js';
20
- /**
21
- * The C++ statements one lowered body renders to, as artifacts for the
22
- * emission boundary.
23
- *
24
- * `hostMembers` is every host spelling this compilation installed -- the
25
- * backend's own plus every plugin's. It is a parameter rather than an import
26
- * because which host is in front of the compiler is a property of the
27
- * compilation, not of this file.
28
- *
29
- * `deriver` is what `targets/cpp/emit-properties.ts` asks for a receiver's
30
- * own declared field representation, to widen a concrete value into a
31
- * `dynamic` field the same way this function's own `return` handling widens
32
- * into a `dynamic` ABI result -- see citations.md finding 1.
33
- *
34
- * `captures` defaults to `emptyCaptureIndex` (every owner closes over
35
- * nothing) so every existing caller keeps compiling and behaving exactly as
36
- * before; `translation-unit.ts` is the one caller that has an index to pass,
37
- * built once for the whole program by `targets/cpp/captures.ts`.
38
- */
39
- /**
40
- * The namespace every incoming value of a merge stands for, or `null`.
41
- *
42
- * `null` unless at least one arm is a namespace and every other arm is either
43
- * the same namespace or an absent constant -- see the call site for why an
44
- * absent arm is the one thing that may accompany it.
45
- */
46
20
  export declare const emitBody: (body: IrBody, placements: ReadonlyMap<DeclarationId, BindingPlacement>, classes: ReadonlyMap<DeclarationId, ClassLayout>, hosts: HostSpellings, deriver: RepresentationDeriver, wellKnownSymbols: ReadonlyMap<DeclarationId, string> | undefined, captures: CaptureIndex | undefined, symbolKeys: Map<string, string>, templateObjects: Map<string, TemplateObjectDefinition>, directCallableBindings?: ReadonlyMap<DeclarationId, FunctionId>, virtualDispatch?: ReadonlyMap<string, CallableAbi>, narrowedStorage?: IntegerStorageFacts, narrowedFormals?: ReadonlySet<number>, repeatedConstructors?: ReadonlyMap<DeclarationId, DeclarationId>, dyingArguments?: ReadonlySet<IrValueId>, instantiation?: InstantiationFacts, abiOfCallable?: (callable: FunctionId) => IrBody["abi"], functionFacts?: ReadonlyMap<FunctionId, CallableFactsSpelling>, hostMethodAliases?: ReadonlyMap<DeclarationId, HostMethodAlias>, callableMemberCandidates?: ReadonlyMap<string, FunctionId>, borrowableMemberBodies?: ReadonlySet<FunctionId>, stableBorrowEntries?: ReadonlyMap<string, StableBorrowEntry>, printerDrift?: PrinterDrift[], conversions?: ConversionCensus | null, nativeSelections?: ReadonlyMap<string, NativeSelectionHelper> | undefined, callableIdentityDemand?: CallableIdentityDemand, nativeIntegrityRestricted?: IntegrityRestrictions, fixedFieldStateConstant?: boolean, definitionCells?: ReadonlySet<DeclarationId>, constructionOnlyFields?: ConstructionOnlyFields, keyOrderUnobserved?: ReadonlySet<string>, taskBodies?: ReadonlySet<string>) => readonly CppArtifact[];
47
21
  export { cppConstructedThunkName, cppConstructThunkName, cppFormalName, cppReceiverName, cppThunkName, isCppEmitBlockedError } from './emit-context.js';
@@ -889,6 +889,18 @@ const emitCompute = (ctx, lines, operation) => {
889
889
  // `roundingArithmetic`).
890
890
  const rounding = integral && ctx.roundingArithmetic.has(operation.result.id) ? roundingIntegerHelpers.get(operation.operator) : undefined;
891
891
  if (rounding !== undefined) {
892
+ // An ordinary dense window's subscript is `base + counter`, and the
893
+ // window's flag already proved every such sum inside `[0, size())`
894
+ // (`gea::denseIndexWindow`), so under the flag it cannot leave +-2^53 and
895
+ // the rounding check is dead weight on every turn -- eight instructions and
896
+ // two branches per pixel of a rotozoom's `words[line + x]` on a 32-bit
897
+ // core. The fast arm takes a plain sum (wrapping, so it stays defined
898
+ // whatever the operands); the general arm keeps the faithful one. It is
899
+ // TEXT, not a statement: withholding pastes a value only when its operation
900
+ // rendered exactly one, and a second one here left the faithful sum
901
+ // computed on every turn beside the plain one (reel's fire, 64 -> 87 ms).
902
+ if (operation.operator === '+' && isOrdinaryDenseKey(ctx, operation.result.id))
903
+ ctx.denseIndices.set(operation.result.id, `static_cast<long long>(static_cast<unsigned long long>(${left}) + static_cast<unsigned long long>(${right}))`);
892
904
  lines.push(`${name} = ${rounding}(${left}, ${right});`);
893
905
  return;
894
906
  }
@@ -2152,6 +2164,16 @@ const blockLabelsOf = (order) => {
2152
2164
  * the same namespace or an absent constant -- see the call site for why an
2153
2165
  * absent arm is the one thing that may accompany it.
2154
2166
  */
2167
+ /** Whether a value is the subscript of an access in an ordinary (counter-bounded, not wrapped) dense window. */
2168
+ const isOrdinaryDenseKey = (ctx, value) => {
2169
+ for (const [operation, access] of ctx.denseAccesses) {
2170
+ if ((operation.kind !== 'get' && operation.kind !== 'set') || operation.key.value !== value)
2171
+ continue;
2172
+ if (ctx.denseArrays.find((array) => array.ordinal === access.array)?.wrapped === false)
2173
+ return true;
2174
+ }
2175
+ return false;
2176
+ };
2155
2177
  export const emitBody = (body, placements, classes, hosts, deriver, wellKnownSymbols = new Map(), captures = emptyCaptureIndex,
2156
2178
  // No default: `symbolKeys`/`templateObjects` are ONE table for the whole
2157
2179
  // program (`translation-unit.ts`'s own comment on its `templateObjects`
@@ -192,14 +192,18 @@ const storageSpelling = (type, name, realm = false) => realm
192
192
  * guessed type -- the body that reads it then refuses by name, which is the
193
193
  * answer, instead of this file inventing a layout to make the file compile.
194
194
  */
195
- const globalStorage = (placements, omit, realm = false) => [...placements.entries()]
195
+ const globalStorage = (placements, omit, realm = false, integerCells = new Set()) => [...placements.entries()]
196
196
  .filter(([declaration, placement]) => placement.storage.kind === 'region' && placement.representation !== null && !omit.has(declaration))
197
197
  .sort(([left], [right]) => left.localeCompare(right))
198
198
  .flatMap(([declaration, placement]) => {
199
199
  const representation = placement.representation;
200
200
  if (!representation || representation.kind === 'unresolved' || representation.kind === 'void')
201
201
  return [];
202
- return [storageSpelling(cppTypeOf(representation), cppGlobalName(declaration), realm)];
202
+ // A cell the program writes once with a bounded integer is held as one: a
203
+ // `double` here is read back through a double->integer conversion in every
204
+ // index built from it, which is a libcall on a core with no double FPU.
205
+ const type = integerCells.has(declaration) ? cppNarrowedIntegerType : cppTypeOf(representation);
206
+ return [storageSpelling(type, cppGlobalName(declaration), realm)];
203
207
  });
204
208
  const absentDefinitions = (placements, realm = false) => [...placements.entries()]
205
209
  .filter(([, placement]) => placement.storage.kind === 'absent' && placement.representation !== null)
@@ -1638,6 +1642,14 @@ const renderTranslationUnitSession = (input) => {
1638
1642
  }
1639
1643
  const narrowedStorage = integerStorageCensusOf({
1640
1644
  bodies: input.bodies,
1645
+ integerCellEligible: (cell) => {
1646
+ const placement = input.placements.get(cell);
1647
+ const representation = placement?.representation;
1648
+ return (placement?.storage.kind === 'region' &&
1649
+ !input.omitGlobals.has(cell) &&
1650
+ representation?.kind === 'scalar' &&
1651
+ representation.domain === 'number');
1652
+ },
1641
1653
  structNameOf: cppStructNameOf,
1642
1654
  structFamilyOf,
1643
1655
  fieldStructNameOf,
@@ -1754,7 +1766,7 @@ const renderTranslationUnitSession = (input) => {
1754
1766
  // name the host member instead (`buildHostMethodAliasIndex`) -- so declaring
1755
1767
  // it would leave a `CallableObject` of the method's own convention in the
1756
1768
  // unit, boxing an `any` formal that no code ever passes.
1757
- const globals = globalStorage(input.placements, new Set([...input.omitGlobals, ...hostMethodAliases.keys()]), input.realmStorage);
1769
+ const globals = globalStorage(input.placements, new Set([...input.omitGlobals, ...hostMethodAliases.keys()]), input.realmStorage, narrowedStorage.integerCells);
1758
1770
  // Environment structs ahead of every forward signature: a capturing body's
1759
1771
  // own formal names its struct as a pointer type, so the struct must already
1760
1772
  // be a complete type by the time that formal is spelled.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.23",
3
+ "version": "1.0.25",
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": {
@@ -7995,6 +7995,13 @@ inline long long integerImul(std::uint32_t left, std::uint32_t right) {
7995
7995
  return static_cast<long long>(static_cast<std::int32_t>(left * right));
7996
7996
  }
7997
7997
 
7998
+ // `Math.abs` of a value the integer census holds in a `long long` (its
7999
+ // magnitude is below 2^63, so the negation cannot overflow).
8000
+ inline long long integerAbs(long long value) { return value < 0 ? -value : value; }
8001
+
8002
+ // `Math.clz32` of an argument that has already undergone ToUint32.
8003
+ inline long long integerClz32(std::uint32_t value) { return value == 0 ? 32 : __builtin_clz(value); }
8004
+
7998
8005
  inline long long integerBitwiseOr(long long left, long long right) {
7999
8006
  return static_cast<std::int32_t>(static_cast<std::uint32_t>(left) | static_cast<std::uint32_t>(right));
8000
8007
  }
@@ -8208,22 +8215,42 @@ class TypedArray {
8208
8215
 
8209
8216
  // The caller owns an admitted NON-SHARED dense window. Shared views are
8210
8217
  // excluded before emission because only instance access can enter their
8211
- // backing-store mutex. memcpy preserves aliasing between differently typed
8212
- // views of the same ArrayBuffer; native T* dereferences would let the C++
8213
- // optimizer assume those views are disjoint.
8214
- [[gnu::always_inline]] static T readInBounds(const T* base, std::size_t index) {
8215
- T value;
8216
- std::memcpy(&value, reinterpret_cast<const std::uint8_t*>(base) + index * sizeof(T), sizeof(T));
8217
- return value;
8218
+ // backing-store mutex. The element is accessed through a `may_alias` type:
8219
+ // differently typed views of one ArrayBuffer overlap, and a plain T*
8220
+ // dereference would let the C++ optimizer assume they are disjoint. It is
8221
+ // NOT a byte memcpy: GCC for rv32 expands a 4-byte memcpy into a `float` as
8222
+ // an integer load and a trip through the stack into the FPU register (a
8223
+ // store and a reload per element -- bloom's 18-tap stencil spent most of
8224
+ // its ~150 instructions a cell on them). A view's elements are aligned
8225
+ // (ECMA-262 requires byteOffset to be a multiple of the element size), so
8226
+ // the typed access is a plain `flw`/`fsw`. `may_alias` cannot be attached to
8227
+ // an already-defined class (`ClampedUint8`), which keeps the byte copy -- a
8228
+ // one-byte memcpy is a plain `lbu`/`sb` anyway.
8229
+ [[gnu::always_inline]] static T loadElement(const T* base, std::size_t index) {
8230
+ if constexpr (std::is_arithmetic_v<T>) {
8231
+ typedef T __attribute__((__may_alias__)) Aliased;
8232
+ return reinterpret_cast<const Aliased*>(base)[index];
8233
+ } else {
8234
+ T value;
8235
+ std::memcpy(&value, reinterpret_cast<const std::uint8_t*>(base) + index * sizeof(T), sizeof(T));
8236
+ return value;
8237
+ }
8238
+ }
8239
+ [[gnu::always_inline]] static void storeElement(T* base, std::size_t index, T value) {
8240
+ if constexpr (std::is_arithmetic_v<T>) {
8241
+ typedef T __attribute__((__may_alias__)) Aliased;
8242
+ reinterpret_cast<Aliased*>(base)[index] = value;
8243
+ } else {
8244
+ std::memcpy(reinterpret_cast<std::uint8_t*>(base) + index * sizeof(T), &value, sizeof(T));
8245
+ }
8218
8246
  }
8247
+ [[gnu::always_inline]] static T readInBounds(const T* base, std::size_t index) { return loadElement(base, index); }
8219
8248
  [[gnu::always_inline]] static void writeInBounds(T* base, std::size_t index, double value) {
8220
- const T converted = detail::typedArrayElement<T>(value);
8221
- std::memcpy(reinterpret_cast<std::uint8_t*>(base) + index * sizeof(T), &converted, sizeof(T));
8249
+ storeElement(base, index, detail::typedArrayElement<T>(value));
8222
8250
  }
8223
8251
  /** `writeInBounds` for a value the integer census holds as an integer (`detail::typedArrayIntegerElement`). */
8224
8252
  [[gnu::always_inline]] static void writeIntegerInBounds(T* base, std::size_t index, long long value) {
8225
- const T converted = detail::typedArrayIntegerElement<T>(value);
8226
- std::memcpy(reinterpret_cast<std::uint8_t*>(base) + index * sizeof(T), &converted, sizeof(T));
8253
+ storeElement(base, index, detail::typedArrayIntegerElement<T>(value));
8227
8254
  }
8228
8255
  /** An integer element as the integer it is, for a result the integer census holds in a `long long`. */
8229
8256
  [[gnu::always_inline]] static long long readIntegerInBounds(const T* base, std::size_t index) {
@@ -1,41 +0,0 @@
1
- import type { SemanticResultId, StructuralTypeId } from '../identity/ids.js';
2
- import type { SemanticGraph } from '../semantics/model/graph.js';
3
- /**
4
- * The record members an `any` value writes `null` into although their
5
- * declared type admits no `null`, and every read of one.
6
- *
7
- * `any` is the unchecked top: the checker lets it into every position, so a
8
- * declared type says nothing about what an `any` write stores. mongodb's
9
- * `ServerDescription` declares `$clusterTime?: ClusterTime` and writes
10
- * `this.$clusterTime = hello?.$clusterTime ?? null` with `hello` a
11
- * `Document`; the right-hand side is `any`, and node stores the `null` the
12
- * `?? null` produces. Laid out from the declaration alone the member had one
13
- * `undefined` absence, the write converted the boxed `null` through a checked
14
- * record unwrap, and the driver threw a TypeError building its first
15
- * topology.
16
- *
17
- * Only a `null` the program SPELLS is admitted -- the literal itself, or the
18
- * fallback arm of a `??`/`||`, or an arm of a conditional -- reached from a
19
- * write whose value the checker typed `any`. A `null` arriving inside an
20
- * opaque `any` (a parsed document's field) is not visible here and still
21
- * meets the checked unwrap: this widens the layouts a program visibly writes
22
- * `null` into, it does not guess at what a dynamic value holds.
23
- *
24
- * Such a member is laid out as its declared type plus `null` (`derive.ts`'s
25
- * `recordFieldsOf`), and each constant-keyed read publishes that same field
26
- * carrier, so the read observes the `null` rather than converting it back
27
- * into the declaration's carrier.
28
- *
29
- * Keyed by the object shape the record -- or a class instance, through its
30
- * body -- is laid out under, exactly as `unwritten-record-members.ts` keys its
31
- * census.
32
- */
33
- export interface AnyNullRecordMembers {
34
- readonly members: ReadonlyMap<StructuralTypeId, ReadonlySet<string>>;
35
- /** Every constant-keyed read of one of those members, with the layout it reads. */
36
- readonly reads: ReadonlyMap<SemanticResultId, {
37
- readonly layout: StructuralTypeId;
38
- readonly key: string;
39
- }>;
40
- }
41
- export declare const anyNullRecordMembersOf: (graph: SemanticGraph) => AnyNullRecordMembers;