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 | 185x 185x 185x 185x 185x 199x 199x 199x 199x 199x 36x 42x 42x 42x 42x 42x 6x 42x 199x 199x 199x 213x 213x 213x 213x 192x 192x 72x 120x 120x 120x 120x 120x 120x 20x 120x 120x 67x 67x 67x 67x 67x 67x 43x 43x 24x 24x 17x 17x 17x 7x 21x 21x 21x 21x 21x 22x 22x 22x 12x 410x 410x 388x 162x 162x 162x 162x 49x 113x 410x 162x 88x 74x 74x 1x 73x 73x 48x 48x 48x 25x 74x 74x 74x 72x 72x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 2x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 7x 7x 7x 7x 2x 2x 2x 2x 2x 2x 6x 6x 6x 5x 5x 9x 9x 9x 9x 9x 4x 5x 187x 187x 187x 187x 187x 142x 21x 41x 12x 29x 29x 27x 3x 2x 27x 185x 185x 185x 185x 185x 185x 185x 185x 185x 185x 298x 298x 298x 298x 64x 64x 64x 64x 298x 298x 22x 22x 33x 33x 33x 8x 8x 8x 8x 8x 8x 72x 185x 298x 298x 24x 24x 24x 41x 41x 24x 598x 412x 200x 200x 200x 200x 200x 200x 200x 79x 79x 74x 13x 61x 74x 13x 13x 12x 12x 12x 24x 12x 7x 61x 61x 3x 3x 3x 162x 162x 63x 99x 23x 76x 10x 23x 21x 21x 2x 2x 21x 21x 21x 5x 2x 2x 1x 74x 17x 10x 4x 5x 5x 1x 5x 16x 16x 2x 413x 43x 1x 43x 43x 43x 43x | /**
* Initialization Analyzer
* Detects use of uninitialized variables (Rust-style E0381 errors)
*
* Phases:
* 1. Linear code tracking
* 2. Control flow (if/else branches)
* 3. Loop analysis
* 4. Scope tracking
* 5. Function parameters (always initialized)
* 7. Per-field struct tracking
*/
import { ParseTreeWalker } from "antlr4ng";
import { CNextListener } from "../parser/grammar/CNextListener";
import * as Parser from "../parser/grammar/CNextParser";
import IInitializationError from "./types/IInitializationError";
import IDeclarationInfo from "./types/IDeclarationInfo";
import ScopeStack from "./ScopeStack";
import ExpressionUtils from "../../../utils/ExpressionUtils";
import ParserUtils from "../../../utils/ParserUtils";
import analyzePostfixOps from "../../../utils/PostfixAnalysisUtils";
import SymbolTable from "../symbols/SymbolTable";
import ESourceLanguage from "../../../utils/types/ESourceLanguage";
import ESymbolKind from "../../../utils/types/ESymbolKind";
/**
* Tracks the initialization state of a variable
*/
interface IVariableState {
/** Where the variable was declared */
declaration: IDeclarationInfo;
/** Whether the variable has been initialized */
initialized: boolean;
/** Type of the variable (for struct field tracking) */
typeName: string | null;
/** For structs: which fields have been initialized */
initializedFields: Set<string>;
/** Is this a struct type? */
isStruct: boolean;
/** Is this a string type? (string<N> or string) */
isStringType: boolean;
}
/**
* Listener that walks the parse tree and tracks initialization
*/
class InitializationListener extends CNextListener {
private readonly analyzer: InitializationAnalyzer;
/** Stack of saved states before each if statement */
private readonly savedStates: Map<string, IVariableState>[] = [];
/** Track when we're inside a function call's argument list */
private inFunctionCallArgs: number = 0;
/** Track nesting depth inside functions/methods (0 = global level) */
private functionDepth: number = 0;
constructor(analyzer: InitializationAnalyzer) {
super();
this.analyzer = analyzer;
}
// ========================================================================
// Scope Entry/Exit
// ========================================================================
override enterFunctionDeclaration = (
ctx: Parser.FunctionDeclarationContext,
): void => {
this.functionDepth++;
this.analyzer.enterScope();
// Declare parameters as initialized
const paramList = ctx.parameterList();
if (paramList) {
for (const param of paramList.parameter()) {
const name = param.IDENTIFIER().getText();
const { line, column } = ParserUtils.getPosition(param);
// Get type name for struct tracking
const typeCtx = param.type();
let typeName: string | null = null;
if (typeCtx.userType()) {
typeName = typeCtx.userType()!.IDENTIFIER().getText();
}
this.analyzer.declareParameter(name, line, column, typeName);
}
}
};
override exitFunctionDeclaration = (
_ctx: Parser.FunctionDeclarationContext,
): void => {
this.analyzer.exitScope();
this.functionDepth--;
};
override enterBlock = (_ctx: Parser.BlockContext): void => {
this.analyzer.enterScope();
};
override exitBlock = (_ctx: Parser.BlockContext): void => {
this.analyzer.exitScope();
};
// ========================================================================
// Variable Declarations
// ========================================================================
override enterVariableDeclaration = (
ctx: Parser.VariableDeclarationContext,
): void => {
// Skip global variables - they're already handled by createGlobalScope()
if (this.functionDepth === 0) {
return;
}
const name = ctx.IDENTIFIER().getText();
const { line, column } = ParserUtils.getPosition(ctx);
const hasInitializer = ctx.expression() !== null;
// Get type name for struct tracking
const typeCtx = ctx.type();
let typeName: string | null = null;
if (typeCtx.userType()) {
typeName = typeCtx.userType()!.IDENTIFIER().getText();
}
// Check if this is a string type (string<N> or string)
const isStringType = typeCtx.stringType() !== null;
this.analyzer.declareVariable(
name,
line,
column,
hasInitializer,
typeName,
isStringType,
);
};
// ========================================================================
// Assignments
// ========================================================================
override enterAssignmentStatement = (
ctx: Parser.AssignmentStatementContext,
): void => {
const targetCtx = ctx.assignmentTarget();
const baseId = targetCtx.IDENTIFIER()?.getText();
const postfixOps = targetCtx.postfixTargetOp();
Iif (!baseId) {
return;
}
// Simple variable assignment: x <- value (no postfix ops)
if (postfixOps.length === 0) {
this.analyzer.recordAssignment(baseId);
return;
}
// Analyze postfix operations
const { identifiers, hasSubscript } = analyzePostfixOps(baseId, postfixOps);
// Member access: p.x <- value (struct field)
if (identifiers.length >= 2 && !hasSubscript) {
const varName = identifiers[0];
const fieldName = identifiers[1];
this.analyzer.recordAssignment(varName, fieldName);
} else {
// Array access or mixed: arr[i] <- value or arr[i].field <- value
// Consider the array/base as a whole initialized
this.analyzer.recordAssignment(baseId);
}
};
// ========================================================================
// Function Call Arguments (ADR-006: pass-by-reference may initialize)
// ========================================================================
override enterArgumentList = (_ctx: Parser.ArgumentListContext): void => {
// When inside function call arguments, variables passed may be output params
// We don't error on uninitialized reads, and we mark them as initialized after
this.inFunctionCallArgs++;
};
override exitArgumentList = (ctx: Parser.ArgumentListContext): void => {
this.inFunctionCallArgs--;
// Mark any simple identifiers passed as arguments as initialized
// (they might be output parameters that the function writes to)
for (const expr of ctx.expression()) {
// Walk down to find simple identifiers
this.markArgumentsAsInitialized(expr);
}
};
/**
* Mark simple identifier arguments as initialized.
* Only marks truly simple identifiers (not complex expressions like `a + b`).
*/
private markArgumentsAsInitialized(expr: Parser.ExpressionContext): void {
const identifier = ExpressionUtils.extractIdentifier(expr);
if (identifier) {
this.analyzer.recordAssignment(identifier);
}
}
// ========================================================================
// Variable Reads (in expressions)
// ========================================================================
override enterPrimaryExpression = (
ctx: Parser.PrimaryExpressionContext,
): void => {
if (this._shouldSkipReadCheck()) return;
if (!ctx.IDENTIFIER()) return;
const name = ctx.IDENTIFIER()!.getText();
const { line, column } = ParserUtils.getPosition(ctx);
// Check if this is part of a postfixExpression with member access
const parent = ctx.parent as Parser.PostfixExpressionContext | undefined;
if (this._handlePostfixExpression(parent, name, line, column)) {
return;
}
this.analyzer.checkRead(name, line, column);
};
/**
* Check if we should skip read checking in current context
*/
private _shouldSkipReadCheck(): boolean {
return this.analyzer.isInWriteContext() || this.inFunctionCallArgs > 0;
}
/**
* Handle postfix expression member access. Returns true if handled.
*/
private _handlePostfixExpression(
parent: Parser.PostfixExpressionContext | undefined,
name: string,
line: number,
column: number,
): boolean {
if (!parent?.postfixOp || parent.postfixOp().length === 0) {
return false;
}
const ops = parent.postfixOp();
// Check if we should skip for .length on non-string types
if (this._shouldSkipLengthCheck(name, ops)) {
return true;
}
// If the first postfixOp is a member access, check the field
const firstOpText = ops[0].getText();
if (firstOpText.startsWith(".")) {
const fieldName = firstOpText.slice(1);
this.analyzer.checkRead(name, line, column, fieldName);
return true;
}
return false;
}
/**
* Issue #196 Bug 2: Check if we should skip init check for .length
* on non-string types (compile-time property)
*/
private _shouldSkipLengthCheck(
name: string,
ops: Parser.PostfixOpContext[],
): boolean {
const varState = this.analyzer.lookupVariableState(name);
const isStringType = varState?.isStringType ?? false;
if (isStringType) return false;
const lastOp = ops.at(-1)!.getText();
if (lastOp !== ".length") return false;
const firstOpText = ops[0].getText();
// Skip if: direct .length or array element .length
// Don't skip for struct member access (.field.length)
return ops.length === 1 || firstOpText.startsWith("[");
}
// ========================================================================
// Control Flow: If Statements
// ========================================================================
override enterIfStatement = (_ctx: Parser.IfStatementContext): void => {
// Save current state before entering if
const stateBefore = this.analyzer.cloneScopeState();
this.savedStates.push(stateBefore);
};
override exitIfStatement = (ctx: Parser.IfStatementContext): void => {
const stateBefore = this.savedStates.pop();
Iif (!stateBefore) return;
// Check if there's an else clause
const hasElse = ctx.ELSE() !== null;
if (hasElse) {
// With else: the tree walker processes both branches in order.
// If a variable is initialized in both branches, it ends up initialized.
// If only one branch initializes it, it may or may not be initialized
// depending on which branch ran last in the traversal.
// For now, we'll trust the final state - this is optimistic but
// often correct for the common pattern where both branches initialize.
// (A more precise analysis would track both branches separately)
// Don't restore - keep whatever state the branches produced.
} else {
// No else: the if might not execute, so restore to state before if
// Any initializations inside the if are not guaranteed
this.analyzer.restoreFromState(stateBefore);
}
};
// ========================================================================
// Control Flow: Loops
// ========================================================================
override enterWhileStatement = (_ctx: Parser.WhileStatementContext): void => {
// Save state before loop - we'll restore after because loop might not run
this.savedStates.push(this.analyzer.cloneScopeState());
};
override exitWhileStatement = (_ctx: Parser.WhileStatementContext): void => {
// Loops are conservative: we assume they might not run at all
// So we restore state to before the loop
const stateBeforeLoop = this.savedStates.pop();
Eif (stateBeforeLoop) {
this.analyzer.restoreFromState(stateBeforeLoop);
}
};
override enterForStatement = (_ctx: Parser.ForStatementContext): void => {
// Save state before loop
this.savedStates.push(this.analyzer.cloneScopeState());
};
/**
* Check if a for-loop is deterministic (will definitely run at least once)
* A loop is deterministic if it has the form: for (var <- 0; var < CONSTANT; ...)
* where CONSTANT > 0
*/
private isDeterministicForLoop(ctx: Parser.ForStatementContext): boolean {
const init = ctx.forInit();
const cond = ctx.expression();
Iif (!init || !cond) return false;
// Check if init is a variable declaration starting at 0
const forVarDecl = init.forVarDecl();
if (forVarDecl) {
const initExpr = forVarDecl.expression();
Iif (!initExpr) return false;
const initText = initExpr.getText();
if (initText !== "0") return false;
} else {
// forAssignment case: check if assigning 0
const forAssign = init.forAssignment();
Iif (!forAssign) return false;
const assignExpr = forAssign.expression();
Iif (!assignExpr) return false;
const assignText = assignExpr.getText();
if (assignText !== "0") return false;
}
// Check if condition is var < POSITIVE_CONSTANT
const condText = cond.getText();
// Match patterns like "i<4" or "ti<3" (no spaces in AST getText())
const match = /^\w+<(\d+)$/.exec(condText);
if (!match) return false;
const bound = Number.parseInt(match[1], 10);
return bound > 0;
}
override exitForStatement = (ctx: Parser.ForStatementContext): void => {
const stateBeforeLoop = this.savedStates.pop();
Eif (stateBeforeLoop) {
const isDeterministic = this.isDeterministicForLoop(ctx);
if (isDeterministic) {
// Deterministic loop - preserve initialization (loop WILL run)
this.analyzer.mergeInitializationState(stateBeforeLoop);
} else {
// Non-deterministic loop - conservative restore (loop might not run)
this.analyzer.restoreFromState(stateBeforeLoop);
}
}
};
}
/**
* Analyzes C-Next AST for use-before-initialization errors
*/
class InitializationAnalyzer {
private errors: IInitializationError[] = [];
private scopeStack: ScopeStack<IVariableState> = new ScopeStack();
/** Known struct types and their fields */
private readonly structFields: Map<string, Set<string>> = new Map();
/** Track if we're processing a write target (left side of assignment) */
private inWriteContext: boolean = false;
/** Symbol table for checking C++ types (Issue #503) */
private symbolTable: SymbolTable | null = null;
/**
* Register external struct fields from C/C++ headers
* This allows the analyzer to recognize types defined in headers
*
* @param externalFields Map of struct name -> Set of field names
*/
public registerExternalStructFields(
externalFields: Map<string, Set<string>>,
): void {
for (const [structName, fields] of externalFields) {
this.structFields.set(structName, fields);
}
}
/**
* Issue #503: Check if a type name is a C++ class/struct
* C++ classes with default constructors are automatically initialized.
*
* @param typeName The type name to check
* @returns true if the type is from C++ (has constructor-based init)
*/
private isCppClass(typeName: string): boolean {
if (!this.symbolTable) {
return false;
}
const symbols = this.symbolTable.getOverloads(typeName);
for (const sym of symbols) {
if (sym.sourceLanguage === ESourceLanguage.Cpp) {
// C++ classes and structs have default constructors
if (sym.kind === ESymbolKind.Struct || sym.kind === ESymbolKind.Class) {
return true;
}
}
}
return false;
}
/**
* Analyze a parsed program for initialization errors
* @param tree The parsed program AST
* @param symbolTable Optional symbol table for C++ type detection
* @returns Array of initialization errors
*/
public analyze(
tree: Parser.ProgramContext,
symbolTable?: SymbolTable,
): IInitializationError[] {
this.errors = [];
this.scopeStack = new ScopeStack();
this.symbolTable = symbolTable ?? null;
// Don't clear structFields - external fields may have been registered
// First pass: collect struct definitions
this.collectStructDefinitions(tree);
// Create global scope with all global/namespace variable declarations
this.createGlobalScope(tree);
// Second pass: analyze initialization
const listener = new InitializationListener(this);
ParseTreeWalker.DEFAULT.walk(listener, tree);
return this.errors;
}
/**
* Create the global scope with all top-level variable declarations
* Global variables are considered "initialized" (zero-init by ADR-015)
*/
private createGlobalScope(tree: Parser.ProgramContext): void {
this.enterScope(); // Create global scope
for (const decl of tree.declaration()) {
this._processGlobalVariable(decl);
this._processScopeMembers(decl);
}
}
/**
* Process a global variable declaration
*/
private _processGlobalVariable(decl: Parser.DeclarationContext): void {
const varDecl = decl.variableDeclaration();
if (!varDecl) return;
const name = varDecl.IDENTIFIER().getText();
const { line, column } = ParserUtils.getPosition(varDecl);
const typeName = this._extractUserTypeName(varDecl.type());
// Globals are always initialized (zero-init or explicit)
this.declareVariable(name, line, column, true, typeName);
}
/**
* Process scope member variable declarations (ADR-016)
*/
private _processScopeMembers(decl: Parser.DeclarationContext): void {
const scopeDecl = decl.scopeDeclaration();
if (!scopeDecl) return;
const scopeName = scopeDecl.IDENTIFIER().getText();
for (const member of scopeDecl.scopeMember()) {
this._processScopeMemberVariable(member, scopeName);
}
}
/**
* Process a single scope member variable
*/
private _processScopeMemberVariable(
member: Parser.ScopeMemberContext,
scopeName: string,
): void {
const memberVar = member.variableDeclaration();
if (!memberVar) return;
const varName = memberVar.IDENTIFIER().getText();
const fullName = `${scopeName}_${varName}`; // Mangled name
const { line, column } = ParserUtils.getPosition(memberVar);
const typeName = this._extractUserTypeName(memberVar.type());
// Register with both raw name and mangled name for scope resolution
this.declareVariable(varName, line, column, true, typeName);
this.declareVariable(fullName, line, column, true, typeName);
}
/**
* Extract user type name from a type context
*/
private _extractUserTypeName(typeCtx: Parser.TypeContext): string | null {
return typeCtx.userType()?.IDENTIFIER().getText() ?? null;
}
/**
* Collect struct definitions to know their fields
*/
private collectStructDefinitions(tree: Parser.ProgramContext): void {
for (const decl of tree.declaration()) {
const structDecl = decl.structDeclaration();
if (structDecl) {
const structName = structDecl.IDENTIFIER().getText();
const fields = new Set<string>();
for (const member of structDecl.structMember()) {
const fieldName = member.IDENTIFIER().getText();
fields.add(fieldName);
}
this.structFields.set(structName, fields);
}
}
}
// ========================================================================
// Scope Management (delegated to ScopeStack)
// ========================================================================
/**
* Enter a new scope (function, block, etc.)
*/
public enterScope(): void {
this.scopeStack.enterScope();
}
/**
* Exit the current scope
*/
public exitScope(): void {
this.scopeStack.exitScope();
}
// ========================================================================
// Variable Tracking
// ========================================================================
/**
* Declare a variable (may or may not be initialized)
*/
public declareVariable(
name: string,
line: number,
column: number,
hasInitializer: boolean,
typeName: string | null,
isStringType: boolean = false,
): void {
Iif (!this.scopeStack.hasActiveScope()) {
// Global scope - create implicit scope
this.enterScope();
}
const isStruct = typeName !== null && this.structFields.has(typeName);
const fields = isStruct
? this.structFields.get(typeName)!
: new Set<string>();
// Issue #503: C++ classes with default constructors are automatically initialized
const isCppClassType = typeName !== null && this.isCppClass(typeName);
const isInitialized = hasInitializer || isCppClassType;
const state: IVariableState = {
declaration: { name, line, column },
initialized: isInitialized,
typeName,
isStruct,
isStringType,
// If initialized with full struct initializer or C++ class, all fields are initialized
initializedFields: isInitialized ? new Set(fields) : new Set(),
};
this.scopeStack.declare(name, state);
}
/**
* Record that a variable (or field) has been assigned
* SonarCloud S3776: Refactored to use helper methods.
*/
public recordAssignment(name: string, field?: string): void {
const structFields = this.structFields;
this.scopeStack.update(name, (state) => {
if (field) {
this.recordFieldAssignment(state, field, structFields);
} else {
this.recordWholeAssignment(state, structFields);
}
return state;
});
}
/**
* Handle field-level assignment.
*/
private recordFieldAssignment(
state: IVariableState,
field: string,
structFields: Map<string, Set<string>>,
): void {
state.initializedFields.add(field);
// Check if all fields are now initialized
if (!state.isStruct || !state.typeName) return;
const allFields = structFields.get(state.typeName);
Iif (!allFields) return;
const allInitialized = [...allFields].every((f) =>
state.initializedFields.has(f),
);
if (allInitialized) {
state.initialized = true;
}
}
/**
* Handle whole-variable assignment.
*/
private recordWholeAssignment(
state: IVariableState,
structFields: Map<string, Set<string>>,
): void {
state.initialized = true;
// Mark all fields as initialized too
if (!state.isStruct || !state.typeName) return;
const fields = structFields.get(state.typeName);
Eif (fields) {
state.initializedFields = new Set(fields);
}
}
/**
* Check if a variable (or field) is used before initialization
* SonarCloud S3776: Refactored to use helper methods.
*/
public checkRead(
name: string,
line: number,
column: number,
field?: string,
): void {
const state = this.scopeStack.lookup(name);
if (!state) {
// Variable not found - let undefined variable handling deal with it
return;
}
if (field) {
this.checkFieldRead(name, line, column, field, state);
} else if (!state.initialized) {
this.addError(name, line, column, state.declaration, false);
}
}
/**
* Check field read for uninitialized access.
* SonarCloud S3776: Extracted from checkRead().
*/
private checkFieldRead(
name: string,
line: number,
column: number,
field: string,
state: IVariableState,
): void {
if (state.isStruct && state.typeName) {
this.checkStructFieldRead(name, line, column, field, state);
return;
}
Eif (state.isStringType) {
this.checkStringPropertyRead(name, line, column, field, state);
}
// Other types: .field is a compile-time property, no check needed
}
/**
* Check struct field read for initialization.
*/
private checkStructFieldRead(
name: string,
line: number,
column: number,
field: string,
state: IVariableState,
): void {
const structFields = this.structFields.get(state.typeName!);
Iif (!structFields?.has(field)) return;
if (!state.initializedFields.has(field)) {
this.addError(`${name}.${field}`, line, column, state.declaration, false);
}
}
/**
* Check string property read for initialization.
*/
private checkStringPropertyRead(
name: string,
line: number,
column: number,
field: string,
state: IVariableState,
): void {
const runtimeProperties = ["length", "capacity", "size"];
if (runtimeProperties.includes(field) && !state.initialized) {
this.addError(name, line, column, state.declaration, false);
}
}
/**
* Public method to look up variable state
* Issue #196 Bug 2: Used by visitor to check if variable is string type
*/
public lookupVariableState(name: string): IVariableState | null {
return this.scopeStack.lookup(name);
}
// ========================================================================
// Control Flow (using ScopeStack's clone/restore)
// ========================================================================
/**
* Clone the current scope state for branch analysis
*/
public cloneScopeState(): Map<string, IVariableState> {
return this.scopeStack.cloneState((state) => ({
...state,
initializedFields: new Set(state.initializedFields),
}));
}
/**
* Restore initialization state from a saved snapshot
* Used for control flow analysis to "undo" branch changes
*/
public restoreFromState(savedState: Map<string, IVariableState>): void {
this.scopeStack.restoreState(savedState, (_current, saved) => ({
...saved,
initializedFields: new Set(saved.initializedFields),
}));
}
/**
* Merge initialization state from a saved snapshot
* Used for deterministic loops where initialization inside the loop
* should be preserved (the loop WILL run at least once)
*/
public mergeInitializationState(
beforeState: Map<string, IVariableState>,
): void {
// For each variable, keep current init state but merge in any fields
// that were initialized before the loop
for (const [name, beforeVar] of beforeState) {
this.scopeStack.update(name, (currentState) => {
for (const field of beforeVar.initializedFields) {
currentState.initializedFields.add(field);
}
return currentState;
});
}
}
// ========================================================================
// Error Reporting
// ========================================================================
private addError(
variable: string,
line: number,
column: number,
declaration: IDeclarationInfo,
mayBeUninitialized: boolean,
): void {
const certainty = mayBeUninitialized ? "possibly " : "";
this.errors.push({
code: "E0381",
variable,
line,
column,
declaration,
mayBeUninitialized,
message: `use of ${certainty}uninitialized variable '${variable}'`,
});
}
// ========================================================================
// Write Context Tracking
// ========================================================================
public setWriteContext(inWrite: boolean): void {
this.inWriteContext = inWrite;
}
public isInWriteContext(): boolean {
return this.inWriteContext;
}
// ========================================================================
// Function Parameters
// ========================================================================
/**
* Declare function parameters (always initialized by caller)
*/
public declareParameter(
name: string,
line: number,
column: number,
typeName: string | null,
): void {
if (!this.scopeStack.hasActiveScope()) {
this.enterScope();
}
const isStruct = typeName !== null && this.structFields.has(typeName);
const fields = isStruct
? this.structFields.get(typeName)!
: new Set<string>();
const state: IVariableState = {
declaration: { name, line, column },
initialized: true, // Parameters are always initialized by caller
typeName,
isStruct,
isStringType: false, // Not tracked for parameters since they're always initialized
initializedFields: new Set(fields), // All fields initialized
};
this.scopeStack.declare(name, state);
}
}
export default InitializationAnalyzer;
|