All files / transpiler/output/codegen/helpers FunctionContextManager.ts

93.47% Statements 129/138
80.61% Branches 79/98
100% Functions 14/14
94.53% Lines 121/128

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                                                                                                              6x     6x     6x     6x           6x 6x 6x 6x               7x 7x 7x 7x 7x 7x 7x 7x                             3x   1x 1x 1x             2x 3x                   926x 926x   222x 222x 254x                       259x     259x 259x 259x     259x               259x   259x       259x             259x             259x     259x     259x                       259x     259x                                 269x 154x               115x 59x 59x               56x 2x     4x 2x 2x               54x 4x 4x     4x               50x 4x 4x               46x 8x                 38x 37x 37x 30x             7x 3x 3x               4x 4x 4x                   1x                                     262x 262x   262x 262x     262x             262x       262x 3x     262x                                   262x                     267x     45x 7x       38x 38x   37x 37x 44x 44x 41x 41x 40x     37x                   500x   493x     493x                                                         265x     12x 8x 8x 8x         4x 4x 4x 4x                       901x 245x   901x 901x               924x 924x 924x 924x 924x               896x 896x 896x 896x 896x 896x          
/**
 * FunctionContextManager - Manages function context lifecycle and parameter processing
 *
 * Issue #793: Extracted from CodeGenerator to reduce file size.
 *
 * Handles:
 * - Function context setup/cleanup lifecycle
 * - Parameter type resolution and registration
 * - Return type resolution (including main() special case)
 * - Function body enter/exit coordination
 */
 
import * as Parser from "../../../logic/parser/grammar/CNextParser.js";
import CodeGenState from "../../../state/CodeGenState.js";
import TYPE_WIDTH from "../types/TYPE_WIDTH.js";
import ArrayDimensionParser from "./ArrayDimensionParser.js";
import IFunctionContextCallbacks from "../types/IFunctionContextCallbacks.js";
// Issue #895: Parse typedef signatures to determine pointer vs value params
import TypedefParamParser from "./TypedefParamParser.js";
 
/**
 * Result from resolving parameter type information.
 */
interface IParameterTypeInfo {
  typeName: string;
  isStruct: boolean;
  isCallback: boolean;
  isString: boolean;
}
 
/**
 * Result from resolving return type and params for a function.
 */
interface IReturnTypeAndParams {
  actualReturnType: string;
  initialParams: string;
}
 
/**
 * Manages function context lifecycle and parameter processing.
 */
class FunctionContextManager {
  /**
   * Set up context for function generation.
   * - Sets current function name (with scope prefix if in a scope)
   * - Sets return type for enum inference
   * - Processes parameters for ADR-006 pointer semantics
   * - Clears local variables and marks in function body
   */
  static setupFunctionContext(
    name: string,
    ctx: Parser.FunctionDeclarationContext,
    callbacks: IFunctionContextCallbacks,
  ): void {
    // Issue #269: Set current function name for pass-by-value lookup
    const fullFuncName = CodeGenState.currentScope
      ? `${CodeGenState.currentScope}_${name}`
      : name;
    CodeGenState.currentFunctionName = fullFuncName;
 
    // Issue #477: Set return type for enum inference in return statements
    CodeGenState.currentFunctionReturnType = ctx.type().getText();
 
    // Track parameters for ADR-006 pointer semantics
    FunctionContextManager.processParameterList(
      ctx.parameterList() ?? null,
      callbacks,
    );
 
    // ADR-016: Clear local variables and mark that we're in a function body
    CodeGenState.localVariables.clear();
    CodeGenState.floatBitShadows.clear();
    CodeGenState.floatShadowCurrent.clear();
    CodeGenState.inFunctionBody = true;
  }
 
  /**
   * Clean up context after function generation.
   * Resets all function-related state.
   */
  static cleanupFunctionContext(): void {
    CodeGenState.inFunctionBody = false;
    CodeGenState.localVariables.clear();
    CodeGenState.floatBitShadows.clear();
    CodeGenState.floatShadowCurrent.clear();
    CodeGenState.mainArgsName = null;
    CodeGenState.currentFunctionName = null;
    CodeGenState.currentFunctionReturnType = null;
    FunctionContextManager.clearParameters();
  }
 
  /**
   * Resolve return type and initial params for function.
   * Handles main() special cases:
   * - main(u8 args[][]) -> int main(int argc, char *argv[])
   * - main() -> int main() (for C++ compatibility)
   */
  static resolveReturnTypeAndParams(
    name: string,
    returnType: string,
    isMainWithArgs: boolean,
    ctx: Parser.FunctionDeclarationContext,
  ): IReturnTypeAndParams {
    if (isMainWithArgs) {
      // Special case: main(u8 args[][]) -> int main(int argc, char *argv[])
      const argsParam = ctx.parameterList()!.parameter()[0];
      CodeGenState.mainArgsName = argsParam.IDENTIFIER().getText();
      return {
        actualReturnType: "int",
        initialParams: "int argc, char *argv[]",
      };
    }
 
    // For main() without args, always use int return type for C++ compatibility
    const actualReturnType = name === "main" ? "int" : returnType;
    return { actualReturnType, initialParams: "" };
  }
 
  /**
   * Process parameter list and register parameters in state.
   */
  static processParameterList(
    params: Parser.ParameterListContext | null,
    callbacks: IFunctionContextCallbacks,
  ): void {
    CodeGenState.currentParameters.clear();
    if (!params) return;
 
    const paramList = params.parameter();
    for (let i = 0; i < paramList.length; i++) {
      FunctionContextManager.processParameter(paramList[i], callbacks, i);
    }
  }
 
  /**
   * Process a single parameter declaration.
   */
  static processParameter(
    param: Parser.ParameterContext,
    callbacks: IFunctionContextCallbacks,
    paramIndex: number,
  ): void {
    const name = param.IDENTIFIER().getText();
    // Check both C-Next style (u8[8] param) and legacy style (u8 param[8])
    const isArray =
      param.arrayDimension().length > 0 || param.type().arrayType() !== null;
    const isConst = param.constModifier() !== null;
    const typeCtx = param.type();
 
    // Resolve type information
    const typeInfo = FunctionContextManager.resolveParameterTypeInfo(
      typeCtx,
      callbacks,
    );
 
    // Issue #895: For callback-compatible functions, check the typedef signature
    // to determine if the param should be a pointer or value
    const callbackTypedefInfo =
      FunctionContextManager.getCallbackTypedefParamInfo(paramIndex);
    const isCallbackPointerParam =
      callbackTypedefInfo?.shouldBePointer ?? false;
 
    // Issue #958: Check if type is a typedef'd struct from C headers
    const isTypedefStruct =
      callbacks.isTypedefStructType?.(typeInfo.typeName) ?? false;
 
    // Determine isStruct: for callback-compatible params, both typedef AND type info matter
    // - If typedef says pointer AND it's actually a struct, use -> access (isStruct=true)
    // - If typedef says pointer BUT it's a primitive (like u8), don't treat as struct
    //   (primitives use forcePointerSemantics for dereference instead)
    // Issue #958: C-header typedef struct types are always treated as struct (pointer semantics)
    const isStruct = callbackTypedefInfo
      ? isCallbackPointerParam && typeInfo.isStruct
      : typeInfo.isStruct || isTypedefStruct;
 
    // Issue #895: Primitive types that become pointers need dereferencing when used as values
    // e.g., "u8 buf" becoming "uint8_t* buf" requires "*buf" when accessing the value
    const isCallbackPointerPrimitive =
      isCallbackPointerParam && !typeInfo.isStruct && !isArray;
 
    // Issue #958: typedef struct params need pointer semantics (like callback pointer params)
    const forcePointerSemantics = isCallbackPointerParam || isTypedefStruct;
 
    // Register in currentParameters
    const paramInfo = {
      name,
      baseType: typeInfo.typeName,
      isArray,
      isStruct,
      isConst,
      isCallback: typeInfo.isCallback,
      isString: typeInfo.isString,
      isCallbackPointerPrimitive,
      // Issue #895/#958: Force pointer semantics for callback-compatible and typedef struct params
      forcePointerSemantics,
    };
    CodeGenState.currentParameters.set(name, paramInfo);
 
    // Register in typeRegistry
    FunctionContextManager.registerParameterType(
      name,
      typeInfo,
      param,
      isArray,
      isConst,
      isTypedefStruct,
    );
  }
 
  /**
   * Resolve type name and flags from a type context.
   */
  static resolveParameterTypeInfo(
    typeCtx: Parser.TypeContext,
    callbacks: IFunctionContextCallbacks,
  ): IParameterTypeInfo {
    if (typeCtx.primitiveType()) {
      return {
        typeName: typeCtx.primitiveType()!.getText(),
        isStruct: false,
        isCallback: false,
        isString: false,
      };
    }
 
    if (typeCtx.userType()) {
      const typeName = typeCtx.userType()!.getText();
      return {
        typeName,
        isStruct: callbacks.isStructType(typeName),
        isCallback: CodeGenState.callbackTypes.has(typeName),
        isString: false,
      };
    }
 
    if (typeCtx.qualifiedType()) {
      const identifierNames = typeCtx
        .qualifiedType()!
        .IDENTIFIER()
        .map((id) => id.getText());
      const typeName = callbacks.resolveQualifiedType(identifierNames);
      return {
        typeName,
        isStruct: callbacks.isStructType(typeName),
        isCallback: false,
        isString: false,
      };
    }
 
    if (typeCtx.scopedType()) {
      const localTypeName = typeCtx.scopedType()!.IDENTIFIER().getText();
      const typeName = CodeGenState.currentScope
        ? `${CodeGenState.currentScope}_${localTypeName}`
        : localTypeName;
      return {
        typeName,
        isStruct: callbacks.isStructType(typeName),
        isCallback: false,
        isString: false,
      };
    }
 
    if (typeCtx.globalType()) {
      const typeName = typeCtx.globalType()!.IDENTIFIER().getText();
      return {
        typeName,
        isStruct: callbacks.isStructType(typeName),
        isCallback: false,
        isString: false,
      };
    }
 
    if (typeCtx.stringType()) {
      return {
        typeName: "string",
        isStruct: false,
        isCallback: false,
        isString: true,
      };
    }
 
    // Handle C-Next style array type (u8[8] param) - extract base type
    if (typeCtx.arrayType()) {
      const arrayTypeCtx = typeCtx.arrayType()!;
      if (arrayTypeCtx.primitiveType()) {
        return {
          typeName: arrayTypeCtx.primitiveType()!.getText(),
          isStruct: false,
          isCallback: false,
          isString: false,
        };
      }
      if (arrayTypeCtx.userType()) {
        const typeName = arrayTypeCtx.userType()!.getText();
        return {
          typeName,
          isStruct: callbacks.isStructType(typeName),
          isCallback: CodeGenState.callbackTypes.has(typeName),
          isString: false,
        };
      }
      // Handle string array type (string<32>[5] param)
      Eif (arrayTypeCtx.stringType()) {
        const stringCtx = arrayTypeCtx.stringType()!;
        return {
          typeName: stringCtx.getText(), // "string<32>"
          isStruct: false,
          isCallback: false,
          isString: true,
        };
      }
    }
 
    // Fallback
    return {
      typeName: typeCtx.getText(),
      isStruct: false,
      isCallback: false,
      isString: false,
    };
  }
 
  /**
   * Register a parameter in the type registry.
   */
  static registerParameterType(
    name: string,
    typeInfo: IParameterTypeInfo,
    param: Parser.ParameterContext,
    isArray: boolean,
    isConst: boolean,
    isTypedefStruct = false,
  ): void {
    const { typeName, isString } = typeInfo;
    const typeCtx = param.type();
 
    const isEnum = CodeGenState.symbols!.knownEnums.has(typeName);
    const isBitmap = CodeGenState.symbols!.knownBitmaps.has(typeName);
 
    // Extract array dimensions
    const arrayDimensions = FunctionContextManager.extractParamArrayDimensions(
      param,
      typeCtx,
      isArray,
    );
 
    // Add string capacity dimension if applicable
    const stringCapacity = FunctionContextManager.getStringCapacity(
      typeCtx,
      isString,
    );
    if (isArray && stringCapacity !== undefined) {
      arrayDimensions.push(stringCapacity + 1);
    }
 
    const registeredType = {
      baseType: typeName,
      bitWidth: isBitmap
        ? CodeGenState.symbols!.bitmapBitWidth.get(typeName) || 0
        : TYPE_WIDTH[typeName] || 0,
      isArray,
      arrayDimensions: arrayDimensions.length > 0 ? arrayDimensions : undefined,
      isConst,
      isEnum,
      enumTypeName: isEnum ? typeName : undefined,
      isBitmap,
      bitmapTypeName: isBitmap ? typeName : undefined,
      isString,
      stringCapacity,
      isParameter: true,
      // Issue #958: typedef struct params are already pointers — prevent &arg in call sites
      ...(isTypedefStruct && { isPointer: true }),
    };
    CodeGenState.setVariableTypeInfo(name, registeredType);
  }
 
  /**
   * Extract array dimensions from parameter (C-style or C-Next style).
   */
  static extractParamArrayDimensions(
    param: Parser.ParameterContext,
    typeCtx: Parser.TypeContext,
    isArray: boolean,
  ): number[] {
    if (!isArray) return [];
 
    // Try C-style first (param.arrayDimension())
    if (param.arrayDimension().length > 0) {
      return ArrayDimensionParser.parseForParameters(param.arrayDimension());
    }
 
    // C-Next style: get dimensions from arrayType
    const arrayTypeCtx = typeCtx.arrayType();
    if (!arrayTypeCtx) return [];
 
    const dimensions: number[] = [];
    for (const dim of arrayTypeCtx.arrayTypeDimension()) {
      const expr = dim.expression();
      if (!expr) continue;
      const size = Number.parseInt(expr.getText(), 10);
      if (!Number.isNaN(size)) {
        dimensions.push(size);
      }
    }
    return dimensions;
  }
 
  /**
   * Issue #895: Get callback typedef parameter info from the C header.
   * Returns null if not callback-compatible or index is invalid.
   */
  static getCallbackTypedefParamInfo(
    paramIndex: number,
  ): { shouldBePointer: boolean; shouldBeConst: boolean } | null {
    if (CodeGenState.currentFunctionName === null) return null;
 
    const typedefName = CodeGenState.callbackCompatibleFunctions.get(
      CodeGenState.currentFunctionName,
    );
    Eif (!typedefName) return null;
 
    const typedefType = CodeGenState.getTypedefType(typedefName);
    if (!typedefType) return null;
 
    const shouldBePointer = TypedefParamParser.shouldBePointer(
      typedefType,
      paramIndex,
    );
    const shouldBeConst = TypedefParamParser.shouldBeConst(
      typedefType,
      paramIndex,
    );
 
    if (shouldBePointer === null) return null;
 
    return {
      shouldBePointer,
      shouldBeConst: shouldBeConst ?? false,
    };
  }
 
  /**
   * Extract string capacity from a string type context.
   */
  static getStringCapacity(
    typeCtx: Parser.TypeContext,
    isString: boolean,
  ): number | undefined {
    if (!isString) return undefined;
 
    // Check direct stringType (e.g., string<32> param)
    if (typeCtx.stringType()) {
      const intLiteral = typeCtx.stringType()!.INTEGER_LITERAL();
      Eif (intLiteral) {
        return Number.parseInt(intLiteral.getText(), 10);
      }
    }
 
    // Check arrayType with stringType (e.g., string<32>[5] param)
    Eif (typeCtx.arrayType()?.stringType()) {
      const intLiteral = typeCtx.arrayType()!.stringType()!.INTEGER_LITERAL();
      Eif (intLiteral) {
        return Number.parseInt(intLiteral.getText(), 10);
      }
    }
 
    return undefined;
  }
 
  /**
   * Clear parameter tracking when leaving a function.
   */
  static clearParameters(): void {
    // ADR-025: Remove parameter types from typeRegistry
    for (const name of CodeGenState.currentParameters.keys()) {
      CodeGenState.deleteVariableTypeInfo(name);
    }
    CodeGenState.currentParameters.clear();
    CodeGenState.localArrays.clear();
  }
 
  /**
   * Enter function body - clears local variables and sets inFunctionBody flag.
   * This is a simpler version used when only body lifecycle is needed.
   */
  static enterFunctionBody(): void {
    CodeGenState.localVariables.clear();
    CodeGenState.floatBitShadows.clear();
    CodeGenState.floatShadowCurrent.clear();
    CodeGenState.inFunctionBody = true;
    CodeGenState.enterFunctionBody();
  }
 
  /**
   * Exit function body - clears local variables and inFunctionBody flag.
   * This is a simpler version used when only body lifecycle is needed.
   */
  static exitFunctionBody(): void {
    CodeGenState.inFunctionBody = false;
    CodeGenState.localVariables.clear();
    CodeGenState.floatBitShadows.clear();
    CodeGenState.floatShadowCurrent.clear();
    CodeGenState.mainArgsName = null;
    CodeGenState.exitFunctionBody();
  }
}
 
export default FunctionContextManager;