@geastack/compiler 1.0.44 → 1.0.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import ts from '#typescript';
2
2
  import { inheritedAccessorOfAssignment } from '../inherited-accessor.js';
3
- import { annotationStatesNothing, containsUnstatedPosition, derivedExpressionType, disjointUnionMembersOf, exactEmptyObjectLiteralType, indexedTypeOf, explicitThisCallReturnType, overloadInvariantReturnTypeAt, joinOfWrites, jsDocTypeStatesNothing, literalMemberNameOf, narrowsOnlyUnstatedPositions, memberTypeOf, objectAssignTargetType, unwrapExplicitThisCall } from './derived-expression-type.js';
3
+ import { annotationStatesNothing, containsUnstatedPosition, derivedExpressionType, disjointUnionMembersOf, exactEmptyObjectLiteralType, indexedTypeOf, isGlobalObjectConstructor, explicitThisCallReturnType, overloadInvariantReturnTypeAt, joinOfWrites, jsDocTypeStatesNothing, literalMemberNameOf, narrowsOnlyUnstatedPositions, memberTypeOf, objectAssignTargetType, unwrapExplicitThisCall } from './derived-expression-type.js';
4
4
  import { carriesUnsubstitutedGeneric, emptyParameterBindingCensus } from './parameter-bindings.js';
5
5
  import { emptyCollectionBindingCensus } from './collection-bindings.js';
6
6
  import { classFamilyMemberReadTypeOf } from './flow/class-family-member-read.js';
@@ -8,19 +8,22 @@ import { createCensusComputedKeysOf } from './host-mutation-computed-keys.js';
8
8
  import { closedCallableAuthorityOf } from './flow/callable-reach.js';
9
9
  import { argumentsObjectUsesAt } from './arguments-objects.js';
10
10
  import { deferredIntrinsicProtocolLedgerOf } from './deferred-intrinsic-protocols.js';
11
- import { forEachReachableStatement } from './reachability.js';
11
+ import { forEachReachableStatement, nodeIsReachable } from './reachability.js';
12
12
  import { censusRefusal } from './census-refusal.js';
13
13
  import { NullableMemo } from './nullable-memo.js';
14
+ import { readsStatedDynamicValue } from './stated-dynamic-value.js';
14
15
  /** A census that binds nothing, for callers that state no program. */
15
16
  export const emptyFieldBindingCensus = {
16
17
  typeAt: () => null,
17
18
  unionArmsAt: () => null,
18
19
  statedTypeAt: () => null,
19
20
  boundCount: 0,
21
+ widenedCount: 0,
20
22
  refusals: [],
21
23
  refusalOf: () => null
22
24
  };
23
25
  const WIDENED = process.env['GEA_FLOW_WIDE'] === '1';
26
+ const WIDEN_DEBUG = process.env['GEA_WIDEN_DEBUG'] === '1';
24
27
  const isAnyType = (type) => (type.flags & ts.TypeFlags.Any) !== 0;
25
28
  const isNullish = (type) => (type.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) !== 0;
26
29
  /** Duplicated from `parameter-bindings.ts` (not exported there): `any`/`void`/`never` say nothing about storage. */
@@ -657,17 +660,20 @@ flow) => {
657
660
  const keySymbol = checker.getSymbolAtLocation(key);
658
661
  return keySymbol && checker.getSymbolAtLocation(read.argumentExpression) === keySymbol ? read.expression : null;
659
662
  };
663
+ /** The classes that declare `symbol`'s storage. */
664
+ const ownersOf = (symbol) => new Set((symbol.declarations ?? []).map((declaration) => ts.findAncestor(declaration, ts.isClassLike)).filter((owner) => owner !== undefined));
665
+ /** Whether a store into an instance of `owner` can land in storage one of `owners` declares. */
666
+ const reachesOwners = (owners, owner) => [...owners].some((declared) => ancestryOf(declared).has(owner) || ancestryOf(owner).has(declared));
667
+ /** Every keyed store, proven or not, that can land in `symbol`'s storage. */
668
+ const keyedStoresInto = (symbol) => {
669
+ const owners = ownersOf(symbol);
670
+ return owners.size === 0 ? [] : keyedStoresNamed(symbol.name).filter((store) => reachesOwners(owners, store.owner));
671
+ };
660
672
  /** Each proven-key store into `symbol`: the type it writes, or `null` where nothing types it. */
661
673
  const keyedWriteTypesOf = (symbol) => {
662
- const owners = new Set((symbol.declarations ?? []).map((declaration) => ts.findAncestor(declaration, ts.isClassLike)).filter((owner) => owner !== undefined));
663
- if (owners.size === 0)
664
- return [];
665
674
  const answers = [];
666
675
  const requirements = [];
667
- for (const store of keyedStoresNamed(symbol.name)) {
668
- const related = [...owners].some((owner) => ancestryOf(owner).has(store.owner) || ancestryOf(store.owner).has(owner));
669
- if (!related)
670
- continue;
676
+ for (const store of keyedStoresInto(symbol)) {
671
677
  requirements.push(...store.requirements);
672
678
  const source = enumeratedSourceOf(store.value, store.key);
673
679
  if (source) {
@@ -1301,15 +1307,607 @@ flow) => {
1301
1307
  nodeMemo.set(node, answer);
1302
1308
  return answer;
1303
1309
  };
1310
+ /**
1311
+ * Storage the program never typed is laid out from what its writes say, and
1312
+ * a write of a value nothing types says nothing -- yet it stores whatever
1313
+ * the value is. `this.vertexShader = 'default'` in a constructor and
1314
+ * `this.vertexShader = source.vertexShader` in a `copy(source)` whose
1315
+ * `source` no census can type: the checker answers `string` from the
1316
+ * constructor alone (and the relaxed phase above joins only the writes that
1317
+ * speak), the copy converts its boxed value through a checked unbox, and the
1318
+ * first source without the key aborts where Node stores `undefined`.
1319
+ *
1320
+ * Such a field can hold any value, so it holds `any`. Published through
1321
+ * `statedTypeAt`, which the layout resolver and the member mapper both take
1322
+ * ahead of the checker, so the slot, its writes and every read of it agree.
1323
+ * A field written only with typed values -- including a copy whose source
1324
+ * the parameter census typed -- keeps its narrow carrier. A program that
1325
+ * typed the field (an annotation, a JSDoc tag) keeps its statement.
1326
+ */
1327
+ const statesNothingAbout = (declaration) => {
1328
+ if (isBareFieldDeclaration(checker, declaration))
1329
+ return true;
1330
+ if (!isAssignmentDeclaration(declaration))
1331
+ return false;
1332
+ const jsDocType = ts.getJSDocType(declaration);
1333
+ return !jsDocType || jsDocTypeStatesNothing(checker, jsDocType);
1334
+ };
1335
+ const widenedFields = new Set();
1336
+ /**
1337
+ * The candidate field a member read copies, by declaration: a read through a
1338
+ * receiver only the census typed names the instance type's own property
1339
+ * symbol, a different object from the one the writes declared, and that one
1340
+ * was never resolved -- `this.text = source.text` with `source` bound to
1341
+ * the class itself would otherwise read as a value nothing types.
1342
+ */
1343
+ const copiedFieldOf = (read) => {
1344
+ const symbol = memberSymbolAt(read);
1345
+ if (!symbol)
1346
+ return null;
1347
+ if (candidateSymbols.has(symbol) || statedFieldSymbols.has(symbol))
1348
+ return symbol;
1349
+ const first = symbol.declarations?.[0];
1350
+ return first === undefined ? null : (candidateByDeclaration().get(first) ?? null);
1351
+ };
1352
+ let candidatesByDeclaration;
1353
+ const candidateByDeclaration = () => {
1354
+ if (candidatesByDeclaration)
1355
+ return candidatesByDeclaration;
1356
+ candidatesByDeclaration = new Map();
1357
+ for (const symbol of [...candidateSymbols, ...statedFieldSymbols])
1358
+ for (const declaration of symbol.declarations ?? [])
1359
+ candidatesByDeclaration.set(declaration, symbol);
1360
+ return candidatesByDeclaration;
1361
+ };
1362
+ const readsWidenedField = (value) => {
1363
+ const unwrapped = unwrapParens(value);
1364
+ if (ts.isPropertyAccessExpression(unwrapped)) {
1365
+ const symbol = copiedFieldOf(unwrapped);
1366
+ return symbol !== null && widenedFields.has(symbol);
1367
+ }
1368
+ if (ts.isConditionalExpression(unwrapped))
1369
+ return readsWidenedField(unwrapped.whenTrue) || readsWidenedField(unwrapped.whenFalse);
1370
+ if (ts.isBinaryExpression(unwrapped)) {
1371
+ const operator = unwrapped.operatorToken.kind;
1372
+ if (operator === ts.SyntaxKind.QuestionQuestionToken ||
1373
+ operator === ts.SyntaxKind.BarBarToken ||
1374
+ operator === ts.SyntaxKind.AmpersandAmpersandToken)
1375
+ return readsWidenedField(unwrapped.left) || readsWidenedField(unwrapped.right);
1376
+ }
1377
+ return false;
1378
+ };
1379
+ /**
1380
+ * Whether `source` -- an object a field's value is read out of under
1381
+ * `key` (`null` for a merge or a keyed copy, which reads only the keys the
1382
+ * object holds) -- can hand the field a value nothing types.
1383
+ *
1384
+ * A source the census typed reads that layout, where a member it lacks is
1385
+ * an absence, not an unknown value. A parameter no census typed holds what
1386
+ * its callers pass: it is such a source only when some call site passes an
1387
+ * object nothing types, or a record that lacks `key` or declares it `any`.
1388
+ * Every caller passing a typed object -- a vector, a camera, an options
1389
+ * literal -- leaves the read typed although the parameter itself is boxed.
1390
+ * A class instance is not taken to lack a member a subclass may declare.
1391
+ */
1392
+ const untypedSource = (source, key, depth = 0) => {
1393
+ if (ts.isParameter(source))
1394
+ return parameterSuppliesUntypedSource(source, key, depth);
1395
+ if (readsWidenedField(source))
1396
+ return true;
1397
+ if ((checker.getTypeAtLocation(source).flags & ts.TypeFlags.Any) === 0)
1398
+ return false;
1399
+ if (parameters.statedTypeAt(source) || receiverTypeOf(source))
1400
+ return false;
1401
+ const unwrapped = unwrapParens(source);
1402
+ // An object the checker types `any` is only as untyped as where it came
1403
+ // from: a call's result, a member read, a `const` holding either.
1404
+ if (ts.isCallExpression(unwrapped) || ts.isNewExpression(unwrapped))
1405
+ return callReturnsDynamicValue(unwrapped, depth);
1406
+ if (ts.isPropertyAccessExpression(unwrapped) || ts.isElementAccessExpression(unwrapped))
1407
+ return writesDynamicValue(unwrapped, depth + 1);
1408
+ if (!ts.isIdentifier(unwrapped))
1409
+ return true;
1410
+ const declaration = checker.getSymbolAtLocation(unwrapped)?.valueDeclaration;
1411
+ if (declaration && ts.isParameter(declaration))
1412
+ return parameterSuppliesUntypedSource(declaration, key, depth);
1413
+ if (declaration && ts.isVariableDeclaration(declaration) && parameters.typeAt(declaration))
1414
+ return false;
1415
+ if (declaration &&
1416
+ ts.isVariableDeclaration(declaration) &&
1417
+ declaration.initializer &&
1418
+ (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) !== 0 &&
1419
+ depth <= 8)
1420
+ return untypedSource(declaration.initializer, key, depth + 1);
1421
+ return true;
1422
+ };
1423
+ /** The values a parameter receives: its default, its call sites' arguments, and its body's own assignments to it. */
1424
+ const valuesReceivedBy = (parameter) => {
1425
+ const symbol = ts.isIdentifier(parameter.name) ? checker.getSymbolAtLocation(parameter.name) : undefined;
1426
+ const received = parameter.initializer ? [parameter.initializer] : [];
1427
+ for (const write of symbol ? flow.writesToSymbol(symbol) : [])
1428
+ if (write.value !== null &&
1429
+ write.slot === 'whole' &&
1430
+ (write.edge === 'call-argument' ||
1431
+ write.edge === 'super-argument' ||
1432
+ write.edge === 'identifier-assignment' ||
1433
+ write.edge === 'logical-assignment'))
1434
+ received.push(write.value);
1435
+ return received;
1436
+ };
1437
+ /** Whether a typed object of `type` can answer `key` with an absence or an `any`. */
1438
+ const typedSourceLeavesKeyUntyped = (type, key, at) => {
1439
+ const holder = checker.getNonNullableType(type);
1440
+ const arms = holder.isUnion() ? holder.types : [holder];
1441
+ return arms.some((arm) => {
1442
+ if ((arm.flags & ts.TypeFlags.Object) === 0)
1443
+ return false;
1444
+ const member = checker.getPropertyOfType(arm, key);
1445
+ if (!member) {
1446
+ if (isClassInstanceType(arm))
1447
+ return false;
1448
+ const index = checker.getIndexTypeOfType(arm, ts.IndexKind.String);
1449
+ return index === undefined || (index.flags & ts.TypeFlags.Any) !== 0;
1450
+ }
1451
+ const declaration = member.valueDeclaration;
1452
+ if (declaration && ts.isPropertyAssignment(declaration))
1453
+ return writesDynamicValue(declaration.initializer);
1454
+ if (declaration && ts.isShorthandPropertyAssignment(declaration))
1455
+ return writesDynamicValue(declaration.name);
1456
+ if (declaration && ts.isBinaryExpression(declaration))
1457
+ return false;
1458
+ return (checker.getTypeOfSymbolAtLocation(member, at).flags & ts.TypeFlags.Any) !== 0;
1459
+ });
1460
+ };
1461
+ const visitingSourceParameters = new Set();
1462
+ const parameterSuppliesUntypedSource = (parameter, key, depth) => {
1463
+ if (parameters.typeAt(parameter))
1464
+ return false;
1465
+ // A destructured parameter names no slot the flow index files call-site
1466
+ // arguments against, so its callers cannot be asked: its own type is the
1467
+ // pattern's implied record of `any` members, and that is what it supplies.
1468
+ if (!ts.isIdentifier(parameter.name))
1469
+ return true;
1470
+ if (depth > 8 || visitingSourceParameters.has(parameter))
1471
+ return false;
1472
+ visitingSourceParameters.add(parameter);
1473
+ try {
1474
+ return valuesReceivedBy(parameter).some((value) => {
1475
+ if (untypedSource(value, key, depth + 1))
1476
+ return true;
1477
+ if (key === null)
1478
+ return false;
1479
+ const type = knownOrResolve(value);
1480
+ return type !== null && typedSourceLeavesKeyUntyped(type, key, value);
1481
+ });
1482
+ }
1483
+ finally {
1484
+ visitingSourceParameters.delete(parameter);
1485
+ }
1486
+ };
1487
+ /**
1488
+ * A member read off a receiver the census typed, whose own type for the
1489
+ * member is `any`: an index signature of `any` (`Record<string, any>`),
1490
+ * a member a statement declares `any`, or an object literal's member
1491
+ * filled with a dynamic value. The layout knows the receiver and not what
1492
+ * the member holds. A member the receiver lacks is an absence, and a
1493
+ * literal's member holds what its initializer does.
1494
+ */
1495
+ const readsDeclaredDynamicMember = (read, depth) => {
1496
+ const receiver = receiverTypeOf(read.expression);
1497
+ if (!receiver)
1498
+ return false;
1499
+ const holder = checker.getNonNullableType(receiver);
1500
+ const key = ts.isPropertyAccessExpression(read) ? read.name.text : literalMemberNameOf(read);
1501
+ const isAny = (type) => type !== undefined && (type.flags & ts.TypeFlags.Any) !== 0;
1502
+ if (key === null) {
1503
+ const keyType = ts.isElementAccessExpression(read) ? checker.getTypeAtLocation(read.argumentExpression) : undefined;
1504
+ const numeric = keyType !== undefined && (keyType.flags & ts.TypeFlags.NumberLike) !== 0;
1505
+ return isAny(checker.getIndexTypeOfType(holder, numeric ? ts.IndexKind.Number : ts.IndexKind.String) ?? undefined);
1506
+ }
1507
+ const member = checker.getPropertyOfType(holder, key);
1508
+ if (!member)
1509
+ return isAny(checker.getIndexTypeOfType(holder, ts.IndexKind.String) ?? undefined);
1510
+ const declaration = member.valueDeclaration;
1511
+ if (declaration && ts.isPropertyAssignment(declaration))
1512
+ return writesDynamicValue(declaration.initializer, depth + 1);
1513
+ if (declaration && ts.isShorthandPropertyAssignment(declaration))
1514
+ return writesDynamicValue(declaration.name, depth + 1);
1515
+ if (declaration && ts.isBinaryExpression(declaration))
1516
+ return false;
1517
+ return isAny(checker.getTypeOfSymbolAtLocation(member, read));
1518
+ };
1519
+ /** The object a binding element destructures, when the pattern is one level deep. */
1520
+ const destructuredSourceOf = (element) => {
1521
+ if (element.dotDotDotToken || !ts.isObjectBindingPattern(element.parent))
1522
+ return null;
1523
+ const holder = element.parent.parent;
1524
+ if (ts.isParameter(holder))
1525
+ return holder;
1526
+ return ts.isVariableDeclaration(holder) && holder.initializer ? holder.initializer : null;
1527
+ };
1528
+ /** Whether `value` reaches its field as an untyped dynamic value, whatever it holds. */
1529
+ const writesDynamicValue = (value, depth = 0) => {
1530
+ if (depth > 8)
1531
+ return false;
1532
+ if (readsWidenedField(value))
1533
+ return true;
1534
+ if ((checker.getTypeAtLocation(value).flags & ts.TypeFlags.Any) === 0)
1535
+ return false;
1536
+ const unwrapped = unwrapParens(value);
1537
+ // A copy out of another candidate field holds what that field holds:
1538
+ // dynamic exactly when that field is widened, which the fixpoint decides.
1539
+ if (ts.isPropertyAccessExpression(unwrapped) && copiedFieldOf(unwrapped))
1540
+ return false;
1541
+ if (parameters.statedTypeAt(value) || exactEmptyObjectLiteralType(checker, value))
1542
+ return false;
1543
+ // The checker's `any` for a conditional or a logical fallback is only as
1544
+ // dynamic as its operands: `opts ? opts.deduplicate : null` or
1545
+ // `opts.pageOffset || 0` over an `opts` the census typed stores that
1546
+ // record's member, an absence, or the literal.
1547
+ if (ts.isConditionalExpression(unwrapped))
1548
+ return writesDynamicValue(unwrapped.whenTrue, depth + 1) || writesDynamicValue(unwrapped.whenFalse, depth + 1);
1549
+ if (ts.isBinaryExpression(unwrapped)) {
1550
+ const operator = unwrapped.operatorToken.kind;
1551
+ if (operator === ts.SyntaxKind.QuestionQuestionToken ||
1552
+ operator === ts.SyntaxKind.BarBarToken ||
1553
+ operator === ts.SyntaxKind.AmpersandAmpersandToken)
1554
+ return writesDynamicValue(unwrapped.left, depth + 1) || writesDynamicValue(unwrapped.right, depth + 1);
1555
+ }
1556
+ // A member read out of an untyped object hands the field whatever the
1557
+ // object holds: `source.label`, `values[ key ]`, a binding destructured
1558
+ // from one, or a `const` holding one. Off a typed receiver it is dynamic
1559
+ // only where the receiver declares the member `any`.
1560
+ if (ts.isPropertyAccessExpression(unwrapped) || ts.isElementAccessExpression(unwrapped)) {
1561
+ if (resolveExpr(value) !== null)
1562
+ return false;
1563
+ const key = ts.isPropertyAccessExpression(unwrapped) ? unwrapped.name.text : literalMemberNameOf(unwrapped);
1564
+ return untypedSource(unwrapped.expression, key, depth) || readsDeclaredDynamicMember(unwrapped, depth);
1565
+ }
1566
+ if (ts.isCallExpression(unwrapped) || ts.isNewExpression(unwrapped))
1567
+ return callReturnsDynamicValue(unwrapped, depth);
1568
+ if (!ts.isIdentifier(unwrapped))
1569
+ return false;
1570
+ const declaration = checker.getSymbolAtLocation(unwrapped)?.valueDeclaration;
1571
+ if (declaration && ts.isParameter(declaration))
1572
+ return parameterReceivesDynamicValue(declaration, depth);
1573
+ if (declaration && ts.isBindingElement(declaration)) {
1574
+ const source = destructuredSourceOf(declaration);
1575
+ const name = declaration.propertyName ?? declaration.name;
1576
+ const key = ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name) ? name.text : null;
1577
+ return source !== null && untypedSource(source, key, depth);
1578
+ }
1579
+ if (!declaration || !ts.isVariableDeclaration(declaration) || !declaration.initializer || !ts.isIdentifier(declaration.name))
1580
+ return false;
1581
+ if ((ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) === 0)
1582
+ return false;
1583
+ return writesDynamicValue(declaration.initializer, depth + 1);
1584
+ };
1585
+ /**
1586
+ * A parameter no census typed holds what its callers pass, and what its own
1587
+ * body assigns it: dynamic only where one of those is. Every caller passing
1588
+ * a typed value -- a vector's `set( x, y, z )` called with numbers and with
1589
+ * a typed record's members -- leaves the field it fills native, although
1590
+ * the parameter itself is boxed. A parameter that reaches itself (a
1591
+ * recursive call forwarding it) adds nothing.
1592
+ */
1593
+ const visitingParameters = new Set();
1594
+ const parameterReceivesDynamicValue = (parameter, depth) => {
1595
+ if (parameters.typeAt(parameter) || visitingParameters.has(parameter) || !ts.isIdentifier(parameter.name))
1596
+ return false;
1597
+ const symbol = checker.getSymbolAtLocation(parameter.name);
1598
+ if (!symbol)
1599
+ return false;
1600
+ visitingParameters.add(parameter);
1601
+ try {
1602
+ const dynamic = valuesReceivedBy(parameter).find((value) => writesDynamicValue(value, depth + 1));
1603
+ if (dynamic && WIDEN_DEBUG) {
1604
+ const file = dynamic.getSourceFile();
1605
+ const line = file.getLineAndCharacterOfPosition(dynamic.getStart()).line + 1;
1606
+ process.stderr.write(`[WIDEN-ARG] ${parameter.name.getText()} <- ${file.fileName}:${line} ${dynamic.getText().replace(/\s+/g, ' ').slice(0, 100)}\n`);
1607
+ }
1608
+ return dynamic !== undefined;
1609
+ }
1610
+ finally {
1611
+ visitingParameters.delete(parameter);
1612
+ }
1613
+ };
1614
+ /**
1615
+ * A call the checker types `any` and no census resolved: a host function
1616
+ * declared to return `any` (`JSON.parse`) or a callee nothing names
1617
+ * returns whatever it produces; a function of the program returns what its
1618
+ * `return` statements do.
1619
+ */
1620
+ const visitingCallees = new Set();
1621
+ const isGlobalObjectCreate = (call) => {
1622
+ const target = call.expression;
1623
+ return (ts.isCallExpression(call) &&
1624
+ ts.isPropertyAccessExpression(target) &&
1625
+ target.name.text === 'create' &&
1626
+ isGlobalObjectConstructor(checker, target.expression, checker.getTypeAtLocation(target.expression)));
1627
+ };
1628
+ /**
1629
+ * `attribute.getX( index )` where `attribute` is a parameter no census
1630
+ * typed: the checker names no callee, but each call site passes an object
1631
+ * the census types, and the method that object declares returns what its
1632
+ * own `return` statements do. A receiver nothing types at some call site
1633
+ * makes the result dynamic; any other receiver is asked through the
1634
+ * census's own type for it, and one the census cannot type is no evidence.
1635
+ * A call that is not a method call returns whatever it produces.
1636
+ */
1637
+ const methodOfUntypedReceiverReturnsDynamicValue = (call, depth) => {
1638
+ const target = unwrapParens(call.expression);
1639
+ if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(target))
1640
+ return true;
1641
+ const receiver = unwrapParens(target.expression);
1642
+ const declaration = ts.isIdentifier(receiver) ? checker.getSymbolAtLocation(receiver)?.valueDeclaration : undefined;
1643
+ const isUntypedParameter = declaration !== undefined && ts.isParameter(declaration) && !parameters.typeAt(declaration);
1644
+ if (depth > 8)
1645
+ return false;
1646
+ if (!isUntypedParameter) {
1647
+ // Any other receiver: the census's own type for it, when it has one.
1648
+ if (untypedSource(receiver, null, depth + 1))
1649
+ return true;
1650
+ const type = knownOrResolve(receiver);
1651
+ return type !== null && methodOfTypeReturnsDynamicValue(type, target.name.text, call, depth);
1652
+ }
1653
+ const parameter = declaration;
1654
+ if (visitingSourceParameters.has(parameter))
1655
+ return false;
1656
+ visitingSourceParameters.add(parameter);
1657
+ try {
1658
+ return valuesReceivedBy(parameter).some((value) => {
1659
+ if (untypedSource(value, null, depth + 1))
1660
+ return true;
1661
+ const type = knownOrResolve(value);
1662
+ return type !== null && methodOfTypeReturnsDynamicValue(type, target.name.text, call, depth);
1663
+ });
1664
+ }
1665
+ finally {
1666
+ visitingSourceParameters.delete(parameter);
1667
+ }
1668
+ };
1669
+ /** Whether calling `name` on an object of `type` can return a value nothing types. */
1670
+ const methodOfTypeReturnsDynamicValue = (type, name, call, depth) => {
1671
+ const holder = checker.getNonNullableType(type);
1672
+ return (holder.isUnion() ? holder.types : [holder]).some((arm) => {
1673
+ const method = checker.getPropertyOfType(arm, name);
1674
+ const body = method?.valueDeclaration;
1675
+ if (!method || !body)
1676
+ return false;
1677
+ if (body.getSourceFile().isDeclarationFile) {
1678
+ const signatures = checker.getTypeOfSymbolAtLocation(method, call).getCallSignatures();
1679
+ return signatures.some((signature) => (checker.getReturnTypeOfSignature(signature).flags & ts.TypeFlags.Any) !== 0);
1680
+ }
1681
+ return ts.isFunctionLike(body) && functionReturnsDynamicValue(body, depth);
1682
+ });
1683
+ };
1684
+ /** Whether one of a program function's own `return` statements hands back a value nothing types. */
1685
+ const functionReturnsDynamicValue = (callee, depth) => {
1686
+ if (!('body' in callee) || !callee.body)
1687
+ return true;
1688
+ if (visitingCallees.has(callee))
1689
+ return false;
1690
+ visitingCallees.add(callee);
1691
+ try {
1692
+ const body = callee.body;
1693
+ if (!ts.isBlock(body))
1694
+ return writesDynamicValue(body, depth + 1);
1695
+ let dynamic = false;
1696
+ const visit = (node) => {
1697
+ if (dynamic || (node !== body && ts.isFunctionLike(node)))
1698
+ return;
1699
+ if (ts.isReturnStatement(node) && node.expression && writesDynamicValue(node.expression, depth + 1))
1700
+ dynamic = true;
1701
+ else
1702
+ ts.forEachChild(node, visit);
1703
+ };
1704
+ visit(body);
1705
+ return dynamic;
1706
+ }
1707
+ finally {
1708
+ visitingCallees.delete(callee);
1709
+ }
1710
+ };
1711
+ /**
1712
+ * `entries.get( key )` on a Map or Set the program built without type
1713
+ * arguments: the checker answers `any`, but the collection holds what the
1714
+ * program's own `set`/`add` calls put in it -- dynamic only where one of
1715
+ * those values is.
1716
+ */
1717
+ const collectionReadIsTyped = (call, depth) => {
1718
+ const target = unwrapParens(call.expression);
1719
+ if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(target) || target.name.text !== 'get')
1720
+ return false;
1721
+ const receiver = unwrapParens(target.expression);
1722
+ const symbol = ts.isIdentifier(receiver)
1723
+ ? checker.getSymbolAtLocation(receiver)
1724
+ : ts.isPropertyAccessExpression(receiver)
1725
+ ? memberSymbolAt(receiver)
1726
+ : null;
1727
+ if (!symbol)
1728
+ return false;
1729
+ const values = flow.writesToSymbol(symbol).filter((write) => write.edge === 'collection-value' && write.value !== null);
1730
+ return values.length > 0 && !values.some((write) => writesDynamicValue(write.value, depth + 1));
1731
+ };
1732
+ const callReturnsDynamicValue = (call, depth) => {
1733
+ if (resolveExpr(call) !== null)
1734
+ return false;
1735
+ const callee = checker.getResolvedSignature(call)?.getDeclaration();
1736
+ if (!callee)
1737
+ return methodOfUntypedReceiverReturnsDynamicValue(call, depth);
1738
+ // `Object.create( proto )` is declared to return `any`, but it builds a
1739
+ // fresh object holding none of the program's values; storing it is the
1740
+ // ordinary conversion of an empty object into the field's carrier.
1741
+ if (callee.getSourceFile().isDeclarationFile)
1742
+ return !isGlobalObjectCreate(call) && !collectionReadIsTyped(call, depth);
1743
+ return !ts.isFunctionLike(callee) || functionReturnsDynamicValue(callee, depth);
1744
+ };
1745
+ const dynamicWriteEvidence = (write) => write.slot === 'whole' &&
1746
+ write.value !== null &&
1747
+ (write.edge === 'property-assignment' ||
1748
+ write.edge === 'class-field-initializer' ||
1749
+ write.edge === 'index-assignment' ||
1750
+ write.edge === 'logical-assignment' ||
1751
+ write.edge === 'destructuring-default');
1752
+ /**
1753
+ * The object a destructuring ASSIGNMENT target is filled from, when the
1754
+ * pattern is the left side of the `=` itself: `({ label: this.label } = source)`.
1755
+ */
1756
+ const assignedPatternSourceOf = (target) => {
1757
+ let node = target;
1758
+ // `this.label = fallback` inside the pattern is the target with a default.
1759
+ if (ts.isBinaryExpression(node.parent) && node.parent.left === node)
1760
+ node = node.parent;
1761
+ const property = node.parent;
1762
+ if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property))
1763
+ return null;
1764
+ const pattern = property.parent;
1765
+ const assignment = pattern.parent;
1766
+ if (!ts.isObjectLiteralExpression(pattern) || !ts.isBinaryExpression(assignment))
1767
+ return null;
1768
+ return assignment.left === pattern && assignment.operatorToken.kind === ts.SyntaxKind.EqualsToken ? assignment.right : null;
1769
+ };
1770
+ /**
1771
+ * `Object.assign(target, source)` with an untyped `source` copies whatever
1772
+ * keys it holds onto `target`: a write of an unknown value into every field
1773
+ * of each class `target` may be an instance of.
1774
+ */
1775
+ let untypedMerges;
1776
+ const untypedMergeInto = (symbol) => {
1777
+ untypedMerges ??= flow.allWrites.flatMap((write) => {
1778
+ if (write.edge !== 'object-assign' || !write.naming || !write.value || !untypedSource(write.value, null))
1779
+ return [];
1780
+ const owners = instanceClassesOf(write.naming);
1781
+ return owners.length > 0 ? [{ owners, site: write.site }] : [];
1782
+ });
1783
+ if (untypedMerges.length === 0)
1784
+ return null;
1785
+ const owners = ownersOf(symbol);
1786
+ return untypedMerges.find((merge) => merge.owners.some((owner) => reachesOwners(owners, owner)))?.site ?? null;
1787
+ };
1788
+ /** The first write that stores a value nothing types into `symbol`'s storage, or `null`. */
1789
+ const dynamicWriteInto = (symbol) => {
1790
+ // A JavaScript field's declarations are its writes, listed whether or not
1791
+ // the program runs them; the flow index already leaves pruned code out.
1792
+ for (const declaration of symbol.declarations ?? [])
1793
+ if (ts.isBinaryExpression(declaration) && nodeIsReachable(reachable, declaration) && writesDynamicValue(declaration.right))
1794
+ return declaration;
1795
+ for (const write of flow.writesToSymbol(symbol)) {
1796
+ if (dynamicWriteEvidence(write) && writesDynamicValue(write.value))
1797
+ return write.site;
1798
+ if (write.edge !== 'destructuring' || write.slot !== 'whole' || !write.naming)
1799
+ continue;
1800
+ const source = assignedPatternSourceOf(write.naming);
1801
+ const property = write.naming.parent;
1802
+ const name = ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)
1803
+ ? property.name
1804
+ : ts.isBinaryExpression(property) &&
1805
+ (ts.isPropertyAssignment(property.parent) || ts.isShorthandPropertyAssignment(property.parent))
1806
+ ? property.parent.name
1807
+ : undefined;
1808
+ const key = name && (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) ? name.text : null;
1809
+ if (source && untypedSource(source, key))
1810
+ return write.site;
1811
+ }
1812
+ for (const store of keyedStoresInto(symbol)) {
1813
+ const source = enumeratedSourceOf(store.value, store.key);
1814
+ if (source ? untypedSource(source, null) : writesDynamicValue(store.value))
1815
+ return store.value;
1816
+ }
1817
+ return untypedMergeInto(symbol);
1818
+ };
1819
+ const widenDynamicallyWrittenFields = () => {
1820
+ // A field the program typed is held to that statement everywhere the
1821
+ // checker relates a value to it -- and an `any` value is related to
1822
+ // nothing: `this.label = document.label` off an `any`-valued record
1823
+ // stores whatever the document held. Such a field is widened exactly as
1824
+ // an untyped one is, from the same evidence; a typed field every write of
1825
+ // which is typed keeps its native carrier.
1826
+ const unstated = [
1827
+ ...[...candidateSymbols].filter((symbol) => (symbol.declarations ?? []).every(statesNothingAbout)),
1828
+ ...statedFieldSymbols
1829
+ ];
1830
+ if (unstated.length === 0)
1831
+ return;
1832
+ // Asked again of the settled census: a write read during the strict phase
1833
+ // may have been silent only because the field it reads was still being
1834
+ // resolved -- `this.text = source.text` copying another instance's own.
1835
+ nodeMemo.clear();
1836
+ for (let changed = true; changed;) {
1837
+ changed = false;
1838
+ for (const symbol of unstated) {
1839
+ if (widenedFields.has(symbol))
1840
+ continue;
1841
+ const evidence = dynamicWriteInto(symbol);
1842
+ if (!evidence)
1843
+ continue;
1844
+ widenedFields.add(symbol);
1845
+ changed = true;
1846
+ // `GEA_WIDEN_DEBUG=1` names each widened field and the write that
1847
+ // widened it -- the one fact a moved carrier needs to be judged by.
1848
+ if (WIDEN_DEBUG) {
1849
+ const file = evidence.getSourceFile();
1850
+ const line = file.getLineAndCharacterOfPosition(evidence.getStart()).line + 1;
1851
+ const owner = ownersOf(symbol).values().next().value?.name?.text ?? '?';
1852
+ const kind = statedFieldSymbols.has(symbol) ? 'stated' : 'inferred';
1853
+ process.stderr.write(`[WIDEN] ${owner}.${symbol.name} ${kind} <- ${file.fileName}:${line} ${evidence.getText().replace(/\s+/g, ' ').slice(0, 120)}\n`);
1854
+ }
1855
+ }
1856
+ }
1857
+ if (widenedFields.size === 0)
1858
+ return;
1859
+ const dynamic = checker.getAnyType();
1860
+ for (const symbol of widenedFields) {
1861
+ // A field the checker already types `any` (or `Object`) and this census
1862
+ // never narrowed is laid out dynamic as it is: stating it again would
1863
+ // change nothing about its storage and would retype every read of it,
1864
+ // re-laying out typed cells the program fills from those reads.
1865
+ const anchor = symbol.declarations?.[0];
1866
+ const checkerAnswer = anchor ? checker.getTypeOfSymbolAtLocation(symbol, anchor) : null;
1867
+ const alreadyDynamic = !bound.has(symbol) &&
1868
+ !unionArms.has(symbol) &&
1869
+ !statedBindings.has(symbol) &&
1870
+ checkerAnswer !== null &&
1871
+ anchor !== undefined &&
1872
+ (isUnusableEvidence(checkerAnswer) || annotationStatesNothing(checker, anchor, checkerAnswer));
1873
+ bound.delete(symbol);
1874
+ unionArms.delete(symbol);
1875
+ refusalOf.set(symbol, 'write-dynamic');
1876
+ if (!alreadyDynamic)
1877
+ state(symbol, dynamic);
1878
+ }
1879
+ nodeMemo.clear();
1880
+ };
1304
1881
  // Enumerate every candidate SYMBOL up front, from every `x.field = expr`
1305
1882
  // write's left-hand side, so `boundCount`/`refusals` reflect the whole
1306
1883
  // program rather than only the nodes some other pass happened to query.
1307
1884
  const candidateSymbols = new Set();
1885
+ /** Class fields the program typed -- an annotation or a JSDoc tag -- that some write in the program assigns. */
1886
+ const statedFieldSymbols = new Set();
1887
+ const statesFieldType = (declaration) => {
1888
+ if (declaration.getSourceFile().isDeclarationFile || isAmbientDeclaration(declaration))
1889
+ return false;
1890
+ if (ts.isPropertyDeclaration(declaration)) {
1891
+ if (!ts.isClassLike(declaration.parent))
1892
+ return false;
1893
+ if (declaration.type)
1894
+ return true;
1895
+ const jsDocType = ts.getJSDocType(declaration);
1896
+ return jsDocType !== undefined && !jsDocTypeStatesNothing(checker, jsDocType);
1897
+ }
1898
+ if (!isAssignmentDeclaration(declaration))
1899
+ return false;
1900
+ const jsDocType = ts.getJSDocType(declaration);
1901
+ return jsDocType !== undefined && !jsDocTypeStatesNothing(checker, jsDocType);
1902
+ };
1308
1903
  const visit = (node) => {
1309
1904
  if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken && ts.isPropertyAccessExpression(node.left)) {
1310
1905
  const symbol = checker.getSymbolAtLocation(node.left);
1311
1906
  if (symbol && isCandidateSymbol(checker, symbol))
1312
1907
  candidateSymbols.add(symbol);
1908
+ const declarations = symbol?.declarations ?? [];
1909
+ if (symbol && declarations.length > 0 && declarations.every(statesFieldType))
1910
+ statedFieldSymbols.add(symbol);
1313
1911
  }
1314
1912
  // A bare `field;` is a candidate whether or not anything writes it -- one
1315
1913
  // nothing writes must be REFUSED rather than absent, or `refusals` stops
@@ -1345,6 +1943,7 @@ flow) => {
1345
1943
  if (bound.size === before)
1346
1944
  break;
1347
1945
  }
1946
+ widenDynamicallyWrittenFields();
1348
1947
  deferredIntrinsicProtocolLedgerOf(flow)?.replace('field-bindings-keyed-stores', [...keyedRequirements].flatMap(([symbol, requirements]) => (bound.has(symbol) ? requirements : [])));
1349
1948
  /**
1350
1949
  * A refusal's `owner` for a field SYMBOL: its own name and where the
@@ -1432,6 +2031,7 @@ flow) => {
1432
2031
  unionArmsAt,
1433
2032
  statedTypeAt,
1434
2033
  boundCount: bound.size + unionArms.size,
2034
+ widenedCount: widenedFields.size,
1435
2035
  refusals,
1436
2036
  refusalOf: (symbol) => refusalOf.get(symbol) ?? null
1437
2037
  };
@@ -1508,17 +2108,73 @@ export const withFieldBindings = (checker, files, reachable, parameters, collect
1508
2108
  return callResultAt(declaration.initializer);
1509
2109
  };
1510
2110
  const held = new NullableMemo();
2111
+ /**
2112
+ * A value read out of a field `widenDynamicallyWrittenFields` widened is
2113
+ * whatever the field holds, and so is a cell initialized from one and
2114
+ * anything read off it: the checker types all of these from the field's
2115
+ * narrow inference, and a slot laid out from that answer would convert the
2116
+ * boxed value through the checked unbox the widening removed from the field.
2117
+ * Asked only once the census widened something.
2118
+ */
2119
+ const dynamic = fields.widenedCount > 0 ? checker.getAnyType() : null;
2120
+ const unstatedCellOf = (node) => {
2121
+ const declaration = ts.isVariableDeclaration(node)
2122
+ ? node
2123
+ : ts.isIdentifier(node) && !ts.isVariableDeclaration(node.parent)
2124
+ ? checker.getSymbolAtLocation(node)?.valueDeclaration
2125
+ : undefined;
2126
+ if (!declaration || !ts.isVariableDeclaration(declaration) || declaration.type || !declaration.initializer)
2127
+ return null;
2128
+ if (!ts.isIdentifier(declaration.name) || ts.getJSDocType(declaration))
2129
+ return null;
2130
+ // A JSDoc tag on the statement types its declaration too: the program
2131
+ // stated what the cell holds.
2132
+ const statement = declaration.parent.parent;
2133
+ if (ts.isVariableStatement(statement) && ts.getJSDocTags(statement).some(ts.isJSDocTypeTag))
2134
+ return null;
2135
+ return declaration;
2136
+ };
2137
+ const checkerAnswersAny = (node) => {
2138
+ const declared = ts.isVariableDeclaration(node) ? checker.getSymbolAtLocation(node.name) : undefined;
2139
+ const type = declared ? checker.getTypeOfSymbolAtLocation(declared, node) : checker.getTypeAtLocation(node);
2140
+ return (type.flags & ts.TypeFlags.Any) !== 0;
2141
+ };
2142
+ const dynamicThrough = (node) => {
2143
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
2144
+ return readsStatedDynamicValue(statedTypeAt, node.expression);
2145
+ if (ts.isCallExpression(node))
2146
+ return ((ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression)) &&
2147
+ readsStatedDynamicValue(statedTypeAt, node.expression.expression));
2148
+ if (ts.isBinaryExpression(node))
2149
+ return (node.operatorToken.kind === ts.SyntaxKind.PlusToken &&
2150
+ (readsStatedDynamicValue(statedTypeAt, node.left) || readsStatedDynamicValue(statedTypeAt, node.right)));
2151
+ const cell = unstatedCellOf(node);
2152
+ return cell !== null && readsStatedDynamicValue(statedTypeAt, cell.initializer);
2153
+ };
1511
2154
  const statedTypeAt = (node) => {
1512
2155
  const answer = own(node);
1513
2156
  if (answer)
1514
2157
  return answer;
1515
- if (ts.isCallExpression(node))
1516
- return memberCallResultAt(node);
1517
- if (!ts.isVariableDeclaration(node) && !ts.isIdentifier(node))
2158
+ const reads = ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node);
2159
+ const sum = ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken;
2160
+ if (!reads && !sum && !ts.isCallExpression(node) && !ts.isVariableDeclaration(node) && !ts.isIdentifier(node))
1518
2161
  return null;
1519
2162
  if (held.has(node))
1520
2163
  return held.get(node) ?? null;
1521
- const result = heldCallResultAt(node);
2164
+ // Placed first so a cell whose initializer reaches back to it answers
2165
+ // nothing rather than looping.
2166
+ held.set(node, null);
2167
+ const result =
2168
+ // Only where the checker types the node: an `any` it already answers is
2169
+ // dynamic as it stands, and restating it would outrank a census that
2170
+ // narrowed it.
2171
+ dynamic && !checkerAnswersAny(node) && dynamicThrough(node)
2172
+ ? dynamic
2173
+ : ts.isCallExpression(node)
2174
+ ? memberCallResultAt(node)
2175
+ : reads
2176
+ ? null
2177
+ : heldCallResultAt(node);
1522
2178
  held.set(node, result);
1523
2179
  return result;
1524
2180
  };