feat: Add content-based C++ detection for .h headers

Addresses C++ classes missing from .h files where extension-based detection defaults to 'c' language which has no class extraction support. Adds looksLikeCpp() heuristic that scans first 8KB for C++-specific patterns (namespace, class, template, access specifiers) to promote .h files to 'cpp' language when C++ constructs are detected. Ensures cpp grammar is loaded alongside c to handle potential .h promotion during parsing.
This commit is contained in:
Colby McHenry
2026-04-06 23:38:13 -05:00
parent 237fb3b206
commit 4a8d2f0396
5 changed files with 36 additions and 11 deletions
+18 -2
View File
@@ -174,9 +174,25 @@ export function getParser(language: Language): Parser | null {
/**
* Detect language from file extension
*/
export function detectLanguage(filePath: string): Language {
export function detectLanguage(filePath: string, source?: string): Language {
const ext = filePath.substring(filePath.lastIndexOf('.')).toLowerCase();
return EXTENSION_MAP[ext] || 'unknown';
const lang = EXTENSION_MAP[ext] || 'unknown';
// .h files could be C or C++ — check source content for C++ features
if (lang === 'c' && ext === '.h' && source) {
if (looksLikeCpp(source)) return 'cpp';
}
return lang;
}
/**
* Heuristic: does a .h file contain C++ constructs?
* Checks the first ~8KB for patterns that are unique to C++ and never valid C.
*/
function looksLikeCpp(source: string): boolean {
const sample = source.substring(0, 8192);
return /\bnamespace\b|\bclass\s+\w+\s*[:{]|\btemplate\s*<|\b(?:public|private|protected)\s*:|\bvirtual\b|\busing\s+(?:namespace\b|\w+\s*=)/.test(sample);
}
/**