All files / TRANSPILE/3-Render/codegen/generators/expressions CallExprGenerator.ts

97.27% Statements 107/110
95% Branches 95/100
100% Functions 13/13
99% Lines 100/101

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 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538                                                                    48x           165x 131x     34x 34x 3x 2x 2x       32x                                                   48x               9x                 9x 1x           8x   8x 9x                     48x           35x 35x 2x 2x 1x 35x 1x       48x                   48x         35x 5x   30x               48x               72x 72x     72x       72x       1x                   71x             72x 36x                   35x 35x             72x                                       72x                         72x   72x                     48x             170x   168x 168x 168x                 168x                             170x             170x                                     48x           220x 220x                             48x               308x         308x 88x     220x     220x     220x 8x         212x       143x       212x       212x 212x     242x           242x     242x 72x       170x                   93x         93x                 77x         212x                       48x                 8x           8x 8x           8x 8x           8x 8x               8x 8x 8x 8x   8x           8x 8x   8x                                         48x         143x 170x 170x     102x     24x   7x            
/**
 * Function Call Expression Generator
 *
 * Generates C code for function calls:
 * - safe_div/safe_mod built-in functions (ADR-051)
 * - C-Next function calls with pass-by-reference semantics
 * - C function calls with pass-by-value semantics
 * - Const-to-non-const validation (ADR-013)
 *
 * #1445 box 3: takes `IPlannedCallArgument[]`, not nodes. It asked an argument
 * node four things -- is it a bare identifier, what type is it, render it,
 * render it by reference -- and three of those are deferred because exactly
 * ONE render may happen per argument. See `IPlannedCallArgument`.
 */
import invariant from "../../../../../utils/invariant";
import IGeneratorOutput from "../IGeneratorOutput";
import TGeneratorEffect from "../TGeneratorEffect";
import IGeneratorInput from "../IGeneratorInput";
import IGeneratorState from "../IGeneratorState";
import IOrchestrator from "../IOrchestrator";
import CallExprUtils from "./CallExprUtils";
import C_TYPE_WIDTH from "../../types/C_TYPE_WIDTH";
import type IPlannedCallArgument from "../../types/IPlannedCallArgument";
 
/**
 * Issue #304: Wrap argument with static_cast if it's a C++ enum class
 * being passed to an integer parameter.
 *
 * @param argCode - The generated argument code
 * @param arg - The planned argument (for its type)
 * @param targetParamBaseType - The target parameter's base type (if known)
 * @param orchestrator - Orchestrator for type checking methods
 * @returns The argument code, possibly wrapped with static_cast
 */
const wrapWithCppEnumCast = (
  argCode: string,
  arg: IPlannedCallArgument,
  targetParamBaseType: string | undefined,
  orchestrator: IOrchestrator,
): string => {
  if (!orchestrator.isCppMode() || !targetParamBaseType) {
    return argCode;
  }
 
  const argType = arg.expressionType();
  if (argType && orchestrator.isCppEnumClass(argType)) {
    if (orchestrator.isIntegerType(targetParamBaseType)) {
      const cType = CallExprUtils.mapTypeToCType(targetParamBaseType);
      return `static_cast<${cType}>(${argCode})`;
    }
  }
 
  return argCode;
};
 
/**
 * Resolved parameter info from local signature or cross-file lookup
 */
interface IResolvedParam {
  param: { baseType: string; isArray?: boolean } | undefined;
  isCrossFile: boolean;
}
 
/**
 * Issue #832: Check if parameter expects address-of for typedef'd pointer types.
 *
 * When a parameter type is `T*` and the argument type is `T`, we need to add `&`.
 * This handles cases like `handle_t` (typedef'd pointer) passed to `handle_t*`.
 *
 * IMPORTANT: This should NOT match primitive types like uint8_t, because arrays
 * of primitives decay to pointers naturally (uint8_t[] → uint8_t*).
 * It SHOULD match typedef'd pointer types like handle_t → handle_t*.
 *
 * @param paramType - The parameter's base type (e.g., "handle_t*")
 * @param argType - The argument's type (e.g., "handle_t")
 * @param orchestrator - For type checking (isIntegerType, isFloatType)
 * @returns true if parameter expects `argType*` (address-of needed)
 */
const _parameterExpectsAddressOf = (
  paramType: string,
  argType: string,
  orchestrator: IOrchestrator,
): boolean => {
  // Don't add & for primitive types - arrays decay to pointers naturally
  // e.g., uint8_t[] passed to uint8_t* should NOT get &
  // Check C-Next primitives (u8, i8, etc.)
  Iif (
    orchestrator.isIntegerType(argType) ||
    orchestrator.isFloatType(argType) ||
    CallExprUtils.isKnownPrimitiveType(argType)
  ) {
    return false;
  }
 
  // Check C standard types (uint8_t, int32_t, etc.)
  if (argType in C_TYPE_WIDTH) {
    return false;
  }
 
  // paramType should end with * (already checked by caller)
  // Remove trailing pointer markers to get the base type
  // Use indexOf/slice instead of regex to avoid ReDoS concerns (SonarCloud S5852)
  const starIndex = paramType.indexOf("*");
  const paramBaseType =
    starIndex >= 0 ? paramType.slice(0, starIndex).trim() : paramType.trim();
  return paramBaseType === argType;
};
 
/**
 * Resolve an argument expression's C-Next type for the address-of decision.
 * Prefers the expression type, then the codegen variable registry, then the C
 * symbol table — the last covers extern C globals (e.g. an lvgl font
 * `lv_font_montserrat_32` of type `lv_font_t`, Issue #985) whose type only
 * header symbol collection knows. Returns null when the type can't be resolved
 * or the argument is already an address-of expression.
 */
const _resolveArgType = (
  arg: IPlannedCallArgument,
  argCode: string,
  typeInfoBaseType: string | undefined,
  orchestrator: IOrchestrator,
): string | null => {
  const exprType = arg.expressionType();
  if (exprType) return exprType;
  Iif (argCode.startsWith("&")) return null;
  if (typeInfoBaseType) return typeInfoBaseType;
  const cSymbol = orchestrator.state.symbolTable?.getCSymbol(argCode);
  Iif (cSymbol?.kind === "variable" && !cSymbol.isArray) return cSymbol.type;
  return null;
};
 
/** How many levels of pointer a C type spells: `Dev**` is 2, `const Dev*` 1. */
const _pointerDepth = (cType: string): number => cType.split("*").length - 1;
 
/**
 * How many pointers deep an argument's VALUE already is.
 *
 * A C variable says so in its declared type: `Dev**` is 2. Issue #895 Bug B:
 * a variable inferred as a pointer is one; so is an opaque handle (ADR-030),
 * held in a scope variable (#948) or as an element of an array of handles
 * (#996). Anything else is a value, 0.
 */
const _argPointerDepth = (
  argType: string | null,
  isRegisteredPointer: boolean,
  isHandleArrayElement: boolean,
): number => {
  if (argType?.endsWith("*")) {
    return _pointerDepth(argType);
  }
  return isRegisteredPointer || isHandleArrayElement ? 1 : 0;
};
 
/**
 * Generate argument code for a C/C++ function call.
 * Handles automatic address-of (&) for struct arguments passed to pointer params.
 * Issue #872: Sets expectedType for MISRA 7.2 U suffix on unsigned literals.
 */
const _generateCFunctionArg = (
  arg: IPlannedCallArgument,
  targetParam: IResolvedParam["param"],
  orchestrator: IOrchestrator,
): string => {
  // Issue #937: Check if argument is a callback-promoted parameter (already a pointer)
  // BEFORE generating the expression. If target expects a pointer and we have a
  // callback-promoted param, use the identifier directly instead of dereferencing.
  const argIdentifier = arg.simpleIdentifier;
  const paramInfo = argIdentifier
    ? orchestrator.state.currentParameters.get(argIdentifier)
    : undefined;
  const isCallbackPromotedParam = paramInfo?.forcePointerSemantics ?? false;
 
  // If target expects a pointer and argument is a callback-promoted param,
  // use the identifier directly (it's already a pointer matching the typedef)
  if (targetParam?.baseType?.endsWith("*") && isCallbackPromotedParam) {
    // `argIdentifier` is non-null here only because `isCallbackPromotedParam`
    // implies it -- `paramInfo` is undefined without it. That coupling is the
    // assertion's only guard.
    return wrapWithCppEnumCast(
      argIdentifier!,
      arg,
      targetParam?.baseType,
      orchestrator,
    );
  }
 
  // Issue #872: Set expectedType for MISRA 7.2 compliance, but suppress bare enum resolution
  // (bare enums in function args was never allowed - changing that requires ADR approval)
  const argCode = orchestrator.state.withExpectedType(
    targetParam?.baseType,
    arg.render,
    true, // suppressEnumResolution
  );
 
  // Issue #322: Check if parameter expects a pointer and argument is a struct
  if (!targetParam?.baseType?.endsWith("*")) {
    return wrapWithCppEnumCast(
      argCode,
      arg,
      targetParam?.baseType,
      orchestrator,
    );
  }
 
  // Resolve the argument's type (expression type → variable registry → C symbol
  // table for extern globals) to decide whether it needs address-of.
  const typeInfo = arg.declared;
  const argType = _resolveArgType(
    arg,
    argCode,
    typeInfo?.baseType,
    orchestrator,
  );
 
  const argPointerDepth = _argPointerDepth(
    argType,
    typeInfo?.isPointer ?? false,
    arg.isHandleArrayElement(),
  );
 
  // Add & if argument needs address-of to match parameter type.
  // Issue #322: struct types passed to pointer params.
  // Issue #832: typedef'd pointer types (e.g., handle_t passed to handle_t*).
  //
  // A value that is already a pointer takes `&` only for a parameter exactly
  // one pointer deeper: a handle IS the argument for a `Dev*`, and its address
  // is the argument for a `Dev**`, an out-parameter the callee writes a new
  // handle through. "Already a pointer, pass it directly" asked no depth and
  // passed `Board__held` to `dev_create_into(Dev** out)`.
  //
  // A whole array never takes `&`. C decays it to a pointer to its first
  // element, which is what a pointer parameter takes; its address is a pointer
  // to the ARRAY -- `CPoint (*)[2]`, or `CPoint**` for a parameter.
  const needsAddressOf =
    argType !== null &&
    !argCode.startsWith("&") &&
    !targetParam.isArray &&
    !arg.isArray() &&
    (argPointerDepth > 0
      ? _pointerDepth(targetParam.baseType) === argPointerDepth + 1
      : orchestrator.isKnownStruct(argType) ||
        _parameterExpectsAddressOf(
          targetParam.baseType,
          argType,
          orchestrator,
        ));
 
  const finalArgCode = needsAddressOf ? `&${argCode}` : argCode;
 
  return wrapWithCppEnumCast(
    finalArgCode,
    arg,
    targetParam?.baseType,
    orchestrator,
  );
};
 
/**
 * Determine if a C-Next parameter should be passed by value.
 */
const _shouldPassByValue = (
  funcExpr: string,
  idx: number,
  targetParam: IResolvedParam["param"],
  isCrossFile: boolean,
  orchestrator: IOrchestrator,
): boolean => {
  if (!targetParam) return false;
 
  const isFloatParam = orchestrator.isFloatType(targetParam.baseType);
  const isEnumParam = orchestrator.getKnownEnums().has(targetParam.baseType);
  const isPrimitivePassByValue = orchestrator.isParameterPassByValue(
    funcExpr,
    idx,
  );
 
  // Issue #786: For cross-file calls, check if parameter is a known primitive type.
  // Known primitives (u8-u64, i8-i64, bool) should always be pass-by-value.
  // This handles the case where local passByValueParams isn't populated for cross-file functions.
  const isCrossFilePrimitive =
    isCrossFile &&
    CallExprUtils.isKnownPrimitiveType(targetParam.baseType) &&
    !orchestrator.isKnownStruct(targetParam.baseType) &&
    !CallExprUtils.isStringType(targetParam.baseType);
 
  // Issue #551: Unknown types (external enums, typedefs) use pass-by-value
  //
  // ADR-030 / #1722: an opaque handle lands here too, and that is the right
  // route rather than a lucky one -- the handle's C value IS the pointer the
  // callee's `T*` parameter takes. Rendering an opaque PARAMETER as that value
  // is the parameter registry's decision (`TParameterInfo.isOpaqueHandle`),
  // not this function's. The by-reference route would take `&` of every opaque
  // scope variable and array element (`&UI__held`), which #996's and #1722's
  // fixtures pin.
  const isUnknownType =
    !orchestrator.isKnownStruct(targetParam.baseType) &&
    !CallExprUtils.isKnownPrimitiveType(targetParam.baseType) &&
    !CallExprUtils.isStringType(targetParam.baseType) &&
    !isFloatParam &&
    !isEnumParam &&
    !isCrossFilePrimitive;
 
  return (
    isFloatParam ||
    isEnumParam ||
    isPrimitivePassByValue ||
    isCrossFilePrimitive ||
    isUnknownType
  );
};
 
/**
 * The name a call's parameters are looked up by.
 *
 * ADR-029: a value of a callback type -- a struct field, a variable, a
 * parameter -- holds a function with the parameters of the function that IS
 * the type. A call through it takes exactly the arguments a direct call to
 * that function takes, so every question about them is asked of that
 * function's name. Asked of `h.onPeek`, which names no function, they found no
 * parameters, and a struct argument went by value into a `const Point*`.
 */
const _signatureName = (
  funcExpr: string,
  calleeType: string | null,
  input: IGeneratorInput,
): string => {
  const callbackType =
    calleeType === null ? undefined : input.callbackTypes.get(calleeType);
  return callbackType?.functionName ?? funcExpr;
};
 
/**
 * Generate C code for a function call.
 *
 * @param funcExpr - The function name or expression being called
 * @param args - The planned arguments (null when the call declares none)
 * @param input - Generator input (type registry, function signatures, etc.)
 * @param _state - Generator state (unused but part of signature)
 * @param orchestrator - Orchestrator for callbacks into CodeGenerator
 * @param calleeType - The C-Next type of the value being called, or null
 *   when it is not a typed value (a function's own name)
 * @returns Generated code and effects
 */
const generateFunctionCall = (
  funcExpr: string,
  args: readonly IPlannedCallArgument[] | null,
  input: IGeneratorInput,
  _state: IGeneratorState,
  orchestrator: IOrchestrator,
  calleeType: string | null = null,
): IGeneratorOutput => {
  const effects: TGeneratorEffect[] = [];
 
  // Empty function call. This test stays FIRST: a `safe_div` written with no
  // argument list emits `safe_div()` here, BEFORE the four-argument invariant
  // below can fire.
  if (!args) {
    return { code: `${funcExpr}()`, effects };
  }
 
  const signatureName = _signatureName(funcExpr, calleeType, input);
 
  // Check if this is a C-Next function (uses pass-by-reference)
  const isCNextFunc = orchestrator.isCNextFunction(signatureName);
 
  // ADR-051: Handle safe_div() and safe_mod() built-in functions
  if (funcExpr === "safe_div" || funcExpr === "safe_mod") {
    return generateSafeDivMod(funcExpr, args, effects);
  }
 
  // Regular function call handling
  // #1322: a const argument to a non-const parameter is E0878 in pass 2.1.
  if (isCNextFunc) {
    // Issue #268: Track pass-through modifications for auto-const. Runs BEFORE
    // any argument renders, and mutates auto-const state -- it must not be
    // folded into the map below.
    trackPassThroughModifications(signatureName, args, orchestrator);
  }
 
  // Get function signature once for all arguments
  const sig = input.functionSignatures.get(signatureName);
 
  // Issue #992: Clear inDeclarationInit for function call arguments — struct
  // initializers inside function args need compound literals, not plain designated initializers.
  const rendered = orchestrator.state.withoutDeclarationInit(() =>
    args
      .map((arg, idx) => {
        // Get parameter type info from local signature or cross-file SymbolTable
        const resolved = CallExprUtils.resolveTargetParam(
          sig,
          idx,
          signatureName,
          input.symbolTable,
        );
        const targetParam = resolved.param;
 
        // C/C++ function: use pass-by-value semantics
        if (!isCNextFunc) {
          return _generateCFunctionArg(arg, targetParam, orchestrator);
        }
 
        // C-Next function: check if target parameter should be passed by value
        if (
          _shouldPassByValue(
            signatureName,
            idx,
            targetParam,
            resolved.isCrossFile,
            orchestrator,
          )
        ) {
          // Issue #872: Set expectedType for MISRA 7.2 compliance, but suppress bare enum resolution
          const argCode = orchestrator.state.withExpectedType(
            targetParam?.baseType,
            arg.render,
            true, // suppressEnumResolution
          );
          return wrapWithCppEnumCast(
            argCode,
            arg,
            targetParam?.baseType,
            orchestrator,
          );
        }
 
        // Target parameter is pass-by-reference: use & logic
        return arg.renderByReference(targetParam?.baseType);
      })
      .join(", "),
  );
 
  return { code: `${funcExpr}(${rendered})`, effects };
};
 
/**
 * Generate code for safe_div() or safe_mod() built-in functions (ADR-051).
 *
 * These functions take 4 arguments:
 * - output: Variable to store result (passed by reference)
 * - numerator: The dividend
 * - divisor: The divisor
 * - defaultValue: Value to use if divisor is 0
 */
const generateSafeDivMod = (
  funcName: string,
  args: readonly IPlannedCallArgument[],
  effects: TGeneratorEffect[],
): IGeneratorOutput => {
  // #1322: ADR-051's call shape is E0884 (four arguments) and E0885 (the first
  // is a variable to receive the result) in pass 2.1, and a `const` output is
  // E0877 there -- that last one was accepted here and emitted `&K` into a
  // non-const pointer parameter.
  invariant(
    args.length === 4,
    `${funcName} takes four arguments -- E0884 rejects this in pass 2.1, before this runs`,
  );
 
  // Get the output parameter (first argument) to determine type
  const outputArgId = args[0].simpleIdentifier;
  invariant(
    outputArgId,
    `${funcName}'s first argument is a variable -- E0885 rejects this in pass 2.1, before this runs`,
  );
 
  // Look up the type of the output parameter
  const typeInfo = args[0].declared;
  invariant(
    typeInfo,
    `${funcName}'s output parameter is a declared variable with a type -- E0885 rejects this in pass 2.1, before this runs`,
  );
 
  // Map C-Next type to helper function suffix
  const cnxType = typeInfo.baseType;
  invariant(
    cnxType,
    `a registered variable always has a non-empty baseType (output parameter '${outputArgId}' of ${funcName})`,
  );
 
  // Generate arguments: &output, numerator, divisor, defaultValue
  // These four render OUTSIDE `withoutDeclarationInit`, because the early
  // return above precedes that scope. Every other route renders inside it.
  const outputArg = `&${args[0].render()}`;
  const numeratorArg = args[1].render();
  const divisorArg = args[2].render();
  const defaultArg = args[3].render();
 
  const helperName = CallExprUtils.generateSafeDivModHelperName(
    funcName as "safe_div" | "safe_mod",
    cnxType,
  );
 
  // Track that this operation is used for helper generation
  const opType: "div" | "mod" = funcName === "safe_div" ? "div" : "mod";
  effects.push({ type: "safe-div", operation: opType, cnxType });
 
  return {
    code: `${helperName}(${outputArg}, ${numeratorArg}, ${divisorArg}, ${defaultArg})`,
    effects,
  };
};
 
/**
 * Issue #268: Track pass-through modifications for auto-const inference.
 *
 * When a parameter of the current function is passed to another function
 * that modifies its corresponding parameter, we must mark our parameter
 * as modified too (since it's pass-by-reference).
 *
 * Example:
 *   void modifies(u32 val) { val <- 42; }
 *   void passesThrough(u32 val) { modifies(val); }  // val is effectively modified
 *
 * Note: This only works when the callee is defined before the caller.
 * If the callee is defined later, we can't know if it modifies the param,
 * and the C compiler will catch any const-mismatch errors.
 */
const trackPassThroughModifications = (
  funcName: string,
  args: readonly IPlannedCallArgument[],
  orchestrator: IOrchestrator,
): void => {
  for (let argIdx = 0; argIdx < args.length; argIdx++) {
    const argId = args[argIdx].simpleIdentifier;
    if (!argId) continue;
 
    // Check if this argument is a parameter of the current function
    if (!orchestrator.isCurrentParameter(argId)) continue;
 
    // Check if the callee's parameter at this index is modified
    if (orchestrator.isCalleeParameterModified(funcName, argIdx)) {
      // The callee modifies this parameter, so our parameter is also modified
      orchestrator.markParameterModified(argId);
    }
  }
};
 
export default generateFunctionCall;