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

92.98% Statements 53/57
74.28% Branches 26/35
100% Functions 5/5
92.98% Lines 53/57

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                                                                            649x 647x     2x 649x       2x                       20x   20x 20x   20x 20x 9x     11x 8x       3x                                     17x   17x 20x         20x 20x       17x                       63x 63x 70x   70x   3x 3x 3x 3x     3x                 67x   63x                                           649x 649x     649x       649x 649x     649x     649x 649x         649x         649x 649x 649x 649x 649x 649x     649x 63x                   649x 17x                   649x     649x                                         649x          
/**
 * 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 DimensionResolver from "../utils/DimensionResolver";
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 StringUtils from "../../../../../utils/StringUtils";
import TTypeUtils from "../../../../../utils/TTypeUtils";
import type TType from "../../../../types/TType";
import ScopeUtils from "../../../../../utils/ScopeUtils";
import OverflowBehaviorUtils from "../../../../../utils/OverflowBehaviorUtils";
 
class VariableCollector {
  /**
   * Resolve a variable's declared type.
   *
   * ADR-045: a bare `string` takes its capacity from the initializing literal.
   * TypeResolver cannot do this on the type string alone — bare `string` matches
   * no pattern there and falls through to a *struct* named "string", which the
   * header then emits verbatim (`extern const string VERSION;`). The `.c` path
   * inferred the capacity independently, so the two disagreed silently until
   * the `.c` began including its own header (#1164).
   *
   * The inference rule itself is StringUtils.literalLength, shared with codegen.
   */
  private static resolveDeclaredType(
    typeStr: string,
    ctx: Parser.VariableDeclarationContext,
  ): TType {
    if (typeStr !== "string") {
      return TypeResolver.resolve(typeStr);
    }
 
    const initText = ctx.expression()?.getText() ?? "";
    Iif (!initText.startsWith('"') || !initText.endsWith('"')) {
      return TypeResolver.resolve(typeStr);
    }
 
    return TTypeUtils.createString(StringUtils.literalLength(initText));
  }
 
  /**
   * 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();
 
    Eif (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
    if (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, u16[] arr).
   * Handles size inference from initializer when dimension is empty.
   */
  private static collectArrayTypeDimensions(
    arrayTypeCtx: Parser.ArrayTypeContext,
    constValues: Map<string, number> | undefined,
    initExpr: Parser.ExpressionContext | null,
  ): (number | string)[] {
    const dimensions: (number | string)[] = [];
    for (const dim of arrayTypeCtx.arrayTypeDimension()) {
      const sizeExpr = dim.expression();
 
      if (!sizeExpr) {
        // Issue #636: Empty dimension [] - infer size from array initializer
        Eif (initExpr) {
          const inferredSize = ArrayInitializerUtils.getInferredSize(initExpr);
          Eif (inferredSize !== undefined) {
            dimensions.push(inferredSize);
          }
        }
        continue;
      }
 
      // Issue #1127: fold through the shared resolver so a dimension resolves
      // identically here and in codegen. Folding only literals and consts here
      // meant `u8[sizeof(u32)]` reached the header as `sizeof(u32)` -- a
      // C-Next type name in generated C, which does not compile -- while the
      // .c correctly said [4]. Text that does not fold is still kept, for macro and
      // enum references.
      dimensions.push(DimensionResolver.resolve(sizeExpr, constValues));
    }
    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)
   * @param isScopeType ADR-057 predicate: is this *qualified* name a scope type?
   * @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>,
    isScopeType?: (qualifiedName: string) => boolean,
  ): IVariableSymbol {
    const name = ctx.IDENTIFIER().getText();
    const line = ctx.start?.line ?? 0;
 
    // Get type string and convert to TType
    const typeCtx = ctx.type();
    // #1285: the scope REFERENCE flows on from here. Flattening it to its
    // leaf name was the choke point that made every downstream qualification
    // one level deep, whatever the chain actually was.
    const typeStr = TypeUtils.getTypeName(typeCtx, scope, isScopeType);
    const type = VariableCollector.resolveDeclaredType(typeStr, ctx);
 
    // Check for const modifier
    const isConst = ctx.constModifier() !== null;
 
    // Issue #468: Check for atomic modifier
    const isAtomic = ctx.atomicModifier() !== null;
    const isVolatile = ctx.volatileModifier() !== null;
 
    // Issue #1303: ADR-044's clamp/wrap is a declared fact like const and
    // volatile above, so it is read HERE and carried on the symbol. Reading it
    // only in codegen meant it existed for the declaring file and nowhere else.
    const overflowBehavior = OverflowBehaviorUtils.fromModifier(
      ctx.overflowModifier(),
    );
 
    // 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,
          initExpr,
        ),
      );
    }
 
    // 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,
      // #1285: identity computed once, from the scope chain, not
      // re-derived by every consumer.
      ...ScopeUtils.identityOf({ name, scope }),
      sourceFile,
      sourceLine: line,
      sourceLanguage: ESourceLanguage.CNext,
      isExported: isPublic,
      type,
      isConst,
      isAtomic,
      isVolatile,
      overflowBehavior,
      isArray,
      arrayDimensions: arrayDimensions.length > 0 ? arrayDimensions : undefined,
      initialValue,
    };
 
    return symbol;
  }
}
 
export default VariableCollector;