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 | 143x 6430x 6430x 6430x 6430x 6430x 6430x 6430x 6430x 6430x 6430x 6430x 6430x 6430x 11216x 11216x 2030x 9186x 3420x 3420x 3420x 3420x 3420x 241x 241x 424x 424x 1680x 3375x 23x 23x 1574x 1602x 447x 447x 1034x 447x 1x 2x 1x 1x 1x 1x 471x 471x 1055x 471x 393x 393x 393x 33x 33x 36x 111x 219x 13x 109x 12x 4812x 4812x 1203x 1203x 22x 8956x 138x 1804x 1804x 366x 1804x 85x 85x 23x 39x 1697x 1697x 9043x 138x 1804x 1804x 101x 1804x 442x 18x 1574x 7382x 7382x 138x 471x 471x 471x 128x 471x 471x 471x 43x 471x 441x 441x 441x 441x 723x 716x 7x 441x 441x 441x 441x 1224x 492x 732x 732x 732x 1x 731x 731x 731x 731x 8x 723x 441x 1224x 193x 1031x 271x 760x 7x 7x 15x 7x 635x 635x 348x 348x 635x 5x 5x 278x 278x 1244x 100x 100x 76x 76x 285x 76x 1404x 19x 7x 7x 7x 7x 7x 12x 68x 96x 96x 26x 601x 34x 15x 193x 114x 22x 22x 22x 22x 22x 110x 110x 110x 66x 11x 44x 44x 8x 38x 38x 17x 17x 422x 4307x 1362x 1373x 33x 33x 33x 5x 27x 27x 6x 1x 1x 6x 1375x 1x 14x 4x 34x 15x 4x | /**
* Unified Symbol Table
* Stores symbols from all source languages and detects conflicts
*
* ADR-055 Phase 7: Fully typed symbol storage using discriminated unions.
* - TSymbol: C-Next symbols (rich type system with TType)
* - TCSymbol: C header symbols (string types)
* - TCppSymbol: C++ header symbols (string types)
*/
import DeclarationSite from "../../utils/DeclarationSite";
import OpaqueTypeResolution from "../../utils/OpaqueTypeResolution";
import { produce, enableMapSet } from "immer";
import ESourceLanguage from "../../utils/types/ESourceLanguage";
import IConflict from "../../types/IConflict";
import IStructFieldInfo from "../../types/symbols/IStructFieldInfo";
import IStructSymbolState from "../../types/symbols/IStructSymbolState";
import TJsonSafe from "../../utils/types/TJsonSafe";
import TSymbol from "../../types/symbols/TSymbol";
import TCSymbol from "../../types/symbols/c/TCSymbol";
import TCppSymbol from "../../types/symbols/cpp/TCppSymbol";
import TAnySymbol from "../../types/symbols/TAnySymbol";
import IStructSymbol from "../../types/symbols/IStructSymbol";
import IEnumSymbol from "../../types/symbols/IEnumSymbol";
import IFunctionSymbol from "../../types/symbols/IFunctionSymbol";
import TypeResolver from "../../utils/TypeResolver";
import type ITargetDescription from "../../types/ITargetDescription";
import invariant from "../../utils/invariant";
// Enable immer support for Map and Set (must be called once at module scope)
enableMapSet();
/** Create a fresh initial struct symbol state */
function createInitialStructState(): IStructSymbolState {
return {
opaqueTypes: new Set(),
structTagAliases: new Map(),
typedefToTag: new Map(),
structTagsWithBodies: new Set(),
pointerTypedefs: new Set(),
};
}
/**
* Central symbol table for cross-language interoperability
*
* Per user requirement: Symbol conflicts between C-Next and C/C++ are ERRORS.
* - ERROR: Same symbol defined in C-Next and C/C++
* - OK: Multiple `extern` declarations in C (declaration, not definition)
* - OK: Function overloads in C++ (different signatures)
*/
class SymbolTable {
// ========================================================================
// C-Next Symbol Storage (TSymbol)
// ========================================================================
/** All C-Next TSymbols indexed by bare name (ADR-055: `init`, not `Motor__init`) */
private readonly tSymbols: Map<string, TSymbol[]> = new Map();
/**
* All C-Next TSymbols indexed by transpiled C name — their canonical identity.
*
* ADR-063 makes the qualified name injective, so it identifies a symbol
* without needing a scope to interpret it. The bare-name index above answers
* a different question ("what does `init` mean *here*?", which needs ADR-057
* local->scope->global context); this one answers "which symbol is
* `Motor__init`?". Codegen holds the latter, and before this index existed it
* had to ask the former and got a silent empty result.
*
* For a global symbol both indexes share a key, since its bare name already
* is its canonical identity.
*/
private readonly tSymbolsByCName: Map<string, TSymbol[]> = new Map();
/** C-Next TSymbols indexed by source file */
private readonly tSymbolsByFile: Map<string, TSymbol[]> = new Map();
// ========================================================================
// C Symbol Storage (TCSymbol)
// ========================================================================
/** All C symbols indexed by name */
private readonly cSymbols: Map<string, TCSymbol[]> = new Map();
/** C symbols indexed by source file */
private readonly cSymbolsByFile: Map<string, TCSymbol[]> = new Map();
// ========================================================================
// C++ Symbol Storage (TCppSymbol)
// ========================================================================
/** All C++ symbols indexed by name */
private readonly cppSymbols: Map<string, TCppSymbol[]> = new Map();
/** C++ symbols indexed by source file */
private readonly cppSymbolsByFile: Map<string, TCppSymbol[]> = new Map();
// ========================================================================
// Auxiliary Data (shared across languages)
// ========================================================================
/** Struct field information: struct name -> (field name -> field info) */
private readonly structFields: Map<string, Map<string, IStructFieldInfo>> =
new Map();
/**
* Issue #196 Bug 3: Track C struct names that need the 'struct' keyword
* These are structs defined as 'struct Name { ... }' without typedef
* In C, they must be referred to as 'struct Name', not just 'Name'
*/
private readonly needsStructKeyword: Set<string> = new Set();
/**
* Issue #985 recovery: names of external function-like MACROS recovered by
* translation-unit preprocessing (ExternalDeclarationOracle) for headers cnext
* could not preprocess standalone. Macros have no declaration to parse, so
* only their names are known; consulted by the undeclared-`global.`-call check
* so it does not false-positive on a real macro (e.g. FreeRTOS pdMS_TO_TICKS).
* Recovered FUNCTIONS are registered as full symbols (with signatures) instead.
*/
private readonly externalDeclarationNames: Set<string> = new Set();
/**
* Issue #958: Immutable struct symbol state — additive only, query-time resolution.
* Replaces separate opaqueTypes and structTagAliases fields.
*/
private structState: IStructSymbolState = createInitialStructState();
/**
* Issue #208: Track enum backing type bit widths
* C++14 typed enums: enum Name : uint8_t { ... } have explicit bit widths
*/
private readonly enumBitWidth: Map<string, number> = new Map();
// ========================================================================
// C-Next Symbol Methods (TSymbol)
// ========================================================================
/**
* Append a symbol to one of the multi-value indexes, creating the bucket on
* first use.
*
* Every index in this class is `Map<string, T[]>` and was maintained by its
* own copy of this get/push-or-set block. Adding an index meant writing the
* block again and remembering `clear()` — the "edit it in two places"
* anti-pattern CLAUDE.md calls the worst in the project.
*/
private static appendToIndex<T>(
index: Map<string, T[]>,
key: string,
symbol: T,
): void {
const existing = index.get(key);
if (existing) {
existing.push(symbol);
} else {
index.set(key, [symbol]);
}
}
/**
* Add a C-Next TSymbol to the table
*/
addTSymbol(symbol: TSymbol): void {
// #1285: read the identity the symbol was built with rather than deriving
// it again. The symbol and its index key can no longer disagree, because
// there is no second derivation to disagree with -- previously this called
// the encoder a second time and stayed correct only because it happened to
// be the same encoder.
const cName = symbol.fullyQualifiedCName;
SymbolTable.appendToIndex(this.tSymbols, symbol.name, symbol);
SymbolTable.appendToIndex(this.tSymbolsByCName, cName, symbol);
SymbolTable.appendToIndex(this.tSymbolsByFile, symbol.sourceFile, symbol);
// Auto-register struct fields for TypeResolver.getMemberTypeInfo()
if (symbol.kind === "struct") {
this.registerStructFields(symbol, cName);
}
}
/**
* Register struct fields in structFields map for cross-file type resolution.
* Called automatically when adding struct symbols.
* Issue #981: Now preserves string dimensions (macro names) for proper array detection.
*
* @param cName The struct's transpiled C name, already computed by the caller —
* passed in rather than re-derived so this symbol's identity has one producer
* per call, matching the canonical-identity rule the index above relies on.
*/
private registerStructFields(struct: IStructSymbol, cName: string): void {
for (const [fieldName, fieldInfo] of struct.fields) {
// Convert TType to string for structFields map
const typeString = TypeResolver.getTypeName(fieldInfo.type);
this.addStructField(
cName,
fieldName,
typeString,
fieldInfo.dimensions && fieldInfo.dimensions.length > 0
? fieldInfo.dimensions
: undefined,
);
}
}
/**
* Add multiple C-Next TSymbols at once
*/
addTSymbols(symbols: readonly TSymbol[]): void {
for (const symbol of symbols) {
this.addTSymbol(symbol);
}
}
/**
* Get a TSymbol by name (returns first match, or undefined)
*/
getTSymbol(name: string): TSymbol | undefined {
const symbols = this.tSymbols.get(name);
return symbols?.[0];
}
/**
* Get all TSymbols with a given name (for overload detection)
*/
getTOverloads(name: string): TSymbol[] {
return this.tSymbols.get(name) ?? [];
}
/**
* Get TSymbols by source file
*/
getTSymbolsByFile(file: string): TSymbol[] {
return this.tSymbolsByFile.get(file) ?? [];
}
/**
* Get all TSymbols
*/
getAllTSymbols(): TSymbol[] {
const result: TSymbol[] = [];
for (const symbols of this.tSymbols.values()) {
result.push(...symbols);
}
return result;
}
/**
* Get all struct symbols (type-safe filtering)
*/
getStructSymbols(): IStructSymbol[] {
return this.getAllTSymbols().filter(
(s): s is IStructSymbol => s.kind === "struct",
);
}
/**
* Get all enum symbols (type-safe filtering)
*/
getEnumSymbols(): IEnumSymbol[] {
return this.getAllTSymbols().filter(
(s): s is IEnumSymbol => s.kind === "enum",
);
}
/**
* Get all function symbols (type-safe filtering)
*/
getFunctionSymbols(): IFunctionSymbol[] {
return this.getAllTSymbols().filter(
(s): s is IFunctionSymbol => s.kind === "function",
);
}
/**
* Get TSymbol count
*/
getTSize(): number {
let count = 0;
for (const symbols of this.tSymbols.values()) {
count += symbols.length;
}
return count;
}
// ========================================================================
// C Symbol Methods (TCSymbol)
// ========================================================================
/**
* Add a C symbol to the table
* Issue #981: Also register struct fields for type resolution
*/
addCSymbol(symbol: TCSymbol): void {
SymbolTable.appendToIndex(this.cSymbols, symbol.name, symbol);
SymbolTable.appendToIndex(this.cSymbolsByFile, symbol.sourceFile, symbol);
// Issue #981: Register struct fields for getMemberTypeInfo() lookups
if (symbol.kind === "struct" && symbol.fields) {
this.registerCStructFields(symbol.name, symbol.fields);
}
}
/**
* Register C struct fields in structFields map for cross-file type resolution.
* Issue #981: Required for macro-sized array field detection on local struct variables.
*/
private registerCStructFields(
structName: string,
fields: ReadonlyMap<
string,
import("../../types/symbols/c/ICFieldInfo").default
>,
): void {
for (const [fieldName, fieldInfo] of fields) {
this.addStructField(
structName,
fieldName,
fieldInfo.type,
fieldInfo.arrayDimensions,
);
}
}
/**
* Add multiple C symbols at once
*/
addCSymbols(symbols: TCSymbol[]): void {
for (const symbol of symbols) {
this.addCSymbol(symbol);
}
}
/**
* Register external declaration names recovered via TU preprocessing.
* @see externalDeclarationNames
*/
addExternalDeclarationNames(names: ReadonlySet<string>): void {
for (const name of names) {
this.externalDeclarationNames.add(name);
}
}
/** Whether a name was recovered as an external function / function-like macro. */
hasExternalDeclaration(name: string): boolean {
return this.externalDeclarationNames.has(name);
}
/**
* Get a C symbol by name (returns first match, or undefined)
*/
getCSymbol(name: string): TCSymbol | undefined {
const symbols = this.cSymbols.get(name);
return symbols?.[0];
}
/**
* Whether `typeName` is a C typedef of a function pointer: its underlying
* type contains "(*)".
*
* One rule for two readers (#1825): 1.4 recognizes a function assigned to
* such a typedef as an ADR-029 callback, and 2.1 treats a variable of one as
* callable (ADR-040).
*/
isCFunctionPointerTypedef(typeName: string): boolean {
const sym = this.getCSymbol(typeName);
if (sym?.kind !== "type") return false;
// ICTypedefSymbol has a `type` field with the underlying C type string
return (
"type" in sym && typeof sym.type === "string" && sym.type.includes("(*)")
);
}
/**
* Get all C symbols with a given name
*/
getCOverloads(name: string): TCSymbol[] {
return this.cSymbols.get(name) ?? [];
}
/**
* Get C symbols by source file
*/
getCSymbolsByFile(file: string): TCSymbol[] {
return this.cSymbolsByFile.get(file) ?? [];
}
/**
* Get all C symbols
*/
getAllCSymbols(): TCSymbol[] {
const result: TCSymbol[] = [];
for (const symbols of this.cSymbols.values()) {
result.push(...symbols);
}
return result;
}
// ========================================================================
// C++ Symbol Methods (TCppSymbol)
// ========================================================================
/**
* Add a C++ symbol to the table
*/
addCppSymbol(symbol: TCppSymbol): void {
SymbolTable.appendToIndex(this.cppSymbols, symbol.name, symbol);
SymbolTable.appendToIndex(this.cppSymbolsByFile, symbol.sourceFile, symbol);
}
/**
* Add multiple C++ symbols at once
*/
addCppSymbols(symbols: TCppSymbol[]): void {
for (const symbol of symbols) {
this.addCppSymbol(symbol);
}
}
/**
* Get a C++ symbol by name (returns first match, or undefined)
*/
getCppSymbol(name: string): TCppSymbol | undefined {
const symbols = this.cppSymbols.get(name);
return symbols?.[0];
}
/**
* Get all C++ symbols with a given name
*/
getCppOverloads(name: string): TCppSymbol[] {
return this.cppSymbols.get(name) ?? [];
}
/**
* Get C++ symbols by source file
*/
getCppSymbolsByFile(file: string): TCppSymbol[] {
return this.cppSymbolsByFile.get(file) ?? [];
}
/**
* Get all C++ symbols
*/
getAllCppSymbols(): TCppSymbol[] {
const result: TCppSymbol[] = [];
for (const symbols of this.cppSymbols.values()) {
result.push(...symbols);
}
return result;
}
// ========================================================================
// Cross-Language Methods
// ========================================================================
/**
* Get all symbols across all languages
*/
getAllSymbols(): TAnySymbol[] {
return [
...this.getAllTSymbols(),
...this.getAllCSymbols(),
...this.getAllCppSymbols(),
];
}
/**
* Get first symbol matching a name across all languages.
* Searches TSymbol, then C, then C++ collections.
* Used by ISymbolLookup interface for constructor detection.
*/
/**
* Supplied to `ISymbolLookup` by STRUCTURAL conformance -- `SymbolTable` is
* passed where that interface is expected, so this is used without ever
* being named. `tsc` enforces it; knip cannot see it.
*
* @public
*/
getSymbol(name: string): TAnySymbol | undefined {
return (
this.getTSymbol(name) ?? this.getCSymbol(name) ?? this.getCppSymbol(name)
);
}
/**
* Get all overloads for a name across all languages.
*
* C-Next symbols are matched on their **bare** name, so a scoped member is
* found by the name it carries inside its scope (`readValue`), not by its
* transpiled C name. Callers holding a transpiled C name want
* getOverloadsByCName instead.
*/
getOverloads(name: string): TAnySymbol[] {
return [
...this.getTOverloads(name),
...this.getCOverloads(name),
...this.getCppOverloads(name),
];
}
/**
* Get all C-Next overloads whose canonical identity is the given transpiled
* C name (e.g. "Motor__init").
*
* The inverse of ScopeUtils.getTranspiledCName: that builds the name, this
* resolves it back to the symbol. Exact match — no decomposition, so nothing
* has to re-derive how a qualified name is spelled.
*/
getTOverloadsByCName(cName: string): TSymbol[] {
return this.tSymbolsByCName.get(cName) ?? [];
}
/**
* Get all overloads across all languages for a transpiled C name.
*
* Use this wherever the caller already holds a generated C identifier —
* codegen and anything downstream of it. C and C++ symbols have no scopes,
* so their name is already their identity and they are matched directly;
* C-Next symbols are matched through the canonical-identity index.
*/
getOverloadsByCName(cName: string): TAnySymbol[] {
return [
...this.getTOverloadsByCName(cName),
...this.getCOverloads(cName),
...this.getCppOverloads(cName),
];
}
/**
* Get symbols by source file across all languages
*/
getSymbolsByFile(file: string): TAnySymbol[] {
return [
...this.getTSymbolsByFile(file),
...this.getCSymbolsByFile(file),
...this.getCppSymbolsByFile(file),
];
}
/**
* Get total symbol count
*/
get size(): number {
return this.getTSize() + this.getCSize() + this.getCppSize();
}
/**
* Get C symbol count
*/
getCSize(): number {
let count = 0;
for (const symbols of this.cSymbols.values()) {
count += symbols.length;
}
return count;
}
/**
* Get C++ symbol count
*/
getCppSize(): number {
let count = 0;
for (const symbols of this.cppSymbols.values()) {
count += symbols.length;
}
return count;
}
// ========================================================================
// MISRA C:2012 Rule 5.1 - External Identifier Length
// ========================================================================
/**
* Reject two external identifiers that are indistinguishable within the
* target's significant-character limit (MISRA C:2012 Rule 5.1, issue #1307).
*
* C99 5.2.4.1 guarantees only 31 significant initial characters in an
* external identifier, and `Scope__member` spends that budget on the
* *encoding* rather than on the author's names -- the `__` separator costs two
* characters per level and the scope name costs its full length. Two members
* of `TemperatureSensorController` agree for 29 characters before their own
* names begin, so a conforming implementation may treat them as one
* identifier. On a hosted GCC nothing happens; on the minimal embedded
* toolchain that is C-Next's target audience the two variables silently
* become one, and `cppcheck --addon=misra` does not report it.
*
* Scoped to identifiers C-Next itself generates, and among those to the ones
* with external linkage:
* - A C or C++ header's identifiers are not this transpiler's to rename, and
* C++ names are mangled rather than truncated.
* - `static` members (ADR-016 emits `private` as `static`) have internal
* linkage, which C99 gives a 63-character budget under a different rule.
* - Types (struct/enum/bitmap/register) have no linkage at all.
* - Two identifiers that are equal outright are `detectConflict`'s job
* (ADR-063, #1117), not this one.
*
* @param target The target, whose identifier significance limits apply
* @returns One conflict per group of identifiers sharing a truncated prefix
*/
detectMISRA51Conflicts(target: ITargetDescription): IConflict[] {
const limit = target.external_identifier_chars;
const byPrefix = SymbolTable.groupExternalCNextSymbolsByPrefix(
this.getAllSymbols(),
limit,
);
const conflicts: IConflict[] = [];
for (const group of byPrefix.values()) {
if (group.length < 2) {
continue;
}
conflicts.push(SymbolTable.buildMISRA51Conflict(group, limit));
}
return conflicts;
}
/**
* Bucket every externally-linked C-Next identifier by its truncated prefix.
*
* Deduplicated by `fullyQualifiedCName`: one declaration can be registered
* more than once when a file is reached along two include paths, and identity
* -- not arrival count -- is what a linker sees.
*/
private static groupExternalCNextSymbolsByPrefix(
symbols: TAnySymbol[],
limit: number,
): Map<string, TSymbol[]> {
const byPrefix = new Map<string, TSymbol[]>();
const seen = new Set<string>();
for (const symbol of symbols) {
if (!SymbolTable.hasExternalLinkage(symbol)) {
continue;
}
const cnextSymbol = symbol as TSymbol;
const identifier = cnextSymbol.fullyQualifiedCName;
if (seen.has(identifier)) {
continue;
}
seen.add(identifier);
const prefix = identifier.slice(0, limit);
const group = byPrefix.get(prefix);
if (group) {
group.push(cnextSymbol);
} else {
byPrefix.set(prefix, [cnextSymbol]);
}
}
return byPrefix;
}
/**
* True when the symbol is a C-Next declaration emitted with external linkage.
*
* Only variables and functions have linkage in C; a typedef or an enumeration
* constant names nothing the linker resolves.
*/
private static hasExternalLinkage(symbol: TAnySymbol): boolean {
if (symbol.sourceLanguage !== ESourceLanguage.CNext) {
return false;
}
if (symbol.kind !== "variable" && symbol.kind !== "function") {
return false;
}
return symbol.visibility === "public";
}
/**
* Build the Rule 5.1 diagnostic for one group of colliding identifiers.
*
* Names the C-Next names the author wrote (`cnxScopedName`) rather than the
* generated identifiers, per #1292 -- reporting `Scope__member` names
* something that appears in no source file.
*/
private static buildMISRA51Conflict(
group: TSymbol[],
limit: number,
): IConflict {
const shared = group[0].fullyQualifiedCName.slice(0, limit);
// Rendered through DeclarationSite like every other conflict location. This
// producer landed concurrently with #1342 and carried its own `basename`
// copy, which is ambiguous for the `can/config.cnx` + `uart/config.cnx`
// layout #1133 supports -- both render as `config.cnx`.
const locations = group
.map(
(symbol) =>
` ${symbol.cnxScopedName} (${DeclarationSite.display(symbol.sourceFile, symbol.span.line)})`,
)
.join("\n");
return {
code: "E0204",
symbolName: group[0].name,
definitions: [...group],
severity: "error",
sourceFile: group[0].sourceFile,
line: group[0].span.line,
// #1318: the symbol's own column, not a hardcoded 0.
column: group[0].span.column,
message:
`External identifiers are not distinct within the target's ` +
`${limit} significant characters (MISRA C:2012 Rule 5.1). ` +
`All of these generate an identifier beginning '${shared}':\n${locations}\n` +
` Shorten the scope name or the member names so the first ${limit} ` +
`characters differ.`,
};
}
// ========================================================================
// Struct Field Information
// ========================================================================
/**
* Add struct field information.
* Issue #981: Accept (number | string)[] for arrayDimensions to support macro-sized arrays.
* @param structName Name of the struct
* @param fieldName Name of the field
* @param fieldType Type of the field (e.g., "uint32_t")
* @param arrayDimensions Optional array dimensions - numbers for resolved, strings for macros
*/
addStructField(
structName: string,
fieldName: string,
fieldType: string,
arrayDimensions?: readonly (number | string)[],
): void {
let fields = this.structFields.get(structName);
if (!fields) {
fields = new Map();
this.structFields.set(structName, fields);
}
// Copy to mutable array for storage
fields.set(fieldName, {
type: fieldType,
arrayDimensions: arrayDimensions ? [...arrayDimensions] : undefined,
});
}
/**
* Get struct field type
* @param structName Name of the struct
* @param fieldName Name of the field
* @returns Field type or undefined if not found
*/
getStructFieldType(
structName: string,
fieldName: string,
): string | undefined {
const fields = this.structFields.get(structName);
return fields?.get(fieldName)?.type;
}
/**
* Get struct field info (type and array dimensions)
* @param structName Name of the struct
* @param fieldName Name of the field
* @returns Field info or undefined if not found
*/
getStructFieldInfo(
structName: string,
fieldName: string,
): IStructFieldInfo | undefined {
const fields = this.structFields.get(structName);
return fields?.get(fieldName);
}
/**
* Get all fields for a struct
* @param structName Name of the struct
* @returns Map of field names to field info, or undefined if struct not found
*/
getStructFields(
structName: string,
): Map<string, IStructFieldInfo> | undefined {
return this.structFields.get(structName);
}
/**
* Get struct field types as a simple map (fieldName -> typeName).
* Used by code generation for nested struct initializers.
* @param structName Name of the struct
* @returns Map of field names to type strings, or undefined if struct not found
*/
getStructFieldTypes(structName: string): Map<string, string> | undefined {
const fields = this.structFields.get(structName);
if (!fields) return undefined;
const result = new Map<string, string>();
for (const [fieldName, info] of fields) {
result.set(fieldName, info.type);
}
return result;
}
/**
* Get all struct fields for cache serialization
* @returns Map of struct name -> (field name -> field info)
*/
getAllStructFields(): Map<string, Map<string, IStructFieldInfo>> {
return this.structFields;
}
/**
* Restore struct fields from cache
* Merges cached fields into the existing structFields map
* @param fields Map of struct name -> (field name -> field info)
*/
restoreStructFields(
fields: Map<string, Map<string, IStructFieldInfo>>,
): void {
for (const [structName, fieldMap] of fields) {
let existingFields = this.structFields.get(structName);
Eif (!existingFields) {
existingFields = new Map();
this.structFields.set(structName, existingFields);
}
for (const [fieldName, fieldInfo] of fieldMap) {
existingFields.set(fieldName, fieldInfo);
}
}
}
/**
* Get struct names defined in a specific source file
* @param file Source file path
* @returns Array of struct names defined in that file
*/
getStructNamesByFile(file: string): string[] {
const fileSymbols = this.getSymbolsByFile(file);
const symbolNames = fileSymbols.map((s) => s.name);
return symbolNames.filter((name) => this.structFields.has(name));
}
// ========================================================================
// Struct Keyword Tracking
// ========================================================================
/**
* Issue #196 Bug 3: Mark a struct as requiring 'struct' keyword in C
* @param structName Name of the struct (e.g., "NamedPoint")
*/
markNeedsStructKeyword(structName: string): void {
this.needsStructKeyword.add(structName);
}
/**
* Issue #196 Bug 3: Check if a struct requires 'struct' keyword in C
* @param structName Name of the struct
* @returns true if the struct was defined as 'struct Name { ... }' without typedef
*/
checkNeedsStructKeyword(structName: string): boolean {
return this.needsStructKeyword.has(structName);
}
/**
* Issue #196 Bug 3: Get all struct names requiring 'struct' keyword
* @returns Array of struct names
*/
getAllNeedsStructKeyword(): string[] {
return Array.from(this.needsStructKeyword);
}
/**
* Issue #196 Bug 3: Restore needsStructKeyword from cache
* @param structNames Array of struct names requiring 'struct' keyword
*/
restoreNeedsStructKeyword(structNames: string[]): void {
for (const name of structNames) {
this.needsStructKeyword.add(name);
}
}
// ========================================================================
// Struct Symbol State (Issue #948, #958) — immer-managed, additive only
// ========================================================================
/**
* Issue #1225: capture the whole struct state for the cache.
*
* The return type is derived from `IStructSymbolState`, so a field added
* there makes this method fail to compile until it is written here. That
* replaces a hand-maintained capture list which silently omitted
* `pointerTypedefs` when #1164 added it — a warm-cache build then emitted a
* header that contradicted the real typedef.
*
* `typedefToTag` is captured even though `restoreStructTagAliases` derives
* it: covering every key removes "is this one derived?" as something anyone
* has to remember.
*/
serializeStructState(): TJsonSafe<Required<IStructSymbolState>> {
return {
opaqueTypes: Array.from(this.structState.opaqueTypes),
structTagAliases: Array.from(this.structState.structTagAliases),
typedefToTag: Array.from(this.structState.typedefToTag),
structTagsWithBodies: Array.from(this.structState.structTagsWithBodies),
pointerTypedefs: Array.from(this.structState.pointerTypedefs),
};
}
/**
* Issue #1225: the keys `serializeStructState` produces.
*
* Derived by running the serializer rather than listing them, so it cannot
* fall behind the interface. Two callers need it and must agree: the reader
* that validates an entry's struct state, and the cache-config fingerprint
* that invalidates entries written under an older shape.
*/
static structStateKeys(): string[] {
return Object.keys(new SymbolTable().serializeStructState());
}
/**
* Issue #1225: restore struct state from the cache.
*
* Additive, like every other mutation of this state: a warm build merges
* cached facts into whatever the current run has already learned.
*
* Coverage is enforced twice. The `IStructSymbolState` annotation below
* fails to compile if a field is not revived, and `mergeStructState` walks
* the object rather than naming fields, so it cannot skip one.
*/
restoreStructState(state: TJsonSafe<Required<IStructSymbolState>>): void {
const revived: Required<IStructSymbolState> = {
opaqueTypes: new Set(state.opaqueTypes),
structTagAliases: new Map(state.structTagAliases),
typedefToTag: new Map(state.typedefToTag),
structTagsWithBodies: new Set(state.structTagsWithBodies),
pointerTypedefs: new Set(state.pointerTypedefs),
};
this.structState = produce(this.structState, (draft) => {
SymbolTable.mergeStructState(draft, revived);
});
}
/**
* Merge every field of `incoming` into `draft`.
*
* Deliberately generic: it reads the keys off the object instead of listing
* them, so a new field is merged without anyone editing this method. The
* throw is the counterpart — a field that is neither a Set nor a Map has no
* merge rule, and failing loudly beats the silent skip that produced #1225.
*/
private static mergeStructState(
draft: IStructSymbolState,
incoming: IStructSymbolState,
): void {
// Safe: `incoming` is built from an IStructSymbolState-annotated literal
// directly above, so its own keys are exactly the interface's keys.
const keys = Object.keys(incoming) as Array<keyof IStructSymbolState>;
for (const key of keys) {
const target = draft[key];
const source = incoming[key];
if (target instanceof Set && source instanceof Set) {
for (const member of source) {
target.add(member);
}
} else if (target instanceof Map && source instanceof Map) {
for (const [entryKey, entryValue] of source) {
target.set(entryKey, entryValue);
}
} else E{
// A field with no merge rule would be skipped in silence, which is how
// #1225 happened. Add the rule above.
invariant(
false,
`every struct-state field has a merge rule, "${key}" included`,
);
}
}
}
/**
* Issue #948: Mark a typedef as aliasing an opaque (forward-declared) struct type.
* @param typeName Typedef name (e.g., "widget_t")
*/
markOpaqueType(typeName: string): void {
this.structState = produce(this.structState, (draft) => {
draft.opaqueTypes.add(typeName);
});
}
/**
* Issue #957/#1164: record a typedef of a pointer to a struct.
*/
markPointerTypedef(typeName: string): void {
this.structState = produce(this.structState, (draft) => {
draft.pointerTypedefs.add(typeName);
});
}
/**
* Issue #957/#1164: is this typedef a pointer to a struct?
*
* Such a type must never be forward-declared as `typedef struct X X;` -- the
* header has to include the one that defines it.
*/
isPointerTypedef(typeName: string): boolean {
return this.structState.pointerTypedefs.has(typeName);
}
/**
* Issue #948/#958: Check if a typedef aliases a truly opaque struct type.
* Query-time resolution: if the underlying struct tag has a body, it's not opaque.
* @param typeName Typedef name
* @returns true if the type is opaque (forward-declared with no body found)
*/
isOpaqueType(typeName: string): boolean {
// #1511: the rule is shared with 1.4 Resolve, which authors this as a fact
// of the whole program; 1.4's parameter stamp (#1722) reads that. This is
// the same rule over the same marks, for the readers that hold a table:
// #985 phantom-body recovery (a throwaway table), `ForeignTypeFacts`'
// struct checks, and `DeclaredPointer.isHandleType` (ADR-030). There used
// to be a second mark, `typedefStructTypes`, set under the identical
// condition and resolved by a copy of this rule; one mark and one rule
// mean a handle parameter's signature and call site cannot disagree.
return OpaqueTypeResolution.isOpaque(
typeName,
this.structState.opaqueTypes,
this.structState.typedefToTag,
this.structState.structTagsWithBodies,
);
}
/**
* Every typedef-to-struct-tag pairing, for whoever must resolve opacity.
*
* #1511: the resolution moved to 1.4 Resolve, which needs the mapping rather
* than one lookup at a time. Exposed as the pairs it is stored as, so the
* caller is not inverting `structTagAliases` and relying on the two staying
* reverses of one another.
*/
getAllTypedefToTag(): Array<[string, string]> {
return [...this.structState.typedefToTag.entries()];
}
/**
* Issue #948: Get all opaque type names for cache serialization.
* Returns the raw set — resolution happens at query time via isOpaqueType().
* @returns Array of opaque typedef names
*/
getAllOpaqueTypes(): string[] {
return Array.from(this.structState.opaqueTypes);
}
/**
* Issue #948: Register a struct tag -> typedef name relationship.
* Called when processing: typedef struct _foo foo_t;
* Populates both forward (tag→typedef) and reverse (typedef→tag) maps.
* @param structTag The struct tag name (e.g., "_foo")
* @param typedefName The typedef alias name (e.g., "foo_t")
*/
registerStructTagAlias(structTag: string, typedefName: string): void {
this.structState = produce(this.structState, (draft) => {
draft.structTagAliases.set(structTag, typedefName);
draft.typedefToTag.set(typedefName, structTag);
});
}
/**
* Issue #948: Get the typedef alias for a struct tag, if any.
* @param structTag The struct tag name
* @returns The typedef alias name, or undefined if none registered
*/
getStructTagAlias(structTag: string): string | undefined {
return this.structState.structTagAliases.get(structTag);
}
/**
* Issue #958: Record that a struct tag has a full definition (body).
* Used by query-time resolution: opaque types with bodies are not truly opaque.
* @param structTag The struct tag name (e.g., "_widget_t")
*/
markStructTagHasBody(structTag: string): void {
this.structState = produce(this.structState, (draft) => {
draft.structTagsWithBodies.add(structTag);
});
}
/**
* Issue #985: Clear a struct tag's recorded body. Used by external-declaration
* recovery to undo a PHANTOM body — one fabricated by ANTLR error-recovery when
* the normal pass parsed a header's huge preprocessed blob — so a type the
* clean per-file re-parse proves opaque (e.g. lvgl `lv_obj_t`) resolves as
* opaque again (and codegen uses a pointer).
* @param structTag The struct tag name (e.g., "_lv_obj_t")
*/
clearStructTagHasBody(structTag: string): void {
if (!this.structState.structTagsWithBodies.has(structTag)) return;
this.structState = produce(this.structState, (draft) => {
draft.structTagsWithBodies.delete(structTag);
});
}
/** Issue #985: The struct tag a typedef aliases, if any (e.g. lv_obj_t -> _lv_obj_t). */
getStructTagForTypedef(typedefName: string): string | undefined {
return this.structState.typedefToTag.get(typedefName);
}
/**
* Issue #958: Get all struct tags with bodies for cache serialization.
* @returns Array of struct tag names
*/
getAllStructTagsWithBodies(): string[] {
return Array.from(this.structState.structTagsWithBodies);
}
/**
* Issue #958: Get all struct tag aliases for cache serialization.
* @returns Array of [structTag, typedefName] pairs
*/
getAllStructTagAliases(): Array<[string, string]> {
return Array.from(this.structState.structTagAliases.entries());
}
// ========================================================================
// Issue #958: Typedef Struct Type Tracking
// ========================================================================
// ========================================================================
// Enum Bit Width Tracking
// ========================================================================
/**
* Issue #208: Add enum bit width for a typed enum
* @param enumName Name of the enum (e.g., "EPressureType")
* @param bitWidth Bit width from backing type (e.g., 8 for uint8_t)
*/
addEnumBitWidth(enumName: string, bitWidth: number): void {
this.enumBitWidth.set(enumName, bitWidth);
}
/**
* Issue #208: Get enum bit width for a typed enum
* @param enumName Name of the enum
* @returns Bit width or undefined if not a typed enum
*/
getEnumBitWidth(enumName: string): number | undefined {
return this.enumBitWidth.get(enumName);
}
/**
* Issue #208: Get all enum bit widths for cache serialization
* @returns Map of enum name -> bit width
*/
getAllEnumBitWidths(): Map<string, number> {
return this.enumBitWidth;
}
/**
* Issue #208: Restore enum bit widths from cache
* @param bitWidths Map of enum name -> bit width
*/
restoreEnumBitWidths(bitWidths: Map<string, number>): void {
for (const [enumName, width] of bitWidths) {
this.enumBitWidth.set(enumName, width);
}
}
// ========================================================================
// External Array Dimension Resolution
// ========================================================================
// ========================================================================
// Clear / Reset
// ========================================================================
}
export default SymbolTable;
|