All files / transpiler/logic/analysis FunctionCallAnalyzer.ts

100% Statements 136/136
95.65% Branches 66/69
100% Functions 24/24
100% Lines 134/134

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 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664                                            13x                 13x                                                                                                                                                                                                                                                                                                                                                                                                   175x     175x 175x                     132x     132x 132x     132x 2x 2x               39x 39x 39x     39x 1x 1x               195x     195x       195x 31x   164x       195x 195x     195x       195x             27x     27x     27x     27x                   335x     335x 335x     335x 335x     149x 149x     56x 56x                           335x 146x   189x 3x   186x                       149x   149x   98x 38x 38x 24x   14x 14x       60x 56x 56x 56x         69x                   38x     38x 3x       35x 11x       24x               175x     175x     175x     175x     175x     175x     175x     175x                       175x 175x 175x 175x 175x 175x 175x 175x     175x 175x 175x     175x 175x   175x             175x 280x 27x 27x                 175x   34x 34x 34x 34x                 22x 4x 4x 4x     18x               175x 280x 164x 164x                 168x             3x             195x             195x             195x             35x                                 56x 1x             1x       55x 31x       24x 2x       22x 4x       18x 2x       16x 2x           14x 3x 3x 1x         13x                         18x 15x     3x 3x 3x         2x       1x          
/**
 * Function Call Analyzer
 * Enforces define-before-use for functions (ADR-030)
 *
 * C-Next requires functions to be defined before they can be called.
 * This catches errors at C-Next compile time rather than deferring to
 * the C compiler or runtime.
 */
 
import { ParseTreeWalker } from "antlr4ng";
import { CNextListener } from "../parser/grammar/CNextListener";
import * as Parser from "../parser/grammar/CNextParser";
import SymbolTable from "../symbols/SymbolTable";
import ESourceLanguage from "../../../utils/types/ESourceLanguage";
import ESymbolKind from "../../../utils/types/ESymbolKind";
import IFunctionCallError from "./types/IFunctionCallError";
import ParserUtils from "../../../utils/ParserUtils";
 
/**
 * C-Next built-in functions
 * These are compiler intrinsics that don't need to be defined by the user
 */
const CNEXT_BUILTINS: Set<string> = new Set([
  "safe_div", // ADR-051: Safe division with default value
  "safe_mod", // ADR-051: Safe modulo with default value
]);
 
/**
 * Standard library functions from common C headers
 * These are considered "external" and don't need to be defined in C-Next
 */
const STDLIB_FUNCTIONS: Map<string, Set<string>> = new Map([
  [
    "stdio.h",
    new Set([
      "printf",
      "fprintf",
      "sprintf",
      "snprintf",
      "scanf",
      "fscanf",
      "sscanf",
      "fopen",
      "fclose",
      "fread",
      "fwrite",
      "fgets",
      "fputs",
      "fgetc",
      "fputc",
      "puts",
      "putchar",
      "getchar",
      "gets",
      "perror",
      "fflush",
      "fseek",
      "ftell",
      "rewind",
      "feof",
      "ferror",
      "clearerr",
      "remove",
      "rename",
      "tmpfile",
      "tmpnam",
      "setbuf",
      "setvbuf",
    ]),
  ],
  [
    "stdlib.h",
    new Set([
      "malloc",
      "calloc",
      "realloc",
      "free",
      "atoi",
      "atof",
      "atol",
      "atoll",
      "strtol",
      "strtoul",
      "strtoll",
      "strtoull",
      "strtof",
      "strtod",
      "strtold",
      "rand",
      "srand",
      "exit",
      "abort",
      "atexit",
      "system",
      "getenv",
      "abs",
      "labs",
      "llabs",
      "div",
      "ldiv",
      "lldiv",
      "qsort",
      "bsearch",
    ]),
  ],
  [
    "string.h",
    new Set([
      "strlen",
      "strcpy",
      "strncpy",
      "strcat",
      "strncat",
      "strcmp",
      "strncmp",
      "strchr",
      "strrchr",
      "strstr",
      "strtok",
      "memcpy",
      "memmove",
      "memset",
      "memcmp",
      "memchr",
    ]),
  ],
  [
    "math.h",
    new Set([
      "sin",
      "cos",
      "tan",
      "asin",
      "acos",
      "atan",
      "atan2",
      "sinh",
      "cosh",
      "tanh",
      "exp",
      "log",
      "log10",
      "log2",
      "pow",
      "sqrt",
      "cbrt",
      "ceil",
      "floor",
      "round",
      "trunc",
      "fabs",
      "fmod",
      "remainder",
      "fmax",
      "fmin",
      "hypot",
      "ldexp",
      "frexp",
      "modf",
    ]),
  ],
  [
    "ctype.h",
    new Set([
      "isalnum",
      "isalpha",
      "isdigit",
      "isxdigit",
      "islower",
      "isupper",
      "isspace",
      "ispunct",
      "isprint",
      "isgraph",
      "iscntrl",
      "tolower",
      "toupper",
    ]),
  ],
  [
    "time.h",
    new Set([
      "time",
      "clock",
      "difftime",
      "mktime",
      "strftime",
      "localtime",
      "gmtime",
      "asctime",
      "ctime",
    ]),
  ],
  ["assert.h", new Set(["assert"])],
  // Arduino framework
  [
    "Arduino.h",
    new Set([
      "pinMode",
      "digitalWrite",
      "digitalRead",
      "analogRead",
      "analogWrite",
      "delay",
      "delayMicroseconds",
      "millis",
      "micros",
      "attachInterrupt",
      "detachInterrupt",
      "noInterrupts",
      "interrupts",
      "Serial",
      "Wire",
      "SPI",
    ]),
  ],
]);
 
/**
 * Listener that walks the parse tree and checks function calls
 */
class FunctionCallListener extends CNextListener {
  private readonly analyzer: FunctionCallAnalyzer;
 
  /** Current scope name (for member function resolution) */
  private currentScope: string | null = null;
 
  constructor(analyzer: FunctionCallAnalyzer) {
    super();
    this.analyzer = analyzer;
  }
 
  // ========================================================================
  // ISR/Callback Variable Tracking (ADR-040)
  // ========================================================================
 
  /**
   * Track ISR-typed variables from variable declarations
   * e.g., `ISR handler <- myFunction;`
   */
  override enterVariableDeclaration = (
    ctx: Parser.VariableDeclarationContext,
  ): void => {
    const typeCtx = ctx.type();
    const typeName = typeCtx.getText();
 
    // Check if this is an ISR type or a callback type (function-as-type)
    if (typeName === "ISR" || this.analyzer.isCallbackType(typeName)) {
      const varName = ctx.IDENTIFIER().getText();
      this.analyzer.defineCallableVariable(varName);
    }
  };
 
  /**
   * Track ISR-typed parameters in function declarations
   * e.g., `void execute(ISR handler) { handler(); }`
   */
  override enterParameter = (ctx: Parser.ParameterContext): void => {
    const typeCtx = ctx.type();
    const typeName = typeCtx.getText();
 
    // Check if this is an ISR type or a callback type (function-as-type)
    if (typeName === "ISR" || this.analyzer.isCallbackType(typeName)) {
      const paramName = ctx.IDENTIFIER().getText();
      this.analyzer.defineCallableVariable(paramName);
    }
  };
 
  // ========================================================================
  // Function Definitions
  // ========================================================================
 
  override enterFunctionDeclaration = (
    ctx: Parser.FunctionDeclarationContext,
  ): void => {
    const name = ctx.IDENTIFIER().getText();
 
    // If inside a scope, the full name is Scope_functionName
    let fullName: string;
    if (this.currentScope) {
      fullName = `${this.currentScope}_${name}`;
    } else {
      fullName = name;
    }
 
    // Track that we're currently inside this function (for self-recursion detection)
    this.analyzer.enterFunction(fullName);
    this.analyzer.defineFunction(fullName);
  };
 
  override exitFunctionDeclaration = (
    _ctx: Parser.FunctionDeclarationContext,
  ): void => {
    // We're leaving the function definition
    this.analyzer.exitFunction();
  };
 
  // ========================================================================
  // Scope Handling
  // ========================================================================
 
  override enterScopeDeclaration = (
    ctx: Parser.ScopeDeclarationContext,
  ): void => {
    this.currentScope = ctx.IDENTIFIER().getText();
  };
 
  override exitScopeDeclaration = (
    _ctx: Parser.ScopeDeclarationContext,
  ): void => {
    this.currentScope = null;
  };
 
  // ========================================================================
  // Function Calls
  // ========================================================================
 
  /**
   * SonarCloud S3776: Refactored to use helper method.
   */
  override enterPostfixExpression = (
    ctx: Parser.PostfixExpressionContext,
  ): void => {
    const ops = ctx.postfixOp();
    const primary = ctx.primaryExpression();
 
    // Determine the base name: could be an identifier or 'this'
    const baseName = this.extractBaseName(primary);
    if (!baseName) return;
 
    // Walk through postfix ops to find the call and resolve the name
    const { resolvedName, foundCall } = this.resolveCallTarget(ops, baseName);
    if (!foundCall) return;
 
    // Check if the function is defined
    const { line, column } = ParserUtils.getPosition(ctx);
    this.analyzer.checkFunctionCall(
      resolvedName,
      line,
      column,
      this.currentScope,
    );
  };
 
  /**
   * Extract base name from primary expression.
   */
  private extractBaseName(
    primary: Parser.PrimaryExpressionContext,
  ): string | null {
    if (primary.IDENTIFIER()) {
      return primary.IDENTIFIER()!.getText();
    }
    if (primary.THIS()) {
      return "this";
    }
    return null;
  }
 
  /**
   * Resolve call target by walking postfix operations.
   * Returns the resolved function name and whether a call was found.
   * SonarCloud S3776: Extracted from enterPostfixExpression().
   */
  private resolveCallTarget(
    ops: Parser.PostfixOpContext[],
    baseName: string,
  ): { resolvedName: string; foundCall: boolean } {
    let resolvedName = baseName;
 
    for (const op of ops) {
      // Member access: check if it's Scope.member or this.member pattern
      if (op.IDENTIFIER()) {
        const resolved = this.resolveMemberAccess(resolvedName, op);
        if (resolved === null) {
          return { resolvedName, foundCall: false };
        }
        resolvedName = resolved;
        continue;
      }
 
      // Function call: () or (args)
      if (op.argumentList() || op.getChildCount() === 2) {
        const text = op.getText();
        Eif (text.startsWith("(")) {
          return { resolvedName, foundCall: true };
        }
      }
    }
 
    return { resolvedName, foundCall: false };
  }
 
  /**
   * Resolve member access pattern. Returns new name or null if not a C-Next function.
   */
  private resolveMemberAccess(
    resolvedName: string,
    op: Parser.PostfixOpContext,
  ): string | null {
    const memberName = op.IDENTIFIER()!.getText();
 
    // Handle this.member -> CurrentScope_member (when inside a scope)
    if (resolvedName === "this" && this.currentScope) {
      return `${this.currentScope}_${memberName}`;
    }
 
    // Check if base is a known scope
    if (this.analyzer.isScope(resolvedName)) {
      return `${resolvedName}_${memberName}`;
    }
 
    // Object.method or chained access - not a C-Next function call
    return null;
  }
}
 
/**
 * Analyzes C-Next AST for function calls before definition
 */
class FunctionCallAnalyzer {
  private errors: IFunctionCallError[] = [];
 
  /** Functions that have been defined (in order of appearance) */
  private definedFunctions: Set<string> = new Set();
 
  /** Known scopes (for Scope.member -> Scope_member resolution) */
  private knownScopes: Set<string> = new Set();
 
  /** External symbol table for C/C++ interop */
  private symbolTable: SymbolTable | null = null;
 
  /** Included headers (for stdlib function lookup) */
  private includedHeaders: Set<string> = new Set();
 
  /** Current function being defined (for self-recursion detection) */
  private currentFunctionName: string | null = null;
 
  /** ADR-040: Variables of type ISR or callback types that can be invoked */
  private callableVariables: Set<string> = new Set();
 
  /** ADR-029: Callback types (function-as-type pattern) */
  private callbackTypes: Set<string> = new Set();
 
  /**
   * Analyze a parsed program for function call errors
   * @param tree The parsed program AST
   * @param symbolTable Optional symbol table for external function lookup
   * @returns Array of function call errors
   */
  public analyze(
    tree: Parser.ProgramContext,
    symbolTable?: SymbolTable,
  ): IFunctionCallError[] {
    this.errors = [];
    this.definedFunctions = new Set();
    this.knownScopes = new Set();
    this.includedHeaders = new Set();
    this.symbolTable = symbolTable ?? null;
    this.currentFunctionName = null;
    this.callableVariables = new Set();
    this.callbackTypes = new Set();
 
    // First pass: collect scope names, includes, and callback types
    this.collectScopes(tree);
    this.collectIncludes(tree);
    this.collectCallbackTypes(tree);
 
    // Second pass: walk tree in order, tracking definitions and checking calls
    const listener = new FunctionCallListener(this);
    ParseTreeWalker.DEFAULT.walk(listener, tree);
 
    return this.errors;
  }
 
  /**
   * Collect scope names for member function resolution
   */
  private collectScopes(tree: Parser.ProgramContext): void {
    for (const decl of tree.declaration()) {
      if (decl.scopeDeclaration()) {
        const name = decl.scopeDeclaration()!.IDENTIFIER().getText();
        this.knownScopes.add(name);
      }
    }
  }
 
  /**
   * Collect included headers for stdlib function lookup
   */
  private collectIncludes(tree: Parser.ProgramContext): void {
    for (const include of tree.includeDirective()) {
      // Extract header name from #include <header.h> or #include "header.h"
      const text = include.getText();
      const match = /#include\s*[<"]([^>"]+)[>"]/.exec(text);
      Eif (match) {
        this.includedHeaders.add(match[1]);
      }
    }
  }
 
  /**
   * Check if a function is from an included standard library header
   */
  private isStdlibFunction(name: string): boolean {
    for (const header of this.includedHeaders) {
      const funcs = STDLIB_FUNCTIONS.get(header);
      Eif (funcs?.has(name)) {
        return true;
      }
    }
    return false;
  }
 
  /**
   * ADR-029: Collect callback types (function-as-type pattern)
   * Any function definition creates a type that can be used for callback fields/parameters
   */
  private collectCallbackTypes(tree: Parser.ProgramContext): void {
    for (const decl of tree.declaration()) {
      if (decl.functionDeclaration()) {
        const name = decl.functionDeclaration()!.IDENTIFIER().getText();
        this.callbackTypes.add(name);
      }
    }
  }
 
  /**
   * ADR-029: Check if a type name is a callback type (function-as-type)
   */
  public isCallbackType(name: string): boolean {
    return this.callbackTypes.has(name);
  }
 
  /**
   * ADR-040: Register a variable that holds a callable (ISR or callback)
   */
  public defineCallableVariable(name: string): void {
    this.callableVariables.add(name);
  }
 
  /**
   * Register a function as defined
   */
  public defineFunction(name: string): void {
    this.definedFunctions.add(name);
  }
 
  /**
   * Track entering a function definition (for self-recursion detection)
   */
  public enterFunction(name: string): void {
    this.currentFunctionName = name;
  }
 
  /**
   * Track exiting a function definition
   */
  public exitFunction(): void {
    this.currentFunctionName = null;
  }
 
  /**
   * Check if a function name is a known scope
   */
  public isScope(name: string): boolean {
    return this.knownScopes.has(name);
  }
 
  /**
   * Check if a function call is valid (function is defined or external)
   * @param name The function name being called
   * @param line Source line number
   * @param column Source column number
   * @param currentScope The current scope name (if inside a scope)
   */
  public checkFunctionCall(
    name: string,
    line: number,
    column: number,
    currentScope: string | null,
  ): void {
    // Check for self-recursion (MISRA C:2012 Rule 17.2)
    if (this.currentFunctionName && name === this.currentFunctionName) {
      this.errors.push({
        code: "E0423",
        functionName: name,
        line,
        column,
        message: `recursive call to '${name}' is forbidden (MISRA C:2012 Rule 17.2)`,
      });
      return;
    }
 
    // Check if function is defined in C-Next
    if (this.definedFunctions.has(name)) {
      return; // OK - defined before use
    }
 
    // Check if function is a C-Next built-in
    if (CNEXT_BUILTINS.has(name)) {
      return; // OK - built-in function
    }
 
    // Check if function is from an included standard library header
    if (this.isStdlibFunction(name)) {
      return; // OK - standard library function
    }
 
    // Check if function is external (from symbol table)
    if (this.isExternalFunction(name)) {
      return; // OK - external C/C++ function
    }
 
    // ADR-040: Check if this is an ISR or callback variable being invoked
    if (this.callableVariables.has(name)) {
      return; // OK - invoking a function pointer variable
    }
 
    // ADR-057: Allow implicit scope function calls without this. prefix
    // Check if this is an unqualified call to a scope function
    // e.g., calling helper() instead of this.helper() inside a scope
    if (currentScope) {
      const qualifiedName = `${currentScope}_${name}`;
      if (this.definedFunctions.has(qualifiedName)) {
        return; // OK - implicit resolution will handle it
      }
    }
 
    // Not defined - report error
    this.errors.push({
      code: "E0422",
      functionName: name,
      line,
      column,
      message: `function '${name}' called before definition`,
    });
  }
 
  /**
   * Check if a function is defined externally (C/C++ interop)
   */
  private isExternalFunction(name: string): boolean {
    if (!this.symbolTable) {
      return false;
    }
 
    const symbols = this.symbolTable.getOverloads(name);
    for (const sym of symbols) {
      if (
        (sym.sourceLanguage === ESourceLanguage.C ||
          sym.sourceLanguage === ESourceLanguage.Cpp) &&
        sym.kind === ESymbolKind.Function
      ) {
        return true;
      }
    }
 
    return false;
  }
}
 
export default FunctionCallAnalyzer;