All files / transpiler/output/headers HeaderGeneratorUtils.ts

99.35% Statements 155/156
96.8% Branches 91/94
100% Functions 39/39
99.34% Lines 151/152

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                                      16x                     235x     235x   235x 3x     232x             232x 371x 371x 371x 371x 371x 371x 371x                 322x     322x     322x   322x             110x   109x   89x                   8x 1x       7x 3x       4x                                     237x     237x   237x 194x   237x   315x 244x   71x 7x     64x 36x   28x     237x 317x 315x 315x 28x         237x 131x 131x 81x         237x 105x     237x                       234x   33x                                 233x   109x                                               106x       106x 106x 18x 18x   18x       88x                   232x 232x   232x 107x 9x 9x 3x 3x         232x                       231x 28x 21x 1x 3x                       231x                                     235x     235x 234x       235x 15x 15x         235x 2x         235x     235x 234x     235x             231x             233x 214x     19x     19x 20x   19x 19x                   233x 212x     21x 21x 22x 16x   6x     21x 21x                   233x 229x     4x 4x 4x 2x   2x     4x 4x             233x 231x     2x 2x 4x 3x 3x     2x 2x                     232x 209x     23x   23x 18x 18x 21x   18x       5x 5x 6x   5x 1x     23x 23x             235x 148x     87x 87x 100x 100x   100x 17x     100x             100x   87x 87x             231x                        
/**
 * Header Generator Utilities
 *
 * Pure utility functions for header generation, shared by both
 * CHeaderGenerator and CppHeaderGenerator.
 */
 
import ISymbol from "../../../utils/types/ISymbol";
import ESymbolKind from "../../../utils/types/ESymbolKind";
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";
 
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: ISymbol[]): IGroupedSymbols {
    return {
      structs: symbols.filter((s) => s.kind === ESymbolKind.Struct),
      classes: symbols.filter((s) => s.kind === ESymbolKind.Class),
      functions: symbols.filter((s) => s.kind === ESymbolKind.Function),
      variables: symbols.filter((s) => s.kind === ESymbolKind.Variable),
      enums: symbols.filter((s) => s.kind === ESymbolKind.Enum),
      types: symbols.filter((s) => s.kind === ESymbolKind.Type),
      bitmaps: symbols.filter((s) => s.kind === ESymbolKind.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: ISymbol[],
    variables: ISymbol[],
    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: ISymbol[],
    symbolTable?: SymbolTable,
  ): ISymbol[] {
    return variables.filter(
      (v) =>
        !v.type?.includes("::") &&
        !v.type?.includes(".") &&
        !HeaderGeneratorUtils.isCppTemplateType(v.type) &&
        !CppNamespaceUtils.isCppNamespaceType(v.type ?? "", symbolTable),
    );
  }
 
  /**
   * Format a variable declaration with proper C syntax
   *
   * In C, array dimensions follow the variable name, not the type:
   *   char greeting[33];      // Correct
   *   char[33] greeting;      // Wrong
   *
   * Handles types that include embedded dimensions (like char[33] from
   * mapType("string<32>")) and places them correctly after the variable name.
   */
  static formatVariableDeclaration(
    cnextType: string,
    name: string,
    additionalDims: string,
    constPrefix: string,
    volatilePrefix: string = "",
  ): string {
    const cType = mapType(cnextType);
 
    // Check if the mapped type has embedded array dimensions (e.g., char[33])
    // This happens for string<N> types which map to char[N+1]
    const embeddedMatch = /^(\w+)\[(\d+)\]$/.exec(cType);
    if (embeddedMatch) {
      const baseType = embeddedMatch[1];
      const embeddedDim = embeddedMatch[2];
      // Format: volatile const char name[additionalDims][embeddedDim]
      return `${volatilePrefix}${constPrefix}${baseType} ${name}${additionalDims}[${embeddedDim}]`;
    }
 
    // No embedded dimensions - standard format
    return `${volatilePrefix}${constPrefix}${cType} ${name}${additionalDims}`;
  }
 
  /**
   * 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): string[] {
    return [
      `#ifndef ${guard}`,
      `#define ${guard}`,
      "",
      "/**",
      " * Generated by C-Next Transpiler",
      " * 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
    if (options.userIncludes && options.userIncludes.length > 0) {
      for (const include of options.userIncludes) {
        lines.push(include);
      }
    }
 
    // External type header includes
    for (const directive of headersToInclude) {
      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: ISymbol[],
    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: ISymbol[],
    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: ISymbol[]): 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: ISymbol[],
    classes: ISymbol[],
    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
   */
  static generateVariableSection(variables: ISymbol[]): string[] {
    if (variables.length === 0) {
      return [];
    }
 
    const lines: string[] = ["/* External variables */"];
    for (const sym of variables) {
      const constPrefix = sym.isConst ? "const " : "";
      const volatilePrefix = sym.isAtomic ? "volatile " : "";
      const arrayDims =
        sym.isArray && sym.arrayDimensions
          ? sym.arrayDimensions.map((d) => `[${d}]`).join("")
          : "";
 
      const declaration = HeaderGeneratorUtils.formatVariableDeclaration(
        sym.type || "int",
        sym.name,
        arrayDims,
        constPrefix,
        volatilePrefix,
      );
      lines.push(`extern ${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;