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 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 | 90x 625x 625x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 257x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 2672x 1131x 1131x 2220x 2220x 2220x 2220x 2220x 1089x 1089x 1758x 188x 1570x 1570x 1570x 1570x 123x 1570x 1570x 1570x 1570x 931x 931x 931x 931x 931x 207x 207x 207x 207x 207x 152x 152x 152x 152x 152x 152x 152x 152x 245x 17x 13x 13x 116x 1091x 210x 210x 46x 7x 5x 460x 94x 2356x 2356x 74x 2282x 2082x 200x 200x 122x 122x 8x 8316x 8316x 6082x 2234x 2234x 2234x 2234x 72x 2162x 2162x 34x 34x 31x 2131x 1x 9x 3x 6x 6x 1x 5x 5x 4x 4x 1x 1874x 311x 15114x 38x 38x 2x 38x 72x 72x 72x 72x 72x 72x 72x 72x 6x 4x 2x 2x 14x 196x 196x 252x 252x 252x 104x 78x 252x 196x 1061x 1061x 1061x 2x 2x 115x 217x 14705x 6x 5x 1252x 158x 158x 64x 1188x 68x 7x 7x 3x 4x 7x 4x 4x 4x 4x 4x 7x 7x 7x 7x 7x 3x 2x 307x 307x 307x 19x 19x 26x 22x 19x 18x 61x 118x 1x 1x 1x 1x 1x 1x 1x 3x 875x 643x 2x 641x 2x 639x 2x 1599x 2258x 2258x 649x 649x 649x 2x 649x 649x 647x 2x 1x 1x 1x 1x 95x 1190x 1190x 1189x 1189x 1x 35x 35x 35x 32x 32x 3x 32x 1x 2x 2x 2x 2x 12x 33x 6x 27x 27x 24x 3x 3x 1x 1x 1x 14x | /**
* CodeGenState - Global state for code generation
*
* Centralizes all code generation state in a single static class.
* Eliminates dependency injection complexity and makes debugging easier.
*
* Usage:
* import CodeGenState from "../state/CodeGenState";
* const type = CodeGenState.typeRegistry.get(name);
* if (CodeGenState.isKnownStruct(name)) { ... }
*
* Lifecycle:
* 1. CodeGenerator.generate() calls CodeGenState.reset()
* 2. CodeGenerator sets CodeGenState.generator = this
* 3. All generators/helpers read from CodeGenState directly
* 4. State persists for the duration of one generate() call
*
* SymbolTable ownership:
* CodeGenState owns the single SymbolTable instance. It persists across
* reset() calls (which are per-file). The Transpiler clears it via
* CodeGenState.symbolTable.clear() at the start of each run().
*/
import SymbolTable from "../logic/symbols/SymbolTable";
import TYPE_FORMING_KINDS from "../logic/symbols/TYPE_FORMING_KINDS";
import ESourceLanguage from "../../utils/types/ESourceLanguage";
import type TSymbolKindCNext from "../types/symbol-kinds/TSymbolKindCNext";
import ReservedCnxName from "../../utils/ReservedCnxName";
import ICodeGenSymbols from "../types/ICodeGenSymbols";
import TTypeInfo from "../types/TTypeInfo";
import TParameterInfo from "../types/TParameterInfo";
import IFunctionSignature from "../types/IFunctionSignature";
import ICallbackTypeInfo from "../types/ICallbackTypeInfo";
import type IRequirementSite from "../types/IRequirementSite";
import type TRequirementKey from "../types/TRequirementKey";
import RequirementSites from "../../utils/RequirementSites";
import ITargetCapabilities from "../types/ITargetCapabilities";
import TOverflowBehavior from "../types/TOverflowBehavior";
import TYPE_WIDTH from "../constants/TYPE_WIDTH";
import UNRESOLVED_DIMENSION from "../constants/UNRESOLVED_DIMENSION";
import type ICodeGenApi from "../types/ICodeGenApi";
import TypeResolver from "../../utils/TypeResolver";
import type IVariableSymbol from "../types/symbols/IVariableSymbol";
import QualifiedCName from "../../utils/QualifiedCName";
import IScopeSymbol from "../types/symbols/IScopeSymbol";
import ScopeUtils from "../../utils/ScopeUtils";
import SymbolRegistry from "./SymbolRegistry";
import DEFAULT_TARGET from "../constants/DEFAULT_TARGET";
/**
* Default target capabilities (safe fallback)
* Uses C99 guarantees: 31 external, 63 internal significant characters.
*/
/**
* Assignment context for overflow behavior tracking (ADR-044)
*/
interface IAssignmentContext {
targetName: string | null;
targetType: string | null;
overflowBehavior: TOverflowBehavior;
}
/**
* Function call graph entry for transitive modification analysis
*/
interface ICallGraphEntry {
callee: string;
paramIndex: number;
argParamName: string;
}
/**
* Global state for code generation.
* All fields are static - import and use directly from any module.
*
* NOTE: All static properties are intentionally mutable (not readonly).
* This class holds session state that is reset via reset() and modified
* during code generation.
*/
export default class CodeGenState {
// ===========================================================================
// GENERATOR REFERENCE (for handler access)
// ===========================================================================
/**
* Reference to the CodeGenerator instance for handlers to call its methods,
* typed to the method subset they use (ICodeGenApi).
*
* #1297: `ICodeGenApi` lives in `transpiler/types/`, a layer both sides may
* depend on, rather than in `output/`. The previous note here argued the edge
* was harmless because it was `import type` and CodeGenState already imported
* siblings from `output/codegen/types` -- but that was the whole problem:
* `logic/ -> state/ -> output/` was live through exactly those imports while
* `logic-cannot-import-output` reported clean, because it matched only direct
* edges. The rule is now transitive and `state/` has one of its own.
*
* The reference itself is still a `state/` object holding a codegen contract.
* That coupling is by design today and is #1323's to move; what this removes
* is the layer VIOLATION, not the dependency.
*/
static generator: ICodeGenApi | null = null;
/**
* The CodeGenerator instance, asserted present. Handlers call this instead of
* each casting `generator` themselves — one source of truth for the access and
* null-check (the generator is always set before any handler runs).
*/
static requireGenerator(): ICodeGenApi {
Iif (CodeGenState.generator === null) {
throw new Error(
"CodeGenState.generator is not set; codegen accessed before initialization.",
);
}
return CodeGenState.generator;
}
// ===========================================================================
// SYMBOL DATA (read-only after initialization)
// ===========================================================================
/** ADR-055: Pre-collected symbol info from CNextResolver + TSymbolInfoAdapter */
static symbols: ICodeGenSymbols | null = null;
/** External symbol table for cross-language interop (C headers).
* Owned by CodeGenState; persists across per-file reset() calls.
* Cleared via symbolTable.clear() at the start of each Transpiler run.
*/
static symbolTable: SymbolTable = new SymbolTable();
/**
* External struct fields from C/C++ headers for initialization analysis.
* Maps struct name -> Set of non-array field names.
* Persists across per-file reset() calls, cleared at start of run.
*/
static externalStructFields: Map<string, Set<string>> = new Map();
// ===========================================================================
// TYPE TRACKING
// ===========================================================================
/**
* Track variable types for bit access, .length, and type inference.
* PRIVATE: Use getVariableTypeInfo()/setVariableTypeInfo() instead.
* This ensures cross-file variables from SymbolTable are also found.
*/
private static typeRegistry: Map<string, TTypeInfo> = new Map();
/** Bug #8: Compile-time const values for array size resolution */
static constValues: Map<string, number> = new Map();
// ===========================================================================
// FUNCTION & CALLBACK TRACKING
// ===========================================================================
/** Track C-Next defined functions */
static knownFunctions: Set<string> = new Set();
/**
* #1399 review: whether the file being analyzed can see a C/C++ header,
* directly or through any `.cnx` it includes. Set by `Transpiler` from the
* resolver's categorization before `runAnalyzers`.
*
* Defaults to `true` so an unset value declines rather than diagnoses: a
* false positive stops valid code compiling, a false negative is the status
* quo.
*/
static currentFileReachesForeignHeader = true;
/** ADR-013: Track function parameter const-ness for call-site validation */
static functionSignatures: Map<string, IFunctionSignature> = new Map();
/** ADR-029: Callback types registry (function-as-type pattern) */
static callbackTypes: Map<string, ICallbackTypeInfo> = new Map();
/** Callback field types: "Struct.field" -> callbackTypeName */
static callbackFieldTypes: Map<string, string> = new Map();
/**
* ADR-029 / Issues #1200, #1201: every type name referenced by a field or a
* parameter, wherever it appears -- top-level struct, scope-nested struct,
* scope member, or function parameter.
*
* Emitting a callback's `_fp` typedef is one decision, and it used to be
* derived from callbackFieldTypes alone. That map is populated only while
* walking TOP-LEVEL struct declarations, so a callback used anywhere else was
* registered as known, referenced in the output, and never given a typedef --
* generated C that does not compile.
*
* Names go in unfiltered: a parameter may name a callback declared later in
* the file, so membership is intersected with callbackTypes at query time
* rather than at collection time.
*/
static callbackTypeReferences: Set<string> = new Set();
/**
* Issue #1164: does the generated header own this callback's typedef?
*
* When the `.c` includes its own header, whichever typedefs the header emits
* must not be emitted a second time -- C99 rejects even an identical typedef
* redefinition. Both sides ask this one question so they cannot disagree
* about who owns a given typedef.
*
* Keyed on callbackTypeReferences (#1200/#1201) rather than a set of its own:
* that already records every site naming a callback type, so ownership and
* emission cannot drift apart.
*/
static headerOwnsCallbackTypedef(functionName: string): boolean {
return this.callbackTypeReferences.has(functionName);
}
/**
* Issue #1212: callback `_fp` typedefs awaiting placement.
*
* They used to be appended after the function each was derived from, which
* only works when every use appears later in the file. A parameter naming a
* callback declared further down got a typedef after its first use, and the
* generated C did not compile.
*
* They cannot simply be hoisted into the prelude either: a callback typedef
* inherits its parameters' dependencies, so `typedef void (*onReceive_fp)(const
* Message*)` must follow `Message`'s definition. Collecting them here lets
* generateAllDeclarations place the whole block after the type declarations
* and before the first function.
*/
static pendingCallbackTypedefs: string[] = [];
/**
* Functions that are assigned to C callback typedefs.
* Maps function name -> typedef name (e.g., "my_flush" -> "flush_cb_t")
* Issue #895: We need the typedef name to look up parameter types.
*/
static callbackCompatibleFunctions: Map<string, string> = new Map();
// ===========================================================================
// PASS-BY-VALUE ANALYSIS (Issue #269)
// ===========================================================================
/** Tracks which parameters are modified (directly or transitively) */
static modifiedParameters: Map<string, Set<string>> = new Map();
/** Parameters that should pass by value (small, unmodified primitives) */
static passByValueParams: Map<string, Set<string>> = new Map();
/** Function call relationships for transitive modification analysis */
static functionCallGraph: Map<string, ICallGraphEntry[]> = new Map();
/** Function parameter lists for call graph analysis */
static functionParamLists: Map<string, string[]> = new Map();
/** Issue #558: Cross-file modifications to inject */
static pendingCrossFileModifications: ReadonlyMap<
string,
ReadonlySet<string>
> | null = null;
/** Issue #558: Cross-file parameter lists to inject */
static pendingCrossFileParamLists: ReadonlyMap<
string,
readonly string[]
> | null = null;
// ===========================================================================
// OVERFLOW & DIVISION HELPERS (ADR-044, ADR-051)
// ===========================================================================
/** Track which overflow helper types/operations are needed: "add_u8", etc. */
static usedClampOps: Set<string> = new Set();
/** Track which safe division helpers are needed: "div_u32", "mod_i16" */
static usedSafeDivOps: Set<string> = new Set();
// ===========================================================================
// TOOLCHAIN REQUIREMENTS (Issue #1143)
// ===========================================================================
/**
* What the generated output for this file actually costs the user, recorded
* by each emitter as it produces the text.
*
* Consumers read this; nothing re-derives it. PR #1141 failed by re-deriving
* -- its #error guard keyed on `usedClampOps.size > 0` while the emission it
* described keyed on the template family, so 96 snapshots shipped a guard for
* a builtin they did not contain.
*/
static recordedRequirements: Map<TRequirementKey, IRequirementSite[]> =
new Map();
/**
* Source sites for emissions that are DEFERRED to assembleGeneratedOutput --
* clamp helpers, IRQ wrappers, float asserts. Keyed by the request that
* triggered the deferral ("add_u32", "irq_wrappers", "float_static_assert").
*
* Kept separate from recordedRequirements because at request time the code
* has not been emitted yet, so there is nothing to record a requirement for.
* The emitter claims these sites when it actually produces the block.
*/
static deferredRequirementSites: Map<string, IRequirementSite[]> = new Map();
// ===========================================================================
// CURRENT CONTEXT (changes during AST traversal)
// ===========================================================================
/** ADR-016: Current scope for name resolution */
static currentScope: IScopeSymbol | null = null;
/** Issue #269: Current function for modification tracking */
static currentFunctionName: string | null = null;
/** Issue #477: Current function return type for enum inference */
static currentFunctionReturnType: string | null = null;
/** ADR-006: Current function parameters for pointer semantics */
static currentParameters: Map<string, TParameterInfo> = new Map();
/** ADR-016: Local variables in current function (allowed as bare identifiers) */
static localVariables: Set<string> = new Set();
/** ADR-006: Local array variables (no & needed when passing) */
static localArrays: Set<string> = new Set();
/**
* ADR-057: bare source name -> the C identifier a shadowing local is emitted
* under.
*
* A local that shadows a file-scope name must NOT be emitted under that bare
* name: C has no `::` and no other syntax for reaching a shadowed outer
* identifier, so `global.x` would silently bind to the local. C-Next promises
* shadowing works and that `global.` still reaches past it, which means the
* *local* moves rather than the global becoming unreachable.
*
* Populated only when a collision actually exists, so the generated C keeps
* plain names in the common case -- the generated file is a certification
* artifact and a reviewer should not have to decode every local. Empty for
* the overwhelming majority of functions.
*/
private static localRenames: Map<string, string> = new Map();
/** Scope member names: scope -> Set of member names */
private static scopeMembers: Map<string, Set<string>> = new Map();
/** Float bit indexing: declared shadow variables */
static floatBitShadows: Set<string> = new Set();
/** Float bit indexing: shadows with current value (skip redundant reads) */
static floatShadowCurrent: Set<string> = new Set();
// ===========================================================================
// GENERATION STATE
// ===========================================================================
/** Current indentation level */
static indentLevel: number = 0;
/** Whether we're inside a function body */
static inFunctionBody: boolean = false;
/** Whether we're generating the RHS of a variable declaration initializer.
* When true, struct literals use { .field = value } instead of (Type){ .field = value }
* because plain designated initializers are valid C99 at any scope, while compound
* literals are not constant expressions and fail at file scope on GCC < 13. */
static inDeclarationInit: boolean = false;
/** Expected type for struct initializers and enum inference */
static expectedType: string | null = null;
/**
* Suppress bare enum resolution even when expectedType is set.
* Issue #872: MISRA 7.2 requires expectedType for U suffix on function args,
* but bare enum resolution in function args was never allowed and changing
* that would require ADR approval.
*/
static suppressBareEnumResolution: boolean = false;
/** Track args parameter name for main() translation */
static mainArgsName: string | null = null;
/** ADR-044: Current assignment context for overflow behavior */
static assignmentContext: IAssignmentContext = {
targetName: null,
targetType: null,
overflowBehavior: "clamp",
};
/** ADR-035: Element count for array size inference */
static lastArrayInitCount: number = 0;
/** ADR-035: Fill-all value for array initialization */
static lastArrayFillValue: string | undefined = undefined;
/** strlen optimization: variable name -> temp variable name */
static lengthCache: Map<string, string> | null = null;
/** ADR-049: Target platform capabilities */
static targetCapabilities: ITargetCapabilities = DEFAULT_TARGET;
// ===========================================================================
// INCLUDE FLAGS (track required standard library includes)
// ===========================================================================
/** For u8, u16, u32, u64, i8, i16, i32, i64 */
static needsStdint: boolean = false;
/** For bool type */
static needsStdbool: boolean = false;
/** ADR-045: For strlen, strncpy, etc. */
static needsString: boolean = false;
/** For float bit indexing size verification */
static needsFloatStaticAssert: boolean = false;
/** ADR-040: For ISR function pointer type */
static needsISR: boolean = false;
/** ADR-049/050: For atomic intrinsics and critical sections */
static needsCMSIS: boolean = false;
/** Issue #632: For float-to-int clamp casts */
static needsLimits: boolean = false;
/** Issue #473: IRQ wrappers for critical sections */
static needsIrqWrappers: boolean = false;
// ===========================================================================
// OPAQUE TYPE SCOPE VARIABLES (Issue #948)
// ===========================================================================
/**
* Tracks scope variables with opaque (forward-declared) struct types.
* These are generated as pointers with NULL initialization and should
* be passed directly (not with &) since they're already pointers.
* Maps qualified name (e.g., "MyScope_widget") to true.
*/
private static opaqueScopeVariables: Set<string> = new Set();
// ===========================================================================
// C++ MODE STATE (Issue #250)
// ===========================================================================
/** Use temp vars instead of compound literals */
static cppMode: boolean = false;
/** Debug mode generates panic-on-overflow helpers (ADR-044) */
static debugMode: boolean = false;
/** Pending temp variable declarations for C++ mode */
static pendingTempDeclarations: string[] = [];
/** Counter for unique temp variable names */
static tempVarCounter: number = 0;
/** Issue #517: Pending field assignments for C++ class struct init */
static pendingCppClassAssignments: string[] = [];
/** Issue #369: Whether self-include was added */
static selfIncludeAdded: boolean = false;
// ===========================================================================
// SOURCE PATHS (ADR-010, Issue #349)
// ===========================================================================
/** Source file path for validating includes */
static sourcePath: string | null = null;
/** Include directories for resolving angle-bracket .cnx includes */
static includeDirs: string[] = [];
/** Input directories for calculating relative paths */
static inputs: string[] = [];
// ===========================================================================
// LIFECYCLE METHODS
// ===========================================================================
/**
* Reset all state for a fresh generation pass.
* Called at the start of CodeGenerator.generate()
*/
static reset(targetCapabilities?: ITargetCapabilities): void {
// Generator reference
this.generator = null;
// Symbol data
this.symbols = null;
// Back to the declining default: reset() runs at the start of
// CodeGenerator.generate(), and a stale `false` here would let the next
// file diagnose names a header it cannot see supplies.
this.currentFileReachesForeignHeader = true;
// Note: symbolTable is NOT reset here — it persists across per-file generates.
// It is cleared via symbolTable.clear() at the start of each Transpiler run.
// Type tracking
this.typeRegistry = new Map();
this.constValues = new Map();
// Function & callback tracking
this.knownFunctions = new Set();
this.functionSignatures = new Map();
this.callbackTypes = new Map();
this.callbackFieldTypes = new Map();
this.callbackTypeReferences = new Set();
this.pendingCallbackTypedefs = [];
// Note: callbackCompatibleFunctions is NOT reset here — it's populated by
// FunctionCallAnalyzer (which runs before CodeGenerator.generate()) and must
// persist into code generation. It is cleared at the start of each Transpiler run.
// Pass-by-value analysis
this.modifiedParameters = new Map();
this.passByValueParams = new Map();
this.functionCallGraph = new Map();
this.functionParamLists = new Map();
// Note: pendingCrossFileModifications/ParamLists are set externally, not reset
// Overflow & division helpers
this.usedClampOps = new Set();
this.usedSafeDivOps = new Set();
// Toolchain requirements (Issue #1143). Both MUST be cleared per file:
// leaking them makes a project report attribute one file's CMSIS or C11
// cost to every later file.
this.recordedRequirements = new Map();
this.deferredRequirementSites = new Map();
// Current context
this.currentScope = null;
this.currentFunctionName = null;
this.currentFunctionReturnType = null;
this.currentParameters = new Map();
this.localVariables = new Set();
this.localArrays = new Set();
this.localRenames = new Map();
this.scopeMembers = new Map();
this.floatBitShadows = new Set();
this.floatShadowCurrent = new Set();
// Generation state
this.indentLevel = 0;
this.inFunctionBody = false;
this.inDeclarationInit = false;
this.expectedType = null;
this.suppressBareEnumResolution = false;
this.mainArgsName = null;
this.assignmentContext = {
targetName: null,
targetType: null,
overflowBehavior: "clamp",
};
this.lastArrayInitCount = 0;
this.lastArrayFillValue = undefined;
this.lengthCache = null;
this.targetCapabilities = targetCapabilities ?? DEFAULT_TARGET;
// Include flags
this.needsStdint = false;
this.needsStdbool = false;
this.needsString = false;
this.needsFloatStaticAssert = false;
this.needsISR = false;
this.needsCMSIS = false;
this.needsLimits = false;
this.needsIrqWrappers = false;
// C++ mode state
this.cppMode = false;
this.debugMode = false;
this.pendingTempDeclarations = [];
this.tempVarCounter = 0;
this.pendingCppClassAssignments = [];
this.selfIncludeAdded = false;
// Issue #948: Opaque scope variables (reset per-file)
this.opaqueScopeVariables = new Set();
// Source paths
this.sourcePath = null;
this.includeDirs = [];
this.inputs = [];
}
/**
* Enter a function body context.
* Clears local tracking and sets inFunctionBody flag.
*/
static enterFunctionBody(): void {
this.inFunctionBody = true;
this.clearFunctionLocals();
}
/**
* Clear every per-function local register.
*
* One owner for the whole family. Four copies of this block existed, and they
* had already diverged: `FunctionContextManager.setupFunctionContext` cleared
* three of the four and left `localArrays` to leak between functions. Adding
* `localRenames` to four call sites would have made that five.
*/
private static clearFunctionLocals(): void {
this.localVariables.clear();
this.localArrays.clear();
this.localRenames.clear();
this.floatBitShadows.clear();
this.floatShadowCurrent.clear();
}
/**
* Exit a function body context.
* Clears local tracking and sets inFunctionBody to false.
*/
static exitFunctionBody(): void {
this.inFunctionBody = false;
this.clearFunctionLocals();
}
/**
* Execute a function with a temporary expectedType, restoring on completion.
* Issue #872: Extracted to eliminate duplicate save/restore pattern and add exception safety.
*
* @param type - The expected type to set (if falsy, no change is made)
* @param fn - The function to execute
* @param suppressEnumResolution - If true, suppress bare enum resolution (for MISRA-only contexts)
* @returns The result of the function
*/
static withExpectedType<T>(
type: string | undefined | null,
fn: () => T,
suppressEnumResolution: boolean = false,
): T {
if (!type) {
return fn();
}
const savedType = this.expectedType;
const savedSuppress = this.suppressBareEnumResolution;
this.expectedType = type;
if (suppressEnumResolution) {
this.suppressBareEnumResolution = true;
}
try {
return fn();
} finally {
this.expectedType = savedType;
this.suppressBareEnumResolution = savedSuppress;
}
}
/** Execute fn with inDeclarationInit=true, restoring prior value on exit. */
static withDeclarationInit<T>(fn: () => T): T {
const saved = this.inDeclarationInit;
this.inDeclarationInit = true;
try {
return fn();
} finally {
this.inDeclarationInit = saved;
}
}
/** Execute fn with inDeclarationInit=false, restoring prior value on exit.
* Used in sub-expression contexts (function args, ternary arms) where
* plain designated initializers are not valid C. */
static withoutDeclarationInit<T>(fn: () => T): T {
const saved = this.inDeclarationInit;
this.inDeclarationInit = false;
try {
return fn();
} finally {
this.inDeclarationInit = saved;
}
}
/**
* Execute fn with expectedType=null, restoring prior value on exit.
* Issue #1032: Used in comparison contexts (relational/equality expressions)
* where MISRA 7.2 U suffix should NOT be applied - comparing `i32 < 0`
* should not generate `signedIdx < 0U` which changes comparison semantics.
*/
static withoutExpectedType<T>(fn: () => T): T {
const savedType = this.expectedType;
const savedSuppress = this.suppressBareEnumResolution;
this.expectedType = null;
this.suppressBareEnumResolution = false;
try {
return fn();
} finally {
this.expectedType = savedType;
this.suppressBareEnumResolution = savedSuppress;
}
}
// ===========================================================================
// CONVENIENCE LOOKUP METHODS
// ===========================================================================
/**
* Check if a type name is a known struct.
* Also includes bitmaps since they're struct-like (Issue #551).
*/
static isKnownStruct(name: string): boolean {
if (this.symbols?.knownStructs.has(name)) return true;
if (this.symbols?.knownBitmaps.has(name)) return true;
Iif (this.symbolTable.getStructFields(name)) return true;
return false;
}
/**
* Check if a type name is a known scope.
*/
static isKnownScope(name: string): boolean {
return this.symbols?.knownScopes.has(name) ?? false;
}
/**
* Check if a type name is a known enum.
*/
static isKnownEnum(name: string): boolean {
return this.symbols?.knownEnums.has(name) ?? false;
}
/**
* Check if a type name is a known bitmap.
*/
static isKnownBitmap(name: string): boolean {
return this.symbols?.knownBitmaps.has(name) ?? false;
}
/**
* Check if a *qualified* name is a known type declared in a scope.
* Used by QualifedCName.qualifyScopeType() to ensure only actual type
* declarations (enum/struct/bitmap/function) capture the name at a type
* position. ADR-029 makes a function definition create a callback type, so a
* scope function is a type declaration for this purpose; a scope VARIABLE is
* not, and deliberately does not capture (ADR-057).
*
* @param qualifiedName The already-joined C name (e.g. "A__B")
* @returns true if the qualified name is a known enum, struct, bitmap, or
* function-as-type (ADR-029)
*/
static isScopeType(qualifiedName: string): boolean {
// #1285: ONE lookup that returns the symbol, then a question about its kind.
//
// This was four parallel string sets -- knownEnums | knownStructs |
// knownBitmaps | callbackTypes -- and #1281 proposed adding a fifth. The sets
// are standing in for a `kind` field the symbol already carries, and asking
// them throws that kind away at the moment of lookup, which is why #1287's
// member access on a function-as-type has nothing left to diagnose with.
//
// TYPE_FORMING_KINDS owns "does this kind introduce a type name", so a new
// kind is answered in one place rather than by remembering to add a set.
// ADR-029 makes a function definition create a callback type, which is why
// `function` is a member.
//
// Measured equivalent to the four sets across the whole corpus before the
// swap: 1119 integration and 124 bug fixtures, zero disagreements, with a
// control confirming the probe fired (breaking the candidate produced 51).
const found = this.symbolTable.getOverloadsByCName(qualifiedName);
return found.some(
(symbol) =>
symbol.sourceLanguage === ESourceLanguage.CNext &&
TYPE_FORMING_KINDS.has(symbol.kind as TSymbolKindCNext),
);
}
/**
* ADR-057: qualify a bare type name against the scope being generated.
*
* Binds `QualifiedCName.qualifyScopeType()` to this state's current scope and
* type sets, so every codegen site asks the question one way. Call this rather
* than re-pairing `currentScope` with `isScopeType()` at each site.
*
* Only bare names belong here — `this.T`, `global.T` and `Scope.T` carry an
* explicit answer in the syntax and must keep their own branches.
*/
static qualifyScopeType(typeName: string): string {
return ScopeUtils.qualifyScopeType(
typeName,
this.currentScope,
(qualifiedName) => CodeGenState.isScopeType(qualifiedName),
);
}
/**
* Check if a type name is a known register.
*/
static isKnownRegister(name: string): boolean {
return this.symbols?.knownRegisters.has(name) ?? false;
}
/**
* Issue #948: Check if a type name is an opaque (forward-declared) struct type.
* Opaque types are incomplete types that can only be used as pointers.
* Example: `typedef struct _widget_t widget_t;` without a body makes `widget_t` opaque.
*/
static isOpaqueType(typeName: string): boolean {
return this.symbols?.opaqueTypes.has(typeName) ?? false;
}
/**
* Issue #958: Check if a type name is an external typedef struct type.
* External typedef struct types should use pointer semantics for scope variables.
* Unlike isOpaqueType, this returns true for both forward-declared and complete structs.
*/
static isTypedefStructType(typeName: string): boolean {
return this.symbolTable?.isTypedefStructType(typeName) ?? false;
}
/**
* The C-Next variable symbol a bare name resolves to in the SymbolTable, or
* undefined when the name is not a typed C-Next variable.
*
* Extracted so "which symbol is this name?" is decided once: both the
* TTypeInfo lookup below and the type-text lookup the analyzers use
* (getCNextVariableTypeName) go through it, instead of each repeating the
* kind/type narrowing and drifting apart.
*/
private static getCNextVariableSymbol(
name: string,
): IVariableSymbol | undefined {
const symbol = this.symbolTable.getTSymbol(name);
if (symbol?.kind === "variable" && symbol.type) {
return symbol;
}
// #1303 / #1139: `tSymbols` is keyed by the BARE name, so a caller holding
// a transpiled C name (`Counter__value` -- which every scope-member call
// site does hold) misses every scoped symbol, and the miss reads as "no
// such variable" rather than "wrong question". The by-C-name index answers
// the identity question instead.
//
// Gated on the name actually being qualified so a bare name still resolves
// exactly as before: this adds an answer where there was none, and changes
// none that existed.
if (!QualifiedCName.isQualified(name)) {
return undefined;
}
const byCName = this.symbolTable.getTOverloadsByCName(name)[0];
return byCName?.kind === "variable" && byCName.type ? byCName : undefined;
}
/**
* Declared type text of a C-Next variable as the SymbolTable records it --
* the same spelling a declaration in THIS file puts in a scope frame
* ("u32", "f32", "u8[4]").
*
* Issue #1220: the essential-type analyzers resolve a name against the
* lexical scope frames first and fall back to here, so a declaration that
* arrives through an #include is as visible to them as a local one. Without
* it, E0800/E0802/E0804/E0805/E0807/E0810 all passed silently the moment
* their operand crossed a file boundary.
*
* Deliberately does NOT consult the per-file typeRegistry. That map is
* cleared by CodeGenerator.generate(), which runs AFTER the analyzers, so
* during analysis it still holds the PREVIOUS file's variables and would
* answer for a name the current file never imported.
*/
static getCNextVariableTypeName(name: string): string | null {
const symbol = this.getCNextVariableSymbol(name);
return symbol ? TypeResolver.getTypeName(symbol.type) : null;
}
/**
* Integer value of a const C-Next variable as the SymbolTable records it,
* wherever it was declared.
*
* Issue #1220: the analyzer-facing companion to getCNextVariableTypeName,
* and deliberately symbol-table-ONLY. The obvious alternative -- reading
* CodeGenState.constValues first -- looks like it works, because that map is
* cleared by CodeGenerator.generate() and so still holds the consts of the
* file generated just before this one. Dependencies happen to be generated
* before their dependents today, which makes the stale map agree with the
* symbol table by coincidence rather than by rule. Asking the symbol table
* makes the answer independent of file order.
*/
static getCNextConstValue(name: string): number | undefined {
return this.symbolTable.getConstValue(name);
}
/**
* Get type info for a variable.
* Checks local typeRegistry first, then falls back to SymbolTable
* for cross-file variables from included .cnx files.
*
* Issue #786: This unified lookup ensures cross-file variables
* (defined in included files) are found even before code generation
* registers them locally.
*/
static getVariableTypeInfo(name: string): TTypeInfo | undefined {
// First check the local type registry (current file's variables)
const localInfo = this.typeRegistry.get(name);
if (localInfo) {
return localInfo;
}
// ADR-057: callers reach here with a RESOLVED identifier -- for a scope
// member that is already the registry key (`Scope__member`), but for a
// shadowing local it is the emitted name while the registry is keyed on
// the source spelling. Resolving both here rather than in each of the
// ~65 call sites keeps one answer to "what type is this?"; without it a
// bit-range write on a shadowing local silently lost its narrowing cast.
const sourceName = this.sourceLocalName(name);
Iif (sourceName !== name) {
const renamedInfo = this.typeRegistry.get(sourceName);
if (renamedInfo) {
return renamedInfo;
}
}
// ADR-055 Phase 7: Fall back to SymbolTable for cross-file C-Next variables only.
const symbol = this.getCNextVariableSymbol(name);
if (symbol) {
return this.convertTSymbolToTypeInfo(symbol);
}
// Issue #978: Fall back to C symbols for external struct globals from .h headers.
// Only return type info for struct-typed variables — returning info for all
// C types would cause regressions (e.g., array indexing misread as bit extraction).
const cSymbol = this.symbolTable.getCSymbol(name);
if (cSymbol?.kind === "variable" && cSymbol.type) {
const baseType = CodeGenState.stripTrailingPointers(cSymbol.type);
if (
this.symbolTable.isTypedefStructType(baseType) ||
this.symbolTable.getStructFields(baseType)
) {
return {
baseType,
bitWidth: 0,
isArray: cSymbol.isArray || false,
isConst: cSymbol.isConst || false,
isPointer: cSymbol.type.endsWith("*"),
};
}
}
return undefined;
}
/**
* Legacy alias for getVariableTypeInfo.
* @deprecated Use getVariableTypeInfo() instead
*/
static getTypeInfo(name: string): TTypeInfo | undefined {
return this.getVariableTypeInfo(name);
}
/**
* Check if a variable type is registered (locally or in SymbolTable).
* ADR-055 Phase 7: Uses getTSymbol for typed symbol lookup.
*/
static hasVariableTypeInfo(name: string): boolean {
if (this.typeRegistry.has(name)) {
return true;
}
const symbol = this.symbolTable.getTSymbol(name);
if (symbol?.kind === "variable" && symbol.type !== undefined) {
return true;
}
// Issue #978: Check C symbols for external struct globals only
const cSymbol = this.symbolTable.getCSymbol(name);
if (cSymbol?.kind === "variable" && cSymbol.type) {
const baseType = CodeGenState.stripTrailingPointers(cSymbol.type);
return (
this.symbolTable.isTypedefStructType(baseType) ||
!!this.symbolTable.getStructFields(baseType)
);
}
return false;
}
/**
* Set variable type info in the local registry.
*/
static setVariableTypeInfo(name: string, info: TTypeInfo): void {
this.typeRegistry.set(name, info);
}
/**
* Delete variable type info from the local registry.
*/
static deleteVariableTypeInfo(name: string): void {
this.typeRegistry.delete(name);
}
/**
* Get a read-only view of the local type registry.
* Used for passing to helper functions that need to iterate over types.
* Note: This only returns locally registered types, not cross-file symbols.
*/
static getTypeRegistryView(): ReadonlyMap<string, TTypeInfo> {
return this.typeRegistry;
}
/**
* Convert a TSymbol IVariableSymbol to TTypeInfo for unified type lookups.
* ADR-055 Phase 7: Works with typed TSymbol instead of ISymbol.
*/
/**
* Strip trailing pointer stars from a C type string (e.g., "font_t*" → "font_t").
* Uses string operations instead of regex to avoid SonarCloud ReDoS flag (S5852).
*/
private static stripTrailingPointers(type: string): string {
let end = type.length;
while (end > 0 && type[end - 1] === "*") {
end--;
}
return type.slice(0, end).trim();
}
private static convertTSymbolToTypeInfo(symbol: IVariableSymbol): TTypeInfo {
const typeName = TypeResolver.getTypeName(symbol.type);
// Parse string capacity using regex
const stringPattern = /^string<(\d+)>$/;
const stringMatch = stringPattern.exec(typeName);
const isString = stringMatch !== null;
const stringCapacity = stringMatch
? Number.parseInt(stringMatch[1], 10)
: undefined;
// Use char for string types to match local convention
const baseType = isString ? "char" : typeName;
const isEnum = this.isKnownEnum(baseType);
return {
baseType,
bitWidth: isString ? 8 : TYPE_WIDTH[baseType] || 0,
isArray: symbol.isArray || false,
// #1360: keep the slot. Filtering a dimension that cannot be folded out shifted
// every dimension after it, so a cross-file `u8[BUF_SIZE][3]` arrived as
// [3] and dimension 2's bound was applied to dimension 1 -- rejecting a
// valid `grid[10][0]` and never checking dimension 2 at all. That is the
// same defect #1127 fixed in getMemberTypeInfo, whose comment already
// records the reasoning; this path simply did not follow it.
//
// A numeric string still parses to its value -- only a genuinely
// dimension that cannot be folded (a macro name, or "" for an unsized `[]`) becomes
// UNRESOLVED_DIMENSION, which reads as "size unknown, cannot validate"
// because checkArrayBounds skips a non-positive bound.
arrayDimensions: symbol.arrayDimensions?.map((d) => {
if (typeof d === "number") {
return d;
}
const parsed = Number.parseInt(d, 10);
return Number.isNaN(parsed) ? UNRESOLVED_DIMENSION : parsed;
}),
isConst: symbol.isConst || false,
isAtomic: symbol.isAtomic || false,
// #1303: the declared ADR-044 behavior, carried on the symbol so an
// imported `u8` arrives saturating rather than silently wrapping.
overflowBehavior: symbol.overflowBehavior,
isEnum,
enumTypeName: isEnum ? baseType : undefined,
isString,
stringCapacity,
};
}
/**
* Check if a parameter in a function is modified.
*/
static isParameterModified(funcName: string, paramName: string): boolean {
return this.modifiedParameters.get(funcName)?.has(paramName) ?? false;
}
/**
* Compute unmodified parameters for all functions on-demand.
* Returns a map of function name -> Set of parameter names NOT modified.
* Computed from functionSignatures and modifiedParameters (no cached state).
*/
static getUnmodifiedParameters(): Map<string, Set<string>> {
const result = new Map<string, Set<string>>();
for (const [funcName, signature] of this.functionSignatures) {
const modifiedSet = this.modifiedParameters.get(funcName);
const unmodified = new Set<string>();
for (const param of signature.parameters) {
if (!modifiedSet?.has(param.name)) {
unmodified.add(param.name);
}
}
result.set(funcName, unmodified);
}
return result;
}
/**
* Check if a parameter should pass by value.
*/
static isPassByValue(funcName: string, paramName: string): boolean {
return this.passByValueParams.get(funcName)?.has(paramName) ?? false;
}
/**
* Get the function signature for a function.
*/
static getFunctionSignature(name: string): IFunctionSignature | undefined {
return this.functionSignatures.get(name);
}
/**
* Get callback type info for a function name.
*/
static getCallbackType(name: string): ICallbackTypeInfo | undefined {
return this.callbackTypes.get(name);
}
/**
* Issue #895: Get the typedef type string for a C typedef by name.
* Used to look up function pointer typedef signatures for callback-compatible functions.
*
* @param typedefName - Name of the typedef (e.g., "flush_cb_t")
* @returns The type string (e.g., "void (*)(widget_t *, const rect_t *, uint8_t *)") or undefined
*/
static getTypedefType(typedefName: string): string | undefined {
const symbol = this.symbolTable.getCSymbol(typedefName);
Iif (symbol?.kind === "type") {
return symbol.type;
}
return undefined;
}
/**
* Check if a type name is a known C-Next function.
*/
static isCNextFunction(name: string): boolean {
return this.knownFunctions.has(name);
}
/**
* Check if a name is a compile-time const value.
*/
static isConstValue(name: string): boolean {
return this.constValues.has(name);
}
/**
* Get the compile-time value of a const.
*/
static getConstValue(name: string): number | undefined {
return this.constValues.get(name);
}
/**
* Get parameter info from current function context.
*/
static getParameterInfo(name: string): TParameterInfo | undefined {
return this.currentParameters.get(name);
}
/**
* Check if a name is a local variable.
*/
static isLocalVariable(name: string): boolean {
return this.localVariables.has(name);
}
/**
* Check if a name is a local array.
*/
static isLocalArray(name: string): boolean {
return this.localArrays.has(name);
}
/**
* Get members of a scope.
*/
static getScopeMembers(scopeName: string): Set<string> | undefined {
return this.scopeMembers.get(scopeName);
}
/**
* Set members of a scope.
*/
static setScopeMembers(scopeName: string, members: Set<string>): void {
this.scopeMembers.set(scopeName, members);
}
/**
* Get all scope members (for IGeneratorState).
*/
static getAllScopeMembers(): ReadonlyMap<string, ReadonlySet<string>> {
return this.scopeMembers;
}
/**
* Check if an identifier is a member of the current scope.
*/
static isCurrentScopeMember(identifier: string): boolean {
if (!this.currentScope) return false;
// `scopeMembers` is keyed by the scope's LEAF name, so this passes `.name`
// deliberately rather than the scope's identity. That key is itself a
// leaf-only encoder and collides at depth two -- tracked as #1295, not
// changed here, because its producer and every other reader move with it.
return (
this.scopeMembers.get(this.currentScope.name)?.has(identifier) ?? false
);
}
/**
* Resolve an identifier to its fully-scoped name.
* Inside a scope, checks if the identifier is a scope member first.
*/
static resolveIdentifier(identifier: string): string {
if (this.currentScope) {
const members = this.scopeMembers.get(this.currentScope.name);
if (members?.has(identifier)) {
// Built from the scope CHAIN, so a member of a nested scope gets every
// component rather than just the innermost one.
return ScopeUtils.getTranspiledCName({
name: identifier,
scope: this.currentScope,
});
}
}
return identifier;
}
/**
* Get struct field type (simple lookup).
*/
static getStructFieldType(
structName: string,
fieldName: string,
): string | undefined {
return this.symbols?.structFields.get(structName)?.get(fieldName);
}
/**
* Get struct field info including dimensions (checks SymbolTable then local symbols).
*/
static getStructFieldInfo(
structType: string,
fieldName: string,
): { type: string; dimensions?: (number | string)[] } | null {
// First check SymbolTable (C header structs)
const fieldInfo = this.symbolTable.getStructFieldInfo(
structType,
fieldName,
);
if (fieldInfo) {
return {
type: fieldInfo.type,
dimensions: fieldInfo.arrayDimensions,
};
}
// Fall back to local C-Next struct fields
const localFields = this.symbols?.structFields.get(structType);
if (localFields) {
const fieldType = localFields.get(fieldName);
Eif (fieldType) {
const fieldDimensions =
this.symbols?.structFieldDimensions.get(structType);
const dimensions = fieldDimensions?.get(fieldName);
return {
type: fieldType,
dimensions: dimensions ? [...dimensions] : undefined,
};
}
}
return null;
}
/**
* Get member type info for a struct field.
* Returns full TTypeInfo for the field, or null if not found.
*/
static getMemberTypeInfo(
structType: string,
memberName: string,
): TTypeInfo | null {
const fieldInfo = this.getStructFieldInfo(structType, memberName);
Iif (!fieldInfo) return null;
const isArray =
(fieldInfo.dimensions !== undefined && fieldInfo.dimensions.length > 0) ||
(this.symbols?.structFieldArrays.get(structType)?.has(memberName) ??
false);
// Issue #1127: map a non-numeric dimension to UNRESOLVED_DIMENSION rather
// than filtering it out. TTypeInfo.arrayDimensions is number[], so an
// enum-qualified count cannot be carried here -- but dropping it shifts
// every dimension after it, so `u8[EColor.COUNT][3] cells` came back as
// [3] and put dimension 2's bound in dimension 1's slot.
//
// UNRESOLVED_DIMENSION holds the slot and reads as "size unknown";
// TypeValidator.checkArrayBounds skips it because it is not > 0.
const dims = fieldInfo.dimensions?.map((d) =>
typeof d === "number" ? d : UNRESOLVED_DIMENSION,
);
return {
baseType: fieldInfo.type,
bitWidth: TYPE_WIDTH[fieldInfo.type] ?? 32,
isConst: false,
isArray,
arrayDimensions: dims && dims.length > 0 ? dims : undefined,
};
}
/**
* Check if a struct field is an array.
*/
static isStructFieldArray(structName: string, fieldName: string): boolean {
return (
this.symbols?.structFieldArrays.get(structName)?.has(fieldName) ?? false
);
}
/**
* Get enum members for an enum.
*/
static getEnumMembers(
enumName: string,
): ReadonlyMap<string, number> | undefined {
return this.symbols?.enumMembers.get(enumName);
}
/**
* Build external struct fields from the symbol table.
* Called once per run after all headers are processed.
* Issue #355: Excludes array fields from init checking.
*/
static buildExternalStructFields(): void {
this.externalStructFields.clear();
const allStructFields = this.symbolTable.getAllStructFields();
for (const [structName, fieldMap] of allStructFields) {
const nonArrayFields = new Set<string>();
for (const [fieldName, fieldInfo] of fieldMap) {
// Only include non-array fields in init checking
if (
!fieldInfo.arrayDimensions ||
fieldInfo.arrayDimensions.length === 0
) {
nonArrayFields.add(fieldName);
}
}
if (nonArrayFields.size > 0) {
this.externalStructFields.set(structName, nonArrayFields);
}
}
}
/**
* Get external struct fields for initialization analysis.
*/
static getExternalStructFields(): Map<string, Set<string>> {
return this.externalStructFields;
}
/**
* Get function return type.
*/
static getFunctionReturnType(funcName: string): string | undefined {
return this.symbols?.functionReturnTypes.get(funcName);
}
// ===========================================================================
// INCLUDE FLAG HELPERS
// ===========================================================================
/**
* Mark that stdint.h is needed.
*/
static requireStdint(): void {
this.needsStdint = true;
}
/**
* Mark that stdbool.h is needed.
*/
static requireStdbool(): void {
this.needsStdbool = true;
}
/**
* Mark that string.h is needed.
*/
static requireString(): void {
this.needsString = true;
}
/**
* Mark that CMSIS headers are needed.
*/
static requireCMSIS(): void {
this.needsCMSIS = true;
}
/**
* Mark that limits.h is needed.
*/
static requireLimits(): void {
this.needsLimits = true;
}
/**
* Mark that ISR type is needed.
*/
static requireISR(): void {
this.needsISR = true;
}
// ===========================================================================
// TYPE REGISTRATION HELPERS
// ===========================================================================
/**
* Register a variable type.
*/
static registerType(name: string, info: TTypeInfo): void {
this.setVariableTypeInfo(name, info);
}
/**
* Register a const value.
*/
static registerConstValue(name: string, value: number): void {
this.constValues.set(name, value);
}
/**
* Enter a scope by its DOTTED PATH, resolving it to the scope symbol that
* carries the parent chain.
*
* The parameter is a path (`Outer.Inner`), not a leaf, because that is what
* `SymbolRegistry.getOrCreateScope` takes. Pass a leaf for a nested scope and
* it does not fail -- it CREATES a fresh scope parented to global and
* registers it under the leaf, after which every qualification through
* `currentScope` silently returns a one-level name.
*
* Every codegen caller currently passes a leaf, and that is correct for every
* program C-Next can express: `scopeMember` admits no `scopeDeclaration`
* (grammar/CNext.g4:81-89), so a scope's leaf IS its whole path. It stops
* being correct the moment scopes can nest, which is why the gap is tracked
* as #1304 rather than left to be rediscovered.
*/
static setCurrentScopeByPath(name: string | null): void {
this.currentScope =
name === null ? null : SymbolRegistry.getOrCreateScope(name);
}
/**
* ADR-057: whether a bare name is already taken by a FILE-SCOPE C identifier.
*
* Asks the canonical-identity index, not the bare-name one: a symbol whose
* transpiled C name IS the bare spelling is by definition at file scope,
* because anything inside a scope carries its scope in that name
* (`Counter__count`). So a scope member never counts as a collision -- it is
* still reachable as `this.count` regardless of what the local is called.
*
* An outer *local* is excluded deliberately. C block scoping already gives
* the language's shadowing semantics there, and neither `global.` nor `this.`
* can name an outer local, so nothing becomes unreachable.
*/
static shadowsFileScopeSymbol(name: string): boolean {
if (this.localVariables.has(name)) {
return false;
}
if (this.knownFunctions.has(name)) {
return true;
}
return this.symbolTable.getOverloadsByCName(name).length > 0;
}
/**
* Record that a shadowing local is emitted under a different C identifier.
*
* Keyed on the BARE name because that is what every reference in the source
* says and what every registry (`typeRegistry`, `localVariables`,
* `constValues`) is keyed by. Only the emitted text moves.
*/
static registerLocalRename(name: string, emittedName: string): void {
this.localRenames.set(name, emittedName);
}
/**
* The C identifier a local is emitted under -- its own name unless it shadows
* a file-scope symbol. Call at every point a local's name is WRITTEN into C;
* never when looking one up.
*/
static emittedLocalName(name: string): string {
return this.localRenames.get(name) ?? name;
}
/**
* The source name behind an emitted local identifier -- the inverse of
* `emittedLocalName`.
*
* Derived by scanning the one rename map rather than kept as a second map,
* so the two directions cannot drift apart. The map holds only shadowing
* locals, so it is empty in almost every function.
*
* Needed where a helper is handed the emitted name for code generation but
* must still register under the name the source used: every registry
* (`localVariables`, `localArrays`, `typeRegistry`) is keyed by the source
* spelling, because that is what references in the source say.
*/
static sourceLocalName(emittedName: string): string {
for (const [source, emitted] of this.localRenames) {
if (emitted === emittedName) {
return source;
}
}
return emittedName;
}
/**
* Register a local variable, deciding its emitted C name first.
*
* The single registration point for every kind of local -- declarations,
* `for` init variables, and generator effects all arrive here. The shadow
* decision has to sit in front of the registration and cannot be duplicated
* into the callers: `shadowsFileScopeSymbol` consults `localVariables`, so a
* caller that registered first would ask about a name that is already local
* and always be told "no collision".
*/
static registerLocalVariable(name: string, isArray: boolean = false): void {
this.planShadowingLocalName(name);
this.localVariables.add(name);
if (isArray) {
this.localArrays.add(name);
}
}
/**
* ADR-057: give a local that shadows a file-scope name a distinct C
* identifier, so `global.x` still reaches past it.
*
* C has no `::`. Emitting the local as plain `count` makes an outer `count`
* unreachable for the rest of the function, so `global.count` would silently
* bind to the local -- wrong code, no diagnostic, clean compile. C-Next
* guarantees shadowing works AND that `global.` sees through it, so the local
* is what moves.
*
* `currentFunctionName` is already the qualified function name
* (`Counter__test`), so this adds one component to the existing encoder
* rather than inventing a second naming scheme.
*/
private static planShadowingLocalName(name: string): void {
const functionName = this.currentFunctionName;
if (!functionName || !this.shadowsFileScopeSymbol(name)) {
return;
}
this.registerLocalRename(
name,
QualifiedCName.fromParts([functionName, name]),
);
}
/**
* Register a function signature.
*/
static registerFunctionSignature(
name: string,
sig: IFunctionSignature,
): void {
this.functionSignatures.set(name, sig);
this.knownFunctions.add(name);
}
/**
* Register a callback type.
*/
static registerCallbackType(name: string, info: ICallbackTypeInfo): void {
this.callbackTypes.set(name, info);
}
/**
* Register a callback field type.
*/
static registerCallbackFieldType(key: string, typeName: string): void {
this.callbackFieldTypes.set(key, typeName);
}
/**
* Mark a clamp operation as used.
*/
static markClampOpUsed(operation: string, cnxType: string): void {
// Internal helper-op key (e.g. "add_u32"), not a scope-qualified C name.
// HelperGenerator splits this on a single underscore.
this.usedClampOps.add(`${operation}_${cnxType}`);
}
/**
* Issue #1143: THE recording sink for toolchain requirements.
*
* Every requirement, from every transport -- generator effects, the include
* funnel, and direct calls from static helpers -- lands here. Call it from
* the branch that emits the text, never from a caller that infers which
* branch ran.
*/
static requireToolchain(
key: TRequirementKey,
sites: readonly IRequirementSite[] = [],
): void {
const existing = this.recordedRequirements.get(key);
if (existing === undefined) {
this.recordedRequirements.set(key, [...sites]);
return;
}
for (const site of sites) {
RequirementSites.addUnique(existing, site);
}
}
/**
* Issue #1143: Note where a deferred emission was requested, so the emitter
* can attribute it once it actually produces the block.
*/
static noteDeferredSite(requestKey: string, line: number | null): void {
const site: IRequirementSite = {
sourcePath: this.sourcePath ?? "",
line,
};
const existing = this.deferredRequirementSites.get(requestKey);
if (existing === undefined) {
this.deferredRequirementSites.set(requestKey, [site]);
return;
}
RequirementSites.addUnique(existing, site);
}
/** Issue #1143: Sites recorded for a deferred emission. */
static takeDeferredSites(requestKey: string): readonly IRequirementSite[] {
return this.deferredRequirementSites.get(requestKey) ?? [];
}
/**
* Mark a safe div operation as used.
*/
static markSafeDivOpUsed(operation: string, cnxType: string): void {
// Internal helper-op key (e.g. "div_u32"), not a scope-qualified C name.
// HelperGenerator matches these with a single underscore.
this.usedSafeDivOps.add(`${operation}_${cnxType}`);
}
// ===========================================================================
// FLOAT BIT SHADOW HELPERS
// ===========================================================================
/**
* Register a float bit shadow variable.
*/
static registerFloatBitShadow(name: string): void {
this.floatBitShadows.add(name);
}
/**
* Check if a float bit shadow exists.
*/
static hasFloatBitShadow(name: string): boolean {
return this.floatBitShadows.has(name);
}
/**
* Mark a float shadow as having current value.
*/
static markFloatShadowCurrent(name: string): void {
this.floatShadowCurrent.add(name);
}
/**
* Check if a float shadow has current value.
*/
static isFloatShadowCurrent(name: string): boolean {
return this.floatShadowCurrent.has(name);
}
// ===========================================================================
// OPAQUE SCOPE VARIABLE HELPERS (Issue #948)
// ===========================================================================
/**
* Mark a scope variable as having an opaque (forward-declared) struct type.
* These are generated as pointers with NULL initialization.
*
* @param qualifiedName - The fully qualified variable name (e.g., "MyScope_widget")
*/
static markOpaqueScopeVariable(qualifiedName: string): void {
this.opaqueScopeVariables.add(qualifiedName);
}
/**
* Check if generated code accesses an opaque scope variable (and is thus
* already a pointer). Used during argument generation to decide whether an
* address-of (&) prefix is needed.
*
* Handles two forms:
* - Direct access: "MyScope_widget" → the handle itself (pointer)
* - Array-element access: "MyScope_widgets[i]" → an element of an opaque
* handle array, which is itself a pointer (Issue #996)
*
* @param generatedCode - The generated access expression (e.g. "UI_widgets[i]")
* @returns true if this resolves to an opaque scope variable (already a pointer)
*/
static isOpaqueScopeVariableAccess(generatedCode: string): boolean {
if (this.opaqueScopeVariables.has(generatedCode)) {
return true;
}
// Issue #996: An element of an opaque-handle array is already a pointer.
// Match on the base array name that precedes the subscript.
const bracketIndex = generatedCode.indexOf("[");
if (bracketIndex === -1) {
return false;
}
return this.opaqueScopeVariables.has(generatedCode.slice(0, bracketIndex));
}
// ===========================================================================
// C++ MODE HELPERS
// ===========================================================================
/**
* Add a pending temp declaration for C++ mode.
*/
static addPendingTempDeclaration(decl: string): void {
this.pendingTempDeclarations.push(decl);
}
/**
* Flush and return pending temp declarations.
*/
static flushPendingTempDeclarations(): string[] {
const decls = this.pendingTempDeclarations;
this.pendingTempDeclarations = [];
return decls;
}
/**
* Get a unique temp variable name.
*/
static getNextTempVarName(): string {
return ReservedCnxName.temporary(this.tempVarCounter++);
}
}
|