@geastack/compiler 1.0.46 → 1.0.48

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.
@@ -861,6 +861,9 @@ staticCommonJsRequireOutcomeOf = () => null, trustSeed = initialCensusSeed) => {
861
861
  * intrinsic prototype the component had been merged with, `Map.prototype`
862
862
  * among them, for every `x` and `width` handed to a `readPixels`-style
863
863
  * native, and refused obligations no native could touch.
864
+ *
865
+ * An argument whose own type is primitive as well reaches nothing at all
866
+ * (`primitiveArgumentReachesNothing` below).
864
867
  */
865
868
  const NO_SCALAR_POSITIONS = new Map();
866
869
  const hostNativeScalarParametersOf = (call) => {
@@ -6926,8 +6929,26 @@ staticCommonJsRequireOutcomeOf = () => null, trustSeed = initialCensusSeed) => {
6926
6929
  const component = target ? factsByComponent.get(target) : undefined;
6927
6930
  // A scalar host parameter reaches what its primitive reaches, and
6928
6931
  // nothing else of the cell's component (`hostNativeScalarParametersOf`).
6932
+ //
6933
+ // A primitive argument reaches nothing at all. The wrapper chain is
6934
+ // `Object.prototype` and the `Object` constructor, stamped `every`
6935
+ // for each uncontracted native taking a `number`, which revoked
6936
+ // `Object.assign` and every absent-key read in the program over one
6937
+ // `bindBufferBase( target, index, buffer )`. A native that could
6938
+ // reach those realm intrinsics through a `double` could reach them
6939
+ // with no argument at all, and this stamp has never charged a
6940
+ // zero-argument native with anything: what a native does to the
6941
+ // realm on its own is its contract's business (`host-effect-contracts.ts`).
6942
+ // Only the argument's OWN type answers that: `define as unknown as
6943
+ // number` or an `any` cell may still hold an object, and keeps the
6944
+ // wrapper chain.
6929
6945
  const scalar = scalarParameters.get(position);
6930
- const reach = scalar === undefined ? null : primitivePrototypeReachOf(scalar, current);
6946
+ const primitiveArgumentReachesNothing = scalar !== undefined && primitiveResult(checker.getTypeAtLocation(current));
6947
+ const reach = scalar === undefined
6948
+ ? null
6949
+ : primitiveArgumentReachesNothing
6950
+ ? new Set()
6951
+ : primitivePrototypeReachOf(scalar, current);
6931
6952
  const facts = component === undefined || reach === null
6932
6953
  ? component
6933
6954
  : { ...component, prototypes: new Set([...component.prototypes].filter((declaration) => reach.has(declaration))) };
@@ -4,6 +4,7 @@ import { emptyParameterBindingCensus } from './parameter-bindings.js';
4
4
  import { emptyCollectionBindingCensus } from './collection-bindings.js';
5
5
  import { emptyObjectBagCensus } from './object-bag-bindings.js';
6
6
  import { iteratorYieldTypesOf } from './producers/iteration-yield.js';
7
+ import { testsItsOperand } from './producers/nullish.js';
7
8
  import { arrayAssignmentPatternSourceExpression, arrayAssignmentTargetOf, objectAssignmentElementOfTarget, objectAssignmentSource } from './assignment-patterns.js';
8
9
  import { classFamilyMemberReadTypeOf } from './flow/class-family-member-read.js';
9
10
  import { forEachReachableStatement } from './reachability.js';
@@ -745,30 +746,6 @@ moduleRecords = emptyCommonJsModuleRecordCensus) => {
745
746
  const other = parent.left === inner ? parent.right : parent.right === inner ? parent.left : null;
746
747
  return other !== null && (checker.getTypeAtLocation(other).flags & ts.TypeFlags.Undefined) !== 0;
747
748
  };
748
- /** Whether this reference is consumed directly by ToBoolean. */
749
- const directTruthinessTest = (expression) => {
750
- let inner = expression;
751
- let parent = inner.parent;
752
- while (parent && ts.isParenthesizedExpression(parent)) {
753
- inner = parent;
754
- parent = parent.parent;
755
- }
756
- if (!parent)
757
- return false;
758
- if (ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent))
759
- return parent.expression === inner;
760
- if (ts.isForStatement(parent))
761
- return parent.condition === inner;
762
- if (ts.isConditionalExpression(parent))
763
- return parent.condition === inner;
764
- if (ts.isPrefixUnaryExpression(parent))
765
- return parent.operator === ts.SyntaxKind.ExclamationToken;
766
- if (!ts.isBinaryExpression(parent) || parent.left !== inner)
767
- return false;
768
- return (parent.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
769
- parent.operatorToken.kind === ts.SyntaxKind.BarBarToken ||
770
- parent.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken);
771
- };
772
749
  const registerObservedIndexedAbsence = (declaration) => {
773
750
  if (declaration.type || ts.getJSDocType(declaration) || !ts.isIdentifier(declaration.name) || !declaration.initializer)
774
751
  return;
@@ -804,7 +781,7 @@ moduleRecords = emptyCommonJsModuleRecordCensus) => {
804
781
  return;
805
782
  const observing = flow
806
783
  .referencesToSymbol(symbol)
807
- .filter((reference) => directUndefinedComparison(reference) || directTruthinessTest(reference));
784
+ .filter((reference) => directUndefinedComparison(reference) || testsItsOperand(reference));
808
785
  if (observing.length === 0)
809
786
  return;
810
787
  if (untyped) {
@@ -15,6 +15,7 @@ import { deferredIntrinsicProtocolLedgerOf } from './deferred-intrinsic-protocol
15
15
  import { callbackContractParameterType, inlineJsxCallbackParameterType, callbackParameterContractsFor } from './callback-parameter-contracts.js';
16
16
  import { declaredClosedTupleRestElementsOf, impliedPatternElementOfArms, impliedPatternPositionPresentEverywhere } from './parameter-slot.js';
17
17
  import { iteratorYieldTypesOf } from './producers/iteration-yield.js';
18
+ import { holdsUndefined } from './producers/nullish.js';
18
19
  import { annotationStatesNothing, exactEmptyObjectLiteralType, isNullishType, containsUnstatedPosition, derivedExpressionType, indexAliasEvidence, indexedTypeOf, explicitThisCallReturnType, overloadInvariantReturnTypeAt, arrayFromCopyTypeAt, indexNamedCallables, isStandardInterfaceType, isBindingOnlyReference, isCalleeOf, isTrackedCallable, isUnusableEvidence as statesNoStorage, carriesNoEvidence, disjointUnionMembersOf, disjointUnionTypeOf, joinOfWrites, jsDocTypeStatesNothing, literalMemberNameOf, narrowsOnlyUnstatedPositions, isStructuralConstructorType, narrowsStructuralConstructorToClasses, narrowsArrayBufferViewToViews, statesAnArrayBufferView, isLibArrayBufferViewType, withoutUndefinedMember, memberTypeOf, objectAssignTargetType, nameOfCallable, synthesizedUnionArmsAt, readsWholeSynthesizedCell, widestOf, impliedPatternElementRootOf, impliedPatternParameterOf } from './derived-expression-type.js';
19
20
  import { readsStatedDynamicValue } from './stated-dynamic-value.js';
20
21
  import { isUnreducedTypeForm } from './unreduced-type-form.js';
@@ -2310,6 +2311,36 @@ hostProvided = noHostProvidedNames) => {
2310
2311
  }
2311
2312
  return false;
2312
2313
  };
2314
+ /**
2315
+ * An index-signature read handed to a parameter whose contextual type has a
2316
+ * home for `undefined` (`unknown`, `any`, or an explicit `undefined`). The
2317
+ * read's producer publishes it as `T | undefined` there
2318
+ * (`properties.ts`'s `observablyAbsentElementTypeOf`), because a missing key
2319
+ * is `undefined`, not `T`; the parameter must hold that absence too.
2320
+ */
2321
+ const passesAbsentIndexRead = (argument, resolved) => {
2322
+ let read = argument;
2323
+ while (ts.isParenthesizedExpression(read))
2324
+ read = read.expression;
2325
+ if (!ts.isElementAccessExpression(read) && !ts.isPropertyAccessExpression(read))
2326
+ return false;
2327
+ if (holdsUndefined(resolved))
2328
+ return false;
2329
+ const contextual = checker.getContextualType(argument);
2330
+ if (contextual === undefined || !holdsUndefined(contextual))
2331
+ return false;
2332
+ const receiver = checker.getTypeAtLocation(read.expression);
2333
+ if (checker.isArrayType(receiver) || checker.isTupleType(receiver))
2334
+ return false;
2335
+ if (checker.getIndexInfosOfType(receiver).length === 0)
2336
+ return false;
2337
+ const key = ts.isPropertyAccessExpression(read)
2338
+ ? read.name.text
2339
+ : ts.isStringLiteralLike(read.argumentExpression) || ts.isNumericLiteral(read.argumentExpression)
2340
+ ? read.argumentExpression.text
2341
+ : null;
2342
+ return key === null || checker.getPropertyOfType(receiver, key) === undefined;
2343
+ };
2313
2344
  const collectPassedArguments = (calls, declaration, parameter, index, excludeBackEdges, skipSilentSites) => {
2314
2345
  const passed = [];
2315
2346
  const deferredRecursiveArguments = [];
@@ -2421,6 +2452,8 @@ hostProvided = noHostProvidedNames) => {
2421
2452
  // type is a fact about the call, not about the storage it lands in, and a
2422
2453
  // second call site passing `6` would then read as a disagreement.
2423
2454
  passed.push(resolved.isLiteral() ? checker.getBaseTypeOfLiteralType(resolved) : resolved);
2455
+ if (passesAbsentIndexRead(argument, resolved))
2456
+ passed.push(checker.getUndefinedType());
2424
2457
  record(argument);
2425
2458
  }
2426
2459
  return { passed, sawBackEdge, sawOmitted, sawSilentSite, deferredRecursiveArguments };
@@ -10,6 +10,20 @@ import type { ProducerContext } from '../producer-context.js';
10
10
  * `logicalMergeTypeOf`.
11
11
  * - An `Object.create(null)` call, which publishes the carrier
12
12
  * `objectCreateResultOverride` mints rather than the ambient `any`.
13
+ * - A property read, which `properties.ts` publishes under
14
+ * `propertyExpressionValueTypeAt`: an index-signature read a test observes
15
+ * (`dict[key] && x`) carries `T | undefined` where the checker reports `T`,
16
+ * and a merge citing the checker's `T` for it typed its kept branch as a
17
+ * present value and dereferenced the absence.
18
+ * - A name's read of an explicitly optional local at a use that observes
19
+ * absence, which `references.ts` publishes under the declared carrier
20
+ * (`declaredAbsenceTypeAt`) where the checker's flow narrowing says `T`.
21
+ *
22
+ * A non-null assertion (`dict[key]!`) asserts that absence away, and a type
23
+ * assertion naming a type (`dict[key] as T`) states the value's type outright:
24
+ * the citation keeps the checker's type at the assertion, and the operand's
25
+ * conversion proves it there, as it did before the read's own carrier was
26
+ * consulted.
13
27
  *
14
28
  * A citation that re-asked the checker boxed the value at the citation: a
15
29
  * trie router's `Node` does `this.#children = children || Object.create(null)`;
@@ -1,7 +1,9 @@
1
1
  import ts from '#typescript';
2
- import { unwrapErased } from './erasure.js';
2
+ import { assertsPresence, assertsType, unwrapErased } from './erasure.js';
3
3
  import { objectCreateResultOverride } from './invocations.js';
4
4
  import { logicalMergeTypeOf } from './logical-merge-type.js';
5
+ import { propertyExpressionValueTypeAt } from './properties.js';
6
+ import { declaredAbsenceTypeAt } from './references.js';
5
7
  /**
6
8
  * The type an operand citing `node`'s published value carries: the checker's
7
9
  * view of the node, except where a producer publishes that value under a type
@@ -11,6 +13,20 @@ import { logicalMergeTypeOf } from './logical-merge-type.js';
11
13
  * `logicalMergeTypeOf`.
12
14
  * - An `Object.create(null)` call, which publishes the carrier
13
15
  * `objectCreateResultOverride` mints rather than the ambient `any`.
16
+ * - A property read, which `properties.ts` publishes under
17
+ * `propertyExpressionValueTypeAt`: an index-signature read a test observes
18
+ * (`dict[key] && x`) carries `T | undefined` where the checker reports `T`,
19
+ * and a merge citing the checker's `T` for it typed its kept branch as a
20
+ * present value and dereferenced the absence.
21
+ * - A name's read of an explicitly optional local at a use that observes
22
+ * absence, which `references.ts` publishes under the declared carrier
23
+ * (`declaredAbsenceTypeAt`) where the checker's flow narrowing says `T`.
24
+ *
25
+ * A non-null assertion (`dict[key]!`) asserts that absence away, and a type
26
+ * assertion naming a type (`dict[key] as T`) states the value's type outright:
27
+ * the citation keeps the checker's type at the assertion, and the operand's
28
+ * conversion proves it there, as it did before the read's own carrier was
29
+ * consulted.
14
30
  *
15
31
  * A citation that re-asked the checker boxed the value at the citation: a
16
32
  * trie router's `Node` does `this.#children = children || Object.create(null)`;
@@ -24,6 +40,15 @@ export const citedValueTypeAt = (context, node) => {
24
40
  if (created !== null)
25
41
  return created;
26
42
  }
43
+ if (!assertsPresence(node) && !assertsType(node, context.checker)) {
44
+ if (ts.isPropertyAccessExpression(unwrapped) || ts.isElementAccessExpression(unwrapped))
45
+ return propertyExpressionValueTypeAt(context, unwrapped);
46
+ if (ts.isIdentifier(unwrapped)) {
47
+ const declared = declaredAbsenceTypeAt(context, unwrapped);
48
+ if (declared !== null)
49
+ return declared;
50
+ }
51
+ }
27
52
  if (ts.isBinaryExpression(unwrapped)) {
28
53
  const operator = unwrapped.operatorToken.kind;
29
54
  if (operator === ts.SyntaxKind.QuestionQuestionToken ||
@@ -6,7 +6,6 @@ import { logicalMergeTypeOf } from './logical-merge-type.js';
6
6
  import { blocked, mintOperationId, mintResult, operand } from './mint.js';
7
7
  import { isAssignmentOperatorKind, logicalAssignmentOperators, sourceForValue, symbolMemberKeyOf, unwrapErased, valueEdgesInto } from './shared.js';
8
8
  import { normalCompletion, pureEffects, throwingCompletion } from '../../model/operands.js';
9
- import { propertyExpressionValueTypeAt } from './properties.js';
10
9
  import { citedValueTypeAt } from './cited-value-type.js';
11
10
  import { constantConditionalGuardId, constantConditionalGuardResult } from './conditional-guard.js';
12
11
  import { ordinaryObjectDataWriteIsAbsent } from '../callable-data-write.js';
@@ -365,9 +364,7 @@ const contributeConditional = (context, candidate, node) => {
365
364
  };
366
365
  }
367
366
  const condition = operand('condition', 0, conditionSource, context.types.typeAt(node.condition));
368
- const branchValueTypeAt = (branch) => ts.isPropertyAccessExpression(branch) || ts.isElementAccessExpression(branch)
369
- ? propertyExpressionValueTypeAt(context, branch)
370
- : citedValueTypeAt(context, branch);
367
+ const branchValueTypeAt = (branch) => citedValueTypeAt(context, branch);
371
368
  const consequent = operand('consequent', 0, sourceForValue(context, node.whenTrue), branchValueTypeAt(node.whenTrue), {
372
369
  kind: 'conditional',
373
370
  guard: conditionSource.result,
@@ -18,6 +18,8 @@ import ts from '#typescript';
18
18
  export declare const unwrapErased: (node: ts.Node) => ts.Node;
19
19
  /** The same rule where the caller already knows it holds an expression. */
20
20
  export declare const unwrapErasedExpression: (expression: ts.Expression) => ts.Expression;
21
+ /** Whether a non-null assertion is among the erased wrappers `unwrapErased` sees through from `node`. */
22
+ export declare const assertsPresence: (node: ts.Node) => boolean;
21
23
  /**
22
24
  * Whether one of the erased wrappers around `expression` is a type assertion
23
25
  * that names a type -- `SemanticOperand.asserted`. `as any`/`as unknown`
@@ -31,6 +31,20 @@ export const unwrapErased = (node) => {
31
31
  };
32
32
  /** The same rule where the caller already knows it holds an expression. */
33
33
  export const unwrapErasedExpression = (expression) => unwrapErased(expression);
34
+ /** Whether a non-null assertion is among the erased wrappers `unwrapErased` sees through from `node`. */
35
+ export const assertsPresence = (node) => {
36
+ let current = node;
37
+ while (ts.isParenthesizedExpression(current) ||
38
+ ts.isNonNullExpression(current) ||
39
+ ts.isAsExpression(current) ||
40
+ ts.isSatisfiesExpression(current) ||
41
+ ts.isTypeAssertionExpression(current)) {
42
+ if (ts.isNonNullExpression(current))
43
+ return true;
44
+ current = current.expression;
45
+ }
46
+ return false;
47
+ };
34
48
  /**
35
49
  * Whether one of the erased wrappers around `expression` is a type assertion
36
50
  * that names a type -- `SemanticOperand.asserted`. `as any`/`as unknown`
@@ -1,22 +1,41 @@
1
1
  import ts from '#typescript';
2
2
  import { classOfConstructorType } from '../derived-expression-type.js';
3
3
  import { keptLeftPartTypeOf } from '../logical-result-type.js';
4
+ const isNullish = (context, id) => {
5
+ const shape = context.table.get(id).shape;
6
+ return shape.kind === 'primitive' && (shape.primitive === 'undefined' || shape.primitive === 'null');
7
+ };
8
+ const membersOf = (context, id) => {
9
+ const shape = context.table.get(id).shape;
10
+ return shape.kind === 'union' ? shape.members : [id];
11
+ };
12
+ /** The union of `members` (each possibly a union itself), or the one member when they collapse to one. */
13
+ const unionOf = (context, members) => {
14
+ const distinct = [...new Set(members.flatMap((member) => membersOf(context, member)))];
15
+ return distinct.length === 1 ? distinct[0] : context.table.intern({ kind: 'union', members: distinct });
16
+ };
4
17
  /** `type` less its `undefined`/`null` members, or `null` when nothing else is left. */
5
18
  const presentPartOf = (context, type) => {
6
- const nullish = (id) => {
7
- const shape = context.table.get(id).shape;
8
- return shape.kind === 'primitive' && (shape.primitive === 'undefined' || shape.primitive === 'null');
9
- };
10
- const shape = context.table.get(type).shape;
11
- if (shape.kind !== 'union')
12
- return nullish(type) ? null : type;
13
- const present = shape.members.filter((member) => !nullish(member));
14
- if (present.length === shape.members.length)
19
+ const members = membersOf(context, type);
20
+ const present = members.filter((member) => !isNullish(context, member));
21
+ if (present.length === members.length)
15
22
  return type;
16
23
  if (present.length === 0)
17
24
  return null;
18
- return present.length === 1 ? present[0] : context.table.intern({ kind: 'union', members: present });
25
+ return unionOf(context, present);
19
26
  };
27
+ /** The `undefined`/`null` members of `type`, or `null` when it has none. */
28
+ const absentPartOf = (context, type) => {
29
+ const absent = membersOf(context, type).filter((member) => isNullish(context, member));
30
+ return absent.length === 0 ? null : unionOf(context, absent);
31
+ };
32
+ /** The members of `type` that can hold a falsy value: primitives and literals, never an object. */
33
+ const falsyCapableMembersOf = (context, type) => membersOf(context, type).filter((member) => {
34
+ const shape = context.table.get(member).shape;
35
+ if (shape.kind === 'literal')
36
+ return true;
37
+ return shape.kind === 'primitive' && shape.primitive !== 'symbol' && shape.primitive !== 'never' && shape.primitive !== 'void';
38
+ });
20
39
  /**
21
40
  * The receiver an optional chain (`value?.member`) reads once the guard has
22
41
  * passed: the cell less its absence.
@@ -40,12 +59,8 @@ export const guardedReceiverTypeOf = (context, receiver) => {
40
59
  const present = presentPartOf(context, cited);
41
60
  if (present === null || present === checkerPresent)
42
61
  return checkerPresent;
43
- const membersOf = (id) => {
44
- const shape = context.table.get(id).shape;
45
- return shape.kind === 'union' ? shape.members : [id];
46
- };
47
- const held = membersOf(present);
48
- const declared = membersOf(checkerPresent);
62
+ const held = membersOf(context, present);
63
+ const declared = membersOf(context, checkerPresent);
49
64
  return held.length > declared.length && declared.every((member) => held.includes(member)) ? present : checkerPresent;
50
65
  };
51
66
  /**
@@ -138,9 +153,32 @@ export const logicalMergeTypeOf = (context, operator, node, leftType, rightType)
138
153
  // -- an object-typed guard, `obj && obj.x` -- the expression IS the right
139
154
  // operand, and saying so is what keeps a class carrier from being unioned
140
155
  // into a numeric answer.
156
+ //
157
+ // A left operand a census widened by absence alone -- `dict[key] && x`,
158
+ // where the checker says `string` and the read's own carrier is `string |
159
+ // undefined` -- keeps that absence as a falsy arm the checker's left type
160
+ // never had, so the checker's answer for the whole expression (`"" | "x"`)
161
+ // cannot stand: the kept branch would dereference the absent read. The
162
+ // merge then holds the absent members, the present part where the
163
+ // checker's rule finds a falsy arm in it (the whole part, wider but sound,
164
+ // as `||` keeps it), and the right operand. A left the checker sees only
165
+ // through `as any`/`as unknown` states no falsy arms at all, so there the
166
+ // present members that can be falsy are read off the cited type itself.
167
+ const checkerLeft = context.checker.getTypeAtLocation(node.left);
168
+ const absent = absentPartOf(context, leftType);
169
+ const erasedLeft = (checkerLeft.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0;
170
+ if (absent !== null &&
171
+ leftType !== context.types.typeOf(checkerLeft) &&
172
+ (erasedLeft || presentPartOf(context, leftType) === context.types.typeOf(context.checker.getNonNullableType(checkerLeft)))) {
173
+ const present = presentPartOf(context, leftType);
174
+ if (erasedLeft)
175
+ return unionOf(context, [absent, ...(present === null ? [] : falsyCapableMembersOf(context, present)), rightType]);
176
+ const presentKept = keptLeftPartTypeOf(context.checker, '&&', context.checker.getNonNullableType(checkerLeft));
177
+ return unionOf(context, [absent, ...(present !== null && presentKept !== null ? [present] : []), rightType]);
178
+ }
141
179
  if (rightType === context.types.typeOf(context.checker.getTypeAtLocation(node.right)))
142
180
  return null;
143
- const keptType = keptLeftPartTypeOf(context.checker, '&&', context.checker.getTypeAtLocation(node.left));
181
+ const keptType = keptLeftPartTypeOf(context.checker, '&&', checkerLeft);
144
182
  // An `any`/`unknown` guard keeps an arm that states nothing, and a union
145
183
  // built on it states nothing either -- `inferred-logical-result` (`/**
146
184
  // @param {*} value */ value && value.isMarker`) is the measured case: this
@@ -14,3 +14,17 @@ import ts from '#typescript';
14
14
  * operator's own -- and so removable -- or the declaration's, and not.
15
15
  */
16
16
  export declare const excludesNullish: (type: ts.Type) => boolean;
17
+ /** Whether a checker type explicitly has an `undefined` constituent. */
18
+ export declare const includesUndefined: (type: ts.Type) => boolean;
19
+ /** Whether a consumer of this checker type has a home for `undefined`: an explicit `undefined` constituent, or `unknown`/`any`. */
20
+ export declare const holdsUndefined: (type: ts.Type) => boolean;
21
+ /**
22
+ * Whether an expression sits where ECMA-262 turns its value into a BOOLEAN --
23
+ * `ToBoolean` of whatever it evaluated to -- or into a type tag (`typeof`),
24
+ * rather than where the value itself is consumed.
25
+ *
26
+ * These are test positions that can observe an `undefined` no type mentions.
27
+ * Equality with `undefined` is the other direct observation. See
28
+ * `observablyAbsentElementTypeOf` in properties.ts for why the widening is bounded to them.
29
+ */
30
+ export declare const testsItsOperand: (node: ts.Expression) => boolean;
@@ -25,3 +25,59 @@ export const excludesNullish = (type) => {
25
25
  ts.TypeFlags.IndexedAccess;
26
26
  return constituents.every((member) => (member.flags & nullishOrUnproven) === 0);
27
27
  };
28
+ /** Whether a checker type explicitly has an `undefined` constituent. */
29
+ export const includesUndefined = (type) => {
30
+ if ((type.flags & ts.TypeFlags.Undefined) !== 0)
31
+ return true;
32
+ return type.isUnion() && type.types.some(includesUndefined);
33
+ };
34
+ /** Whether a consumer of this checker type has a home for `undefined`: an explicit `undefined` constituent, or `unknown`/`any`. */
35
+ export const holdsUndefined = (type) => (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0 || includesUndefined(type);
36
+ /** Whether `typeof` takes this expression as its operand: it answers `"undefined"` for an absent read without consuming the value (ECMA-262 13.5.3). */
37
+ const typeofTakesItsOperand = (inner, parent) => ts.isTypeOfExpression(parent) && parent.expression === inner;
38
+ /**
39
+ * Whether an expression sits where ECMA-262 turns its value into a BOOLEAN --
40
+ * `ToBoolean` of whatever it evaluated to -- or into a type tag (`typeof`),
41
+ * rather than where the value itself is consumed.
42
+ *
43
+ * These are test positions that can observe an `undefined` no type mentions.
44
+ * Equality with `undefined` is the other direct observation. See
45
+ * `observablyAbsentElementTypeOf` in properties.ts for why the widening is bounded to them.
46
+ */
47
+ export const testsItsOperand = (node) => {
48
+ let inner = node;
49
+ let parent = inner.parent;
50
+ while (parent && ts.isParenthesizedExpression(parent)) {
51
+ inner = parent;
52
+ parent = parent.parent;
53
+ }
54
+ if (!parent)
55
+ return false;
56
+ if (typeofTakesItsOperand(inner, parent))
57
+ return true;
58
+ if (ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent))
59
+ return parent.expression === inner;
60
+ if (ts.isForStatement(parent))
61
+ return parent.condition === inner;
62
+ if (ts.isConditionalExpression(parent))
63
+ return parent.condition === inner;
64
+ if (ts.isPrefixUnaryExpression(parent))
65
+ return parent.operator === ts.SyntaxKind.ExclamationToken;
66
+ if (ts.isBinaryExpression(parent)) {
67
+ const operator = parent.operatorToken.kind;
68
+ const tested = operator === ts.SyntaxKind.AmpersandAmpersandToken ||
69
+ operator === ts.SyntaxKind.BarBarToken ||
70
+ operator === ts.SyntaxKind.QuestionQuestionToken;
71
+ return tested && parent.left === inner;
72
+ }
73
+ // `?.` IS a test of its base, and the one that consumes nothing on the
74
+ // absent branch: ECMA-262 13.3.9.1 evaluates the whole chain to `undefined`
75
+ // without ever performing the `[[Get]]`. `root.children[3]?.value` therefore
76
+ // needs the same widening `if (array[i])` gets -- without it the base's
77
+ // carrier says never-absent, the chain's guard folds to `if (true)`, and
78
+ // `elementAt` aborts on the read the program wrote `?.` precisely to avoid.
79
+ if (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent) || ts.isCallExpression(parent)) {
80
+ return parent.expression === inner && ts.isOptionalChain(parent) && parent.questionDotToken !== undefined;
81
+ }
82
+ return false;
83
+ };
@@ -6,7 +6,7 @@ import { operationId, semanticResultId } from '../../../identity/ids.js';
6
6
  import { normalCompletion, pureEffects, throwingCompletion } from '../../model/operands.js';
7
7
  import { blocked, mintOperationId, mintResult, operand } from './mint.js';
8
8
  import { optionalChainGuardOf, publishesShortCircuit } from './optional-chain.js';
9
- import { excludesNullish } from './nullish.js';
9
+ import { excludesNullish, holdsUndefined, includesUndefined, testsItsOperand } from './nullish.js';
10
10
  import { guardedReceiverTypeOf } from './logical-merge-type.js';
11
11
  import { calleeAwareTypeAt, isStrictContext, logicalAssignmentOperators, sourceForValue, symbolMemberKeyOf } from './shared.js';
12
12
  import { citeExpressionResult } from './references.js';
@@ -466,74 +466,22 @@ const chainValueTypeOf = (context, node) => {
466
466
  return context.table.intern({ kind: 'union', members: [own, context.table.intern({ kind: 'primitive', primitive: 'undefined' })] });
467
467
  };
468
468
  /**
469
- * Whether an expression sits where ECMA-262 turns its value into a BOOLEAN --
470
- * `ToBoolean` of whatever it evaluated to -- rather than where the value
471
- * itself is consumed.
472
- *
473
- * These are test positions that can observe an `undefined` no type mentions.
474
- * Equality with `undefined` is the other direct observation. See
475
- * `observablyAbsentElementTypeOf` for why the widening is bounded to them.
469
+ * A test that observes this value immediately: a condition, `!`, `typeof`,
470
+ * `?.`, the left operand of `&&` / `||` / `??`, or a logical assignment's own guard.
476
471
  */
477
- const testsItsOperand = (node) => {
478
- let inner = node;
479
- let parent = inner.parent;
480
- while (parent && ts.isParenthesizedExpression(parent)) {
481
- inner = parent;
482
- parent = parent.parent;
483
- }
484
- if (!parent)
485
- return false;
486
- if (ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent))
487
- return parent.expression === inner;
488
- if (ts.isForStatement(parent))
489
- return parent.condition === inner;
490
- if (ts.isConditionalExpression(parent))
491
- return parent.condition === inner;
492
- if (ts.isPrefixUnaryExpression(parent))
493
- return parent.operator === ts.SyntaxKind.ExclamationToken;
494
- if (ts.isBinaryExpression(parent)) {
495
- const operator = parent.operatorToken.kind;
496
- const tested = operator === ts.SyntaxKind.AmpersandAmpersandToken ||
497
- operator === ts.SyntaxKind.BarBarToken ||
498
- operator === ts.SyntaxKind.QuestionQuestionToken;
499
- return tested && parent.left === inner;
500
- }
501
- // `?.` IS a test of its base, and the one that consumes nothing on the
502
- // absent branch: ECMA-262 13.3.9.1 evaluates the whole chain to `undefined`
503
- // without ever performing the `[[Get]]`. `root.children[3]?.value` therefore
504
- // needs the same widening `if (array[i])` gets -- without it the base's
505
- // carrier says never-absent, the chain's guard folds to `if (true)`, and
506
- // `elementAt` aborts on the read the program wrote `?.` precisely to avoid.
507
- if (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent) || ts.isCallExpression(parent)) {
508
- return parent.expression === inner && ts.isOptionalChain(parent) && parent.questionDotToken !== undefined;
509
- }
510
- return false;
511
- };
512
- /** A test that consumes this value immediately, including a logical assignment's own guard. */
513
472
  const directlyTestsItsOperand = (node) => {
473
+ if (testsItsOperand(node))
474
+ return true;
514
475
  let inner = node;
515
476
  let parent = inner.parent;
516
477
  while (parent && ts.isParenthesizedExpression(parent)) {
517
478
  inner = parent;
518
479
  parent = parent.parent;
519
480
  }
520
- if (!parent)
521
- return false;
522
- if (ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent))
523
- return parent.expression === inner;
524
- if (ts.isForStatement(parent))
525
- return parent.condition === inner;
526
- if (ts.isConditionalExpression(parent))
527
- return parent.condition === inner;
528
- if (ts.isBinaryExpression(parent) && parent.left === inner)
529
- return logicalAssignmentOperators.has(parent.operatorToken.kind);
530
- return ts.isPrefixUnaryExpression(parent) && parent.operator === ts.SyntaxKind.ExclamationToken;
531
- };
532
- /** Whether a checker type explicitly has an `undefined` constituent. */
533
- const includesUndefined = (type) => {
534
- if ((type.flags & ts.TypeFlags.Undefined) !== 0)
535
- return true;
536
- return type.isUnion() && type.types.some(includesUndefined);
481
+ return (parent !== undefined &&
482
+ ts.isBinaryExpression(parent) &&
483
+ parent.left === inner &&
484
+ logicalAssignmentOperators.has(parent.operatorToken.kind));
537
485
  };
538
486
  /** Whether an equality operation directly compares this expression with `undefined`. */
539
487
  const comparesWithUndefined = (context, node) => {
@@ -602,6 +550,32 @@ const isIndexedObjectFor = (context, type, key, visiting = new Set()) => {
602
550
  * A TUPLE is excluded: its element types are positional facts, and the checker
603
551
  * states out-of-range for one as an error rather than a silent `T`.
604
552
  */
553
+ /**
554
+ * Whether `node` is the value assigned to a local declared without a type:
555
+ * `let node; ... node = this.#children[key]`. The checker reports such a
556
+ * local's declared type as `any` -- the auto type it then narrows by
557
+ * assignment -- so that contextual `any` is no home for `undefined`. The
558
+ * local's cell takes the read's own carrier, and an absence published at the
559
+ * read is dereferenced on the way into it: Hono's RegExpRouter `Node.insert`
560
+ * aborted on every route at its first missing child.
561
+ */
562
+ const assignsAnUntypedLocal = (context, node) => {
563
+ let inner = node;
564
+ let parent = inner.parent;
565
+ while (parent && ts.isParenthesizedExpression(parent)) {
566
+ inner = parent;
567
+ parent = parent.parent;
568
+ }
569
+ if (!parent || !ts.isBinaryExpression(parent) || parent.operatorToken.kind !== ts.SyntaxKind.EqualsToken || parent.right !== inner)
570
+ return false;
571
+ if (!ts.isIdentifier(parent.left))
572
+ return false;
573
+ const declaration = context.checker.getSymbolAtLocation(parent.left)?.valueDeclaration;
574
+ return (declaration !== undefined &&
575
+ ts.isVariableDeclaration(declaration) &&
576
+ declaration.type === undefined &&
577
+ ts.getJSDocType(declaration) === undefined);
578
+ };
605
579
  const observablyAbsentElementTypeOf = (context, node, valueType) => {
606
580
  // The local-binding census connects `const value = array[index]` to a later
607
581
  // direct `value === undefined` observation. Structural array reads normally
@@ -627,7 +601,8 @@ const observablyAbsentElementTypeOf = (context, node, valueType) => {
627
601
  const contextual = context.checker.getContextualType(node);
628
602
  const receiverType = context.types.typeAt(node.expression);
629
603
  const indexedObject = isIndexedObjectFor(context, receiverType, symbol ? 'symbol' : numeric ? 'number' : 'string');
630
- if (((contextual !== undefined && includesUndefined(contextual)) ||
604
+ if (((contextual !== undefined &&
605
+ (includesUndefined(contextual) || (holdsUndefined(contextual) && !assignsAnUntypedLocal(context, node)))) ||
631
606
  comparesWithUndefined(context, node) ||
632
607
  directlyTestsItsOperand(node)) &&
633
608
  indexedObject &&
@@ -1,5 +1,5 @@
1
1
  import ts from '#typescript';
2
- import { type SemanticResultId } from '../../../identity/ids.js';
2
+ import { type SemanticResultId, type StructuralTypeId } from '../../../identity/ids.js';
3
3
  import type { FamilyProducer } from '../contribution.js';
4
4
  import { type OperandSource } from '../../model/operands.js';
5
5
  import type { NamespacePathCensus } from '../namespace-paths.js';
@@ -7,6 +7,13 @@ import type { ArgumentsObjectCensus } from '../arguments-objects.js';
7
7
  import type { IdentityTable } from '../identities.js';
8
8
  import type { ProducerContext } from '../producer-context.js';
9
9
  import type { UnresolvableNameCensus } from '../unresolvable-names.js';
10
+ /**
11
+ * The declared optional carrier a name's read publishes at a use that
12
+ * observes absence (`destinationPreservesDeclaredAbsence`), for an operand
13
+ * citing that read: a merge that re-asked the checker for `value && x` saw
14
+ * the flow-narrowed `T` and dereferenced the cell on its kept branch.
15
+ */
16
+ export declare const declaredAbsenceTypeAt: (context: ProducerContext, node: ts.Identifier) => StructuralTypeId | null;
10
17
  export type ExpressionCitation = {
11
18
  readonly kind: 'source';
12
19
  readonly source: OperandSource;
@@ -3,6 +3,7 @@ import { genericClassAliasTargetSymbol } from '../../class-alias.js';
3
3
  import { isScriptGlobalObjectPropertyDeclaration } from '../script-global-redefinition.js';
4
4
  import { enclosingCallIfCallee, flowNarrowsType, unwrapErasedExpression } from './erasure.js';
5
5
  import { publishesShortCircuit } from './optional-chain.js';
6
+ import { holdsUndefined, includesUndefined, testsItsOperand } from './nullish.js';
6
7
  import { operationId, regionId, semanticResultId } from '../../../identity/ids.js';
7
8
  import { normalCompletion, pureEffects, throwingCompletion } from '../../model/operands.js';
8
9
  import { familyOf, isClassElementNameEvaluation } from '../census.js';
@@ -37,17 +38,11 @@ const literalConstantOf = (expression) => {
37
38
  return { text: 'undefined', literal: 'undefined' };
38
39
  return null;
39
40
  };
40
- /** Whether a checker type explicitly has an `undefined` constituent. */
41
- const includesUndefined = (type) => {
42
- if ((type.flags & ts.TypeFlags.Undefined) !== 0)
43
- return true;
44
- return type.isUnion() && type.types.some(includesUndefined);
45
- };
46
41
  /**
47
- * Whether this expression is an equality operand or `instanceof`'s left
48
- * operand. Both answer for `undefined` without reading it: IsStrictlyEqual and
49
- * IsLooselyEqual compare it, and OrdinaryHasInstance returns false for a
50
- * non-object.
42
+ * Whether this expression is an equality operand, `instanceof`'s left
43
+ * operand, or `typeof`'s operand. All answer for `undefined` without reading
44
+ * it: IsStrictlyEqual and IsLooselyEqual compare it, OrdinaryHasInstance
45
+ * returns false for a non-object, and `typeof` answers `"undefined"`.
51
46
  */
52
47
  const comparesItsOperand = (node) => {
53
48
  let inner = node;
@@ -56,7 +51,11 @@ const comparesItsOperand = (node) => {
56
51
  inner = parent;
57
52
  parent = parent.parent;
58
53
  }
59
- if (!parent || !ts.isBinaryExpression(parent))
54
+ if (!parent)
55
+ return false;
56
+ if (ts.isTypeOfExpression(parent))
57
+ return parent.expression === inner;
58
+ if (!ts.isBinaryExpression(parent))
60
59
  return false;
61
60
  const operator = parent.operatorToken.kind;
62
61
  if (operator === ts.SyntaxKind.InstanceOfKeyword)
@@ -72,17 +71,18 @@ const comparesItsOperand = (node) => {
72
71
  * dictionary[key]` to `T` when `noUncheckedIndexedAccess` is off, because its
73
72
  * checker type for the initializer omits the missing-key `undefined`. The
74
73
  * property producer restores that absence and the cell therefore physically
75
- * holds `Optional<T>`; dereferencing it at a later optional return or
76
- * `!== undefined` test would discard the very absence the producer recovered.
77
- * An unannotated local has the same cell when the local-binding census
78
- * restored the absence from a later test (`observedIndexedAbsence`), and the
79
- * checker types its other reads `T` just the same.
74
+ * holds `Optional<T>`; dereferencing it at a later optional return,
75
+ * `!== undefined` test or `if (value)` would discard the very absence the
76
+ * producer recovered. An unannotated local has the same cell when the
77
+ * local-binding census restored the absence from a later test
78
+ * (`observedIndexedAbsence`), and the checker types its other reads `T` just
79
+ * the same.
80
80
  *
81
81
  * This does not suppress ordinary control-flow narrowing: only a use whose
82
82
  * contextual destination itself admits `undefined`, or which compares it
83
- * (`comparesItsOperand`), keeps the declaration's stated carrier. A use that
84
- * requires `T` continues to use the checker's narrowed answer and its existing
85
- * presence proof/conversion.
83
+ * (`comparesItsOperand`) or tests it (`testsItsOperand`), keeps the
84
+ * declaration's stated carrier. A use that requires `T` continues to use the
85
+ * checker's narrowed answer and its existing presence proof/conversion.
86
86
  */
87
87
  const destinationPreservesDeclaredAbsence = (context, node, declaration) => {
88
88
  if (!declaration || !ts.isVariableDeclaration(declaration))
@@ -93,10 +93,20 @@ const destinationPreservesDeclaredAbsence = (context, node, declaration) => {
93
93
  if (!declared || !includesUndefined(declared))
94
94
  return null;
95
95
  const contextual = context.checker.getContextualType(node);
96
- if ((contextual === undefined || !includesUndefined(contextual)) && !comparesItsOperand(node))
96
+ if ((contextual === undefined || !holdsUndefined(contextual)) && !comparesItsOperand(node) && !testsItsOperand(node))
97
97
  return null;
98
98
  return context.types.typeAt(declaration);
99
99
  };
100
+ /**
101
+ * The declared optional carrier a name's read publishes at a use that
102
+ * observes absence (`destinationPreservesDeclaredAbsence`), for an operand
103
+ * citing that read: a merge that re-asked the checker for `value && x` saw
104
+ * the flow-narrowed `T` and dereferenced the cell on its kept branch.
105
+ */
106
+ export const declaredAbsenceTypeAt = (context, node) => {
107
+ const symbol = valueSymbolAt(context.checker, node, context.unresolvableNames.hostProvidedNames);
108
+ return destinationPreservesDeclaredAbsence(context, node, symbol ? context.identities.valueDeclarationOfSymbol(symbol) : null);
109
+ };
100
110
  /**
101
111
  * Cite the result an expression's own family producer publishes for it, without
102
112
  * minting anything: `operationId`/`semanticResultId` are pure, so recomputing
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.46",
3
+ "version": "1.0.48",
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": {