All files / transpiler/logic/symbols/cnext/collectors VariableCollector.ts

96.15% Statements 50/52
86.2% Branches 25/29
100% Functions 4/4
98.03% Lines 50/51

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                                                    36x   36x 31x   31x 31x 19x     12x 8x       4x       5x 5x                           30x   30x 36x         36x 36x       30x                   49x 49x 51x 51x   51x 51x 51x 42x 9x 6x     3x     49x                                       603x 603x     603x 603x 603x 603x     603x     603x     603x 603x 603x 603x 603x 603x     603x 49x                 603x 30x                   603x     603x                               603x          
/**
 * VariableCollector - Extracts variable declarations from parse trees.
 * Handles types, const modifier, arrays, and initial values.
 *
 * Produces TType-based IVariableSymbol with proper IScopeSymbol references.
 */
 
import * as Parser from "../../../parser/grammar/CNextParser";
import ESourceLanguage from "../../../../../utils/types/ESourceLanguage";
import IVariableSymbol from "../../../../types/symbols/IVariableSymbol";
import IScopeSymbol from "../../../../types/symbols/IScopeSymbol";
import TypeResolver from "../../../../../utils/TypeResolver";
import ArrayInitializerUtils from "../utils/ArrayInitializerUtils";
import TypeUtils from "../utils/TypeUtils";
import LiteralUtils from "../../../../../utils/LiteralUtils";
 
class VariableCollector {
  /**
   * Resolve a single array dimension to a number or string.
   * Returns undefined if the dimension cannot be resolved.
   */
  private static resolveDimension(
    dim: Parser.ArrayDimensionContext,
    constValues: Map<string, number> | undefined,
    initExpr: Parser.ExpressionContext | null,
  ): number | string | undefined {
    const sizeExpr = dim.expression();
 
    if (sizeExpr) {
      const dimText = sizeExpr.getText();
      // Try parsing as literal number first
      const literalSize = Number.parseInt(dimText, 10);
      if (!Number.isNaN(literalSize)) {
        return literalSize;
      }
      // Issue #455: Resolve constant reference to its value
      if (constValues?.has(dimText)) {
        return constValues.get(dimText)!;
      }
      // Issue #455: Store original text for unresolved dimensions
      // This handles C macros from included headers (e.g., DEVICE_COUNT)
      return dimText;
    }
 
    // Issue #636: Empty dimension [] - infer size from array initializer
    Eif (initExpr) {
      return ArrayInitializerUtils.getInferredSize(initExpr);
    }
 
    return undefined;
  }
 
  /**
   * Collect array dimensions from a variable declaration.
   */
  private static collectArrayDimensions(
    arrayDims: Parser.ArrayDimensionContext[],
    constValues: Map<string, number> | undefined,
    initExpr: Parser.ExpressionContext | null,
  ): (number | string)[] {
    const dimensions: (number | string)[] = [];
 
    for (const dim of arrayDims) {
      const resolved = VariableCollector.resolveDimension(
        dim,
        constValues,
        initExpr,
      );
      Eif (resolved !== undefined) {
        dimensions.push(resolved);
      }
    }
 
    return dimensions;
  }
 
  /**
   * Collect dimensions from C-Next style arrayType syntax (u16[8] arr, u16[4][4] arr).
   */
  private static collectArrayTypeDimensions(
    arrayTypeCtx: Parser.ArrayTypeContext,
    constValues: Map<string, number> | undefined,
  ): (number | string)[] {
    const dimensions: (number | string)[] = [];
    for (const dim of arrayTypeCtx.arrayTypeDimension()) {
      const sizeExpr = dim.expression();
      Iif (!sizeExpr) continue;
 
      const dimText = sizeExpr.getText();
      const literalSize = LiteralUtils.parseIntegerLiteral(dimText);
      if (literalSize !== undefined) {
        dimensions.push(literalSize);
      } else if (constValues?.has(dimText)) {
        dimensions.push(constValues.get(dimText)!);
      } else {
        // Keep as string for macro/enum references
        dimensions.push(dimText);
      }
    }
    return dimensions;
  }
 
  /**
   * Collect a variable declaration and return an IVariableSymbol.
   *
   * @param ctx The variable declaration context
   * @param sourceFile Source file path
   * @param scope The scope this variable belongs to (IScopeSymbol)
   * @param isPublic Whether this variable is public (default true for top-level)
   * @param constValues Map of constant names to their numeric values (for resolving array dimensions)
   * @returns The variable symbol with TType-based types and scope reference
   */
  static collect(
    ctx: Parser.VariableDeclarationContext,
    sourceFile: string,
    scope: IScopeSymbol,
    isPublic: boolean = true,
    constValues?: Map<string, number>,
  ): IVariableSymbol {
    const name = ctx.IDENTIFIER().getText();
    const line = ctx.start?.line ?? 0;
 
    // Get type string and convert to TType
    const typeCtx = ctx.type();
    const scopeName = scope.name === "" ? undefined : scope.name;
    const typeStr = TypeUtils.getTypeName(typeCtx, scopeName);
    const type = TypeResolver.resolve(typeStr);
 
    // Check for const modifier
    const isConst = ctx.constModifier() !== null;
 
    // Issue #468: Check for atomic modifier
    const isAtomic = ctx.atomicModifier() !== null;
 
    // Check for array dimensions - both C-style (arrayDimension) and C-Next style (arrayType)
    const arrayDims = ctx.arrayDimension();
    const arrayTypeCtx = typeCtx.arrayType();
    const hasArrayTypeSyntax = arrayTypeCtx !== null;
    const isArray = arrayDims.length > 0 || hasArrayTypeSyntax;
    const initExpr = ctx.expression();
    const arrayDimensions: (number | string)[] = [];
 
    // Collect dimensions from arrayType syntax (u16[8] arr, u16[4][4] arr, u16[] arr)
    if (hasArrayTypeSyntax) {
      arrayDimensions.push(
        ...VariableCollector.collectArrayTypeDimensions(
          arrayTypeCtx,
          constValues,
        ),
      );
    }
 
    // Collect additional dimensions from arrayDimension syntax
    if (arrayDims.length > 0) {
      arrayDimensions.push(
        ...VariableCollector.collectArrayDimensions(
          arrayDims,
          constValues,
          initExpr,
        ),
      );
    }
 
    // Issue #282: Capture initial value for const inlining
    const initialValue = initExpr?.getText();
 
    // Build base symbol
    const symbol: IVariableSymbol = {
      kind: "variable",
      name,
      scope,
      sourceFile,
      sourceLine: line,
      sourceLanguage: ESourceLanguage.CNext,
      isExported: isPublic,
      type,
      isConst,
      isAtomic,
      isArray,
      arrayDimensions: arrayDimensions.length > 0 ? arrayDimensions : undefined,
      initialValue,
    };
 
    return symbol;
  }
}
 
export default VariableCollector;