All files / utils OperandTyper.ts

95.72% Statements 403/421
87.58% Branches 402/459
100% Functions 75/75
97.87% Lines 369/377

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603                                                                                                                                  80x                                 80x                           1240x                           16x                               6988x 6988x 1027x   5961x 2144x   3817x 3191x   626x 32x   594x 59x   535x 15x   520x 45x   475x   9x 9x   466x 356x   110x                             3855x 3855x 666x 1350x     3189x 9x 9x 18x     3180x       2x   3178x 3178x                                     4086x 1999x   2087x 1x   2086x 19x 4086x 4086x   11x   4086x                     6247x                                         46x       46x                             25x           25x                   980x               8254x 8254x 8254x 8254x 4473x 4473x 4473x 4473x                       4473x   8253x                             1056x 1056x 1056x                           16x                       780x 90x                 395x 388x               6527x 6527x 6326x   6326x 1912x 580x 270x                 11795x 11795x 81951x 81951x 73238x   11795x       666x 666x 2034x 2034x   666x       520x                             941x 941x 908x 908x       5262x                         356x 769x 356x 769x   769x   356x     356x 356x           766x                               29x 5x             15x 15x 14x 14x   14x       15x                                       3x 3x 6x     3x 5x 3x 1x                   59x 59x 59x 15x           44x 39x 39x   39x     39x     5x             4365x 4365x 46x   4319x 4319x 2287x 2287x 2278x 2278x 2116x           2116x               5223x 5223x 20x                       5203x 5203x 5126x 129x                     4997x 4997x 111x                         4886x 4886x                       41x 41x 41x         41x 39x                           3443x                                           471x 471x 8x 8x 8x     8x 8x 8x       8x         463x 471x 313x                   150x         150x 135x       15x     471x                       6897x   4509x 4509x               2124x 2124x               260x         260x       4x                             8944x                   127x           127x   8817x             8817x 8817x 8817x   6512x           162x       2143x                 8944x             2412x 2412x                                 2143x 335x   1808x 47x   1761x                     1027x             8254x                   2195x 2195x 2195x 2195x 254x 254x       1941x 1941x                   6059x 6059x   6059x 6059x 6059x 248x     248x 248x   5811x 3590x   2221x 2221x                             502x 502x 169x           333x 96x       237x 121x 121x             116x     502x                           5531x 5531x 5531x 274x           5256x 4346x 4346x             910x 910x 5531x 407x 407x 280x           630x       630x         630x 630x 416x     214x           5531x 27x           187x 123x   64x                             219x 219x                               559x     559x 559x   71x 71x     239x   79x   164x   6x   6x               4473x 2763x 2763x         1710x 955x   755x           870x               2763x   443x   495x                         191x   191x 191x 191x 122x       122x     69x         69x 69x 69x     7x   1627x                                       3254x                     198x 150x 6x       144x 144x 144x 128x                 1627x           93x   1534x 158x   1376x 1376x 1345x 1345x 1345x                         31x                   158x 158x 157x 157x 158x                                     31x               31x           31x     31x 31x                                                         7x         7x                         1345x 2x                                 955x 953x       953x         4x   949x               955x 955x         955x     953x     1193x     955x   492x 470x                                     22x 4x   18x                             23x                 213x                           225x     225x 225x                                           755x 755x 515x                   240x   9x 9x 3x                     237x                 237x 224x         224x   13x                       225x 225x       225x       244x 32x 27x 2x         7069x           630x           60x                   15612x                                   1038x 1038x          
/**
 * #1668: the one operand typer.
 *
 * Pass 2.1 (the analyzers) and pass 2.2 (planning the C) each typed
 * operands with a chain walker of their own, so every expression shape had
 * to be taught twice, and the two already disagreed. This answers "what is
 * the value type of this operand" once, as a pure function of the node and
 * the typing context -- no field, no state, no registry. Each consuming rule
 * applies its own policy to the facts; none is decided here.
 *
 * Names bind through `IProgram.bindValue`, so a local, a parameter, a scope
 * member and a global are found the same way for typing and emission; a C
 * or C++ header's operand is typed by `ForeignTypeFacts` from its spelling
 * and the run's target.
 */
import { ParserRuleContext, ParseTree, TerminalNode } from "antlr4ng";
 
import * as Parser from "../PARSE/2-Parse/grammar/CNextParser";
import ConstExprLowering from "./ConstExprLowering";
import ConstantEvaluator from "./ConstantEvaluator";
import ConstantFold from "./ConstantFold";
import TTypeUtils from "./TTypeUtils";
import PrimitiveKindUtils from "./PrimitiveKindUtils";
import ChainRoot from "./ChainRoot";
import TypeCheckUtils from "./TypeCheckUtils";
import TYPE_WIDTH from "../types/TYPE_WIDTH";
import ExpressionUtils from "./ExpressionUtils";
import ForeignTypeFacts from "./ForeignTypeFacts";
import LiteralUtils from "./LiteralUtils";
import ParserUtils from "./ParserUtils";
import CompositeType from "./CompositeType";
import QualifiedCName from "./QualifiedCName";
import PROPERTY_NAMES from "./constants/PROPERTY_NAMES";
import ScopeUtils from "./ScopeUtils";
import SubscriptClassifier from "./SubscriptClassifier";
import TypeResolver from "./TypeResolver";
import TypeBinding from "../PARSE/3-Declare/TypeBinding";
import type IChainStep from "../types/IChainStep";
import type IChainTyping from "../types/IChainTyping";
import type IOperandType from "../types/IOperandType";
import type ITargetDescription from "../types/ITargetDescription";
import type ITypingContext from "../types/ITypingContext";
import type TEssentialCategory from "../types/TEssentialCategory";
import type TType from "../types/TType";
import type TValueBinding from "../types/TValueBinding";
import type TSubscriptKind from "../types/TSubscriptKind";
 
/** Where a chain walk stands between operations */
type TChainValue =
  | {
      readonly k: "value";
      readonly t: IOperandType;
      /** A register member: its subscripts are bits */
      readonly register: boolean;
    }
  | { readonly k: "scope"; readonly scopePath: string }
  | { readonly k: "enumType"; readonly name: string }
  | { readonly k: "register"; readonly name: string }
  | { readonly k: "function"; readonly returnType: TType }
  /** An unresolved name path: a C/C++ namespace, class or function */
  | { readonly k: "foreignPath"; readonly parts: readonly string[] }
  /** A header's function pointer, not yet called: its call's result */
  | { readonly k: "foreignFunction"; readonly result: IOperandType | null }
  | { readonly k: "unknown" };
 
const UNKNOWN: TChainValue = { k: "unknown" };
 
/** The operations a chain applies after its head */
type TChainOps = ReadonlyArray<
  Parser.PostfixOpContext | Parser.PostfixTargetOpContext
>;
 
/** A chain's head, typed, and the operations left to apply to it */
interface IChainStart {
  binding: TValueBinding | null;
  value: TChainValue;
  ops: TChainOps;
}
 
/** How an operand came to have its type */
type TOperandForm = IOperandType["form"];
 
const DECLARED: TOperandForm = { kind: "declared" };
 
class OperandTyper {
  /**
   * Whether evaluating an expression has a side effect: it calls a function
   * or reads a volatile or atomic declaration. A call the typer cannot type
   * still counts, found by its spelling. The one test for an element read's
   * own side effect and for a read-modify-write target that would evaluate
   * the expression twice (E0890).
   */
  static hasSideEffect(
    expr: Parser.ExpressionContext,
    ctx: ITypingContext,
  ): boolean {
    return (
      ExpressionUtils.hasFunctionCall(expr) ||
      OperandTyper.typeOf(expr, ctx)?.hasSideEffect === true
    );
  }
 
  /**
   * Whether a bit or bit-range subscript writes the value's bits (ADR-007):
   * an integer's, of any width, or a float's, through a union. The classifier
   * and the member-chain writer ask this one question (#1760 review), which
   * each had answered for integers alone, so a float element or field bit
   * write fell through to a plain subscript store that C rejects.
   */
  static hasWritableBits(t: IOperandType | null): boolean {
    return (
      t?.category === "signed" ||
      t?.category === "unsigned" ||
      t?.category === "floating"
    );
  }
 
  /**
   * The value type of any expression-level node: it descends through
   * single-child levels, parentheses, unary operators, ternaries and
   * composites. Null when the operand has no type this can settle.
   */
  static typeOf(
    node: ParserRuleContext,
    ctx: ITypingContext,
  ): IOperandType | null {
    const inner = OperandTyper.descend(node);
    if (inner instanceof Parser.PostfixExpressionContext) {
      return OperandTyper.chainResult(inner, ctx);
    }
    if (inner instanceof Parser.PrimaryExpressionContext) {
      return OperandTyper.primaryType(inner, ctx);
    }
    if (inner instanceof Parser.LiteralContext) {
      return OperandTyper.literalType(inner);
    }
    if (inner instanceof Parser.CastExpressionContext) {
      return OperandTyper.castType(inner, ctx);
    }
    if (inner instanceof Parser.UnaryExpressionContext) {
      return OperandTyper.unaryType(inner, ctx);
    }
    if (inner instanceof Parser.TernaryExpressionContext) {
      return OperandTyper.ternaryType(inner, ctx);
    }
    if (OperandTyper.isBooleanLevel(inner)) {
      return OperandTyper.booleanValue(false);
    }
    if (inner instanceof Parser.ShiftExpressionContext) {
      // `a << n` is `a`'s type; the shift count is never an operand (C01)
      const left = inner.additiveExpression()[0];
      return left ? OperandTyper.typeOf(left, ctx) : null;
    }
    if (OperandTyper.isCompositeLevel(inner)) {
      return OperandTyper.compositeType(inner, ctx);
    }
    return null;
  }
 
  /**
   * The value leaves of one arithmetic or bitwise level (#1668, ยง3.6), by the
   * one collection rule every consumer shares. It descends through arithmetic
   * and bitwise levels, parentheses, a ternary's VALUE arms (never its
   * condition), and unary `-` and `~`; it stops at a postfix chain, a cast, a
   * Boolean-valued level or `!` (one Boolean leaf) and `sizeof`; it excludes
   * `&x` and a shift count.
   */
  static valueLeaves(
    node: ParserRuleContext,
    ctx: ITypingContext,
  ): Array<IOperandType | null> {
    const inner = OperandTyper.descend(node);
    if (OperandTyper.isCompositeLevel(inner)) {
      return OperandTyper.ruleChildren(inner).flatMap((child) =>
        OperandTyper.valueLeaves(child, ctx),
      );
    }
    if (inner instanceof Parser.TernaryExpressionContext) {
      const arms = ParserUtils.ternaryValueArms(inner);
      Eif (arms !== null) {
        return arms.flatMap((arm) => OperandTyper.valueLeaves(arm, ctx));
      }
    }
    if (
      inner instanceof Parser.UnaryExpressionContext &&
      inner.getChild(0)?.getText() === "&"
    ) {
      return [];
    }
    const operand = OperandTyper.wrappedOperand(inner);
    return operand === null
      ? [OperandTyper.typeOf(inner, ctx)]
      : OperandTyper.valueLeaves(operand, ctx);
  }
 
  /**
   * The one expression a wrapper's value is: a parenthesized expression, a
   * shift's left operand (its count is not a value leaf), or the operand of
   * a unary `-` or `~` -- except a negated literal, `-5`, which is one leaf.
   * Null for anything else.
   *
   * The one descent `valueLeaves` and `compositeLevelOf` share (#1760 second
   * review): the second stopped at a unary or a shift, so the category of
   * `-(a + 'A')` was scanned from leaves that disagree, where `(a + 'A')`
   * had its level's.
   */
  private static wrappedOperand(
    inner: ParserRuleContext,
  ): ParserRuleContext | null {
    if (inner instanceof Parser.PrimaryExpressionContext) {
      return inner.expression();
    }
    if (inner instanceof Parser.ShiftExpressionContext) {
      return inner.additiveExpression()[0] ?? null;
    }
    if (!(inner instanceof Parser.UnaryExpressionContext)) return null;
    const operator = inner.getChild(0)?.getText();
    const operand = inner.unaryExpression();
    if ((operator !== "-" && operator !== "~") || !operand) return null;
    const negatedLiteral =
      operator === "-" &&
      OperandTyper.descend(operand) instanceof Parser.LiteralContext;
    return negatedLiteral ? null : operand;
  }
 
  /**
   * A postfix chain or assignment target, typed one operation at a time. A
   * `this.` or `global.` root has consumed its first `.name`.
   */
  static chainOf(
    node: Parser.PostfixExpressionContext | Parser.AssignmentTargetContext,
    ctx: ITypingContext,
  ): IChainTyping {
    return OperandTyper.walkChain(node, ctx).typing;
  }
 
  /**
   * An operand's compile-time integer value, by the one evaluator (#1175):
   * literals, names that bind here to a const (through the one binder, so a
   * const local shadows as it does everywhere else), and the arithmetic over
   * them that C computes exactly. Anything else -- a call, an element, a
   * variable, arithmetic ADR-044 would clamp or wrap -- is a runtime value:
   * null. So is a comparison, which is a bool, not an integer.
   *
   * This used to read only a literal under leading minus signs or a bare
   * name, and called arithmetic a runtime value, because folding it exactly
   * disagreed with ADR-044's saturating C. The evaluator folds at the
   * operands' width and declines where C would clamp, so that reason is gone,
   * and a fifth rule for a constant's value with it.
   */
  static constantOf(
    node: ParserRuleContext,
    ctx: ITypingContext,
  ): number | null {
    const result = ConstantEvaluator.evaluate(
      ConstExprLowering.lowerNode(node),
      ConstantFold.environment(ctx.program, ctx.sourceFile),
    );
    return result.kind === "value" && result.typeName !== "bool"
      ? (ConstantEvaluator.toNumber(result.value) ?? null)
      : null;
  }
 
  /**
   * A bare name's value type as it binds at `at`: a local, a member, a
   * global or a header's variable, through Program's one binder. For a rule
   * that holds a name rather than an expression node.
   */
  static typeOfName(
    name: string,
    at: ParserRuleContext,
    ctx: ITypingContext,
  ): IOperandType | null {
    const binding = ctx.program.bindValue(
      ctx.sourceFile,
      null,
      name,
      ParserUtils.getPosition(at),
    );
    return binding && binding.kind !== "scope"
      ? OperandTyper.boundValue(binding, ctx)
      : null;
  }
 
  /** The value type an assignment target writes */
  static typeOfTarget(
    target: Parser.AssignmentTargetContext,
    ctx: ITypingContext,
  ): IOperandType | null {
    return OperandTyper.walkChain(target, ctx).last;
  }
 
  /** The chain typed, and the value it ends on */
  private static walkChain(
    node: Parser.PostfixExpressionContext | Parser.AssignmentTargetContext,
    ctx: ITypingContext,
  ): { typing: IChainTyping; last: IOperandType | null } {
    const start = OperandTyper.chainStart(node, ctx);
    const steps: IChainStep[] = [];
    let current = start.value;
    for (const op of start.ops) {
      const before = current.k === "value" ? current.t : null;
      const { next, subscript } = OperandTyper.applyOp(current, op, ctx);
      const member = op.DOT() === null ? null : op.IDENTIFIER()?.getText();
      steps.push({
        before,
        subscript,
        after: next.k === "value" ? next.t : null,
        property:
          before !== null &&
          member !== undefined &&
          member !== null &&
          OperandTyper.readsProperty(before, member, ctx)
            ? member
            : null,
      });
      current = next;
    }
    return {
      typing: { root: start.binding, steps },
      last: current.k === "value" ? current.t : null,
    };
  }
 
  /**
   * Whether an operand's type is a string (ADR-045), an array of them
   * included: a `string<N>`, or the bare `string` keyword, whose capacity is
   * not known here -- main's `string args[]` (ADR-030) and an unsized
   * `const string`. #1668 (C12): three rules stood where this one does, and
   * only this one's callers ask it; the subscript shape knew only a capacity,
   * so the element of `args[0]` was read as a bit rather than a character.
   */
  static isString(t: IOperandType | null): boolean {
    Iif (t === null) return false;
    const name = t.typeName ?? "";
    return (
      t.stringCapacity !== null ||
      name === "string" ||
      TypeCheckUtils.isSizedStringName(name)
    );
  }
 
  /**
   * Whether an operand is a whole array (`pts`, not `pts[0]`), which C decays
   * to a pointer to its first element. Such an argument never takes `&` -- its
   * address is a pointer to the ARRAY. A string's buffer is not asked here: a
   * string argument never reaches that `&` (measured, #1668's merge of main).
   */
  static decaysToPointer(t: IOperandType | null): boolean {
    return t !== null && t.dimensions.length > 0;
  }
 
  /**
   * ADR-057's scope-type predicate for the file being typed: the scope types
   * it declares or its include closure declares (#1724). The one answer 1.4
   * settled the file's symbols with and codegen qualifies with, so the typer
   * cannot see a sibling's scope type the file never includes.
   */
  private static scopeTypesSeenBy(
    ctx: ITypingContext,
  ): (qualifiedName: string) => boolean {
    return (qualifiedName) =>
      ctx.program.isScopeTypeVisibleFrom(ctx.sourceFile, qualifiedName);
  }
 
  /**
   * Whether an operand is essentially Boolean: an applied relational or
   * logical operator, `!`, or a `bool`. A single bit of a scalar is not
   * (ADR-024: it is a bit index), and neither is an array of bools.
   */
  static isBoolean(t: IOperandType | null): boolean {
    if (t === null || t.dimensions.length > 0) return false;
    return (
      t.form.kind === "boolean" ||
      (t.typeName === "bool" && t.form.kind !== "bitIndex")
    );
  }
 
  /** The essential category of a C-Next type name: decided here, once (G8) */
  static categoryOf(typeName: string | null): TEssentialCategory {
    Iif (typeName === null) return "none";
    if (typeName === "bool") return "boolean";
    Iif (typeName === "char") return "character";
    // TypeCheckUtils' lists, not a second spelling of them (#1760 review)
    if (TypeCheckUtils.isUnsigned(typeName)) return "unsigned";
    if (TypeCheckUtils.isSigned(typeName)) return "signed";
    if (TypeCheckUtils.isFloat(typeName)) return "floating";
    return "none";
  }
 
  // --------------------------------------------------------------------------
  // Levels
  // --------------------------------------------------------------------------
 
  /** Through every level that has exactly one rule child and nothing else */
  private static descend(node: ParserRuleContext): ParserRuleContext {
    let current = node;
    while (current.getChildCount() === 1) {
      const child = current.getChild(0);
      if (!(child instanceof ParserRuleContext)) break;
      current = child;
    }
    return current;
  }
 
  private static ruleChildren(node: ParserRuleContext): ParserRuleContext[] {
    const children: ParserRuleContext[] = [];
    for (let i = 0; i < node.getChildCount(); i += 1) {
      const child: ParseTree | null = node.getChild(i);
      if (child instanceof ParserRuleContext) children.push(child);
    }
    return children;
  }
 
  private static isBooleanLevel(node: ParserRuleContext): boolean {
    return (
      node instanceof Parser.OrExpressionContext ||
      node instanceof Parser.AndExpressionContext ||
      node instanceof Parser.EqualityExpressionContext ||
      node instanceof Parser.RelationalExpressionContext
    );
  }
 
  /**
   * The composite operator level (`*`, `+`, `&`, `^`, `|`) an expression IS,
   * through single-child chains and `wrappedOperand`, or null. The same
   * descent `valueLeaves` flattens, for a rule that needs the level itself --
   * Rule 10.4's category of an operand that is an operation (#1760 review).
   */
  static compositeLevelOf(node: ParserRuleContext): ParserRuleContext | null {
    const inner = OperandTyper.descend(node);
    if (OperandTyper.isCompositeLevel(inner)) return inner;
    const operand = OperandTyper.wrappedOperand(inner);
    return operand === null ? null : OperandTyper.compositeLevelOf(operand);
  }
 
  private static isCompositeLevel(node: ParserRuleContext): boolean {
    return (
      node instanceof Parser.BitwiseOrExpressionContext ||
      node instanceof Parser.BitwiseXorExpressionContext ||
      node instanceof Parser.BitwiseAndExpressionContext ||
      node instanceof Parser.AdditiveExpressionContext ||
      node instanceof Parser.MultiplicativeExpressionContext
    );
  }
 
  private static compositeType(
    node: ParserRuleContext,
    ctx: ITypingContext,
  ): IOperandType {
    const leaves = OperandTyper.valueLeaves(node, ctx);
    const typed = leaves.filter((leaf): leaf is IOperandType => leaf !== null);
    const categories = new Set(
      typed.map((leaf) => leaf.category).filter((c) => c !== "none"),
    );
    const names = new Set(typed.map((leaf) => leaf.typeName));
    const category =
      categories.size === 1 ? ([...categories][0] ?? "none") : "none";
    // The integer type the composite computes in, settled here once (#1760
    // second review): four consumers each re-derived it from the leaves
    const integer = CompositeType.integerOf(leaves);
    return {
      ...OperandTyper.plain(
        integer ?? OperandTyper.compositeName(names, category, leaves),
      ),
      category,
      bitWidth: integer === null ? null : OperandTyper.widthOf(integer),
      hasSideEffect: typed.some((leaf) => leaf.hasSideEffect),
      form: { kind: "composite", leaves },
    };
  }
 
  /**
   * A non-integer composite's type name: its leaves' one name, or for
   * floating leaves of different names C's usual arithmetic conversion
   * (`CompositeType`). An integer composite is typed by `CompositeType.
   * integerOf`, with its width, and its `bitWidth` says it is one.
   */
  private static compositeName(
    names: ReadonlySet<string | null>,
    category: TEssentialCategory,
    leaves: ReadonlyArray<IOperandType | null>,
  ): string | null {
    if (names.size === 1) return [...names][0] ?? null;
    return category === "floating" ? CompositeType.floatingOf(leaves) : null;
  }
 
  private static ternaryType(
    node: Parser.TernaryExpressionContext,
    ctx: ITypingContext,
  ): IOperandType | null {
    const arms = ParserUtils.ternaryValueArms(node);
    if (arms === null) return null;
    const whenTrue = OperandTyper.typeOf(arms[0], ctx);
    const whenFalse = OperandTyper.typeOf(arms[1], ctx);
    const same =
      whenTrue !== null &&
      whenFalse !== null &&
      whenTrue.typeName === whenFalse.typeName &&
      whenTrue.category === whenFalse.category;
    return {
      ...(same ? whenTrue : OperandTyper.floatingArms(whenTrue, whenFalse)),
      overflow: null,
      binding: null,
      hasSideEffect:
        (whenTrue?.hasSideEffect ?? false) ||
        (whenFalse?.hasSideEffect ?? false),
      form: { kind: "ternary", arms: [whenTrue, whenFalse] },
    };
  }
 
  /**
   * Two arms of different types: C's usual arithmetic conversion when every
   * arm with an essential category is floating (`c ? k : 2.0` is f64), and
   * untyped otherwise -- E0810 rejects the mixes in 2.1.
   */
  private static floatingArms(
    whenTrue: IOperandType | null,
    whenFalse: IOperandType | null,
  ): IOperandType {
    const arms = [whenTrue, whenFalse];
    const categorized = arms.filter(
      (arm): arm is IOperandType => arm !== null && arm.category !== "none",
    );
    const allFloating =
      categorized.length > 0 &&
      categorized.every((arm) => arm.category === "floating");
    if (!allFloating) return OperandTyper.plain(null);
    return {
      ...OperandTyper.plain(CompositeType.floatingOf(arms)),
      category: "floating",
    };
  }
 
  private static unaryType(
    node: Parser.UnaryExpressionContext,
    ctx: ITypingContext,
  ): IOperandType | null {
    const operator = node.getChild(0)?.getText();
    const operand = node.unaryExpression();
    if (operator === "!") {
      return OperandTyper.booleanValue(
        operand
          ? (OperandTyper.typeOf(operand, ctx)?.hasSideEffect ?? false)
          : false,
      );
    }
    if ((operator === "-" || operator === "~") && operand) {
      const t = OperandTyper.typeOf(operand, ctx);
      Iif (t === null) return null;
      const form =
        operator === "-" && t.form.kind === "literal"
          ? { ...t.form, negated: !t.form.negated }
          : t.form;
      return { ...t, form, overflow: null, binding: null };
    }
    // `&x` is an address, never a value operand (#1152)
    return null;
  }
 
  private static primaryType(
    node: Parser.PrimaryExpressionContext,
    ctx: ITypingContext,
  ): IOperandType | null {
    const parenthesized = node.expression();
    if (parenthesized) {
      return OperandTyper.typeOf(parenthesized, ctx);
    }
    const literal = node.literal();
    if (literal) return OperandTyper.literalType(literal);
    const cast = node.castExpression();
    if (cast) return OperandTyper.castType(cast, ctx);
    const identifier = node.IDENTIFIER();
    if (!identifier) return null;
    const binding = ctx.program.bindValue(
      ctx.sourceFile,
      null,
      identifier.getText(),
      ParserUtils.getPosition(node),
    );
    return binding ? OperandTyper.boundValue(binding, ctx) : null;
  }
 
  // --------------------------------------------------------------------------
  // Leaves
  // --------------------------------------------------------------------------
 
  private static literalType(node: Parser.LiteralContext): IOperandType | null {
    const text = node.getText();
    if (text.startsWith("'")) {
      return {
        ...OperandTyper.plain("char"),
        category: "character",
        bitWidth: 8,
        form: {
          kind: "literal",
          literal: "char",
          suffixed: false,
          negated: false,
        },
      };
    }
    const typeName = LiteralUtils.typeOf(node);
    if (typeName === null) return null;
    if (typeName === "bool") {
      return {
        ...OperandTyper.plain("bool"),
        category: "boolean",
        form: {
          kind: "literal",
          literal: "bool",
          suffixed: false,
          negated: false,
        },
      };
    }
    const floatWidth = LiteralUtils.floatLiteralWidth(text);
    if (floatWidth !== null) {
      return {
        ...OperandTyper.plain(typeName),
        category: "floating",
        form: {
          kind: "literal",
          literal: "float",
          suffixed: /[fF](?:32|64)$/.test(text),
          negated: false,
        },
      };
    }
    // An unsuffixed integer has no essential category of its own (ADR-052);
    // a suffixed one takes its suffix's (R2).
    const suffixed = typeName !== "int";
    return {
      ...OperandTyper.plain(typeName),
      category: suffixed ? OperandTyper.categoryOf(typeName) : "none",
      bitWidth: suffixed ? OperandTyper.widthOf(typeName) : null,
      form: { kind: "literal", literal: "integer", suffixed, negated: false },
    };
  }
 
  private static castType(
    node: Parser.CastExpressionContext,
    ctx: ITypingContext,
  ): IOperandType | null {
    const operand = node.unaryExpression();
    const inner = operand ? OperandTyper.typeOf(operand, ctx) : null;
    const target = OperandTyper.typeOfWritten(
      node.type(),
      ctx,
      ParserUtils.getPosition(node),
    );
    if (target === null) return null;
    return {
      ...target,
      overflow: null,
      binding: null,
      hasSideEffect: inner?.hasSideEffect ?? false,
      form: { kind: "cast" },
    };
  }
 
  /**
   * The scope path enclosing a node, from Program's lexical frames: the one
   * answer to "which scope is this in", which ADR-057 name lookups start from.
   */
  static scopePathAt(node: ParserRuleContext, ctx: ITypingContext): string {
    return ctx.program.lexicalFrameAt(
      ctx.sourceFile,
      ParserUtils.getPosition(node),
    ).scopePath;
  }
 
  /**
   * A written type -- a cast's, a declaration's -- resolved by 1.3's one
   * ladder (`TypeBinding`), so `this.T`, `global.T`, `Scope.T` and a bare `T`
   * name what they name everywhere else; qualifying the source text by hand
   * read `this.EMode` as a type called `this_EMode`.
   *
   * An array type is its element's type with the written dimensions (#1668
   * review: `EColor[2]` had no type at all, so its elements' bare enum
   * members lost their anchor).
   */
  static typeOfWritten(
    typeCtx: Parser.TypeContext | Parser.ArrayTypeContext,
    ctx: ITypingContext,
    at: { line: number; column: number },
  ): IOperandType | null {
    const array =
      typeCtx instanceof Parser.TypeContext ? typeCtx.arrayType() : null;
    if (array) {
      const element = OperandTyper.typeOfWritten(array, ctx, at);
      Iif (element === null) return null;
      const env = ConstantFold.environment(ctx.program, ctx.sourceFile);
      // #1175: the size as 1.4 settles a declared one -- never the source
      // text, which named what C cannot see
      const dimensions = array.arrayTypeDimension().map((dimension) => {
        const size = dimension.expression();
        return size
          ? ConstantFold.dimension(ConstExprLowering.lower(size), env)
          : "";
      });
      return {
        ...element,
        dimensions: [...dimensions, ...element.dimensions],
      };
    }
    const primitive = typeCtx.primitiveType()?.getText();
    if (primitive !== undefined && PrimitiveKindUtils.isPrimitive(primitive)) {
      return OperandTyper.fromType(
        TTypeUtils.createPrimitive(primitive),
        [],
        ctx,
      );
    }
    // ADR-057's qualification is the program's one answer, as for every
    // `TypeBinding` caller; whether the result is a C-Next type this file
    // sees is `declaresNamedType`, as in `fromType` (#1668 review: the trio
    // was spelled out here by hand)
    const cName = TypeBinding.resolveNamedType(
      typeCtx,
      ctx.program.lexicalFrameAt(ctx.sourceFile, at).scopePath,
      { isScopeType: OperandTyper.scopeTypesSeenBy(ctx) },
    );
    if (cName !== null && OperandTyper.declaresNamedType(cName, ctx)) {
      return OperandTyper.fromType({ kind: "struct", name: cName }, [], ctx);
    }
    // A header's type: an array's element is its first child's spelling
    const spelling =
      typeCtx instanceof Parser.ArrayTypeContext
        ? (typeCtx.getChild(0)?.getText() ?? "")
        : typeCtx.getText();
    return ForeignTypeFacts.operandType(
      spelling,
      ctx.symbolTable,
      OperandTyper.target(ctx),
    );
  }
 
  /** A bound name's value: a local, a variable, or a header's variable */
  private static boundValue(
    binding: TValueBinding,
    ctx: ITypingContext,
  ): IOperandType | null {
    switch (binding.kind) {
      case "local": {
        const d = binding.declaration;
        return {
          ...OperandTyper.fromType(d.type, d.arrayDimensions, ctx),
          overflow: d.overflowBehavior,
          hasSideEffect: d.isVolatile || d.isAtomic,
          binding,
        };
      }
      case "variable": {
        const s = binding.symbol;
        return {
          ...OperandTyper.fromType(s.type, s.arrayDimensions ?? [], ctx),
          overflow: s.overflowBehavior,
          hasSideEffect: s.isVolatile || s.isAtomic,
          binding,
        };
      }
      case "foreign": {
        const t = ForeignTypeFacts.variableOperand(
          binding.name,
          ctx.symbolTable,
          OperandTyper.target(ctx),
        );
        return t ? { ...t, binding } : null;
      }
      case "scope":
      case "function":
        return null;
    }
  }
 
  /** A C-Next type, as a declaration states it */
  private static fromType(
    type: TType,
    dimensions: ReadonlyArray<number | string>,
    ctx: ITypingContext,
  ): IOperandType {
    // A header's type named in a C-Next declaration (`real_t x`,
    // `float32_t v`): 1.3 guesses a named type's kind from its spelling
    // (#1720), so a name that is no C-Next struct, enum or bitmap, and that is
    // a C type or a header's, is asked of the header too (#1668 review:
    // it was untyped, and `x * i` went to an integer clamp helper).
    if (
      type.kind === "external" ||
      (OperandTyper.isNamedKind(type) &&
        !OperandTyper.declaresNamedType(type.name, ctx) &&
        ForeignTypeFacts.isForeignType(
          type.name,
          ctx.symbolTable,
          OperandTyper.target(ctx),
        ))
    ) {
      const foreign = ForeignTypeFacts.operandType(
        type.name,
        ctx.symbolTable,
        OperandTyper.target(ctx),
        dimensions,
      );
      Eif (foreign) return { ...foreign, form: DECLARED };
    }
    Iif (type.kind === "array") {
      return OperandTyper.fromType(
        type.elementType,
        [...type.dimensions, ...dimensions],
        ctx,
      );
    }
    const typeName = TypeResolver.getTypeName(type);
    const base = { ...OperandTyper.plain(typeName), dimensions };
    switch (type.kind) {
      case "primitive":
        return {
          ...base,
          category: OperandTyper.categoryOf(typeName),
          bitWidth: OperandTyper.widthOf(typeName),
        };
      case "string":
        return { ...base, stringCapacity: type.capacity };
      case "struct":
      case "enum":
      case "bitmap":
        return { ...base, ...OperandTyper.namedFacts(type.name, ctx) };
      default:
        return base;
    }
  }
 
  private static isNamedKind(
    type: TType,
  ): type is Extract<TType, { kind: "struct" | "enum" | "bitmap" }> {
    return (
      type.kind === "struct" || type.kind === "enum" || type.kind === "bitmap"
    );
  }
 
  /** Whether this file sees `name` declared as a C-Next struct, enum or bitmap */
  private static declaresNamedType(name: string, ctx: ITypingContext): boolean {
    const symbols = ctx.symbols;
    return (
      symbols.knownStructs.has(name) ||
      symbols.knownEnums.has(name) ||
      symbols.knownBitmaps.has(name)
    );
  }
 
  /**
   * What a named C-Next type is, from the names this file sees declared.
   * Never from `TType.kind`: 1.3 guesses a named type's kind from its
   * spelling, so an enum not named `E...` and every bitmap settle as a
   * struct (#1720).
   */
  private static namedFacts(
    name: string,
    ctx: ITypingContext,
  ): Pick<IOperandType, "category" | "enumTypeName" | "bitmapTypeName"> {
    if (ctx.symbols.knownEnums.has(name)) {
      return { category: "enum", enumTypeName: name, bitmapTypeName: null };
    }
    if (ctx.symbols.knownBitmaps.has(name)) {
      return { category: "none", enumTypeName: null, bitmapTypeName: name };
    }
    return { category: "none", enumTypeName: null, bitmapTypeName: null };
  }
 
  // --------------------------------------------------------------------------
  // Chains
  // --------------------------------------------------------------------------
 
  private static chainResult(
    node: Parser.PostfixExpressionContext,
    ctx: ITypingContext,
  ): IOperandType | null {
    return OperandTyper.walkChain(node, ctx).last;
  }
 
  private static chainStart(
    node: Parser.PostfixExpressionContext | Parser.AssignmentTargetContext,
    ctx: ITypingContext,
  ): IChainStart {
    return node instanceof Parser.AssignmentTargetContext
      ? OperandTyper.targetStart(node, ctx)
      : OperandTyper.expressionStart(node, ctx);
  }
 
  /** A target spells `this.name` in the rule itself */
  private static targetStart(
    node: Parser.AssignmentTargetContext,
    ctx: ITypingContext,
  ): IChainStart {
    const at = ParserUtils.getPosition(node);
    const ops = [...node.postfixTargetOp()];
    const root = ChainRoot.ofTarget(node);
    if (root !== null) {
      const name = node.IDENTIFIER()?.getText();
      return name
        ? OperandTyper.rootedStart(root, name, ops, at, ctx)
        : { binding: null, value: UNKNOWN, ops: [] };
    }
    const identifier = node.IDENTIFIER();
    return identifier
      ? OperandTyper.namedStart(identifier, ops, at, ctx)
      : { binding: null, value: UNKNOWN, ops };
  }
 
  /** An expression's first postfix op is a `this.`/`global.` root's `.name` */
  private static expressionStart(
    node: Parser.PostfixExpressionContext,
    ctx: ITypingContext,
  ): IChainStart {
    const at = ParserUtils.getPosition(node);
    const primary = node.primaryExpression();
    // The one head rule (#1760 review: this re-derived it, DOT guard and all)
    const head = ChainRoot.headOf(primary, node.postfixOp());
    const ops = node.postfixOp().slice(head.opsConsumed);
    if (head.root !== null) {
      Iif (head.identifier === null) {
        return { binding: null, value: UNKNOWN, ops: [] };
      }
      const name = head.identifier.getText();
      return OperandTyper.rootedStart(head.root, name, ops, at, ctx);
    }
    if (head.identifier) {
      return OperandTyper.namedStart(head.identifier, ops, at, ctx);
    }
    const t = OperandTyper.primaryType(primary, ctx);
    return {
      binding: null,
      value: t ? { k: "value", t, register: false } : UNKNOWN,
      ops,
    };
  }
 
  /** `this.name` or `global.name`, with that first member consumed */
  private static rootedStart(
    root: "this" | "global",
    name: string,
    ops: TChainOps,
    at: { line: number; column: number },
    ctx: ITypingContext,
  ): IChainStart {
    const binding = ctx.program.bindValue(ctx.sourceFile, root, name, at);
    if (binding?.kind === "scope") {
      return {
        binding,
        value: { k: "scope", scopePath: binding.scopePath },
        ops,
      };
    }
    if (binding?.kind === "foreign") {
      return OperandTyper.foreignStart(binding, name, ops, ctx);
    }
    // A function is typed by the call that follows it, as it was before the
    // binder named it (#1760 review)
    if (binding && binding.kind !== "function") {
      const t = OperandTyper.boundValue(binding, ctx);
      return {
        binding,
        value: t ? { k: "value", t, register: false } : UNKNOWN,
        ops,
      };
    }
    const scopePath =
      root === "this"
        ? ctx.program.lexicalFrameAt(ctx.sourceFile, at).scopePath
        : "";
    return {
      binding: null,
      value: OperandTyper.memberOfScope(scopePath, name, ctx),
      ops,
    };
  }
 
  /** A bare name at the head of a chain */
  private static namedStart(
    identifier: TerminalNode,
    ops: TChainOps,
    at: { line: number; column: number },
    ctx: ITypingContext,
  ): IChainStart {
    const name = identifier.getText();
    const binding = ctx.program.bindValue(ctx.sourceFile, null, name, at);
    if (binding?.kind === "scope") {
      return {
        binding,
        value: { k: "scope", scopePath: binding.scopePath },
        ops,
      };
    }
    if (binding && binding.kind !== "foreign" && binding.kind !== "function") {
      const t = OperandTyper.boundValue(binding, ctx);
      return {
        binding,
        value: t ? { k: "value", t, register: false } : UNKNOWN,
        ops,
      };
    }
 
    const scopePath = ctx.program.lexicalFrameAt(ctx.sourceFile, at).scopePath;
    const nextIsCall = ops[0] !== undefined && OperandTyper.isCall(ops[0]);
    if (nextIsCall) {
      const fn = ctx.program.resolveFunction(name, scopePath);
      if (fn)
        return {
          binding: null,
          value: { k: "function", returnType: fn.returnType },
          ops,
        };
    }
    const symbols = ctx.symbols;
    // ADR-057's qualification, the program's one answer: a scope's own type
    // shadows a global one of the name, whatever kind each is (#1668 review:
    // an enums-only predicate let a global enum through a scope's struct)
    const enumName = ScopeUtils.qualifyScopeType(
      name,
      scopePath,
      OperandTyper.scopeTypesSeenBy(ctx),
    );
    const enumCName = OperandTyper.cNameOf(enumName);
    if (symbols.knownEnums.has(enumCName)) {
      return { binding: null, value: { k: "enumType", name: enumCName }, ops };
    }
    const registerCName =
      scopePath !== "" &&
      symbols.knownRegisters.has(
        ScopeUtils.getTranspiledCName({ name, scopePath }),
      )
        ? ScopeUtils.getTranspiledCName({ name, scopePath })
        : name;
    if (symbols.knownRegisters.has(registerCName)) {
      return {
        binding: null,
        value: { k: "register", name: registerCName },
        ops,
      };
    }
    if (binding?.kind === "foreign") {
      return OperandTyper.foreignStart(binding, name, ops, ctx);
    }
    return { binding: null, value: { k: "foreignPath", parts: [name] }, ops };
  }
 
  /**
   * A header's name at the head of a chain, bare or as `global.name`: its
   * variable's type, or a path a following call or member resolves (a
   * function, a namespace). One arm for both spellings (#1668 review:
   * `global.cGetF()` stopped at an untyped root).
   */
  private static foreignStart(
    binding: TValueBinding,
    name: string,
    ops: TChainOps,
    ctx: ITypingContext,
  ): IChainStart {
    const t = OperandTyper.boundValue(binding, ctx);
    return {
      binding,
      value: t
        ? { k: "value", t, register: false }
        : { k: "foreignPath", parts: [name] },
      ops,
    };
  }
 
  /** What `Scope.name` denotes: a member, a function, an enum or a register */
  private static memberOfScope(
    scopePath: string,
    name: string,
    ctx: ITypingContext,
  ): TChainValue {
    const cName =
      scopePath === ""
        ? name
        : ScopeUtils.getTranspiledCName({ name, scopePath });
    const symbol = ctx.program.symbolByCName(cName);
    switch (symbol?.kind) {
      case "variable": {
        const t = OperandTyper.boundValue({ kind: "variable", symbol }, ctx);
        return t ? { k: "value", t, register: false } : UNKNOWN;
      }
      case "function":
        return { k: "function", returnType: symbol.returnType };
      case "enum":
        return { k: "enumType", name: cName };
      case "register":
        return { k: "register", name: cName };
      default:
        break;
    }
    return UNKNOWN;
  }
 
  private static applyOp(
    current: TChainValue,
    op: Parser.PostfixOpContext | Parser.PostfixTargetOpContext,
    ctx: ITypingContext,
  ): { next: TChainValue; subscript: TSubscriptKind | null } {
    if (op.DOT() !== null) {
      const member = op.IDENTIFIER()?.getText();
      return {
        next: member ? OperandTyper.memberOf(current, member, ctx) : UNKNOWN,
        subscript: null,
      };
    }
    if (op.LBRACKET() !== null) {
      return OperandTyper.subscriptOf(current, op.expression(), ctx);
    }
    return { next: OperandTyper.callOf(current, ctx), subscript: null };
  }
 
  private static isCall(
    op: Parser.PostfixOpContext | Parser.PostfixTargetOpContext,
  ): boolean {
    return op.DOT() === null && op.LBRACKET() === null;
  }
 
  private static memberOf(
    current: TChainValue,
    member: string,
    ctx: ITypingContext,
  ): TChainValue {
    switch (current.k) {
      case "scope":
        return OperandTyper.memberOfScope(current.scopePath, member, ctx);
      case "enumType":
        return {
          k: "value",
          register: false,
          t: {
            ...OperandTyper.plain(current.name),
            category: "enum",
            enumTypeName: current.name,
            form: { kind: "enumMember" },
          },
        };
      case "register": {
        // The register symbol is the one source; the per-file map only
        // records bitmap-typed members
        const register = ctx.program.symbolByCName(current.name);
        const info =
          register?.kind === "register" ? register.members.get(member) : null;
        Iif (!info) return UNKNOWN;
        if (info.bitmapType) {
          const t = {
            ...OperandTyper.plain(info.bitmapType),
            bitmapTypeName: info.bitmapType,
          };
          return { k: "value", register: true, t };
        }
        // A member records its C spelling (`uint16_t`)
        const foreign = ForeignTypeFacts.operandType(
          info.cType,
          ctx.symbolTable,
          OperandTyper.target(ctx),
        );
        Iif (!foreign) return UNKNOWN;
        const t = { ...foreign, form: DECLARED };
        return { k: "value", register: true, t };
      }
      case "foreignPath":
        return OperandTyper.foreignPathOf([...current.parts, member], ctx);
      case "value":
        return OperandTyper.fieldOf(current.t, member, ctx);
      default:
        return UNKNOWN;
    }
  }
 
  /**
   * Whether `.member` on a value of type `t` reads an ADR-058/ADR-045
   * property rather than a field. A field named like a property is a field
   * -- ADR-058's `struct Packet { u32 length; }` is "perfectly fine", and a
   * chain that resolves as a whole is a member access -- so only a property
   * name the value's type declares no field of reads the property. The one
   * answer: the typer records it on the chain step, and 2.1's property rules
   * and render read the step (#1760 review: each decided by the name alone).
   */
  private static readsProperty(
    t: IOperandType,
    member: string,
    ctx: ITypingContext,
  ): boolean {
    return (
      PROPERTY_NAMES.has(member) && !OperandTyper.declaresField(t, member, ctx)
    );
  }
 
  /** Whether a value's type declares the field: a struct's, bitmap's or header's */
  private static declaresField(
    t: IOperandType,
    member: string,
    ctx: ITypingContext,
  ): boolean {
    if (t.dimensions.length > 0) return false;
    if (t.bitmapTypeName !== null) {
      return (
        ctx.symbols.bitmapFields.get(t.bitmapTypeName)?.has(member) ?? false
      );
    }
    Iif (t.typeName === null) return false;
    const struct = ctx.program.symbolByCName(t.typeName);
    if (struct?.kind === "struct") return struct.fields.has(member);
    return ctx.symbolTable.getStructFieldInfo(t.typeName, member) !== undefined;
  }
 
  /** A field of a struct, a bitmap field, or a property (untyped here) */
  private static fieldOf(
    t: IOperandType,
    member: string,
    ctx: ITypingContext,
  ): TChainValue {
    if (
      // ADR-058/ADR-045 properties: typed by their own rules, never as a member
      OperandTyper.readsProperty(t, member, ctx) ||
      t.typeName === null ||
      t.dimensions.length > 0
    ) {
      return UNKNOWN;
    }
    if (t.bitmapTypeName !== null) {
      return OperandTyper.bitmapFieldOf(t, t.bitmapTypeName, member, ctx);
    }
    const struct = ctx.program.symbolByCName(t.typeName);
    if (struct?.kind === "struct") {
      const field = struct.fields.get(member);
      Iif (!field) return UNKNOWN;
      return {
        k: "value",
        register: false,
        t: {
          ...OperandTyper.fromType(
            field.type,
            OperandTyper.fieldDimensions(field.type, field.dimensions ?? []),
            ctx,
          ),
          hasSideEffect: t.hasSideEffect,
        },
      };
    }
    return OperandTyper.foreignFieldOf(t, t.typeName, member, ctx);
  }
 
  /** A bitmap field: a Boolean bit, or an unsigned run of bits */
  private static bitmapFieldOf(
    t: IOperandType,
    bitmapTypeName: string,
    member: string,
    ctx: ITypingContext,
  ): TChainValue {
    const field = ctx.symbols.bitmapFields.get(bitmapTypeName)?.get(member);
    if (!field) return UNKNOWN;
    const width = field.width;
    const typeName = width === 1 ? "bool" : OperandTyper.unsignedFor(width);
    return {
      k: "value",
      register: false,
      t: {
        ...OperandTyper.plain(typeName),
        category: width === 1 ? "boolean" : "unsigned",
        bitWidth: width === 1 ? null : width,
        hasSideEffect: t.hasSideEffect,
      },
    };
  }
 
  /** A member of a header's struct or class */
  private static foreignFieldOf(
    t: IOperandType,
    typeName: string,
    member: string,
    ctx: ITypingContext,
  ): TChainValue {
    const foreign = ForeignTypeFacts.fieldOperand(
      typeName,
      member,
      ctx.symbolTable,
      OperandTyper.target(ctx),
    );
    // A C struct's function-pointer field, `ops.get()` (#1668 review: its
    // call's result was untyped)
    const pointer = ForeignTypeFacts.fieldCallOperand(
      typeName,
      member,
      ctx.symbolTable,
      OperandTyper.target(ctx),
    );
    Iif (pointer !== undefined) {
      return { k: "foreignFunction", result: pointer };
    }
    Eif (foreign) {
      return {
        k: "value",
        register: false,
        // A read of the field has the struct's side effect, or its own: a
        // volatile field is one (#1760 review: the struct's replaced it)
        t: {
          ...foreign,
          hasSideEffect: t.hasSideEffect || foreign.hasSideEffect,
        },
      };
    }
    // A C++ class's member function, `dev.read()`: named `Dev::read`, as a
    // static member's call already is, so the call that follows
    // resolves it (#1668 review: an instance method's result was untyped)
    return t.form.kind === "foreign" || t.form.kind === "declared"
      ? { k: "foreignPath", parts: [typeName, member] }
      : UNKNOWN;
  }
 
  /**
   * A path into a C++ namespace or class, `NS.nf`: a variable the path names
   * is typed where it is reached, so a member after it resolves too
   * (`NS.nps.pf`); anything else stays a path, for a call to resolve
   * (#1668 review: a namespace variable was typed only when called).
   */
  private static foreignPathOf(
    parts: readonly string[],
    ctx: ITypingContext,
  ): TChainValue {
    const t = ForeignTypeFacts.variableOperand(
      parts.join("::"),
      ctx.symbolTable,
      OperandTyper.target(ctx),
    );
    return t ? { k: "value", register: false, t } : { k: "foreignPath", parts };
  }
 
  /**
   * A field's dimensions as the program subscripts them. A string field's
   * symbol carries its C buffer, capacity + 1, as its LAST dimension
   * (`char name[33]`), which a `string<32>` variable's type does not; the
   * buffer is the string's own, typed by its capacity, so it is left off.
   */
  private static fieldDimensions(
    type: TType,
    dimensions: ReadonlyArray<number | string>,
  ): ReadonlyArray<number | string> {
    if (type.kind !== "string" || dimensions.length === 0) return dimensions;
    return dimensions.at(-1) === type.capacity + 1
      ? dimensions.slice(0, -1)
      : dimensions;
  }
 
  /**
   * What the classifier is told about a subscripted value.
   *
   * ADR-024's "a subscript into a scalar is a bit index" is about integers
   * whose bits C-Next can see, so a C or C++ header's scalar integer is one
   * (S25). A header's value that is NOT an integer -- a struct, a C++ type
   * with its own `operator[]` -- is left to C and C++: shown as unknown, so
   * its subscript stays the element access it always was.
   */
  private static subscriptedShape(
    t: IOperandType | null,
  ): { isArray: boolean; isString: boolean } | null {
    if (t === null) return null;
    const isArray = t.dimensions.length > 0;
    // A header scalar with bits -- an integer, or a float (#1760 review: a
    // `double`'s subscript was read as an element) -- is bit-indexed as a
    // C-Next one is (ADR-007); anything else there is untyped
    if (
      t.form.kind === "foreign" &&
      !isArray &&
      !OperandTyper.hasWritableBits(t)
    ) {
      return null;
    }
    return { isArray, isString: OperandTyper.isString(t) };
  }
 
  private static subscriptOf(
    current: TChainValue,
    indices: Parser.ExpressionContext[],
    ctx: ITypingContext,
  ): { next: TChainValue; subscript: TSubscriptKind | null } {
    const t = current.k === "value" ? current.t : null;
    const subscript = SubscriptClassifier.classify({
      typeInfo: OperandTyper.subscriptedShape(t),
      subscriptCount: indices.length,
      isRegisterAccess: current.k === "value" && current.register,
    });
    if (t === null) return { next: UNKNOWN, subscript };
    // An element read whose index calls, or reads a volatile, has that side
    // effect too: `arr[nextIndex()]` is not a pure read
    const keep = {
      hasSideEffect:
        t.hasSideEffect ||
        indices.some((index) => OperandTyper.hasSideEffect(index, ctx)),
    };
 
    switch (subscript) {
      case "array_element": {
        if (t.dimensions.length > 0) {
          return {
            subscript,
            next: {
              k: "value",
              register: false,
              t: {
                ...t,
                dimensions: t.dimensions.slice(1),
                overflow: null,
                binding: null,
                form: DECLARED,
                ...keep,
              },
            },
          };
        }
        // Only a string's element is a character (#1760 review). A header
        // value with no dimensions -- a C++ `operator[]` result, a `T*`
        // field -- is one the typer cannot see into, not a `char`
        if (!OperandTyper.isString(t)) {
          return { subscript, next: UNKNOWN };
        }
        return {
          subscript,
          next: {
            k: "value",
            register: false,
            t: {
              ...OperandTyper.plain("char"),
              category: "character",
              bitWidth: 8,
              ...keep,
            },
          },
        };
      }
      case "array_slice":
        return {
          subscript,
          next: {
            k: "value",
            register: false,
            t: { ...t, overflow: null, binding: null, ...keep },
          },
        };
      case "bit_single":
        return {
          subscript,
          next: {
            k: "value",
            register: false,
            t: {
              ...OperandTyper.plain("bool"),
              category: "boolean",
              form: { kind: "bitIndex" },
              ...keep,
            },
          },
        };
      case "bit_range": {
        const width = OperandTyper.foldedWidth(indices[1], ctx);
        // The unsigned type that holds the bits, as 2.2 always typed a range
        const typeName =
          width === null ? null : OperandTyper.unsignedFor(width);
        return {
          subscript,
          next: {
            k: "value",
            register: false,
            t: {
              ...OperandTyper.plain(typeName),
              category: "unsigned",
              bitWidth: OperandTyper.widthOf(typeName),
              form: { kind: "bitRange", width },
              ...keep,
            },
          },
        };
      }
    }
  }
 
  private static callOf(
    current: TChainValue,
    ctx: ITypingContext,
  ): TChainValue {
    const call: TOperandForm = { kind: "call" };
    if (current.k === "function") {
      return {
        k: "value",
        register: false,
        t: {
          ...OperandTyper.fromType(current.returnType, [], ctx),
          hasSideEffect: true,
          form: call,
        },
      };
    }
    if (current.k === "value" && current.t.typeName !== null) {
      // An ADR-029 callback: its type names the function that defines it
      const definer = ctx.program.symbolByCName(current.t.typeName);
      if (definer?.kind === "function") {
        return {
          k: "value",
          register: false,
          t: {
            ...OperandTyper.fromType(definer.returnType, [], ctx),
            hasSideEffect: true,
            form: call,
          },
        };
      }
    }
    Iif (current.k === "foreignFunction") {
      return current.result
        ? {
            k: "value",
            register: false,
            t: { ...current.result, hasSideEffect: true, form: call },
          }
        : UNKNOWN;
    }
    if (current.k === "foreignPath") {
      const t = ForeignTypeFacts.callOperand(
        current.parts.join("::"),
        ctx.symbolTable,
        OperandTyper.target(ctx),
      );
      return t ? { k: "value", register: false, t } : UNKNOWN;
    }
    return UNKNOWN;
  }
 
  // --------------------------------------------------------------------------
  // Small facts
  // --------------------------------------------------------------------------
 
  /** A bit range's width, when it folds in the constants visible there */
  private static foldedWidth(
    widthExpr: Parser.ExpressionContext | undefined,
    ctx: ITypingContext,
  ): number | null {
    Iif (!widthExpr) return null;
    const value = ConstExprLowering.valueOf(
      widthExpr,
      ConstantFold.environment(ctx.program, ctx.sourceFile),
    );
    return value !== undefined && value > 0 ? value : null;
  }
 
  private static unsignedFor(width: number): string | null {
    if (width <= 8) return "u8";
    if (width <= 16) return "u16";
    if (width <= 32) return "u32";
    Eif (width <= 64) return "u64";
    return null;
  }
 
  private static widthOf(typeName: string | null): number | null {
    return typeName !== null && TypeCheckUtils.isInteger(typeName)
      ? TYPE_WIDTH[typeName]
      : null;
  }
 
  private static cNameOf(sourceName: string): string {
    return sourceName.includes(".")
      ? QualifiedCName.fromParts(sourceName.split("."))
      : sourceName;
  }
 
  private static booleanValue(hasSideEffect: boolean): IOperandType {
    return {
      ...OperandTyper.plain("bool"),
      category: "boolean",
      hasSideEffect,
      form: { kind: "boolean" },
    };
  }
 
  /** An operand with a type name and nothing else settled */
  private static plain(typeName: string | null): IOperandType {
    return {
      typeName,
      cType: null,
      dimensions: [],
      category: "none",
      bitWidth: null,
      stringCapacity: null,
      enumTypeName: null,
      bitmapTypeName: null,
      overflow: null,
      hasSideEffect: false,
      form: DECLARED,
      binding: null,
    };
  }
 
  /** The run's target description, or null while 1.4 has not resolved it */
  static target(ctx: ITypingContext): ITargetDescription | null {
    const target = ctx.program.target();
    return target.kind === "resolved" ? target.description : null;
  }
}
 
export default OperandTyper;