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 | 45x 45x 45x 129x 129x 129x 129x 129x 129x 129x 118x 118x 118x 118x 5x 5x 1x 1x 5x 5x 5x 113x 113x 40x 40x 40x 18x 22x 73x 73x 73x 12x 61x 61x 61x 4x 57x 57x 57x 16x 16x 22x 16x 57x 57x 57x 12x 57x 72x 72x 72x 3x 69x 69x 17x 17x 23x 69x 69x 36x 12x 69x 69x 69x 34x 48x 47x 34x 34x 34x 34x 34x 34x 34x 34x 12x 12x 12x 34x 34x 34x 34x 34x 34x 34x 48x 10x 34x 34x 10x 10x 9x 34x 4x 4x 4x 1x 1x 57x 21x 36x 36x 113x 80x 33x 33x 33x 32x 1x 1x 118x 45x 45x 45x 74x 74x 74x 79x 79x 118x 3x 115x 1x 114x 1x 113x 113x 113x 36x 32x 4x 4x | /**
* CacheManager
*
* Manages persistent cache for parsed C/C++ header symbols, read through the
* port and written by 3.1 Write (#1653).
* 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, one JSON object keyed by path
*/
import { join } from "node:path";
import CacheKeyGenerator from "./CacheKeyGenerator";
import JsonCodec from "./JsonCodec";
import CachedSymbolReader from "./CachedSymbolReader";
import IStructFieldInfo from "../../types/symbols/IStructFieldInfo";
import SymbolTable from "../../PARSE/3-Declare/SymbolTable";
import ICacheConfig from "../../transpiler/types/ICacheConfig";
import ICachedFileEntry from "../../transpiler/types/ICachedFileEntry";
import IStructSymbolState from "../../types/symbols/IStructSymbolState";
import TJsonSafe from "../types/TJsonSafe";
import TJsonValue from "../types/TJsonValue";
import IFileSystem from "../../types/IFileSystem";
import packageJson from "../../../package.json" with { type: "json" };
import ESourceLanguage from "../types/ESourceLanguage";
import Write from "../../WRITE/1-Write/Write";
/** Current cache format version - increment when serialization format changes */
// Bump when the ENTRY shape changes in a way no fingerprint can see -- the
// TCSymbol/TCppSymbol unions are types, so their keys cannot be enumerated at
// runtime. Struct-state drift no longer needs a bump: STRUCT_STATE_SHAPE below
// is derived and invalidates on its own.
// 12: a C declarator's pointer DEPTH is recorded now -- `Dev** out` was
// stored as `Dev*` -- so an entry written before means a different type
// under an unchanged shape, which no fingerprint above can see.
// 13: Issue #1668 -- a C struct/enum specifier is spelled `enum tag` / `foo`,
// not with the keyword run into the tag. Same entry shape, different values.
// Both changes took 12 on their own branches, so an entry either one wrote
// under 12 lacks the other change: the merge takes 13.
// 14: #1760 review -- a C variable's and a typedef's spelling keeps
// `volatile`, so an entry written before reads as non-volatile under an
// unchanged shape: a saturating cast of it would read it three times.
// 15: #1760 review -- a C struct field records its declarator's type
// (`uint8_t*`, `float (*)(void)`), where it recorded its specifiers alone.
// 16: #1653 -- the entries are plain JSON in `symbols.json`, read through the
// port; flat-cache wrote `flatted` to `symbols`, which invalidation removes.
const CACHE_VERSION = 16;
const TRANSPILER_VERSION = packageJson.version;
/**
* Fingerprint of the struct-state shape, derived from the serializer itself.
*
* Issue #1225 review: `TJsonSafe<Required<IStructSymbolState>>` forces the
* writer to persist a new field, but nothing forced already-written entries to
* be discarded -- that was CACHE_VERSION, bumped by hand, so the compile error
* told the next person to write the field without mentioning a second step.
* Deriving it closes the loop for exactly the change that needs it.
*
* Not sorted. `Object.keys` returns string keys in insertion order, which for
* an object literal is the order written in `serializeStructState` -- already
* deterministic. Sorting would need a comparator to satisfy SonarCloud S2871,
* and the obvious one, `localeCompare`, makes a cache fingerprint depend on the
* reader's locale. Reordering that literal changes the fingerprint and
* invalidates once, which costs a re-parse and nothing else.
*/
const STRUCT_STATE_SHAPE = SymbolTable.structStateKeys().join(",");
/**
* Manages symbol cache for faster incremental builds
*/
class CacheManager {
private readonly cacheDir: string;
private readonly cacheSubdir: string;
private readonly configPath: string;
private readonly fs: IFileSystem;
/** Cached entries by file path; null until `initialize` or `invalidateAll` */
private cache: Map<string, unknown> | null = null;
/** Where the entries persist */
private readonly symbolsPath: string;
/** Whether the cache has been modified and needs flushing */
private dirty = false;
constructor(projectRoot: string, fs: IFileSystem) {
this.fs = fs;
this.cacheDir = join(projectRoot, ".cnx");
this.cacheSubdir = join(this.cacheDir, "cache");
this.configPath = join(this.cacheDir, "config.json");
this.symbolsPath = join(this.cacheSubdir, "symbols.json");
}
/**
* Initialize the cache directory and load existing cache
*/
async initialize(): Promise<void> {
// Create .cnx directory structure
Write.directory(this.fs, this.cacheDir);
Write.directory(this.fs, this.cacheSubdir);
// Load or create config
const config = this.loadOrCreateConfig();
// Check if cache should be invalidated
if (this.shouldInvalidateCache(config)) {
// Remove the file flat-cache wrote before #1653, if one is left
const legacyCacheFile = join(this.cacheSubdir, "symbols");
if (this.fs.exists(legacyCacheFile)) {
try {
Write.remove(this.fs, legacyCacheFile);
} catch {
// Ignore if we can't delete
}
}
// Start fresh; the next flush replaces symbols.json
this.cache = new Map();
this.saveConfig();
return;
}
this.cache = this.readEntries();
// Issue #1225: drop anything written in an older entry shape
this.discardOutdatedEntries();
}
/**
* 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.get(filePath);
if (!entry) {
return false;
}
return CacheKeyGenerator.isValid(
filePath,
(entry as ICachedFileEntry).cacheKey,
this.fs,
);
}
/**
* Get cached symbols and struct fields for a file.
*
* Issue #1225: `symbols` comes back as the JSON the file holds; callers run
* it through `CachedSymbolReader` to validate and revive it.
*/
getSymbols(filePath: string): {
symbols: TJsonValue[];
structFields: Map<string, Map<string, IStructFieldInfo>>;
needsStructKeyword: string[];
enumBitWidth: Map<string, number>;
structState: TJsonSafe<Required<IStructSymbolState>>;
preprocessFailed: boolean;
} | null {
Iif (!this.cache) return null;
const entry = this.cache.get(filePath);
if (!entry) {
return null;
}
const cachedEntry = entry as ICachedFileEntry;
// Issue #1225: entries come off disk, so the type annotation above is a
// claim rather than a guarantee. Struct state is validated the same way
// symbols are -- an entry whose struct state is the wrong shape, or is
// merely missing a key, reads as a miss rather than throwing out of the
// transpile or restoring a silently empty Set.
const structState = CachedSymbolReader.readStructState(
cachedEntry.structState,
);
if (structState === null) {
return null;
}
const symbols = cachedEntry.symbols;
// 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,
structState,
preprocessFailed: cachedEntry.preprocessFailed ?? false,
};
}
/**
* Store symbols and struct fields for a file.
*
* Issue #1225: `structState` is required rather than optional. An entry that
* cannot carry the struct state is exactly the half-written entry this bug
* was made of, so the type refuses to express one.
*/
setSymbols(
filePath: string,
symbols: TJsonValue[],
structFields: Map<string, Map<string, IStructFieldInfo>>,
options: {
structState: TJsonSafe<Required<IStructSymbolState>>;
needsStructKeyword?: string[];
enumBitWidth?: Map<string, number>;
preprocessFailed?: boolean;
},
): 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;
}
// 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 (options.enumBitWidth) {
for (const [enumName, width] of options.enumBitWidth) {
serializedEnumBitWidth[enumName] = width;
}
}
// Create entry
const entry: ICachedFileEntry = {
filePath,
cacheKey,
symbols,
structFields: serializedFields,
needsStructKeyword: options.needsStructKeyword,
enumBitWidth: serializedEnumBitWidth,
structState: options.structState,
preprocessFailed: options.preprocessFailed,
};
this.cache.set(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
* @param preprocessFailed - Issue #985: header fell back to raw content, so its
* symbols are degraded and a warm-cache build must re-run recovery
*/
setSymbolsFromTable(
filePath: string,
symbolTable: SymbolTable,
preprocessFailed = false,
): void {
// Issue #1225: encode the real typed symbols. JsonCodec copies every
// field rather than naming any, so a field added to the symbol model is
// cached without anyone editing this method -- which is what the old
// field-by-field serializer could not do.
//
// C-Next symbols are re-parsed from source every run and are never cached;
// filtering them states that invariant instead of relying on no .cnx file
// ever reaching this call site.
const symbols = symbolTable
.getSymbolsByFile(filePath)
.filter((symbol) => symbol.sourceLanguage !== ESourceLanguage.CNext)
.map((symbol) => JsonCodec.encode(symbol));
// 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,
);
this.setSymbols(filePath, symbols, structFields, {
structState: symbolTable.serializeStructState(),
needsStructKeyword,
enumBitWidth,
preprocessFailed,
});
}
/**
* 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.delete(filePath);
this.dirty = true;
}
/**
* Invalidate all cached entries
*/
invalidateAll(): void {
this.cache = new Map();
this.dirty = true;
}
/**
* Flush cache to disk if modified
*/
async flush(): Promise<void> {
if (!this.dirty || !this.cache) {
return;
}
Write.file(
this.fs,
this.symbolsPath,
JSON.stringify(Object.fromEntries(this.cache)),
);
this.dirty = false;
}
/**
* The entries `symbols.json` holds, or none when there is no file or it does
* not parse as an object: a cache that cannot be read is re-derived, never
* trusted.
*/
private readEntries(): Map<string, unknown> {
if (!this.fs.exists(this.symbolsPath)) {
return new Map();
}
try {
const parsed: unknown = JSON.parse(this.fs.readFile(this.symbolsPath));
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
return new Map(Object.entries(parsed));
}
} catch {
// Unreadable: fall through to an empty cache
}
return new Map();
}
/**
* 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,
structStateShape: STRUCT_STATE_SHAPE,
};
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,
structStateShape: STRUCT_STATE_SHAPE,
};
Write.file(this.fs, 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;
}
// Issue #1225: struct state gained or lost a field, so every stored entry
// describes a shape this build does not have.
if (config.structStateShape !== STRUCT_STATE_SHAPE) {
return true;
}
return false;
}
/**
* Drop cache entries written in an older entry shape.
*
* Issue #1225: this used to rebuild a pre-`cacheKey` entry from whatever
* fields it happened to have, which produced an entry missing struct state
* and typed symbols -- a half-written cache of exactly the kind this issue
* is about. Re-parsing the file costs milliseconds; trusting a partial entry
* costs a wrong header.
*/
private discardOutdatedEntries(): void {
Iif (!this.cache) return;
// Deleting from a Map while iterating it is defined: an entry removed
// before it is reached is not visited, and the current one may go.
for (const [key, value] of this.cache) {
// Anything but an object carrying a string cacheKey is outdated,
// including null: the file is plain JSON and can hold anything (#1826).
if (
value !== null &&
typeof value === "object" &&
typeof (value as Record<string, unknown>).cacheKey === "string"
) {
continue;
}
this.cache.delete(key);
this.dirty = true;
}
}
}
export default CacheManager;
|