All files / transpiler/output/codegen/generators/support IncludeGenerator.ts

100% Statements 58/58
97.22% Branches 35/36
100% Functions 8/8
100% Lines 58/58

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                                          13x           4x 1x     3x 3x 3x   3x 1x     2x         2x             13x         9x     9x 4x           4x 1x         8x             13x         17x     17x 16x 16x   16x 4x                 13x                       13x         58x 58x 9x     49x 49x 17x       32x           13x 19x 19x             13x     14x     14x 5x 5x 5x             9x 4x 4x 4x             5x 4x     1x             13x     6x                   13x     8x 5x   3x 1x   2x       13x                  
/**
 * Include directive and preprocessor handling.
 * Extracted from CodeGenerator.ts as part of ADR-053 A5.
 */
import * as path from "node:path";
import * as Parser from "../../../../logic/parser/grammar/CNextParser";
import CnxFileResolver from "../../../../data/CnxFileResolver";
 
/**
 * Issue #349: Options for include transformation
 */
interface IIncludeTransformOptions {
  sourcePath: string | null;
  includeDirs?: string[];
  inputs?: string[];
}
 
/**
 * Resolve angle-bracket include path from inputs.
 * SonarCloud S3776: Extracted from transformIncludeDirective().
 */
const resolveAngleIncludePath = (
  filename: string,
  sourcePath: string,
  includeDirs: string[],
  inputs: string[],
): string | null => {
  if (inputs.length === 0) {
    return null;
  }
 
  const sourceDir = path.dirname(sourcePath);
  const searchPaths = [sourceDir, ...includeDirs];
  const foundPath = CnxFileResolver.findCnxFile(filename, searchPaths);
 
  if (!foundPath) {
    return null;
  }
 
  const relativePath = CnxFileResolver.getRelativePathFromInputs(
    foundPath,
    inputs,
  );
 
  return relativePath ? relativePath.replace(/\.cnx$/, ".h") : null;
};
 
/**
 * Process angle-bracket includes: #include <file.cnx>
 * SonarCloud S3776: Extracted from transformIncludeDirective().
 */
const transformAngleInclude = (
  includeText: string,
  filename: string,
  options: IIncludeTransformOptions,
): string => {
  const { sourcePath, includeDirs = [], inputs = [] } = options;
 
  // Try to resolve the correct output path
  if (sourcePath) {
    const resolvedPath = resolveAngleIncludePath(
      filename,
      sourcePath,
      includeDirs,
      inputs,
    );
    if (resolvedPath) {
      return includeText.replace(`<${filename}.cnx>`, `<${resolvedPath}>`);
    }
  }
 
  // Fallback: simple replacement
  return includeText.replace(`<${filename}.cnx>`, `<${filename}.h>`);
};
 
/**
 * Process quote includes: #include "file.cnx"
 * SonarCloud S3776: Extracted from transformIncludeDirective().
 */
const transformQuoteInclude = (
  includeText: string,
  filepath: string,
  options: IIncludeTransformOptions,
): string => {
  const { sourcePath } = options;
 
  // Validate .cnx file exists if we have source path
  if (sourcePath) {
    const sourceDir = path.dirname(sourcePath);
    const cnxPath = path.resolve(sourceDir, `${filepath}.cnx`);
 
    if (!CnxFileResolver.cnxFileExists(cnxPath)) {
      throw new Error(
        `Error: Included C-Next file not found: ${filepath}.cnx\n` +
          `  Searched at: ${cnxPath}\n` +
          `  Referenced in: ${sourcePath}`,
      );
    }
  }
 
  // Transform to .h
  return includeText.replace(`"${filepath}.cnx"`, `"${filepath}.h"`);
};
 
/**
 * ADR-010: Transform #include directives, converting .cnx to .h
 * Validates that .cnx files exist if sourcePath is available
 * Supports both <file.cnx> and "file.cnx" forms
 *
 * Issue #349: For angle-bracket includes, resolves the correct output path
 * by finding the .cnx file and calculating its relative path from inputs.
 * SonarCloud S3776: Refactored to use helper functions.
 */
const transformIncludeDirective = (
  includeText: string,
  options: IIncludeTransformOptions,
): string => {
  // Match: #include <file.cnx> or #include "file.cnx"
  const angleMatch = /#\s*include\s*<([^>]+)\.cnx>/.exec(includeText);
  if (angleMatch) {
    return transformAngleInclude(includeText, angleMatch[1], options);
  }
 
  const quoteMatch = /#\s*include\s*"([^"]+)\.cnx"/.exec(includeText);
  if (quoteMatch) {
    return transformQuoteInclude(includeText, quoteMatch[1], options);
  }
 
  // Not a .cnx include - pass through unchanged
  return includeText;
};
 
/**
 * Extract the macro name from a #define directive
 */
const extractDefineName = (text: string): string => {
  const match = /#\s*define\s+([a-zA-Z_]\w*)/.exec(text);
  return match ? match[1] : "unknown";
};
 
/**
 * Process a #define directive
 * Only flag-only defines are allowed; value and function macros produce errors
 */
const processDefineDirective = (
  ctx: Parser.DefineDirectiveContext,
): string | null => {
  const text = ctx.getText();
 
  // Check for function-like macro: #define NAME(
  if (ctx.DEFINE_FUNCTION()) {
    const name = extractDefineName(text);
    const line = ctx.start?.line ?? 0;
    throw new Error(
      `E0501: Function-like macro '${name}' is not allowed. ` +
        `Use inline functions instead. Line ${line}`,
    );
  }
 
  // Check for value define: #define NAME value
  if (ctx.DEFINE_WITH_VALUE()) {
    const name = extractDefineName(text);
    const line = ctx.start?.line ?? 0;
    throw new Error(
      `E0502: #define with value '${name}' is not allowed. ` +
        `Use 'const' instead: const u32 ${name} <- value; Line ${line}`,
    );
  }
 
  // Flag-only define: pass through
  if (ctx.DEFINE_FLAG()) {
    return text.trim();
  }
 
  return null;
};
 
/**
 * Process a conditional compilation directive (#ifdef, #ifndef, #else, #endif)
 * These are passed through unchanged
 */
const processConditionalDirective = (
  ctx: Parser.ConditionalDirectiveContext,
): string => {
  return ctx.getText().trim();
};
 
/**
 * Process a preprocessor directive
 * - Flag-only defines (#define FLAG): pass through
 * - Value defines (#define FLAG value): ERROR E0502
 * - Function macros (#define NAME(args)): ERROR E0501
 * - Conditional directives: pass through
 */
const processPreprocessorDirective = (
  ctx: Parser.PreprocessorDirectiveContext,
): string | null => {
  if (ctx.defineDirective()) {
    return processDefineDirective(ctx.defineDirective()!);
  }
  if (ctx.conditionalDirective()) {
    return processConditionalDirective(ctx.conditionalDirective()!);
  }
  return null;
};
 
// Export as an object for consistent module pattern
const includeGenerators = {
  transformIncludeDirective,
  extractDefineName,
  processDefineDirective,
  processConditionalDirective,
  processPreprocessorDirective,
};
 
export default includeGenerators;