All files / transpiler/output/codegen memberAccessChain.ts

98.75% Statements 79/80
93.33% Branches 70/75
100% Functions 12/12
98.75% Lines 79/80

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                                                            49x                               6x                               6x 2x   4x 4x                                                       30x 11x       19x 8x       11x 2x     9x                                                                                                                                                                                 5x                                 6x 1x     5x 5x   6x     6x     6x       1x   4x                                           4x     4x   4x 3x     1x 1x   1x       1x                               3x 1x     2x 2x                       11x 11x 22x   11x                                           18x 18x     18x   18x 18x 18x 18x 18x   18x 6x       18x                                       12x     12x 4x                 4x 1x         11x 11x 11x 11x     11x 3x                   11x     11x 3x     11x                                     14x   14x                     14x 14x 30x   30x 18x 12x 12x 12x 1x   11x   29x     13x                            
/**
 * Helper module for building member access chains with proper separators.
 *
 * This module extracts the shared logic for building member access chains
 * like `conf->tempInputs[idx].assignedSpn` from both read and write contexts.
 *
 * ADR-006: Struct parameters need -> access (passed by pointer in C),
 *          or . access (passed by reference in C++)
 * ADR-016: Cross-scope access uses _ separator
 */
 
import { ParseTree } from "antlr4ng";
import TypeCheckUtils from "../../../utils/TypeCheckUtils.js";
 
/**
 * Options for struct parameter access helpers.
 */
interface StructParamOptions {
  /** Whether we're in C++ mode (struct params are references) */
  cppMode: boolean;
}
 
/**
 * Get the member access separator for struct parameters.
 * C mode: -> (pointer), C++ mode: . (reference)
 *
 * @param options - The struct param options
 * @returns "->" for C mode, "." for C++ mode
 */
function getStructParamSeparator(options: StructParamOptions): string {
  return options.cppMode ? "." : "->";
}
 
/**
 * Wrap a struct parameter used as a whole value (not member access).
 * C mode: (*param) - dereference the pointer
 * C++ mode: param - reference can be used directly
 *
 * @param paramName - The parameter name
 * @param options - The struct param options
 * @returns The wrapped parameter expression
 */
function wrapStructParamValue(
  paramName: string,
  options: StructParamOptions,
): string {
  return options.cppMode ? paramName : `(*${paramName})`;
}
 
/**
 * Build member access for a struct parameter: param->a.b or param.a.b
 *
 * @param paramName - The struct parameter name
 * @param members - Array of member names to access (can be empty)
 * @param options - The struct param options
 * @returns The complete member access expression
 */
function buildStructParamMemberAccess(
  paramName: string,
  members: string[],
  options: StructParamOptions,
): string {
  if (members.length === 0) {
    return paramName;
  }
  const separator = getStructParamSeparator(options);
  return `${paramName}${separator}${members.join(".")}`;
}
 
/**
 * Options for determining the separator between the first identifier and
 * the first member in a member access chain.
 */
interface SeparatorOptions {
  /** Whether the first identifier is a struct parameter (needs -> in C, . in C++) */
  isStructParam: boolean;
  /** Whether the first identifier is a cross-scope access (needs _ in C) */
  isCrossScope: boolean;
  /** Whether we're in C++ mode (struct params are references, use . instead of ->) */
  cppMode?: boolean;
}
 
/**
 * Determines the separator to use between the first identifier and the first member.
 *
 * @param options - The separator options
 * @param idIndex - The current identifier index (1 = first member after base)
 * @returns The separator string: "->" for struct params, "_" for cross-scope, "." otherwise
 */
function determineSeparator(
  options: SeparatorOptions,
  idIndex: number,
): string {
  // Only the first separator (idIndex === 1) can be special
  if (idIndex !== 1) {
    return ".";
  }
 
  // ADR-006: Struct parameters are passed as pointers in C (->), references in C++ (.)
  if (options.isStructParam) {
    return options.cppMode ? "." : "->";
  }
 
  // ADR-016: Cross-scope access uses underscore (scope_member)
  if (options.isCrossScope) {
    return "_";
  }
 
  return ".";
}
 
/**
 * Result of building a member access chain.
 */
interface MemberAccessChainResult {
  /** The generated C code for the member access chain */
  code: string;
  /** Number of identifiers consumed */
  identifiersConsumed: number;
  /** Number of expressions (subscripts) consumed */
  expressionsConsumed: number;
}
 
/**
 * Callback type for generating expression code from subscript expressions.
 */
type ExpressionGenerator<TExpr> = (expr: TExpr) => string;
 
/**
 * Callback type for checking if a type is a known struct.
 */
type StructChecker = (typeName: string) => boolean;
 
/**
 * Type tracking state while walking a member access chain.
 */
interface TypeTrackingState {
  /** Current struct type being accessed (undefined if not in a struct) */
  currentStructType: string | undefined;
  /** Type of the last accessed member */
  lastMemberType: string | undefined;
  /** Whether the last accessed member is an array field */
  lastMemberIsArray: boolean;
}
 
/**
 * Callbacks for type tracking while building the chain.
 */
interface TypeTrackingCallbacks {
  /** Get the fields map for a struct type */
  getStructFields: (
    structType: string,
  ) => ReadonlyMap<string, string> | undefined;
  /** Get the array fields set for a struct type */
  getStructArrayFields: (structType: string) => ReadonlySet<string> | undefined;
  /** Check if a type name is a known struct */
  isKnownStruct: StructChecker;
}
 
/**
 * Options for building a member access chain.
 */
interface BuildChainOptions<TExpr> {
  /** The first identifier (base of the chain) */
  firstId: string;
  /** All identifier names in the chain */
  identifiers: string[];
  /** Subscript expressions */
  expressions: TExpr[];
  /** Parse tree children for walking */
  children: ParseTree[];
  /** Separator options (struct param, cross-scope) */
  separatorOptions: SeparatorOptions;
  /** Function to generate code from an expression */
  generateExpression: ExpressionGenerator<TExpr>;
  /** Optional: Initial type info for type tracking */
  initialTypeInfo?: {
    isArray: boolean;
    baseType: string;
  };
  /** Optional: Type tracking callbacks for bit access detection */
  typeTracking?: TypeTrackingCallbacks;
  /** Optional: Callback when bit access is detected on last subscript */
  onBitAccess?: (
    result: string,
    bitIndex: string,
    memberType: string,
  ) => string | null;
}
 
/**
 * Initialize type tracking state from initial type info.
 */
function initializeTypeState(
  typeTracking: TypeTrackingCallbacks,
  initialTypeInfo: { isArray: boolean; baseType: string },
): TypeTrackingState {
  return {
    currentStructType: typeTracking.isKnownStruct(initialTypeInfo.baseType)
      ? initialTypeInfo.baseType
      : undefined,
    lastMemberType: undefined,
    lastMemberIsArray: false,
  };
}
 
/**
 * Update type tracking state after accessing a struct member.
 */
function updateTypeStateForMember(
  typeState: TypeTrackingState,
  typeTracking: TypeTrackingCallbacks,
  memberName: string,
): void {
  if (!typeState.currentStructType) {
    return;
  }
 
  const fields = typeTracking.getStructFields(typeState.currentStructType);
  typeState.lastMemberType = fields?.get(memberName);
 
  const arrayFields = typeTracking.getStructArrayFields(
    typeState.currentStructType,
  );
  typeState.lastMemberIsArray = arrayFields?.has(memberName) ?? false;
 
  // Check if this member is itself a struct
  if (
    typeState.lastMemberType &&
    typeTracking.isKnownStruct(typeState.lastMemberType)
  ) {
    typeState.currentStructType = typeState.lastMemberType;
  } else {
    typeState.currentStructType = undefined;
  }
}
 
/**
 * Check if bit access applies and return the result if so.
 * Returns null if this is not a bit access scenario.
 */
function tryBitAccess<TExpr>(
  typeState: TypeTrackingState,
  exprIndex: number,
  expressions: TExpr[],
  generateExpression: ExpressionGenerator<TExpr>,
  result: string,
  idIndex: number,
  onBitAccess: (
    result: string,
    bitIndex: string,
    memberType: string,
  ) => string | null,
): MemberAccessChainResult | null {
  const isPrimitiveInt =
    typeState.lastMemberType &&
    !typeState.lastMemberIsArray &&
    TypeCheckUtils.isInteger(typeState.lastMemberType);
  const isLastExpr = exprIndex === expressions.length - 1;
 
  if (!isPrimitiveInt || !isLastExpr || exprIndex >= expressions.length) {
    return null;
  }
 
  const bitIndex = generateExpression(expressions[exprIndex]);
  const bitResult = onBitAccess(result, bitIndex, typeState.lastMemberType!);
 
  Iif (bitResult === null) {
    return null;
  }
 
  return {
    code: bitResult,
    identifiersConsumed: idIndex,
    expressionsConsumed: exprIndex + 1,
  };
}
 
/**
 * Update type tracking after first array subscript.
 */
function updateTypeStateForArraySubscript(
  typeState: TypeTrackingState,
  typeTracking: TypeTrackingCallbacks,
  initialTypeInfo: { isArray: boolean; baseType: string },
  exprIndex: number,
): void {
  if (!initialTypeInfo.isArray || exprIndex !== 1) {
    return;
  }
  // First subscript on array - element type might be a struct
  Eif (typeTracking.isKnownStruct(initialTypeInfo.baseType)) {
    typeState.currentStructType = initialTypeInfo.baseType;
  }
}
 
/**
 * Skip to the closing bracket in children array.
 * Returns the new index position.
 */
function skipToClosingBracket(
  children: ParseTree[],
  startIndex: number,
): number {
  let i = startIndex;
  while (i < children.length && children[i].getText() !== "]") {
    i++;
  }
  return i;
}
 
/**
 * State passed between chain building iterations.
 */
interface ChainBuildState<TExpr> {
  result: string;
  idIndex: number;
  exprIndex: number;
  typeState: TypeTrackingState | undefined;
  options: BuildChainOptions<TExpr>;
}
 
/**
 * Handle dot (.) member access in the chain.
 * Returns the new child index.
 */
function handleDotAccess<TExpr>(
  state: ChainBuildState<TExpr>,
  childIndex: number,
): number {
  const { identifiers, separatorOptions, typeTracking } = state.options;
  const children = state.options.children;
 
  // Consume the dot
  let i = childIndex + 1;
 
  Eif (i < children.length && state.idIndex < identifiers.length) {
    const memberName = identifiers[state.idIndex];
    const separator = determineSeparator(separatorOptions, state.idIndex);
    state.result += `${separator}${memberName}`;
    state.idIndex++;
 
    if (state.typeState && typeTracking) {
      updateTypeStateForMember(state.typeState, typeTracking, memberName);
    }
  }
 
  return i;
}
 
/**
 * Handle bracket ([) subscript access in the chain.
 * Returns either a bit access result (early exit) or null to continue.
 */
function handleBracketAccess<TExpr>(
  state: ChainBuildState<TExpr>,
  childIndex: number,
):
  | { result: MemberAccessChainResult; newIndex: number }
  | { newIndex: number } {
  const {
    expressions,
    generateExpression,
    initialTypeInfo,
    typeTracking,
    onBitAccess,
    children,
  } = state.options;
 
  // Check for bit access on primitive integer (if type tracking enabled)
  if (state.typeState && onBitAccess) {
    const bitAccessResult = tryBitAccess(
      state.typeState,
      state.exprIndex,
      expressions,
      generateExpression,
      state.result,
      state.idIndex,
      onBitAccess,
    );
    if (bitAccessResult) {
      return { result: bitAccessResult, newIndex: childIndex };
    }
  }
 
  // Normal array subscript
  Eif (state.exprIndex < expressions.length) {
    const expr = generateExpression(expressions[state.exprIndex]);
    state.result += `[${expr}]`;
    state.exprIndex++;
 
    // After subscripting an array, update type tracking
    if (state.typeState && typeTracking && initialTypeInfo) {
      updateTypeStateForArraySubscript(
        state.typeState,
        typeTracking,
        initialTypeInfo,
        state.exprIndex,
      );
    }
  }
 
  // Skip forward to find and pass the closing bracket
  const newIndex = skipToClosingBracket(children, childIndex);
 
  // Reset lastMemberType after subscript (no longer on a member)
  if (state.typeState) {
    state.typeState.lastMemberType = undefined;
  }
 
  return { newIndex };
}
 
/**
 * Builds a member access chain with proper separators and subscripts.
 *
 * This function walks through the parse tree children in order, building
 * the C code string incrementally. It handles:
 * - Struct parameter access (-> separator)
 * - Cross-scope access (_ separator)
 * - Array subscripts
 * - Optional type tracking for bit access detection
 *
 * @param options - The build options
 * @returns The result containing the generated code and consumption counts
 */
function buildMemberAccessChain<TExpr>(
  options: BuildChainOptions<TExpr>,
): MemberAccessChainResult {
  const { firstId, children, initialTypeInfo, typeTracking } = options;
 
  const state: ChainBuildState<TExpr> = {
    result: firstId,
    idIndex: 1, // Start at 1 since we already have firstId
    exprIndex: 0,
    typeState:
      typeTracking && initialTypeInfo
        ? initializeTypeState(typeTracking, initialTypeInfo)
        : undefined,
    options,
  };
 
  let i = 1;
  while (i < children.length) {
    const childText = children[i].getText();
 
    if (childText === ".") {
      i = handleDotAccess(state, i);
    E} else if (childText === "[") {
      const bracketResult = handleBracketAccess(state, i);
      if ("result" in bracketResult) {
        return bracketResult.result;
      }
      i = bracketResult.newIndex;
    }
    i++;
  }
 
  return {
    code: state.result,
    identifiersConsumed: state.idIndex,
    expressionsConsumed: state.exprIndex,
  };
}
 
export default {
  determineSeparator,
  buildMemberAccessChain,
  getStructParamSeparator,
  wrapStructParamValue,
  buildStructParamMemberAccess,
};