All files / transpiler/output/codegen/generators/declarationGenerators ArrayDimensionUtils.ts

100% Statements 24/24
100% Branches 10/10
100% Functions 2/2
100% Lines 24/24

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                                          328x 311x       17x 17x 17x 17x 17x 3x 3x     14x 14x   3x   11x       17x                     99x 99x 90x     9x 9x 1x     8x 8x       16x 16x        
/**
 * ArrayDimensionUtils - Shared utilities for generating array dimension strings.
 *
 * Used by StructGenerator and ScopeGenerator for consistent array dimension handling.
 */
 
import * as Parser from "../../../../logic/parser/grammar/CNextParser";
import IOrchestrator from "../IOrchestrator";
 
/**
 * Generate array type dimension string from arrayType syntax (e.g., u8[16]).
 * Evaluates constants when possible, falls back to expression generation.
 *
 * @param arrayTypeCtx - The arrayType context, or null if not present
 * @param orchestrator - The orchestrator for constant evaluation and expression generation
 * @returns Dimension string like "[16]", "[]", or "" if no arrayType
 */
function generateArrayTypeDimension(
  arrayTypeCtx: Parser.ArrayTypeContext | null,
  orchestrator: IOrchestrator,
): string {
  if (arrayTypeCtx === null) {
    return "";
  }
 
  // Handle all dimensions from arrayType (supports u8[4][4], u8[], etc.)
  const dims = arrayTypeCtx.arrayTypeDimension();
  let result = "";
  for (const dim of dims) {
    const sizeExpr = dim.expression();
    if (!sizeExpr) {
      result += "[]";
      continue;
    }
 
    const constValue = orchestrator.tryEvaluateConstant(sizeExpr);
    if (constValue === undefined) {
      // Fall back to expression generation for macros, enums, etc.
      result += `[${orchestrator.generateExpression(sizeExpr)}]`;
    } else {
      result += `[${constValue}]`;
    }
  }
 
  return result;
}
 
/**
 * Generate string capacity dimension if applicable.
 * Adds +1 for null terminator.
 *
 * @param typeCtx - The type context to check for string type
 * @returns Dimension string like "[33]" for string<32>, or "" if not a string
 */
function generateStringCapacityDim(typeCtx: Parser.TypeContext): string {
  const stringCtx = typeCtx.stringType();
  if (!stringCtx) {
    return "";
  }
 
  const intLiteral = stringCtx.INTEGER_LITERAL();
  if (!intLiteral) {
    return "";
  }
 
  const capacity = Number.parseInt(intLiteral.getText(), 10);
  return `[${capacity + 1}]`;
}
 
class ArrayDimensionUtils {
  static readonly generateArrayTypeDimension = generateArrayTypeDimension;
  static readonly generateStringCapacityDim = generateStringCapacityDim;
}
 
export default ArrayDimensionUtils;