All files / transpiler/output/headers BaseHeaderGenerator.ts

100% Statements 49/49
97.14% Branches 34/35
100% Functions 7/7
100% Lines 48/48

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                              15x                                                             230x     230x 244x       230x     230x     230x                       230x           230x       230x               230x           230x                                               230x                     230x 113x     117x 117x 125x         125x 125x     117x 117x                       125x 125x     125x     125x   125x 69x 80x   69x     125x                     80x 80x 80x     80x 13x 11x 2x   9x       69x 4x       65x 8x       57x 7x       50x 24x       26x          
/**
 * Base Header Generator
 *
 * Abstract base class for C and C++ header generators.
 * Uses Template Method pattern - subclasses implement getRefSuffix() to
 * determine pointer (*) vs reference (&) semantics.
 */
 
import ISymbol from "../../../utils/types/ISymbol";
import IParameterSymbol from "../../../utils/types/IParameterSymbol";
import IHeaderOptions from "../codegen/types/IHeaderOptions";
import IHeaderTypeInput from "./generators/IHeaderTypeInput";
import typeUtils from "./generators/mapType";
import HeaderGeneratorUtils from "./HeaderGeneratorUtils";
 
const { mapType } = typeUtils;
 
/** Pass-by-value parameter info from CodeGenerator */
type TPassByValueParams = ReadonlyMap<string, ReadonlySet<string>>;
 
/**
 * Abstract base class for header file generation
 *
 * Generates header files (.h) from C-Next symbols. Subclasses implement
 * getRefSuffix() to control pass-by-reference semantics:
 * - CHeaderGenerator returns "*" for pointer-based C semantics
 * - CppHeaderGenerator returns "&" for reference-based C++ semantics
 */
abstract class BaseHeaderGenerator {
  /**
   * Get the suffix for pass-by-reference parameters
   * @returns "*" for C pointer semantics, "&" for C++ reference semantics
   */
  protected abstract getRefSuffix(): string;
 
  /**
   * Generate a header file from symbols
   */
  generate(
    symbols: ISymbol[],
    filename: string,
    options: IHeaderOptions = {},
    typeInput?: IHeaderTypeInput,
    passByValueParams?: TPassByValueParams,
    allKnownEnums?: ReadonlySet<string>,
  ): string {
    const guard = HeaderGeneratorUtils.makeGuard(filename, options.guardPrefix);
 
    // Filter to exported symbols if requested
    const exportedSymbols = options.exportedOnly
      ? symbols.filter((s) => s.isExported)
      : symbols;
 
    // Group symbols by kind
    const groups = HeaderGeneratorUtils.groupSymbolsByKind(exportedSymbols);
 
    // Get local type names for external type detection
    const localTypes = HeaderGeneratorUtils.getLocalTypeNames(groups);
 
    // Collect external type dependencies
    const externalTypes = HeaderGeneratorUtils.collectExternalTypes(
      groups.functions,
      groups.variables,
      localTypes.localStructNames,
      localTypes.localEnumNames,
      localTypes.localTypeNames,
      localTypes.localBitmapNames,
      allKnownEnums,
    );
 
    // Build external type header includes
    const { typesWithHeaders, headersToInclude } =
      HeaderGeneratorUtils.buildExternalTypeIncludes(
        externalTypes,
        options.externalTypeHeaders,
      );
 
    // Get symbol table for C++ namespace detection
    const symbolTable = typeInput?.symbolTable;
 
    // Filter to C-compatible external types
    const cCompatibleExternalTypes =
      HeaderGeneratorUtils.filterCCompatibleTypes(
        externalTypes,
        typesWithHeaders,
        symbolTable,
      );
 
    // Filter to C-compatible variables
    const cCompatibleVariables =
      HeaderGeneratorUtils.filterCCompatibleVariables(
        groups.variables,
        symbolTable,
      );
 
    // Build header sections using utility methods
    const lines: string[] = [
      ...HeaderGeneratorUtils.generateHeaderStart(guard),
      ...HeaderGeneratorUtils.generateIncludes(options, headersToInclude),
      ...HeaderGeneratorUtils.generateCppWrapperStart(),
      ...HeaderGeneratorUtils.generateForwardDeclarations(
        cCompatibleExternalTypes,
      ),
      ...HeaderGeneratorUtils.generateEnumSection(groups.enums, typeInput),
      ...HeaderGeneratorUtils.generateBitmapSection(groups.bitmaps, typeInput),
      ...HeaderGeneratorUtils.generateTypeAliasSection(groups.types),
      ...HeaderGeneratorUtils.generateStructSection(
        groups.structs,
        groups.classes,
        typeInput,
      ),
      ...HeaderGeneratorUtils.generateVariableSection(cCompatibleVariables),
      ...this.generateFunctionSection(
        groups.functions,
        passByValueParams,
        allKnownEnums,
      ),
      ...HeaderGeneratorUtils.generateHeaderEnd(guard),
    ];
 
    return lines.join("\n");
  }
 
  /**
   * Generate function prototypes section
   */
  private generateFunctionSection(
    functions: ISymbol[],
    passByValueParams?: TPassByValueParams,
    allKnownEnums?: ReadonlySet<string>,
  ): string[] {
    if (functions.length === 0) {
      return [];
    }
 
    const lines: string[] = ["/* Function prototypes */"];
    for (const sym of functions) {
      const proto = this.generateFunctionPrototype(
        sym,
        passByValueParams,
        allKnownEnums,
      );
      Eif (proto) {
        lines.push(proto);
      }
    }
    lines.push("");
    return lines;
  }
 
  /**
   * Generate a function prototype
   */
  private generateFunctionPrototype(
    sym: ISymbol,
    passByValueParams?: TPassByValueParams,
    allKnownEnums?: ReadonlySet<string>,
  ): string | null {
    // Map return type (main() always returns int)
    const mappedType = sym.type ? mapType(sym.type) : "void";
    const returnType = sym.name === "main" ? "int" : mappedType;
 
    // Get pass-by-value parameter names for this function
    const passByValueSet = passByValueParams?.get(sym.name);
 
    // Build parameter list
    let params = "void";
 
    if (sym.parameters && sym.parameters.length > 0) {
      const translatedParams = sym.parameters.map((p) =>
        this.generateParameter(p, passByValueSet, allKnownEnums),
      );
      params = translatedParams.join(", ");
    }
 
    return `${returnType} ${sym.name}(${params});`;
  }
 
  /**
   * Generate a single parameter with appropriate semantics
   */
  private generateParameter(
    p: IParameterSymbol,
    passByValueSet?: ReadonlySet<string>,
    allKnownEnums?: ReadonlySet<string>,
  ): string {
    const baseType = mapType(p.type);
    const constMod = p.isConst ? "const " : "";
    const autoConst = p.isAutoConst ? "const " : "";
 
    // Array parameters - pass naturally as pointers per C semantics
    if (p.isArray && p.arrayDimensions) {
      const dims = p.arrayDimensions.map((d) => `[${d}]`).join("");
      if (p.type === "string") {
        return `${autoConst}${constMod}char* ${p.name}${dims}`;
      }
      return `${autoConst}${constMod}${baseType} ${p.name}${dims}`;
    }
 
    // ISR is a function pointer typedef - no pointer needed
    if (p.type === "ISR") {
      return `${constMod}${baseType} ${p.name}`;
    }
 
    // Float types use standard pass-by-value
    if (p.type === "f32" || p.type === "f64") {
      return `${constMod}${baseType} ${p.name}`;
    }
 
    // Enum types use pass-by-value (like primitives)
    if (allKnownEnums?.has(p.type)) {
      return `${constMod}${baseType} ${p.name}`;
    }
 
    // Check if parameter should be passed by value
    if (passByValueSet?.has(p.name)) {
      return `${constMod}${baseType} ${p.name}`;
    }
 
    // Default: pass by reference using subclass-specific semantics
    return `${autoConst}${constMod}${baseType}${this.getRefSuffix()} ${p.name}`;
  }
}
 
export default BaseHeaderGenerator;