All files / transpiler/output/headers HeaderGeneratorUtils.ts

98.74% Statements 157/159
95.32% Branches 102/107
100% Functions 38/38
99.35% Lines 153/154

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                                        16x                     247x     247x   247x 3x     244x             244x 336x 336x 336x 336x 336x 336x 336x                 341x     341x     341x   341x             108x   107x   87x                   8x 1x       7x 3x       4x                                     249x     249x   249x 210x   249x   334x 259x   75x 7x     68x 36x   32x     249x 336x 334x 334x 32x         249x 145x 145x 88x         249x 103x     249x                       246x   37x                                 245x   107x                           244x 244x   244x 114x 9x 9x 7x 7x         244x                       243x 28x 21x 1x 3x                       245x       245x                                     250x     250x 249x       250x 18x 18x                 250x 250x 22x 22x 22x   250x     250x 8x 4x     4x 4x 2x   2x         250x     250x 249x     250x             243x             245x 227x     18x     18x 20x   18x 18x                   245x 224x     21x 21x 22x 16x   6x     21x 21x                   245x 241x     4x 4x 4x 2x   2x     4x 4x             245x 243x     2x 2x 4x 3x 3x     2x 2x                     244x 221x     23x   23x 18x 18x 21x   18x       5x 5x 6x   5x 1x     23x 23x                 247x 162x     85x 85x   98x                           98x 98x   85x 85x             243x                        
/**
 * Header Generator Utilities
 *
 * Pure utility functions for header generation, shared by both
 * CHeaderGenerator and CppHeaderGenerator.
 */
 
import IHeaderSymbol from "./types/IHeaderSymbol";
import SymbolTable from "../../logic/symbols/SymbolTable";
import CppNamespaceUtils from "../../../utils/CppNamespaceUtils";
import typeUtils from "./generators/mapType";
import IGroupedSymbols from "./types/IGroupedSymbols";
import IHeaderOptions from "../codegen/types/IHeaderOptions";
import IHeaderTypeInput from "./generators/IHeaderTypeInput";
import generateEnumHeader from "./generators/generateEnumHeader";
import generateStructHeader from "./generators/generateStructHeader";
import generateBitmapHeader from "./generators/generateBitmapHeader";
import VariableDeclarationFormatter from "../codegen/helpers/VariableDeclarationFormatter";
import type IVariableFormatInput from "../codegen/types/IVariableFormatInput";
 
const { mapType, isBuiltInType } = typeUtils;
 
/**
 * Static utility class with pure functions for header generation
 */
class HeaderGeneratorUtils {
  /**
   * Create an include guard macro from filename
   */
  static makeGuard(filename: string, prefix?: string): string {
    // Remove path and extension
    const base = filename.replace(/^.*[\\/]/, "").replace(/\.[^.]+$/, "");
 
    // Convert to uppercase and replace non-alphanumeric with underscore
    const sanitized = base.toUpperCase().replaceAll(/[^A-Z0-9]/g, "_");
 
    if (prefix) {
      return `${prefix.toUpperCase()}_${sanitized}_H`;
    }
 
    return `${sanitized}_H`;
  }
 
  /**
   * Group symbols by their kind for organized header output
   */
  static groupSymbolsByKind(symbols: IHeaderSymbol[]): IGroupedSymbols {
    return {
      structs: symbols.filter((s) => s.kind === "struct"),
      classes: symbols.filter((s) => s.kind === "class"),
      functions: symbols.filter((s) => s.kind === "function"),
      variables: symbols.filter((s) => s.kind === "variable"),
      enums: symbols.filter((s) => s.kind === "enum"),
      types: symbols.filter((s) => s.kind === "type"),
      bitmaps: symbols.filter((s) => s.kind === "bitmap"),
    };
  }
 
  /**
   * Extract the base type from a type string, removing pointers, arrays, and const
   */
  static extractBaseType(type: string): string {
    // Remove pointer suffix
    let baseType = type.replace(/\*+$/, "").trim();
 
    // Remove array brackets
    baseType = baseType.replace(/\[\d*\]$/, "").trim();
 
    // Handle const prefix
    baseType = baseType.replace(/^const\s+/, "").trim();
 
    return baseType;
  }
 
  /**
   * Check if a type is a C++ template type (excluding C-Next string<N>)
   */
  static isCppTemplateType(type: string | undefined): boolean {
    if (!type) return false;
    // C-Next string<N> types are allowed (string followed by <digits>)
    if (/^string<\d+>$/.test(type)) return false;
    // Any other <> is a C++ template
    return type.includes("<") || type.includes(">");
  }
 
  /**
   * Check if an array dimension is a macro (non-numeric identifier)
   * Numeric dimensions: "4", "16", "256", ""
   * Macro dimensions: "DEVICE_COUNT", "MAX_SIZE", "NUM_LEDS"
   */
  static isMacroDimension(dimension: string): boolean {
    // Empty string is an unbounded array, not a macro
    if (!dimension || dimension.trim() === "") {
      return false;
    }
 
    // Pure numeric dimensions are not macros
    if (/^\d+$/.test(dimension.trim())) {
      return false;
    }
 
    // Anything else (identifier, expression) is treated as a macro
    return true;
  }
 
  /**
   * Collect external type dependencies from function signatures and variables
   * Returns types that are:
   * - Not primitive types (not in TYPE_MAP)
   * - Not locally defined structs, enums, bitmaps, or type aliases
   * - Not cross-file enums (which can't be forward-declared as structs)
   */
  static collectExternalTypes(
    functions: IHeaderSymbol[],
    variables: IHeaderSymbol[],
    localStructs: Set<string>,
    localEnums: Set<string>,
    localTypes: Set<string>,
    localBitmaps: Set<string>,
    allKnownEnums?: ReadonlySet<string>,
  ): Set<string> {
    const externalTypes = new Set<string>();
 
    // Combine all local types for efficient lookup
    const localTypeSets = [localStructs, localEnums, localTypes, localBitmaps];
 
    const isLocalType = (name: string): boolean =>
      localTypeSets.some((set) => set.has(name));
 
    const isExternalType = (typeName: string): boolean => {
      // Skip empty, pointer markers, built-ins, and namespaced types
      if (!typeName || typeName === "*" || isBuiltInType(typeName)) {
        return false;
      }
      if (typeName.includes("::")) {
        return false;
      }
      // Skip locally defined types and cross-file enums
      if (isLocalType(typeName) || allKnownEnums?.has(typeName)) {
        return false;
      }
      return true;
    };
 
    const addIfExternal = (type: string | undefined): void => {
      if (!type) return;
      const baseType = HeaderGeneratorUtils.extractBaseType(type);
      if (isExternalType(baseType)) {
        externalTypes.add(baseType);
      }
    };
 
    // Check function return types and parameters
    for (const fn of functions) {
      addIfExternal(fn.type);
      for (const param of fn.parameters ?? []) {
        addIfExternal(param.type);
      }
    }
 
    // Check variable types
    for (const v of variables) {
      addIfExternal(v.type);
    }
 
    return externalTypes;
  }
 
  /**
   * Filter external types to those that are C-compatible (can be forward-declared)
   * Excludes C++ templates, namespaces, and underscore-format namespace types
   */
  static filterCCompatibleTypes(
    externalTypes: Set<string>,
    typesWithHeaders: Set<string>,
    symbolTable?: SymbolTable,
  ): string[] {
    return [...externalTypes].filter(
      (t) =>
        !typesWithHeaders.has(t) &&
        !t.includes("<") &&
        !t.includes(">") &&
        !t.includes("::") &&
        !t.includes(".") &&
        !CppNamespaceUtils.isCppNamespaceType(t, symbolTable),
    );
  }
 
  /**
   * Filter variables to those that are C-compatible
   * Excludes C++ namespace types, templates, and underscore-format namespace types
   */
  static filterCCompatibleVariables(
    variables: IHeaderSymbol[],
    symbolTable?: SymbolTable,
  ): IHeaderSymbol[] {
    return variables.filter(
      (v) =>
        !v.type?.includes("::") &&
        !v.type?.includes(".") &&
        !HeaderGeneratorUtils.isCppTemplateType(v.type) &&
        !CppNamespaceUtils.isCppNamespaceType(v.type ?? "", symbolTable),
    );
  }
 
  /**
   * Build headers to include from external type header mappings
   */
  static buildExternalTypeIncludes(
    externalTypes: Set<string>,
    externalTypeHeaders?: ReadonlyMap<string, string>,
  ): { typesWithHeaders: Set<string>; headersToInclude: Set<string> } {
    const typesWithHeaders = new Set<string>();
    const headersToInclude = new Set<string>();
 
    if (externalTypeHeaders) {
      for (const typeName of externalTypes) {
        const directive = externalTypeHeaders.get(typeName);
        if (directive) {
          typesWithHeaders.add(typeName);
          headersToInclude.add(directive);
        }
      }
    }
 
    return { typesWithHeaders, headersToInclude };
  }
 
  /**
   * Get local type names from grouped symbols
   */
  static getLocalTypeNames(groups: IGroupedSymbols): {
    localStructNames: Set<string>;
    localEnumNames: Set<string>;
    localTypeNames: Set<string>;
    localBitmapNames: Set<string>;
  } {
    return {
      localStructNames: new Set(groups.structs.map((s) => s.name)),
      localEnumNames: new Set(groups.enums.map((s) => s.name)),
      localTypeNames: new Set(groups.types.map((s) => s.name)),
      localBitmapNames: new Set(groups.bitmaps.map((s) => s.name)),
    };
  }
 
  // =========================================================================
  // Section Generators - Extract complexity from CHeaderGenerator/CppHeaderGenerator
  // =========================================================================
 
  /**
   * Generate header guard opening and file comment
   */
  static generateHeaderStart(guard: string, sourcePath?: string): string[] {
    const generatedLine = sourcePath
      ? ` * Generated by C-Next Transpiler from: ${sourcePath}`
      : " * Generated by C-Next Transpiler";
 
    return [
      `#ifndef ${guard}`,
      `#define ${guard}`,
      "",
      "/**",
      generatedLine,
      " * Header file for cross-language interoperability",
      " */",
      "",
    ];
  }
 
  /**
   * Generate all include directives (system, user, and external type headers)
   */
  static generateIncludes(
    options: IHeaderOptions,
    headersToInclude: Set<string>,
  ): string[] {
    const lines: string[] = [];
 
    // System includes
    if (options.includeSystemHeaders !== false) {
      lines.push("#include <stdint.h>", "#include <stdbool.h>");
    }
 
    // User includes (already have correct extension from IncludeExtractor)
    if (options.userIncludes && options.userIncludes.length > 0) {
      for (const include of options.userIncludes) {
        lines.push(include);
      }
    }
 
    // External type header includes (skip duplicates of user includes)
    // Dedup by basename stem to handle:
    // - Different path styles (e.g., <AppConfig.hpp> vs "../AppConfig.hpp")
    // - Extension mismatch from timing (.h from IncludeResolver before cppDetected,
    //   .hpp from IncludeExtractor after cppDetected)
    const userIncludeSet = new Set(options.userIncludes ?? []);
    const extractStem = (inc: string): string => {
      const match = /["<]([^">]+)[">]/.exec(inc);
      Iif (!match) return inc;
      return match[1].replace(/^.*\//, "").replace(/\.(?:h|hpp)$/, "");
    };
    const userIncludeStems = new Set(
      (options.userIncludes ?? []).map(extractStem),
    );
    for (const directive of headersToInclude) {
      if (userIncludeSet.has(directive)) {
        continue;
      }
      // Check if a user include already covers the same file
      const stem = extractStem(directive);
      if (stem && userIncludeStems.has(stem)) {
        continue;
      }
      lines.push(directive);
    }
 
    // Add blank line if any includes were added
    const hasIncludes =
      options.includeSystemHeaders !== false ||
      (options.userIncludes && options.userIncludes.length > 0) ||
      headersToInclude.size > 0;
    if (hasIncludes) {
      lines.push("");
    }
 
    return lines;
  }
 
  /**
   * Generate C++ extern "C" wrapper opening
   */
  static generateCppWrapperStart(): string[] {
    return ["#ifdef __cplusplus", 'extern "C" {', "#endif", ""];
  }
 
  /**
   * Generate forward declarations for external types
   */
  static generateForwardDeclarations(cCompatibleTypes: string[]): string[] {
    if (cCompatibleTypes.length === 0) {
      return [];
    }
 
    const lines: string[] = [
      "/* External type dependencies - include appropriate headers */",
    ];
    for (const typeName of cCompatibleTypes) {
      lines.push(`typedef struct ${typeName} ${typeName};`);
    }
    lines.push("");
    return lines;
  }
 
  /**
   * Generate enum section
   */
  static generateEnumSection(
    enums: IHeaderSymbol[],
    typeInput?: IHeaderTypeInput,
  ): string[] {
    if (enums.length === 0) {
      return [];
    }
 
    const lines: string[] = ["/* Enumerations */"];
    for (const sym of enums) {
      if (typeInput) {
        lines.push(generateEnumHeader(sym.name, typeInput));
      } else {
        lines.push(`/* Enum: ${sym.name} (see implementation for values) */`);
      }
    }
    lines.push("");
    return lines;
  }
 
  /**
   * Generate bitmap section
   */
  static generateBitmapSection(
    bitmaps: IHeaderSymbol[],
    typeInput?: IHeaderTypeInput,
  ): string[] {
    if (bitmaps.length === 0) {
      return [];
    }
 
    const lines: string[] = ["/* Bitmaps */"];
    for (const sym of bitmaps) {
      if (typeInput) {
        lines.push(generateBitmapHeader(sym.name, typeInput));
      } else {
        lines.push(`/* Bitmap: ${sym.name} (see implementation for layout) */`);
      }
    }
    lines.push("");
    return lines;
  }
 
  /**
   * Generate type alias section
   */
  static generateTypeAliasSection(types: IHeaderSymbol[]): string[] {
    if (types.length === 0) {
      return [];
    }
 
    const lines: string[] = ["/* Type aliases */"];
    for (const sym of types) {
      if (sym.type) {
        const cType = mapType(sym.type);
        lines.push(`typedef ${cType} ${sym.name};`);
      }
    }
    lines.push("");
    return lines;
  }
 
  /**
   * Generate struct and class definitions section
   */
  static generateStructSection(
    structs: IHeaderSymbol[],
    classes: IHeaderSymbol[],
    typeInput?: IHeaderTypeInput,
  ): string[] {
    if (structs.length === 0 && classes.length === 0) {
      return [];
    }
 
    const lines: string[] = [];
 
    if (typeInput) {
      lines.push("/* Struct definitions */");
      for (const sym of structs) {
        lines.push(generateStructHeader(sym.name, typeInput));
      }
      for (const sym of classes) {
        lines.push(generateStructHeader(sym.name, typeInput));
      }
    } else {
      lines.push("/* Forward declarations */");
      for (const sym of structs) {
        lines.push(`typedef struct ${sym.name} ${sym.name};`);
      }
      for (const sym of classes) {
        lines.push(`typedef struct ${sym.name} ${sym.name};`);
      }
    }
    lines.push("");
    return lines;
  }
 
  /**
   * Generate extern variable declarations section
   *
   * Uses VariableDeclarationFormatter for consistent formatting with CodeGenerator.
   */
  static generateVariableSection(variables: IHeaderSymbol[]): string[] {
    if (variables.length === 0) {
      return [];
    }
 
    const lines: string[] = ["/* External variables */"];
    for (const sym of variables) {
      // Build normalized input for the unified formatter
      const input: IVariableFormatInput = {
        name: sym.name,
        cnextType: sym.type || "int",
        mappedType: mapType(sym.type || "int"),
        modifiers: {
          isConst: sym.isConst ?? false,
          isAtomic: sym.isAtomic ?? false,
          isVolatile: false, // C-Next uses atomic, not volatile directly
          isExtern: true, // Headers always use extern
        },
        arrayDimensions:
          sym.isArray && sym.arrayDimensions ? sym.arrayDimensions : undefined,
      };
 
      const declaration = VariableDeclarationFormatter.format(input);
      lines.push(`${declaration};`);
    }
    lines.push("");
    return lines;
  }
 
  /**
   * Generate C++ extern "C" wrapper closing and header guard end
   */
  static generateHeaderEnd(guard: string): string[] {
    return [
      "#ifdef __cplusplus",
      "}",
      "#endif",
      "",
      `#endif /* ${guard} */`,
      "",
    ];
  }
}
 
export default HeaderGeneratorUtils;