All files / TRANSPILE/1-Analyze FunctionCallAnalyzer.ts

99.28% Statements 139/140
97.4% Branches 75/77
100% Functions 33/33
99.27% Lines 137/138

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                                                        46x                 535x     535x 535x                     644x                                               637x                     507x     507x 507x 6x               135x 135x 135x 3x                     2x 2x 2x                 588x     588x     588x     588x 588x     588x       588x             109x     109x     109x     109x                   1871x     1871x 1871x     1871x 1871x     744x       744x     210x 210x                             1871x                       744x       298x                 536x     536x     536x     536x     536x     536x     536x     536x               536x                       535x 535x 535x 535x 535x 535x 535x 535x       535x 535x 535x     535x 535x   535x             535x 836x 109x 109x                       535x 230x               98x 98x                 21x               109x                         535x   836x 463x         836x 109x 109x 109x 183x 125x       125x                                                                             1273x                       639x             9x             588x             588x             588x             298x                                             209x 93x   116x 3x     113x 5x           108x 9x 9x           2x 2x       106x                                     210x 1x             1x       209x     103x                         106x 8x               8x       98x 7x       91x 70x           21x 21x 21x           210x                                   21x 1x   20x 2x   18x 18x 3x   18x                           91x 3x     88x 16x     72x 72x       66x 66x               6x 4x     2x          
/**
 * 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 "../../PARSE/2-Parse/grammar/CNextListener";
import * as Parser from "../../PARSE/2-Parse/grammar/CNextParser";
import SymbolTable from "../../PARSE/3-Declare/SymbolTable";
import IFunctionCallError from "./types/IFunctionCallError";
import ParserUtils from "../../utils/ParserUtils";
import AdrProvenance from "../../instrumentation/AdrProvenance";
import DynamicAllocation from "./DynamicAllocation";
import StdlibFunctions from "./StdlibFunctions";
import CalleeNameResolver from "./helpers/CalleeNameResolver";
import EnclosingScope from "./helpers/EnclosingScope";
import ScopeUtils from "../../utils/ScopeUtils";
import IncludeDirective from "./helpers/IncludeDirective";
import type IAnalysisContext from "./types/IAnalysisContext";
 
/**
 * 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(StdlibFunctions.builtinNames());
 
/**
 * Listener that walks the parse tree and checks function calls
 */
class FunctionCallListener extends CNextListener {
  private readonly analyzer: FunctionCallAnalyzer;
 
  /** The `scope` currently open, as a reference (#1357). */
  private readonly enclosing = new EnclosingScope();
 
  constructor(analyzer: FunctionCallAnalyzer) {
    super();
    this.analyzer = analyzer;
  }
 
  // ========================================================================
  // ISR/Callback Variable Tracking (ADR-040)
  // ========================================================================
 
  /**
   * Check if a type name represents a callable type (ISR, callback, or C function pointer typedef).
   */
  private isCallableType(typeName: string): boolean {
    return (
      typeName === "ISR" ||
      this.isCallbackTypeHere(typeName) ||
      this.analyzer.isCFunctionPointerTypedef(typeName)
    );
  }
 
  /**
   * ADR-029 + ADR-057: is `typeName`, written HERE, a function-as-type?
   *
   * The scope-qualified reading is asked first and the bare one second, which is
   * ADR-057's local -> scope -> global order. Asking only the bare name is what
   * #1472 fixed: inside `scope Motor`, a field or variable typed `onTick` names
   * `Motor.onTick`, and the analyzer -- which walked only top-level declarations
   * -- concluded it was not callable and reported the call through it as E0422
   * "called before definition". Codegen registered scope functions as callback
   * types all along, so the two derivations of one ADR-029 fact disagreed.
   *
   * `qualifyInScope` handles all three spellings without a branch, because
   * `QualifiedCName.fromParts` expands a dotted part: bare-in-scope `onTick`
   * becomes `Motor__onTick`, qualified `Motor.onTick` at file scope becomes the
   * same key, and a top-level `onTick` stays itself.
   */
  private isCallbackTypeHere(typeName: string): boolean {
    return (
      this.analyzer.isCallbackType(
        ScopeUtils.qualifyInScope(typeName, this.enclosing.current()),
      ) || this.analyzer.isCallbackType(typeName)
    );
  }
 
  /**
   * Track ISR-typed variables from variable declarations
   * e.g., `ISR handler <- myFunction;`
   */
  override enterVariableDeclaration = (
    ctx: Parser.VariableDeclarationContext,
  ): void => {
    const typeName = ctx.type().getText();
    if (this.isCallableType(typeName)) {
      this.analyzer.defineCallableVariable(ctx.IDENTIFIER().getText());
    }
  };
 
  /**
   * Track ISR-typed parameters in function declarations
   * e.g., `void execute(ISR handler) { handler(); }`
   */
  override enterParameter = (ctx: Parser.ParameterContext): void => {
    const typeName = ctx.type().getText();
    if (this.isCallableType(typeName)) {
      this.analyzer.defineCallableVariable(ctx.IDENTIFIER().getText());
    }
  };
 
  /**
   * A `for` init declares a variable too, and `forVarDecl` is its own grammar
   * rule -- `enterVariableDeclaration` above never fires for one (#1484). Left
   * out, `for (onTick f <- onTick; ...) { f(1); }` was rejected with
   * `E0422: function 'f' called before definition`, while the identical
   * declaration one line earlier was accepted.
   */
  override enterForVarDecl = (ctx: Parser.ForVarDeclContext): void => {
    const typeName = ctx.type().getText();
    Iif (this.isCallableType(typeName)) {
      this.analyzer.defineCallableVariable(ctx.IDENTIFIER().getText());
    }
  };
 
  // ========================================================================
  // Function Definitions
  // ========================================================================
 
  override enterFunctionDeclaration = (
    ctx: Parser.FunctionDeclarationContext,
  ): void => {
    const name = ctx.IDENTIFIER().getText();
 
    // If inside a scope, the full name is Scope_functionName
    const fullName = ScopeUtils.qualifyInScope(name, this.enclosing.current());
 
    // 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.enclosing.enter(ctx.IDENTIFIER().getText());
  };
 
  override exitScopeDeclaration = (
    _ctx: Parser.ScopeDeclarationContext,
  ): void => {
    this.enclosing.exit();
  };
 
  // ========================================================================
  // 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, isGlobalCall } = 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.enclosing.current(),
      isGlobalCall,
    );
  };
 
  /**
   * Extract base name from primary expression.
   */
  private extractBaseName(
    primary: Parser.PrimaryExpressionContext,
  ): string | null {
    return CalleeNameResolver.baseName(primary);
  }
 
  /**
   * 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; isGlobalCall: boolean } {
    return CalleeNameResolver.resolveCallTarget(
      ops,
      baseName,
      this.enclosing.current(),
      (name) => this.analyzer.isScope(name),
    );
  }
}
 
/**
 * 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();
 
  /** All functions that will be defined in this file (for distinguishing local vs cross-file) */
  private allLocalFunctions: 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();
 
  /**
   * @param context the 2.1 analysis context. Optional only because this
   *        analyzer's unit tests drive it without one (#1825 removed the
   *        whole-program pass that was the other reason); #1866 makes it
   *        required.
   */
  public constructor(private readonly context?: IAnalysisContext) {}
 
  /**
   * 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.allLocalFunctions = new Set();
    this.knownScopes = new Set();
    this.includedHeaders = new Set();
    this.symbolTable = symbolTable ?? null;
    this.currentFunctionName = null;
    this.callableVariables = new Set();
 
    // First pass: collect scope names, includes, and all local functions --
    // which ADR-029 also makes the set of callback types (see isCallbackType).
    this.collectScopes(tree);
    this.collectIncludes(tree);
    this.collectAllLocalFunctions(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 {
    // #1322: one parse, shared with ADR-010's own rules. The spelling that
    // stood here matched the two delimiters independently, so `<foo.h"` read
    // as an include.
    for (const path of IncludeDirective.pathsIn(tree)) {
      this.includedHeaders.add(path);
    }
  }
 
  /**
   * Check if a function is from an included standard library header
   */
  private isStdlibFunction(name: string): boolean {
    const header = StdlibFunctions.header(name);
    return header !== null && this.includedHeaders.has(header);
  }
 
  /**
   * Issue #787: Find which header a stdlib function belongs to (if any).
   * Returns the header name if found, or null if not a known stdlib function.
   * Checks ALL stdlib functions, not just from included headers.
   */
  private findStdlibHeader(name: string): string | null {
    return StdlibFunctions.header(name);
  }
 
  /**
   * What path a scope NAME has, from the 2.1 context's program. Falling back
   * to the bare name is what the program does for a name it has not seen.
   */
  private scopePathOf(scopeName: string): string {
    return this.context?.program.scopePathOf(scopeName) ?? scopeName;
  }
 
  /**
   * Issue #786: Pre-collect all function names defined in this file.
   * Used to distinguish between local functions (subject to define-before-use)
   * and cross-file functions from includes (allowed without local definition).
   *
   * Scope members are keyed by their transpiled C name. #1472: the set that
   * preceded this one walked `tree.declaration()` alone and silently omitted
   * every scope member.
   */
  private collectAllLocalFunctions(tree: Parser.ProgramContext): void {
    for (const decl of tree.declaration()) {
      // Standalone functions
      if (decl.functionDeclaration()) {
        this.allLocalFunctions.add(
          decl.functionDeclaration()!.IDENTIFIER().getText(),
        );
      }
      // Scope member functions
      if (decl.scopeDeclaration()) {
        const scopeDecl = decl.scopeDeclaration()!;
        const scopePath = this.scopePathOf(scopeDecl.IDENTIFIER().getText());
        for (const member of scopeDecl.scopeMember()) {
          if (member.functionDeclaration()) {
            const funcName = member
              .functionDeclaration()!
              .IDENTIFIER()
              .getText();
            this.allLocalFunctions.add(
              ScopeUtils.qualifyInScope(funcName, scopePath),
            );
          }
        }
      }
    }
  }
 
  /**
   * ADR-029: Check if a type name is a callback type (function-as-type).
   *
   * Reads `allLocalFunctions` rather than a set of its own. ADR-029 makes EVERY
   * function declaration a type, so "the callback types this file declares" and
   * "the functions this file declares" are one fact, and a second derivation of
   * it could only ever agree by coincidence -- which it did not (#1472). The set
   * this replaced walked `tree.declaration()` alone, so it silently omitted
   * every scope member, while the collector it sat beside walked them
   * correctly.
   *
   * #1491: the answer is NOT `allLocalFunctions` alone. That set exists to
   * EXCLUDE cross-file functions, because ADR-030 define-before-use (#786)
   * needs exactly that distinction -- so asking it "is this callable here?"
   * asked one set two questions, and a variable typed by an INCLUDED
   * function-as-type was rejected with E0422 "called before definition" for
   * valid C-Next. ADR-029 draws no line at the include boundary.
   *
   * The second reading is the per-file VISIBLE set, not a second derivation of
   * the first: `functionReturnTypes` is authored once by TSymbolInfoAdapter for
   * every function regardless of return type, carried across the include
   * boundary by `mergeExternalSymbols` on the same terms as the type-forming
   * kinds (#1333), and keyed by transpiled C name -- which is the key this
   * method is given. `allLocalFunctions` is left untouched and keeps answering
   * the ordering question it exists for.
   *
   * @param name The lookup key, already qualified by the caller -- see
   *             `FunctionCallListener.isCallbackTypeHere`.
   */
  public isCallbackType(name: string): boolean {
    return (
      this.allLocalFunctions.has(name) ||
      (this.context?.symbols?.functionReturnTypes.has(name) ?? false)
    );
  }
 
  /**
   * Check if a type name is a C function pointer typedef.
   * Looks up the type in the symbol table and checks if it's a typedef
   * whose underlying type contains "(*)" indicating a function pointer.
   */
  public isCFunctionPointerTypedef(typeName: string): boolean {
    return this.symbolTable?.isCFunctionPointerTypedef(typeName) ?? false;
  }
 
  /**
   * 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);
  }
 
  /**
   * Whether `name` resolves to something DEFINED IN C-NEXT at this call site.
   *
   * This is the boundary ADR-003's diagnostic keys on. A name answering true
   * here is the author's own code and cannot have been imported from anywhere,
   * so the "importing ... from C/C++" message must never reach it.
   *
   * The branches are grouped rather than left inline so that claim is
   * STRUCTURAL. Spread through `checkFunctionCall` they were four returns among
   * seven, correct only while nobody inserted a check between them -- and the
   * regression this fixes came from a second analyzer asking the ADR-003
   * question with none of this context at all, so a C-Next `pool_free` was told
   * it came from a header (#1306 review).
   */
  private resolvesToCNextDefinition(
    name: string,
    line: number,
    currentScopePath: string,
    isGlobalCall: boolean,
  ): boolean {
    if (this.definedFunctions.has(name)) {
      return true; // defined before use
    }
    if (CNEXT_BUILTINS.has(name)) {
      return true;
    }
    // ADR-040: an ISR or callback variable being invoked.
    if (this.callableVariables.has(name)) {
      return true;
    }
 
    // ADR-057: an unqualified call to a member of the enclosing scope --
    // `helper()` for `this.helper()`. Skipped for `global.` calls, which
    // explicitly mean global scope.
    if (currentScopePath && !isGlobalCall) {
      const qualifiedName = ScopeUtils.qualifyInScope(name, currentScopePath);
      if (this.definedFunctions.has(qualifiedName)) {
        // #1241: the enclosing scope resolved a bare call -- ADR-057's rule
        // firing at a position. Recorded HERE, where the candidate is
        // CONFIRMED, not at `scopeQualifiedCandidate`, which only proposes one:
        // recording the proposal would credit a cell for a name that went on to
        // resolve somewhere else entirely.
        AdrProvenance.record("057", line);
        return true;
      }
    }
 
    return false;
  }
 
  /**
   * 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 currentScopePath Path of the scope enclosing the call; `""` at file scope
   * @param isGlobalCall Whether the call used global. prefix
   */
  public checkFunctionCall(
    name: string,
    line: number,
    column: number,
    currentScopePath: string,
    isGlobalCall: boolean = false,
  ): 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;
    }
 
    // Everything the author wrote themselves, in one group -- see the method.
    if (
      this.resolvesToCNextDefinition(name, line, currentScopePath, isGlobalCall)
    ) {
      return; // OK - the author's own code
    }
 
    // ADR-003. THE place this is decided. Below this line the callee is a C or
    // C++ symbol or resolves to nothing at all, so "imported from C/C++" is
    // true by construction rather than by assumption -- which is what the
    // diagnostic's wording claims and what the previous site could not know.
    //
    // It also has to sit above `isStdlibFunction`, or `#include <stdlib.h>`
    // would resolve `malloc` and legalize the heap, and above the E0422 hint
    // below, which otherwise answers an unresolved `malloc` with "available
    // from stdlib.h -- try global.malloc()": the transpiler directing the
    // author to write the include it then rejects them for (#1306 review).
    if (DynamicAllocation.matches(name)) {
      this.errors.push({
        code: DynamicAllocation.CODE,
        functionName: name,
        line,
        column,
        message: DynamicAllocation.message(name),
        helpText: DynamicAllocation.helpText(name),
      });
      return;
    }
 
    // 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
    }
 
    // Not defined - report error with optional hint
    // If the function is local (defined later in this file), it's a
    // define-before-use error regardless of global. prefix
    const isLocalFunction = this.allLocalFunctions.has(name);
    const header = this.findStdlibHeader(name);
    const message = this.buildUndefinedFunctionMessage(
      name,
      header,
      isGlobalCall && !isLocalFunction,
    );
 
    this.errors.push({
      code: "E0422",
      functionName: name,
      line,
      column,
      message,
    });
  }
 
  /**
   * Issue #985: Build error message for undefined function calls.
   * Adjusts hint based on whether the call used global. prefix.
   */
  private buildUndefinedFunctionMessage(
    name: string,
    header: string | null,
    isGlobalCall: boolean,
  ): string {
    if (isGlobalCall && header) {
      return `'${name}' is not declared in any included header; add #include <${header}>`;
    }
    if (isGlobalCall) {
      return `'${name}' is not declared in any included header`;
    }
    let message = `function '${name}' called before definition`;
    if (header) {
      message += `; hint: '${name}' is available from ${header} — try global.${name}()`;
    }
    return message;
  }
 
  /**
   * Check if a function is defined externally (from included files)
   * This includes C/C++ headers AND C-Next includes.
   *
   * Issue #786: Only considers a function "external" if it's NOT defined
   * in the current file. Functions defined locally are subject to
   * define-before-use checking, even if they exist in the SymbolTable.
   */
  private isExternalFunction(name: string): boolean {
    // If the function is defined in this file, it's not external
    // (even if it's also in the SymbolTable from symbol collection)
    if (this.allLocalFunctions.has(name)) {
      return false;
    }
 
    if (!this.symbolTable) {
      return false;
    }
 
    const symbols = this.symbolTable.getOverloads(name);
    for (const sym of symbols) {
      // Accept functions from any source language:
      // - C/C++ functions from header includes
      // - C-Next functions from .cnx file includes
      Eif (sym.kind === "function") {
        return true;
      }
    }
 
    // Issue #985 recovery: a function-like MACRO recovered by translation-unit
    // preprocessing (e.g. FreeRTOS pdMS_TO_TICKS). Recovered functions are
    // registered as full symbols (found above via getOverloads); macros have no
    // declaration to parse, so only their name is known.
    if (this.symbolTable.hasExternalDeclaration(name)) {
      return true;
    }
 
    return false;
  }
}
 
export default FunctionCallAnalyzer;