All files / PARSE/1-Discover/preprocessor Preprocessor.ts

100% Statements 72/72
95.65% Branches 44/46
100% Functions 11/11
100% Lines 71/71

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                                47x               561x         561x 561x   561x 345x                   131x             4x                   97x 1x                   96x 96x   55x           97x       97x               41x                                               48x     48x   48x 48x                   96x 96x           96x 44x         96x 16x       96x           96x 421x       96x 64x 4x 1x 3x 2x                 96x 13x 28x         96x             96x 96x         55x 1x     55x     41x 41x                       29x 29x   29x 29x   29x 343x     343x       343x 140x 140x 203x 193x         193x       29x             26x   6607x                       6x   6x 9x 6x       6x         6x 2x       4x   4x                
/**
 * C/C++ Preprocessor
 * Runs the system preprocessor on C/C++ files before parsing
 */
 
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { basename, dirname } from "node:path";
import IToolchain from "./types/IToolchain";
import IPreprocessResult from "./types/IPreprocessResult";
import ISourceMapping from "./types/ISourceMapping";
import IPreprocessOptions from "./types/IPreprocessOptions";
import ToolchainDetector from "./ToolchainDetector";
import ExecFailure from "../../../utils/ExecFailure";
import IFileSystem from "../../../types/IFileSystem";
 
const execFileAsync = promisify(execFile);
 
/**
 * Handles preprocessing of C/C++ files
 */
class Preprocessor {
  private readonly toolchain: IToolchain | null;
 
  private readonly defaultIncludePaths: string[] = [];
 
  private readonly fs: IFileSystem;
 
  constructor(fs: IFileSystem, toolchain?: IToolchain) {
    this.fs = fs;
    this.toolchain = toolchain ?? ToolchainDetector.detect(fs);
 
    if (this.toolchain) {
      this.defaultIncludePaths = ToolchainDetector.getDefaultIncludePaths(
        this.toolchain,
      );
    }
  }
 
  /**
   * Check if a toolchain is available
   */
  isAvailable(): boolean {
    return this.toolchain !== null;
  }
 
  /**
   * Get the current toolchain
   */
  getToolchain(): IToolchain | null {
    return this.toolchain;
  }
 
  /**
   * Preprocess a C/C++ file
   */
  async preprocess(
    filePath: string,
    options: IPreprocessOptions = {},
  ): Promise<IPreprocessResult> {
    if (!this.toolchain) {
      return {
        content: "",
        sourceMappings: [],
        success: false,
        error:
          "No C/C++ toolchain available. Install gcc, clang, or arm-none-eabi-gcc.",
        originalFile: filePath,
      };
    }
 
    try {
      const content = await this.runPreprocessor(filePath, options);
      const sourceMappings =
        options.keepLineDirectives === false
          ? []
          : this.parseLineDirectives(content);
 
      // Optionally strip #line directives for cleaner output
      const cleanContent =
        options.keepLineDirectives === false
          ? this.stripLineDirectives(content)
          : content;
 
      return {
        content: cleanContent,
        sourceMappings,
        success: true,
        originalFile: filePath,
        toolchain: this.toolchain.name,
      };
    } catch (error) {
      return {
        content: "",
        sourceMappings: [],
        success: false,
        error: error instanceof Error ? error.message : String(error),
        originalFile: filePath,
        toolchain: this.toolchain.name,
      };
    }
  }
 
  /**
   * Preprocess content from a string, through a temporary file the port owns.
   *
   * Not stdin (#1653, measured on gcc and clang): on stdin a quoted `#include`
   * is searched for first in the process's working directory, so a header
   * there would shadow the one the search paths name. A temporary file in an
   * otherwise empty directory keeps the resolution this always had.
   */
  async preprocessString(
    content: string,
    filename: string,
    options: IPreprocessOptions = {},
  ): Promise<IPreprocessResult> {
    const result = await this.fs.withTempFile(
      basename(filename),
      content,
      (tempFile) => this.preprocess(tempFile, options),
    );
    result.originalFile = filename;
    return result;
  }
 
  /**
   * Run the preprocessor command
   */
  private async runPreprocessor(
    filePath: string,
    options: IPreprocessOptions,
  ): Promise<string> {
    const toolchain = options.toolchain ?? this.toolchain!;
    const args: string[] = [
      "-E", // Preprocess only
      "-P", // Don't generate linemarkers (we'll add them back if needed)
    ];
 
    // If we want line directives, don't use -P
    if (options.keepLineDirectives !== false) {
      args.pop(); // Remove -P
    }
 
    // Dump macro definitions (#define list) instead of preprocessed source,
    // to discover function-like macros the normal preprocess would consume.
    if (options.dumpMacros) {
      args.push("-dM");
    }
 
    // Add include paths
    const includePaths = [
      ...this.defaultIncludePaths,
      ...(options.includePaths ?? []),
      dirname(filePath), // Include the file's directory
    ];
 
    for (const path of includePaths) {
      args.push(`-I${path}`);
    }
 
    // Add defines
    if (options.defines) {
      for (const [key, value] of Object.entries(options.defines)) {
        if (value === true) {
          args.push(`-D${key}`);
        } else if (value !== false) {
          args.push(`-D${key}=${value}`);
        }
      }
    }
 
    // Import predecessor macros (gcc/clang -imacros) so include-order-dependent
    // headers get the guards/attribute macros their includer would have defined
    // first. -imacros keeps only the macros, not the predecessors' declarations,
    // so the output stays scoped to the target file.
    if (options.imacros) {
      for (const macroHeader of options.imacros) {
        args.push("-imacros", macroHeader);
      }
    }
 
    // Add the input file
    args.push(filePath);
 
    // Invoke the preprocessor via argv (execFile, NOT a shell). A shell would
    // re-parse -D values that legitimately contain spaces / parentheses (e.g.
    // -DARDUINO_BOARD="Espressif ... (8 MB QD, No PSRAM)"), breaking on the
    // metacharacters. Passing args directly mirrors how the real compiler is
    // invoked and is safe for any value the compiler accepts.
    try {
      const { stdout, stderr } = await execFileAsync(toolchain.cpp, args, {
        maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large headers
      });
 
      // Log warnings to console but don't fail
      if (stderr?.trim()) {
        console.warn(`Preprocessor warnings for ${filePath}:\n${stderr}`);
      }
 
      return stdout;
    } catch (error: unknown) {
      // Include stderr in error message for better debugging
      const failure = ExecFailure.of(error);
      throw new Error(
        `Preprocessor failed for ${filePath}:\n${failure.message}\n${failure.stderr ?? ""}`,
        { cause: error },
      );
    }
  }
 
  /**
   * Parse #line directives to build source mappings
   * Format: # linenum "filename" [flags]
   */
  private parseLineDirectives(content: string): ISourceMapping[] {
    const mappings: ISourceMapping[] = [];
    const lines = content.split("\n");
 
    let currentFile = "";
    let currentOriginalLine = 1;
 
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
 
      // Match # linenum "filename" or #line linenum "filename"
      const match = /^#\s*(?:line\s+)?(\d+)\s+"([^"]+)"(?:\s+\d+)*\s*$/.exec(
        line,
      );
 
      if (match) {
        currentOriginalLine = Number.parseInt(match[1], 10);
        currentFile = match[2];
      } else if (currentFile) {
        mappings.push({
          preprocessedLine: i + 1,
          originalFile: currentFile,
          originalLine: currentOriginalLine,
        });
        currentOriginalLine++;
      }
    }
 
    return mappings;
  }
 
  /**
   * Strip #line directives from preprocessed output
   */
  private stripLineDirectives(content: string): string {
    return content
      .split("\n")
      .filter((line) => !/^#\s*(?:line\s+)?\d+\s+"/.exec(line))
      .join("\n");
  }
 
  /**
   * Map a line in preprocessed output back to original source
   */
  static mapToOriginal(
    mappings: ISourceMapping[],
    preprocessedLine: number,
  ): { file: string; line: number } | null {
    // Find the mapping for this line or the closest previous one
    let bestMapping: ISourceMapping | null = null;
 
    for (const mapping of mappings) {
      if (mapping.preprocessedLine <= preprocessedLine) {
        Eif (
          !bestMapping ||
          mapping.preprocessedLine > bestMapping.preprocessedLine
        ) {
          bestMapping = mapping;
        }
      }
    }
 
    if (!bestMapping) {
      return null;
    }
 
    // Calculate the offset from the mapping
    const offset = preprocessedLine - bestMapping.preprocessedLine;
 
    return {
      file: bestMapping.originalFile,
      line: bestMapping.originalLine + offset,
    };
  }
}
 
export default Preprocessor;