All files / transpiler/logic/preprocessor Preprocessor.ts

100% Statements 78/78
93.75% Branches 45/48
100% Functions 10/10
100% Lines 77/77

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                                16x               242x     242x   242x 238x                   59x             4x                   53x 1x                   52x 52x   37x           53x       53x               15x                                     30x   30x   30x 30x     30x     30x     30x   30x     30x 30x 30x                             52x 52x           52x 32x         52x 10x       52x           52x 224x       52x 19x 4x 1x 3x 2x                 52x 3x 6x         52x             52x 52x         37x 1x     37x       15x 15x                       24x 24x   24x 24x   24x 222x     222x       222x 117x 117x 105x 94x         94x       24x             13x   3952x                       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 { writeFile, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, 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";
 
const execFileAsync = promisify(execFile);
 
/**
 * Handles preprocessing of C/C++ files
 */
class Preprocessor {
  private readonly toolchain: IToolchain | null;
 
  private readonly defaultIncludePaths: string[] = [];
 
  constructor(toolchain?: IToolchain) {
    this.toolchain = toolchain ?? ToolchainDetector.detect();
 
    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 (creates temp file)
   */
  async preprocessString(
    content: string,
    filename: string,
    options: IPreprocessOptions = {},
  ): Promise<IPreprocessResult> {
    let tempDir: string | null = null;
 
    try {
      // Create temp directory
      tempDir = await mkdtemp(join(tmpdir(), "cnext-"));
      const tempFile = join(tempDir, basename(filename));
 
      // Write content to temp file
      await writeFile(tempFile, content, "utf-8");
 
      // Preprocess
      const result = await this.preprocess(tempFile, options);
 
      // Update the original file reference
      result.originalFile = filename;
 
      return result;
    } finally {
      // Clean up temp directory
      Eif (tempDir) {
        try {
          await rm(tempDir, { recursive: true });
        } catch {
          // Ignore cleanup errors
        }
      }
    }
  }
 
  /**
   * 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;
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
      // Include stderr in error message for better debugging
      const stderr = error.stderr ?? "";
      throw new Error(
        `Preprocessor failed for ${filePath}:\n${error.message}\n${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;