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 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 | 19x 271x 271x 271x 3x 268x 268x 522x 522x 522x 522x 522x 522x 522x 459x 459x 459x 459x 168x 167x 147x 8x 1x 7x 3x 4x 273x 273x 273x 214x 273x 452x 373x 79x 7x 72x 40x 32x 273x 454x 452x 452x 32x 273x 193x 193x 98x 273x 163x 273x 270x 37x 269x 167x 268x 268x 268x 138x 9x 9x 7x 7x 268x 267x 50x 31x 1x 13x 269x 269x 22x 22x 3x 19x 19x 19x 274x 18x 18x 18x 18x 274x 274x 274x 8x 4x 4x 2x 274x 274x 273x 274x 274x 274x 274x 273x 274x 267x 269x 251x 18x 18x 20x 18x 18x 269x 244x 25x 25x 32x 26x 6x 25x 25x 269x 261x 8x 8x 14x 12x 2x 8x 8x 269x 267x 2x 2x 4x 3x 3x 2x 2x 272x 268x 4x 4x 5x 8x 5x 4x 1x 3x 3x 3x 4x 3x 3x 272x 268x 4x 4x 4x 6x 3x 3x 3x 4x 4x 4x 268x 239x 29x 29x 24x 24x 43x 24x 5x 5x 6x 5x 1x 29x 29x 271x 174x 97x 97x 158x 158x 158x 97x 97x 267x | /**
* 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";
import MisraSuppressionUtils from "../MisraSuppressionUtils";
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",
" */",
"",
];
}
/**
* Extract header file stem from include directive for deduplication.
* E.g., '#include <foo/bar.hpp>' -> 'bar'
* SonarCloud S8786: Avoid backtracking by using separate patterns.
*/
private static extractIncludeStem(include: string): string {
// Try angle brackets first, then quotes - avoids backtracking regex
const angleMatch = /<([^<>]+)>/.exec(include);
if (angleMatch) {
return angleMatch[1].replace(/^.*\//, "").replace(/\.(?:h|hpp)$/, "");
}
const quoteMatch = /"([^"]+)"/.exec(include);
Eif (quoteMatch) {
return quoteMatch[1].replace(/^.*\//, "").replace(/\.(?:h|hpp)$/, "");
}
return include;
}
/**
* Add user includes with MISRA suppression comments.
* SonarCloud S3776: Extracted from generateIncludes.
*/
private static addUserIncludes(
lines: string[],
userIncludes: string[] | undefined,
): void {
if (!userIncludes || userIncludes.length === 0) return;
for (const include of userIncludes) {
// Issue #850: Add MISRA suppression for banned headers
const suppression =
MisraSuppressionUtils.getMisraSuppressionComment(include);
Iif (suppression) {
lines.push(suppression);
}
lines.push(include);
}
}
/**
* Add external type headers, deduplicating against user includes.
* SonarCloud S3776: Extracted from generateIncludes.
*/
private static addExternalTypeHeaders(
lines: string[],
headersToInclude: Set<string>,
userIncludes: string[] | undefined,
): void {
const userIncludeSet = new Set(userIncludes ?? []);
const userIncludeStems = new Set(
(userIncludes ?? []).map(HeaderGeneratorUtils.extractIncludeStem),
);
for (const directive of headersToInclude) {
if (userIncludeSet.has(directive)) continue;
const stem = HeaderGeneratorUtils.extractIncludeStem(directive);
if (stem && userIncludeStems.has(stem)) continue;
lines.push(directive);
}
}
/**
* 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)
HeaderGeneratorUtils.addUserIncludes(lines, options.userIncludes);
// 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)
HeaderGeneratorUtils.addExternalTypeHeaders(
lines,
headersToInclude,
options.userIncludes,
);
// 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;
}
/**
* ADR-029: Generate forward declarations for structs used in callback typedefs.
* This ensures struct types can be used in callback parameter types before
* the full struct definition.
*/
static generateCallbackStructForwardDecls(
structs: IHeaderSymbol[],
typeInput?: IHeaderTypeInput,
): string[] {
if (!typeInput?.callbackTypes || typeInput.callbackTypes.size === 0) {
return [];
}
// Collect struct types that are used in callback parameters
const usedStructTypes = new Set<string>();
for (const [, cbInfo] of typeInput.callbackTypes) {
for (const p of cbInfo.parameters) {
if (p.isStruct) {
usedStructTypes.add(p.type);
}
}
}
if (usedStructTypes.size === 0) {
return [];
}
// Get local struct names to only forward-declare those
const localStructNames = new Set(structs.map((s) => s.name));
const lines: string[] = [];
for (const structType of usedStructTypes) {
if (localStructNames.has(structType)) {
lines.push(`typedef struct ${structType} ${structType};`);
}
}
return lines.length > 0 ? [...lines, ""] : [];
}
/**
* ADR-029: Generate callback typedef section
* Generates function pointer typedefs for callbacks used as struct field types
*/
static generateCallbackTypedefSection(
typeInput?: IHeaderTypeInput,
isCppMode?: boolean,
): string[] {
if (!typeInput?.callbackTypes || typeInput.callbackTypes.size === 0) {
return [];
}
const lines: string[] = ["/* Callback typedefs */"];
for (const [, cbInfo] of typeInput.callbackTypes) {
const params =
cbInfo.parameters.length > 0
? cbInfo.parameters
.map((p) => {
// ADR-006: Struct parameters become pointers (C) or references (C++)
if (p.isStruct) {
const ptrOrRef = isCppMode ? "&" : "*";
return `${p.type}${ptrOrRef}`;
}
return p.type;
})
.join(", ")
: "void";
lines.push(
`typedef ${cbInfo.returnType} (*${cbInfo.typedefName})(${params});`,
);
}
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;
|