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 | 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 916x 800x 800x 800x 800x 800x 781x 781x 781x 781x 781x 7x 76x 2x 2x 2x 3x 2x 3x 2x 2x 1x 2x 2x 3x 2x 13x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 3x 1x 1x 1x 3x | /**
* 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 "./CodeGenState";
* const type = CodeGenState.typeRegistry.get(name);
* if (CodeGenState.isKnownStruct(name)) { ... }
*
* Lifecycle:
* 1. CodeGenerator.generate() calls CodeGenState.reset()
* 2. CodeGenerator populates state during initialization
* 3. All generators/helpers read from CodeGenState directly
* 4. State persists for the duration of one generate() call
*/
import SymbolTable from "../../logic/symbols/SymbolTable";
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 ITargetCapabilities from "./types/ITargetCapabilities";
import TOverflowBehavior from "./types/TOverflowBehavior";
/**
* Default target capabilities (safe fallback)
*/
const DEFAULT_TARGET: ITargetCapabilities = {
wordSize: 32,
hasLdrexStrex: false,
hasBasepri: false,
};
/**
* 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 {
// ===========================================================================
// 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) */
static symbolTable: SymbolTable | null = null;
// ===========================================================================
// TYPE TRACKING
// ===========================================================================
/** Track variable types for bit access, .length, and type inference */
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();
/** 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();
// ===========================================================================
// PASS-BY-VALUE ANALYSIS (Issue #269)
// ===========================================================================
/** Tracks which parameters are modified (directly or transitively) */
static modifiedParameters: Map<string, Set<string>> = new Map();
/** Issue #579: Parameters with subscript access (must become pointers) */
static subscriptAccessedParameters: 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();
// ===========================================================================
// CURRENT CONTEXT (changes during AST traversal)
// ===========================================================================
/** ADR-016: Current scope for name resolution */
static currentScope: string | 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();
/** Scope member names: scope -> Set of member names */
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;
/** Expected type for struct initializers and enum inference */
static expectedType: string | null = null;
/** 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;
// ===========================================================================
// 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 {
// Symbol data
this.symbols = null;
this.symbolTable = null;
// 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();
// Pass-by-value analysis
this.modifiedParameters = new Map();
this.subscriptAccessedParameters = 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();
// Current context
this.currentScope = null;
this.currentFunctionName = null;
this.currentFunctionReturnType = null;
this.currentParameters = new Map();
this.localVariables = new Set();
this.localArrays = new Set();
this.scopeMembers = new Map();
this.floatBitShadows = new Set();
this.floatShadowCurrent = new Set();
// Generation state
this.indentLevel = 0;
this.inFunctionBody = false;
this.expectedType = null;
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;
// 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.localVariables.clear();
this.localArrays.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.localVariables.clear();
this.localArrays.clear();
this.floatBitShadows.clear();
this.floatShadowCurrent.clear();
}
// ===========================================================================
// 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;
if (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 type name is a known register.
*/
static isKnownRegister(name: string): boolean {
return this.symbols?.knownRegisters.has(name) ?? false;
}
/**
* Get type info for a variable.
*/
static getTypeInfo(name: string): TTypeInfo | undefined {
return this.typeRegistry.get(name);
}
/**
* Check if a parameter in a function is modified.
*/
static isParameterModified(funcName: string, paramName: string): boolean {
return this.modifiedParameters.get(funcName)?.has(paramName) ?? false;
}
/**
* Check if a parameter should pass by value.
*/
static isPassByValue(funcName: string, paramName: string): boolean {
return this.passByValueParams.get(funcName)?.has(paramName) ?? false;
}
/**
* Check if a parameter has subscript access.
*/
static hasSubscriptAccess(funcName: string, paramName: string): boolean {
return (
this.subscriptAccessedParameters.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);
}
/**
* 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);
}
/**
* Check if an identifier is a member of the current scope.
*/
static isCurrentScopeMember(identifier: string): boolean {
if (!this.currentScope) return false;
return this.scopeMembers.get(this.currentScope)?.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);
if (members?.has(identifier)) {
return `${this.currentScope}_${identifier}`;
}
}
return identifier;
}
/**
* Get struct field info.
*/
static getStructFieldType(
structName: string,
fieldName: string,
): string | undefined {
return this.symbols?.structFields.get(structName)?.get(fieldName);
}
/**
* 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);
}
/**
* 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.typeRegistry.set(name, info);
}
/**
* Register a const value.
*/
static registerConstValue(name: string, value: number): void {
this.constValues.set(name, value);
}
/**
* Register a local variable.
*/
static registerLocalVariable(name: string, isArray: boolean = false): void {
this.localVariables.add(name);
if (isArray) {
this.localArrays.add(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 {
this.usedClampOps.add(`${operation}_${cnxType}`);
}
/**
* Mark a safe div operation as used.
*/
static markSafeDivOpUsed(operation: string, cnxType: string): void {
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);
}
// ===========================================================================
// 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 `_tmp${this.tempVarCounter++}`;
}
}
|