All files / utils/cache CacheManager.ts

92.89% Statements 157/169
86.07% Branches 68/79
100% Functions 24/24
95.45% Lines 147/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 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                                                        12x     12x   12x                         88x     88x     88x 88x 88x 88x 88x               80x 59x     80x 60x       80x     80x     3x 3x 2x 2x           3x       3x 3x       77x           77x             19x   19x 19x 12x     7x                               47x   47x 47x 11x   36x     49x     36x 36x     10x 10x 16x   10x       36x 36x 36x     9x       36x                                   56x       56x 56x     3x       62x           53x 53x 10x 10x 16x         53x 53x 26x 13x         53x                 53x 53x                               25x     25x     25x           25x           25x                               25x     25x     25x 25x 7x 7x 7x       25x                     25x     25x 25x                   25x     25x 25x 31x 11x     25x 25x 11x 11x 10x       25x             2x   2x 2x             1x   1x               1x             29x 6x     23x 23x             1x             80x 20x 20x 20x             61x           61x 61x             64x           64x               80x 2x       78x 1x     77x             77x   77x 77x 11x     11x 11x                                                           62x                   62x 62x 6x 62x 62x 62x 1x 62x 62x 1x   62x             49x                   49x 49x 2x 49x 1x 49x 49x 1x 49x 49x 1x   49x          
/**
 * CacheManager
 *
 * Manages persistent cache for parsed C/C++ header symbols using flat-cache.
 * Cache is stored in .cnx/ directory (similar to .git/).
 *
 * Cache structure:
 *   .cnx/
 *     config.json     - Cache metadata (version, timestamps)
 *     cache/
 *       symbols.json  - Cached symbols per file (managed by flat-cache)
 */
 
import { existsSync, unlinkSync } from "node:fs";
import { join } from "node:path";
import { FlatCache, create as createFlatCache } from "flat-cache";
import CacheKeyGenerator from "./CacheKeyGenerator";
import ISymbol from "../types/ISymbol";
import IStructFieldInfo from "../../transpiler/logic/symbols/types/IStructFieldInfo";
import SymbolTable from "../../transpiler/logic/symbols/SymbolTable";
import ICacheConfig from "../../transpiler/types/ICacheConfig";
import ICachedFileEntry from "../../transpiler/types/ICachedFileEntry";
import ISerializedSymbol from "../../transpiler/types/ISerializedSymbol";
import IFileSystem from "../../transpiler/types/IFileSystem";
import NodeFileSystem from "../../transpiler/NodeFileSystem";
import packageJson from "../../../package.json" with { type: "json" };
 
/** Default file system instance (singleton for performance) */
const defaultFs = NodeFileSystem.instance;
 
/** Current cache format version - increment when serialization format changes */
const CACHE_VERSION = 3; // ADR-055 Phase 4: cacheKey replaces mtime
 
const TRANSPILER_VERSION = packageJson.version;
 
/**
 * Manages symbol cache for faster incremental builds
 */
class CacheManager {
  private readonly projectRoot: string;
  private readonly cacheDir: string;
  private readonly cacheSubdir: string;
  private readonly configPath: string;
  private readonly fs: IFileSystem;
 
  /** flat-cache instance for symbol storage */
  private cache: FlatCache | null = null;
 
  /** Whether the cache has been modified and needs flushing */
  private dirty = false;
 
  constructor(projectRoot: string, fs: IFileSystem = defaultFs) {
    this.projectRoot = projectRoot;
    this.fs = fs;
    this.cacheDir = join(projectRoot, ".cnx");
    this.cacheSubdir = join(this.cacheDir, "cache");
    this.configPath = join(this.cacheDir, "config.json");
  }
 
  /**
   * Initialize the cache directory and load existing cache
   */
  async initialize(): Promise<void> {
    // Create .cnx directory structure
    if (!this.fs.exists(this.cacheDir)) {
      this.fs.mkdir(this.cacheDir, { recursive: true });
    }
 
    if (!this.fs.exists(this.cacheSubdir)) {
      this.fs.mkdir(this.cacheSubdir, { recursive: true });
    }
 
    // Load or create config
    const config = this.loadOrCreateConfig();
 
    // Check if cache should be invalidated
    if (this.shouldInvalidateCache(config)) {
      // Remove old cache file if it exists
      // Note: flat-cache manages the actual file, so we use existsSync/unlinkSync here
      const oldCacheFile = join(this.cacheSubdir, "symbols");
      if (existsSync(oldCacheFile)) {
        try {
          unlinkSync(oldCacheFile);
        } catch {
          // Ignore if we can't delete
        }
      }
      // Create fresh cache
      this.cache = createFlatCache({
        cacheId: "symbols",
        cacheDir: this.cacheSubdir,
      });
      this.saveConfig();
      return;
    }
 
    // Load existing cache - create also loads if file exists
    this.cache = createFlatCache({
      cacheId: "symbols",
      cacheDir: this.cacheSubdir,
    });
 
    // Migrate old entries if needed
    this.migrateOldEntries();
  }
 
  /**
   * Check if a file's cache is valid (not modified since cached)
   */
  isValid(filePath: string): boolean {
    Iif (!this.cache) return false;
 
    const entry = this.cache.getKey(filePath);
    if (!entry) {
      return false;
    }
 
    return CacheKeyGenerator.isValid(
      filePath,
      (entry as ICachedFileEntry).cacheKey,
      this.fs,
    );
  }
 
  /**
   * Get cached symbols and struct fields for a file
   */
  getSymbols(filePath: string): {
    symbols: ISymbol[];
    structFields: Map<string, Map<string, IStructFieldInfo>>;
    needsStructKeyword: string[];
    enumBitWidth: Map<string, number>;
  } | null {
    Iif (!this.cache) return null;
 
    const entry = this.cache.getKey(filePath);
    if (!entry) {
      return null;
    }
    const cachedEntry = entry as ICachedFileEntry;
 
    // Deserialize symbols
    const symbols = cachedEntry.symbols.map((s) => this.deserializeSymbol(s));
 
    // Convert struct fields from plain objects to Maps
    const structFields = new Map<string, Map<string, IStructFieldInfo>>();
    for (const [structName, fields] of Object.entries(
      cachedEntry.structFields,
    )) {
      const fieldMap = new Map<string, IStructFieldInfo>();
      for (const [fieldName, fieldInfo] of Object.entries(fields)) {
        fieldMap.set(fieldName, fieldInfo);
      }
      structFields.set(structName, fieldMap);
    }
 
    // Issue #208: Convert enum bit widths from plain object to Map
    const enumBitWidth = new Map<string, number>();
    Eif (cachedEntry.enumBitWidth) {
      for (const [enumName, width] of Object.entries(
        cachedEntry.enumBitWidth,
      )) {
        enumBitWidth.set(enumName, width);
      }
    }
 
    return {
      symbols,
      structFields,
      needsStructKeyword: cachedEntry.needsStructKeyword ?? [],
      enumBitWidth,
    };
  }
 
  /**
   * Store symbols and struct fields for a file
   */
  setSymbols(
    filePath: string,
    symbols: ISymbol[],
    structFields: Map<string, Map<string, IStructFieldInfo>>,
    needsStructKeyword?: string[],
    enumBitWidth?: Map<string, number>,
  ): void {
    Iif (!this.cache) return;
 
    // Generate cache key for current file state
    let cacheKey: string;
    try {
      cacheKey = CacheKeyGenerator.generate(filePath, this.fs);
    } catch {
      // If we can't stat the file, don't cache it
      return;
    }
 
    // Serialize symbols
    const serializedSymbols = symbols.map((s) => this.serializeSymbol(s));
 
    // Convert struct fields from Maps to plain objects
    const serializedFields: Record<
      string,
      Record<string, IStructFieldInfo>
    > = {};
    for (const [structName, fields] of structFields) {
      serializedFields[structName] = {};
      for (const [fieldName, fieldInfo] of fields) {
        serializedFields[structName][fieldName] = fieldInfo;
      }
    }
 
    // Issue #208: Convert enum bit widths from Map to plain object
    const serializedEnumBitWidth: Record<string, number> = {};
    if (enumBitWidth) {
      for (const [enumName, width] of enumBitWidth) {
        serializedEnumBitWidth[enumName] = width;
      }
    }
 
    // Create entry
    const entry: ICachedFileEntry = {
      filePath,
      cacheKey,
      symbols: serializedSymbols,
      structFields: serializedFields,
      needsStructKeyword,
      enumBitWidth: serializedEnumBitWidth,
    };
 
    this.cache.setKey(filePath, entry);
    this.dirty = true;
  }
 
  /**
   * Issue #590: Store symbols from a SymbolTable for a specific file.
   * Extracts all necessary data (symbols, struct fields, enum bit widths)
   * from the SymbolTable and caches it.
   *
   * This method encapsulates the serialization logic that was previously
   * scattered in Transpiler, providing a cleaner API for callers.
   *
   * @param filePath - Path to the file being cached
   * @param symbolTable - SymbolTable containing all parsed symbols
   */
  setSymbolsFromTable(filePath: string, symbolTable: SymbolTable): void {
    // Extract symbols for this file
    const symbols = symbolTable.getSymbolsByFile(filePath);
 
    // Extract struct fields for structs defined in this file
    const structFields = this.extractStructFieldsForFile(filePath, symbolTable);
 
    // Extract struct names that need 'struct' keyword
    const needsStructKeyword = this.extractNeedsStructKeywordForFile(
      filePath,
      symbolTable,
    );
 
    // Extract enum bit widths for enums defined in this file
    const enumBitWidth = this.extractEnumBitWidthsForFile(
      filePath,
      symbolTable,
    );
 
    // Delegate to existing setSymbols method
    this.setSymbols(
      filePath,
      symbols,
      structFields,
      needsStructKeyword,
      enumBitWidth,
    );
  }
 
  /**
   * Issue #590: Extract struct fields for structs defined in a specific file.
   */
  private extractStructFieldsForFile(
    filePath: string,
    symbolTable: SymbolTable,
  ): Map<string, Map<string, IStructFieldInfo>> {
    const result = new Map<string, Map<string, IStructFieldInfo>>();
 
    // Get struct names defined in this file
    const structNames = symbolTable.getStructNamesByFile(filePath);
 
    // Get fields for each struct
    const allStructFields = symbolTable.getAllStructFields();
    for (const structName of structNames) {
      const fields = allStructFields.get(structName);
      Eif (fields) {
        result.set(structName, fields);
      }
    }
 
    return result;
  }
 
  /**
   * Issue #590: Extract struct names requiring 'struct' keyword for a specific file.
   */
  private extractNeedsStructKeywordForFile(
    filePath: string,
    symbolTable: SymbolTable,
  ): string[] {
    // Get struct names defined in this file
    const structNames = symbolTable.getStructNamesByFile(filePath);
 
    // Filter to only those that need struct keyword
    const allNeedsKeyword = symbolTable.getAllNeedsStructKeyword();
    return structNames.filter((name) => allNeedsKeyword.includes(name));
  }
 
  /**
   * Issue #590: Extract enum bit widths for enums defined in a specific file.
   */
  private extractEnumBitWidthsForFile(
    filePath: string,
    symbolTable: SymbolTable,
  ): Map<string, number> {
    const result = new Map<string, number>();
 
    // Get enum names defined in this file
    const fileSymbols = symbolTable.getSymbolsByFile(filePath);
    const enumNames = fileSymbols
      .filter((s) => s.kind === "enum")
      .map((s) => s.name);
 
    // Get bit widths for each enum
    const allBitWidths = symbolTable.getAllEnumBitWidths();
    for (const enumName of enumNames) {
      const width = allBitWidths.get(enumName);
      if (width !== undefined) {
        result.set(enumName, width);
      }
    }
 
    return result;
  }
 
  /**
   * Invalidate cache for a specific file
   */
  invalidate(filePath: string): void {
    Iif (!this.cache) return;
 
    this.cache.removeKey(filePath);
    this.dirty = true;
  }
 
  /**
   * Invalidate all cached entries
   */
  invalidateAll(): void {
    if (this.cache) {
      // Clear all entries
      this.cache.clear();
    } else E{
      // Create fresh cache if not initialized
      this.cache = createFlatCache({
        cacheId: "symbols",
        cacheDir: this.cacheSubdir,
      });
    }
    this.dirty = true;
  }
 
  /**
   * Flush cache to disk if modified
   */
  async flush(): Promise<void> {
    if (!this.dirty || !this.cache) {
      return;
    }
 
    this.cache.save();
    this.dirty = false;
  }
 
  /**
   * Get the cache directory path
   */
  getCacheDir(): string {
    return this.cacheDir;
  }
 
  /**
   * Load or create config file
   */
  private loadOrCreateConfig(): ICacheConfig {
    if (this.fs.exists(this.configPath)) {
      try {
        const content = this.fs.readFile(this.configPath);
        return JSON.parse(content) as ICacheConfig;
      } catch {
        // Config is corrupted, create new one
      }
    }
 
    // Create new config
    const config: ICacheConfig = {
      version: CACHE_VERSION,
      created: Date.now(),
      transpilerVersion: TRANSPILER_VERSION,
    };
 
    this.saveConfig(config);
    return config;
  }
 
  /**
   * Save config file
   */
  private saveConfig(config?: ICacheConfig): void {
    const configToSave = config ?? {
      version: CACHE_VERSION,
      created: Date.now(),
      transpilerVersion: TRANSPILER_VERSION,
    };
 
    this.fs.writeFile(this.configPath, JSON.stringify(configToSave, null, 2));
  }
 
  /**
   * Check if cache should be invalidated based on version
   */
  private shouldInvalidateCache(config: ICacheConfig): boolean {
    // Invalidate if cache version changed
    if (config.version !== CACHE_VERSION) {
      return true;
    }
 
    // Invalidate if transpiler version changed
    if (config.transpilerVersion !== TRANSPILER_VERSION) {
      return true;
    }
 
    return false;
  }
 
  /**
   * Migrate old cache entries from mtime-based to cacheKey-based format
   */
  private migrateOldEntries(): void {
    Iif (!this.cache) return;
 
    const allEntries = this.cache.all();
    for (const [key, value] of Object.entries(allEntries)) {
      const data = value as Record<string, unknown>;
 
      // Already has cacheKey - no migration needed
      Eif (typeof data.cacheKey === "string") {
        continue;
      }
 
      // Migration: convert old mtime to cacheKey format
      if (typeof data.mtime === "number") {
        const migratedEntry: ICachedFileEntry = {
          filePath: data.filePath as string,
          cacheKey: `mtime:${data.mtime}`,
          symbols: data.symbols as ISerializedSymbol[],
          structFields: data.structFields as Record<
            string,
            Record<string, IStructFieldInfo>
          >,
          needsStructKeyword: data.needsStructKeyword as string[] | undefined,
          enumBitWidth: data.enumBitWidth as Record<string, number> | undefined,
        };
        this.cache.setKey(key, migratedEntry);
        this.dirty = true;
      } else {
        // Invalid entry - remove it
        this.cache.removeKey(key);
        this.dirty = true;
      }
    }
  }
 
  /**
   * Serialize an ISymbol to JSON-safe format
   */
  private serializeSymbol(symbol: ISymbol): ISerializedSymbol {
    const serialized: ISerializedSymbol = {
      name: symbol.name,
      kind: symbol.kind, // Already a string from enum
      sourceFile: symbol.sourceFile,
      sourceLine: symbol.sourceLine,
      sourceLanguage: symbol.sourceLanguage, // Already a string from enum
      isExported: symbol.isExported,
    };
 
    // Add optional fields only if present
    if (symbol.type !== undefined) serialized.type = symbol.type;
    if (symbol.isDeclaration !== undefined)
      serialized.isDeclaration = symbol.isDeclaration;
    if (symbol.signature !== undefined) serialized.signature = symbol.signature;
    if (symbol.parent !== undefined) serialized.parent = symbol.parent;
    if (symbol.accessModifier !== undefined)
      serialized.accessModifier = symbol.accessModifier;
    if (symbol.size !== undefined) serialized.size = symbol.size;
    if (symbol.parameters !== undefined)
      serialized.parameters = symbol.parameters;
 
    return serialized;
  }
 
  /**
   * Deserialize a symbol from JSON format back to ISymbol
   */
  private deserializeSymbol(serialized: ISerializedSymbol): ISymbol {
    const symbol: ISymbol = {
      name: serialized.name,
      kind: serialized.kind as ISymbol["kind"], // Cast string back to enum
      sourceFile: serialized.sourceFile,
      sourceLine: serialized.sourceLine,
      sourceLanguage: serialized.sourceLanguage as ISymbol["sourceLanguage"],
      isExported: serialized.isExported,
    };
 
    // Add optional fields only if present
    if (serialized.type !== undefined) symbol.type = serialized.type;
    if (serialized.isDeclaration !== undefined)
      symbol.isDeclaration = serialized.isDeclaration;
    if (serialized.signature !== undefined)
      symbol.signature = serialized.signature;
    if (serialized.parent !== undefined) symbol.parent = serialized.parent;
    if (serialized.accessModifier !== undefined)
      symbol.accessModifier = serialized.accessModifier;
    if (serialized.size !== undefined) symbol.size = serialized.size;
    if (serialized.parameters !== undefined)
      symbol.parameters = serialized.parameters;
 
    return symbol;
  }
}
 
export default CacheManager;