All files / PARSE/1-Discover IncludeDiscovery.ts

100% Statements 142/142
96.59% Branches 85/88
100% Functions 31/31
100% Lines 139/139

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                                                                  556x     556x 556x     556x 556x   167x 167x 501x 501x 167x           167x 167x 63x 63x 44x 44x       63x         63x           556x 556x     556x       51x                     54x   54x 162x 162x 48x                           47x 47x 54x 54x 54x                                 556x 556x   556x     555x         555x 1110x 2x 2x             555x                                 44x   44x   44x 44x 45x 45x 45x             44x                                       63x   63x 63x                       63x 12x 16x 16x   12x   15x 15x 14x               63x                                 1717x                 1717x 1717x 37106x 474x   5921x 5921x 1243x   4678x                             38x                                 224x   224x 224x 12731x 12368x 12368x   363x 363x 242x 242x   121x 121x     224x         363x 363x       246x 9x     354x       853x         478x 478x 129x   478x                     363x 9x     354x 354x 230x     124x 124x 124x 1x     123x 123x 123x         1109x     123x 2x     121x                                               224x     224x 121x           224x                                                     41x 16x                               725x     725x   725x   15507x       387x       387x                 596x                                               596x 283x     283x     313x                                         197x                                       370x 10x         360x     571x                               360x 571x 571x 218x     142x                               283x 283x          
import { dirname, resolve, join, isAbsolute } from "node:path";
 
import { CharStream } from "antlr4ng";
 
import { CNextLexer } from "../2-Parse/grammar/CNextLexer";
import IncludeDirectiveText from "../../utils/IncludeDirectiveText";
import invariant from "../../utils/invariant";
import FileDiscovery from "./FileDiscovery";
import PlatformIOIni from "./PlatformIOIni";
import EFileType from "./types/EFileType";
import IFileSystem from "../../types/IFileSystem";
 
/**
 * Auto-discovery of include paths for C-Next compilation
 *
 * Implements 4-tier include path discovery:
 * 1. File's own directory (for relative #include "header.h")
 * 2. Project root (walk up to find platformio.ini, cnext.config.json, .git)
 * 3. PlatformIO library dependencies (.pio/libdeps/ and lib_extra_dirs)
 * 4. Arduino library paths (~/Arduino/libraries/ or ~/Documents/Arduino/libraries/)
 *
 * Note: System paths (compiler defaults) not included to avoid dependencies.
 * Users can add system paths via --include flag if needed.
 */
class IncludeDiscovery {
  /**
   * Discover include paths for a file
   *
   * @param inputFile - Path to .cnx file being compiled
   * @param fs - File system abstraction
   * @returns Array of include directory paths
   */
  static discoverIncludePaths(inputFile: string, fs: IFileSystem): string[] {
    const paths: string[] = [];
 
    // Tier 1: File's own directory (highest priority)
    const fileDir = dirname(resolve(inputFile));
    paths.push(fileDir);
 
    // Tier 2: Project root detection
    const projectRoot = this.findProjectRoot(fileDir, fs);
    if (projectRoot) {
      // Add common include directories if they exist
      const commonDirs = ["include", "src", "lib"];
      for (const dir of commonDirs) {
        const includePath = join(projectRoot, dir);
        if (fs.exists(includePath) && fs.isDirectory(includePath)) {
          paths.push(includePath);
        }
      }
 
      // Tier 3: Issue #355 - PlatformIO library dependencies
      // When platformio.ini exists, check for .pio/libdeps/ and add all library paths
      const pioIniPath = join(projectRoot, "platformio.ini");
      if (fs.exists(pioIniPath)) {
        const libDepsPath = join(projectRoot, ".pio", "libdeps");
        if (fs.exists(libDepsPath) && fs.isDirectory(libDepsPath)) {
          const pioLibPaths = this.discoverPlatformIOLibPaths(libDepsPath, fs);
          paths.push(...pioLibPaths);
        }
 
        // Issue #355: Also parse lib_extra_dirs from platformio.ini
        const extraDirs = this.parsePlatformIOLibExtraDirs(
          pioIniPath,
          projectRoot,
          fs,
        );
        paths.push(...extraDirs);
      }
    }
 
    // Tier 4: Issue #355 - Arduino library paths
    // Check for Arduino libraries in common locations
    const arduinoPaths = this.discoverArduinoLibPaths(fs);
    paths.push(...arduinoPaths);
 
    // Remove duplicates
    return Array.from(new Set(paths));
  }
 
  /** Common subdirectories where library headers might live */
  private static readonly LIBRARY_SUB_DIRS = ["src", "include", "src/include"];
 
  /**
   * Add a library path and its common subdirectories to the paths array.
   * Checks src/, include/, and src/include/ subdirectories.
   */
  private static _addLibraryWithSubDirs(
    libPath: string,
    paths: string[],
    fs: IFileSystem,
  ): void {
    paths.push(libPath);
 
    for (const subDir of this.LIBRARY_SUB_DIRS) {
      const subPath = join(libPath, subDir);
      if (fs.exists(subPath) && fs.isDirectory(subPath)) {
        paths.push(subPath);
      }
    }
  }
 
  /**
   * Collect all library directories from a parent directory.
   * Each subdirectory is treated as a library root.
   */
  private static _collectLibrariesFromDir(
    parentDir: string,
    paths: string[],
    fs: IFileSystem,
  ): void {
    const entries = fs.readdir(parentDir);
    for (const entry of entries) {
      const entryPath = join(parentDir, entry);
      Eif (fs.isDirectory(entryPath)) {
        this._addLibraryWithSubDirs(entryPath, paths, fs);
      }
    }
  }
 
  /**
   * Discover Arduino library paths
   *
   * Issue #355: Arduino stores libraries in platform-specific locations:
   * - Linux: ~/Arduino/libraries/
   * - macOS: ~/Documents/Arduino/libraries/
   * - Windows: %USERPROFILE%\Documents\Arduino\libraries\
   *
   * @param fs - File system abstraction
   * @returns Array of library directory paths
   */
  private static discoverArduinoLibPaths(fs: IFileSystem): string[] {
    const paths: string[] = [];
    const home = process.env.HOME || process.env.USERPROFILE || "";
 
    if (!home) return paths;
 
    // Common Arduino library locations
    const arduinoLibDirs = [
      join(home, "Arduino", "libraries"), // Linux
      join(home, "Documents", "Arduino", "libraries"), // macOS / Windows
    ];
 
    for (const libDir of arduinoLibDirs) {
      if (fs.exists(libDir) && fs.isDirectory(libDir)) {
        try {
          this._collectLibrariesFromDir(libDir, paths, fs);
        } catch {
          // Expected: directory may not exist or be readable
        }
      }
    }
 
    return paths;
  }
 
  /**
   * Discover PlatformIO library dependency paths
   *
   * PlatformIO stores libraries in .pio/libdeps/<env>/<library>/
   * This function finds all library directories across all environments.
   *
   * @param libDepsPath - Path to .pio/libdeps/
   * @param fs - File system abstraction
   * @returns Array of library directory paths
   */
  private static discoverPlatformIOLibPaths(
    libDepsPath: string,
    fs: IFileSystem,
  ): string[] {
    const paths: string[] = [];
 
    try {
      // Iterate through environment directories (e.g., teensy40, teensy41, esp32)
      const envDirs = fs.readdir(libDepsPath);
      for (const envDir of envDirs) {
        const envPath = join(libDepsPath, envDir);
        Eif (fs.isDirectory(envPath)) {
          this._collectLibrariesFromDir(envPath, paths, fs);
        }
      }
    } catch {
      // Expected: .pio directory may not exist
    }
 
    return paths;
  }
 
  /**
   * Parse platformio.ini for lib_extra_dirs
   *
   * Issue #355: PlatformIO allows specifying additional library directories
   * via lib_extra_dirs in platformio.ini. This parses those and returns
   * resolved absolute paths.
   *
   * @param pioIniPath - Path to platformio.ini
   * @param projectRoot - Project root directory for resolving relative paths
   * @param fs - File system abstraction
   * @returns Array of library directory paths
   */
  private static parsePlatformIOLibExtraDirs(
    pioIniPath: string,
    projectRoot: string,
    fs: IFileSystem,
  ): string[] {
    const paths: string[] = [];
 
    try {
      const content = fs.readFile(pioIniPath);
 
      // Match lib_extra_dirs in any section
      // Format can be:
      //   lib_extra_dirs = path1, path2
      //   lib_extra_dirs =
      //     path1
      //     path2
      // The one list rule (#1760 review: this file split and stripped
      // comments with its own copy). A path in quotes is read without them,
      // as it was before (679035029); PlatformIO keeps them, and quotes are
      // stripped nowhere else, since in a section name they change the section.
      for (const value of PlatformIOIni.valuesOf(content, "lib_extra_dirs")) {
        const dirs = PlatformIOIni.list(value)
          .map((dir) => (/^(["']).*\1$/.test(dir) ? dir.slice(1, -1) : dir))
          .filter((dir) => dir.length > 0);
 
        for (const dir of dirs) {
          // Resolve relative to project root
          const fullPath = isAbsolute(dir) ? dir : join(projectRoot, dir);
          if (fs.exists(fullPath) && fs.isDirectory(fullPath)) {
            paths.push(fullPath);
          }
        }
      }
    } catch {
      // Expected: platformio.ini may not exist or be malformed
    }
 
    return paths;
  }
 
  /**
   * Find the project root by walking up from `startDir` to the nearest
   * directory holding any project marker, the filesystem root included.
   *
   * The one finder (#1668): include discovery and the transpiler's cache and
   * header base used to walk with two marker lists that each lacked a marker
   * the other had. Every marker counts equally -- the nearest directory wins,
   * so the list's order decides nothing.
   *
   * @param startDir - Directory to start search from
   * @param fs - File system abstraction
   * @returns Project root path or null if not found
   */
  static findProjectRoot(startDir: string, fs: IFileSystem): string | null {
    const markers = [
      "cnext.config.json",
      ".cnext.json",
      ".cnextrc",
      "platformio.ini",
      ".git",
      "package.json",
    ];
 
    let dir = resolve(startDir);
    while (true) {
      if (markers.some((marker) => fs.exists(join(dir, marker)))) {
        return dir;
      }
      const parent = dirname(dir);
      if (parent === dir) {
        return null;
      }
      dir = parent;
    }
  }
 
  /**
   * Extract #include directives from source code
   *
   * Matches both:
   * - #include "header.h" (local includes)
   * - #include <header.h> (system includes)
   *
   * @param content - Source file content
   * @returns Array of include paths (for backwards compatibility)
   */
  static extractIncludes(content: string): string[] {
    return this.extractIncludesWithInfo(content).map((info) => info.path);
  }
 
  /**
   * Scan `#include` directives, replacing
   * /^\s*#\s*include\s*([<"])([^>"]+)[>"]/gm, which backtracks
   * super-linearly on its whitespace runs (S8786).
   *
   * Behavior is preserved exactly, including two quirks worth naming:
   * the closing delimiter is not required to match the opening one
   * (`#include <a.h"` is accepted), and every whitespace run may span
   * newlines, so a `#` alone on one line with `include` on the next still
   * matches. Only whitespace may precede the `#` on its own line.
   */
  private static _scanIncludeDirectives(
    content: string,
  ): { delimiter: string; path: string }[] {
    const found: { delimiter: string; path: string }[] = [];
 
    let index = 0;
    while (index < content.length) {
      if (content[index] !== "#") {
        index += 1;
        continue;
      }
      const directive = IncludeDiscovery._readIncludeAt(content, index);
      if (directive === null) {
        index += 1;
        continue;
      }
      found.push({ delimiter: directive.delimiter, path: directive.path });
      index = directive.next;
    }
 
    return found;
  }
 
  /** True when only whitespace separates `index` from the start of its line. */
  private static _lineStartIsClear(content: string, index: number): boolean {
    for (
      let before = index - 1;
      before >= 0 && content[before] !== "\n";
      before -= 1
    ) {
      if (!IncludeDiscovery._isSpace(content[before])) {
        return false;
      }
    }
    return true;
  }
 
  private static _isSpace(character: string | undefined): boolean {
    return character !== undefined && /\s/.test(character);
  }
 
  /** Advance past a run of whitespace. */
  private static _skipSpace(content: string, from: number): number {
    let cursor = from;
    while (IncludeDiscovery._isSpace(content[cursor])) {
      cursor += 1;
    }
    return cursor;
  }
 
  /**
   * Read one `#include` beginning at the `#` in `index`, or null if there
   * isn't one there. `next` is the index just past the closing delimiter.
   */
  private static _readIncludeAt(
    content: string,
    index: number,
  ): { delimiter: string; path: string; next: number } | null {
    if (!IncludeDiscovery._lineStartIsClear(content, index)) {
      return null;
    }
 
    let cursor = IncludeDiscovery._skipSpace(content, index + 1);
    if (!content.startsWith("include", cursor)) {
      return null;
    }
 
    cursor = IncludeDiscovery._skipSpace(content, cursor + "include".length);
    const delimiter = content[cursor];
    if (delimiter !== "<" && delimiter !== '"') {
      return null;
    }
 
    const pathStart = cursor + 1;
    let pathEnd = pathStart;
    while (
      pathEnd < content.length &&
      content[pathEnd] !== ">" &&
      content[pathEnd] !== '"'
    ) {
      pathEnd += 1;
    }
    // [^>"]+ requires at least one character, and a closing delimiter
    if (pathEnd === pathStart || pathEnd >= content.length) {
      return null;
    }
 
    return {
      delimiter,
      path: content.slice(pathStart, pathEnd),
      next: pathEnd + 1,
    };
  }
 
  /**
   * Extract #include directives with local/system info
   *
   * Issue #355: Returns whether each include is local ("...") or system (<...>)
   * so we can warn appropriately when local includes aren't found.
   *
   * A text scan, for C and C++ headers. It does not know about comments, so
   * it reads a directive inside one (#1829). A `.cnx` file's directives are
   * read by `extractCNextIncludes`, which the grammar decides, and
   * `directivesOf` is where a file on disk is given one or the other.
   *
   * @param content - Source file content
   * @returns Array of include info objects
   */
  static extractIncludesWithInfo(
    content: string,
  ): Array<{ path: string; isLocal: boolean }> {
    const includes: Array<{ path: string; isLocal: boolean }> = [];
 
    // Match #include directives, capturing the delimiter to determine local vs system
    for (const directive of IncludeDiscovery._scanIncludeDirectives(content)) {
      includes.push({
        path: directive.path,
        isLocal: directive.delimiter === '"',
      });
    }
 
    return includes;
  }
 
  /**
   * A `.cnx` file's #include directives, as the grammar reads them (#1745).
   *
   * The text scan above did not know about comments, while the parser's
   * `INCLUDE_DIRECTIVE` token treats a comment as a hidden token. So discovery
   * pulled in a file that a block comment had disabled, and missed a directive
   * written after a comment on its line. Reading the parser's own token makes
   * the two agree by construction rather than by what the fixtures exercise.
   *
   * It lexes rather than reading 1.2's artifact because discovery decides
   * which files the run parses, so no parse exists yet when it asks. It is
   * why this module appears in `docs/architecture/parse-tree-sites.md`.
   *
   * The path is everything between the token's delimiters. The grammar makes
   * the closing delimiter the token's last character, so a `"` inside `<...>`
   * belongs to the path, as the parser and 2.1 read it. Splitting the token
   * with the scan above stopped at that quote and named a different file
   * (#1830 review).
   *
   * @param source - A `.cnx` file's text
   */
  static extractCNextIncludes(
    source: string,
  ): Array<{ path: string; isLocal: boolean }> {
    return IncludeDiscovery.directiveTextsOf(source).flatMap(
      (text) => IncludeDirectiveText.split(text) ?? [],
    );
  }
 
  /**
   * The text of every `INCLUDE_DIRECTIVE` token in a `.cnx` file, in source
   * order and exactly as written: the author's spacing and form survive. It
   * is the token 1.2's `includeDirective` holds, so these are the directives
   * the parser sees (#1745).
   *
   * #1444: a file's user includes were derived from that tree in Stage 5,
   * after 1.1 had already lexed the same tokens. 1.1 keeps the text instead.
   *
   * @param source - A `.cnx` file's text
   */
  static directiveTextsOf(source: string): string[] {
    const lexer = new CNextLexer(CharStream.fromString(source));
    // 1.2 Parse reports a lexical error once, with its position. Here it
    // would only print ANTLR's console default a second time.
    lexer.removeErrorListeners();
 
    return lexer
      .getAllTokens()
      .filter((token) => token.type === CNextLexer.INCLUDE_DIRECTIVE)
      .map((token) => {
        // A token the lexer produced always carries its text. The type allows
        // none, and an empty default would drop the directive without a trace.
        invariant(
          token.text !== undefined,
          "an INCLUDE_DIRECTIVE token carries its text",
        );
        return token.text;
      });
  }
 
  /**
   * Whether `include` is a quoted include of C-Next source: the form ADR-010
   * resolves beside the including file only, and whose absence is E0506.
   */
  static isQuotedCNext(include: { path: string; isLocal: boolean }): boolean {
    return (
      include.isLocal &&
      FileDiscovery.classifyFile(include.path).type === EFileType.CNext
    );
  }
 
  /**
   * #1672: where an include resolves -- the one decision, for both routes
   * by which 1.1 resolves a file's includes: a `.cnx` file's own
   * (`IncludeResolver`) and the C/C++ entry point's scan
   * (`CppEntryPointScanner`). A quoted C-Next include resolves beside the
   * including file and only there (ADR-010); anything else by its absolute
   * path or along the search path, as a compiler searches its -I list.
   *
   * @param quotedIncludeDirectory - The including file's directory. It is
   *   required: with no directory, a quoted C-Next include was searched like
   *   any other, which is the second rule #1672 removed (#1835 review)
   */
  static resolveSpelling(
    include: { path: string; isLocal: boolean },
    quotedIncludeDirectory: string,
    searchPaths: string[],
    fs: IFileSystem,
  ): string | null {
    if (IncludeDiscovery.isQuotedCNext(include)) {
      return IncludeDiscovery.resolveQuoted(
        include.path,
        quotedIncludeDirectory,
        (path) => fs.exists(path) && fs.isFile(path),
      );
    }
    return IncludeDiscovery.resolveInclude(include.path, searchPaths, fs);
  }
 
  /**
   * A file's #include directives, read by the rules of its kind: a C-Next
   * file's as the grammar reads them, anything else's by the text scan.
   *
   * The one place that choice is made for the readers that walk files on
   * disk: the C/C++ entry-point scan and the transitive header walk. The
   * #1830 review found the entry-point scan still reading a `.cnx` file it
   * reached with the text scan, so a commented-out include joined the run
   * through that route. #1829 changes the other branch.
   *
   * A file with no path to classify, a source run's in-memory root, never
   * reaches here. The pipeline's own files are C-Next by construction and
   * call `extractCNextIncludes` directly.
   */
  static directivesOf(
    path: string,
    content: string,
  ): Array<{ path: string; isLocal: boolean }> {
    return FileDiscovery.classifyFile(path).type === EFileType.CNext
      ? IncludeDiscovery.extractCNextIncludes(content)
      : IncludeDiscovery.extractIncludesWithInfo(content);
  }
 
  /**
   * Resolve an include path using search directories
   *
   * @param includePath - The include path from #include directive
   * @param searchPaths - Directories to search in
   * @param fs - File system abstraction
   * @returns Resolved absolute path or null if not found
   */
  static resolveInclude(
    includePath: string,
    searchPaths: string[],
    fs: IFileSystem,
  ): string | null {
    // Already absolute: a file there, as every other branch asks (#1672).
    // A directory "resolved" here and was then dropped by `discoverFile`.
    if (isAbsolute(includePath)) {
      return fs.exists(includePath) && fs.isFile(includePath)
        ? includePath
        : null;
    }
 
    return IncludeDiscovery.resolveAlong(
      includePath,
      searchPaths,
      (path) => fs.exists(path) && fs.isFile(path),
    );
  }
 
  /**
   * The first search directory holding `includePath`, in priority order --
   * how an angle include resolves.
   *
   * @param isFile - Whether a path is an existing file, through the run's
   *   file system
   */
  static resolveAlong(
    includePath: string,
    searchPaths: readonly string[],
    isFile: (path: string) => boolean,
  ): string | null {
    for (const searchDir of searchPaths) {
      const fullPath = join(searchDir, includePath);
      if (isFile(fullPath)) {
        return fullPath;
      }
    }
    return null;
  }
 
  /**
   * #1672: where a quoted `.cnx` include resolves -- beside the file it
   * appears in, and only there (ADR-010). 1.1 searched every search path, and
   * pulled in a file 2.1 then said the include could not reach.
   *
   * @param isFile - Whether a path is an existing file, through the run's
   *   file system
   */
  static resolveQuoted(
    includePath: string,
    quotedIncludeDirectory: string,
    isFile: (path: string) => boolean,
  ): string | null {
    const candidate = resolve(quotedIncludeDirectory, includePath);
    return isFile(candidate) ? candidate : null;
  }
}
 
export default IncludeDiscovery;