grammars.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /**
  2. * Grammar Loading and Caching
  3. *
  4. * Uses web-tree-sitter (WASM) for universal cross-platform support.
  5. * Grammars are loaded lazily — only languages actually present in the project
  6. * are compiled, keeping V8 WASM memory pressure low on large codebases.
  7. */
  8. import * as path from 'path';
  9. import { Parser, Language as WasmLanguage } from 'web-tree-sitter';
  10. import { Language } from '../types';
  11. export type GrammarLanguage = Exclude<Language, 'svelte' | 'vue' | 'liquid' | 'yaml' | 'twig' | 'unknown'>;
  12. /**
  13. * WASM filename map — maps each language to its .wasm grammar file
  14. * in the tree-sitter-wasms package.
  15. */
  16. const WASM_GRAMMAR_FILES: Record<GrammarLanguage, string> = {
  17. typescript: 'tree-sitter-typescript.wasm',
  18. tsx: 'tree-sitter-tsx.wasm',
  19. javascript: 'tree-sitter-javascript.wasm',
  20. jsx: 'tree-sitter-javascript.wasm',
  21. python: 'tree-sitter-python.wasm',
  22. go: 'tree-sitter-go.wasm',
  23. rust: 'tree-sitter-rust.wasm',
  24. java: 'tree-sitter-java.wasm',
  25. c: 'tree-sitter-c.wasm',
  26. cpp: 'tree-sitter-cpp.wasm',
  27. csharp: 'tree-sitter-c_sharp.wasm',
  28. php: 'tree-sitter-php.wasm',
  29. ruby: 'tree-sitter-ruby.wasm',
  30. swift: 'tree-sitter-swift.wasm',
  31. kotlin: 'tree-sitter-kotlin.wasm',
  32. dart: 'tree-sitter-dart.wasm',
  33. pascal: 'tree-sitter-pascal.wasm',
  34. scala: 'tree-sitter-scala.wasm',
  35. lua: 'tree-sitter-lua.wasm',
  36. luau: 'tree-sitter-luau.wasm',
  37. };
  38. /**
  39. * File extension to Language mapping
  40. */
  41. export const EXTENSION_MAP: Record<string, Language> = {
  42. '.ts': 'typescript',
  43. '.tsx': 'tsx',
  44. '.js': 'javascript',
  45. '.mjs': 'javascript',
  46. '.cjs': 'javascript',
  47. '.jsx': 'jsx',
  48. '.py': 'python',
  49. '.pyw': 'python',
  50. '.go': 'go',
  51. '.rs': 'rust',
  52. '.java': 'java',
  53. '.c': 'c',
  54. '.h': 'c', // Could also be C++, defaulting to C
  55. '.cpp': 'cpp',
  56. '.cc': 'cpp',
  57. '.cxx': 'cpp',
  58. '.hpp': 'cpp',
  59. '.hxx': 'cpp',
  60. '.cs': 'csharp',
  61. '.php': 'php',
  62. // Drupal-specific PHP file extensions
  63. '.module': 'php',
  64. '.install': 'php',
  65. '.theme': 'php',
  66. '.inc': 'php',
  67. // YAML (used for Drupal routing files; no symbol extraction, file-level tracking only)
  68. '.yml': 'yaml',
  69. '.yaml': 'yaml',
  70. // Twig templates (file-level tracking only, no symbol extraction)
  71. '.twig': 'twig',
  72. '.rb': 'ruby',
  73. '.rake': 'ruby',
  74. '.swift': 'swift',
  75. '.kt': 'kotlin',
  76. '.kts': 'kotlin',
  77. '.dart': 'dart',
  78. '.liquid': 'liquid',
  79. '.svelte': 'svelte',
  80. '.vue': 'vue',
  81. '.pas': 'pascal',
  82. '.dpr': 'pascal',
  83. '.dpk': 'pascal',
  84. '.lpr': 'pascal',
  85. '.dfm': 'pascal',
  86. '.fmx': 'pascal',
  87. '.scala': 'scala',
  88. '.sc': 'scala',
  89. '.lua': 'lua',
  90. '.luau': 'luau',
  91. };
  92. /**
  93. * Caches for loaded grammars and parsers
  94. */
  95. const parserCache = new Map<Language, Parser>();
  96. const languageCache = new Map<Language, WasmLanguage>();
  97. const unavailableGrammarErrors = new Map<Language, string>();
  98. let parserInitialized = false;
  99. /**
  100. * Initialize the tree-sitter WASM runtime. Must be called before loading grammars.
  101. * Does NOT load any grammar WASM files — use loadGrammarsForLanguages() for that.
  102. * Idempotent — safe to call multiple times.
  103. */
  104. export async function initGrammars(): Promise<void> {
  105. if (parserInitialized) return;
  106. await Parser.init();
  107. parserInitialized = true;
  108. }
  109. /**
  110. * Load grammar WASM files for specific languages only.
  111. * Skips languages that are already loaded or have no WASM grammar.
  112. * Must be called after initGrammars().
  113. */
  114. export async function loadGrammarsForLanguages(languages: Language[]): Promise<void> {
  115. if (!parserInitialized) {
  116. await initGrammars();
  117. }
  118. // Deduplicate and filter to languages that have WASM grammars and aren't already loaded
  119. const toLoad = [...new Set(languages)].filter(
  120. (lang): lang is GrammarLanguage =>
  121. lang in WASM_GRAMMAR_FILES &&
  122. !languageCache.has(lang) &&
  123. !unavailableGrammarErrors.has(lang)
  124. );
  125. // Load grammars sequentially to avoid web-tree-sitter WASM race condition on Node 20+
  126. // See: https://github.com/tree-sitter/tree-sitter/issues/2338
  127. for (const lang of toLoad) {
  128. const wasmFile = WASM_GRAMMAR_FILES[lang];
  129. try {
  130. // Some grammars ship their own WASMs (not in tree-sitter-wasms, or the
  131. // tree-sitter-wasms build is too old). Lua: tree-sitter-wasms ships an
  132. // ABI-13 build that corrupts the shared WASM heap under web-tree-sitter
  133. // 0.25 (drops nested calls/imports on every file after the first); we
  134. // vendor the upstream ABI-15 wasm instead.
  135. const wasmPath = (lang === 'pascal' || lang === 'scala' || lang === 'lua' || lang === 'luau')
  136. ? path.join(__dirname, 'wasm', wasmFile)
  137. : require.resolve(`tree-sitter-wasms/out/${wasmFile}`);
  138. const language = await WasmLanguage.load(wasmPath);
  139. languageCache.set(lang, language);
  140. } catch (error) {
  141. const message = error instanceof Error ? error.message : String(error);
  142. console.warn(`[CodeGraph] Failed to load ${lang} grammar — parsing will be unavailable: ${message}`);
  143. unavailableGrammarErrors.set(lang, message);
  144. }
  145. }
  146. }
  147. /**
  148. * Load ALL grammar WASM files. Convenience function for tests and
  149. * backward compatibility. Prefer loadGrammarsForLanguages() in production.
  150. */
  151. export async function loadAllGrammars(): Promise<void> {
  152. const allLanguages = Object.keys(WASM_GRAMMAR_FILES) as GrammarLanguage[];
  153. await loadGrammarsForLanguages(allLanguages);
  154. }
  155. /**
  156. * Check if grammars have been initialized
  157. */
  158. export function isGrammarsInitialized(): boolean {
  159. return parserInitialized;
  160. }
  161. /**
  162. * Get a parser for the specified language.
  163. * Returns synchronously from pre-loaded cache.
  164. */
  165. export function getParser(language: Language): Parser | null {
  166. if (parserCache.has(language)) {
  167. return parserCache.get(language)!;
  168. }
  169. const lang = languageCache.get(language);
  170. if (!lang) {
  171. return null;
  172. }
  173. const parser = new Parser();
  174. parser.setLanguage(lang);
  175. parserCache.set(language, parser);
  176. return parser;
  177. }
  178. /**
  179. * Detect language from file extension
  180. */
  181. export function detectLanguage(filePath: string, source?: string): Language {
  182. const ext = filePath.substring(filePath.lastIndexOf('.')).toLowerCase();
  183. const lang = EXTENSION_MAP[ext] || 'unknown';
  184. // .h files could be C or C++ — check source content for C++ features
  185. if (lang === 'c' && ext === '.h' && source) {
  186. if (looksLikeCpp(source)) return 'cpp';
  187. }
  188. return lang;
  189. }
  190. /**
  191. * Heuristic: does a .h file contain C++ constructs?
  192. * Checks the first ~8KB for patterns that are unique to C++ and never valid C.
  193. */
  194. function looksLikeCpp(source: string): boolean {
  195. const sample = source.substring(0, 8192);
  196. return /\bnamespace\b|\bclass\s+\w+\s*[:{]|\btemplate\s*<|\b(?:public|private|protected)\s*:|\bvirtual\b|\busing\s+(?:namespace\b|\w+\s*=)/.test(sample);
  197. }
  198. /**
  199. * Check if a language is supported (has a grammar defined).
  200. * Returns true if the grammar exists, even if not yet loaded.
  201. */
  202. export function isLanguageSupported(language: Language): boolean {
  203. if (language === 'svelte') return true; // custom extractor (script block delegation)
  204. if (language === 'vue') return true; // custom extractor (script block delegation)
  205. if (language === 'liquid') return true; // custom regex extractor
  206. if (language === 'yaml') return true; // file-level tracking only; Drupal routing extraction via framework resolver
  207. if (language === 'twig') return true; // file-level tracking only
  208. if (language === 'unknown') return false;
  209. return language in WASM_GRAMMAR_FILES;
  210. }
  211. /**
  212. * Check if a grammar has been loaded and is ready for parsing.
  213. */
  214. export function isGrammarLoaded(language: Language): boolean {
  215. if (language === 'svelte' || language === 'vue' || language === 'liquid') return true;
  216. if (language === 'yaml' || language === 'twig') return true; // no WASM grammar needed
  217. return languageCache.has(language);
  218. }
  219. /**
  220. * Get all supported languages (those with grammar definitions).
  221. */
  222. export function getSupportedLanguages(): Language[] {
  223. return [...(Object.keys(WASM_GRAMMAR_FILES) as GrammarLanguage[]), 'svelte', 'vue', 'liquid'];
  224. }
  225. /**
  226. * Reset the cached parser for a language to reclaim WASM heap memory.
  227. * The tree-sitter WASM runtime accumulates fragmented memory over thousands
  228. * of parses. Deleting and recreating the Parser instance forces the WASM
  229. * heap to reset, preventing "memory access out of bounds" crashes in
  230. * large repos.
  231. */
  232. export function resetParser(language: Language): void {
  233. const old = parserCache.get(language);
  234. if (old) {
  235. old.delete();
  236. parserCache.delete(language);
  237. }
  238. }
  239. /**
  240. * Clear parser/grammar caches (useful for testing)
  241. */
  242. export function clearParserCache(): void {
  243. for (const parser of parserCache.values()) {
  244. parser.delete();
  245. }
  246. parserCache.clear();
  247. // Note: languageCache is NOT cleared — WASM languages persist.
  248. // To fully re-init, set parserInitialized = false and call initGrammars() again.
  249. unavailableGrammarErrors.clear();
  250. }
  251. /**
  252. * Report grammars that failed to load.
  253. */
  254. export function getUnavailableGrammarErrors(): Partial<Record<Language, string>> {
  255. const out: Partial<Record<Language, string>> = {};
  256. for (const [language, message] of unavailableGrammarErrors.entries()) {
  257. out[language] = message;
  258. }
  259. return out;
  260. }
  261. /**
  262. * Get language display name
  263. */
  264. export function getLanguageDisplayName(language: Language): string {
  265. const names: Record<Language, string> = {
  266. typescript: 'TypeScript',
  267. javascript: 'JavaScript',
  268. tsx: 'TypeScript (TSX)',
  269. jsx: 'JavaScript (JSX)',
  270. python: 'Python',
  271. go: 'Go',
  272. rust: 'Rust',
  273. java: 'Java',
  274. c: 'C',
  275. cpp: 'C++',
  276. csharp: 'C#',
  277. php: 'PHP',
  278. ruby: 'Ruby',
  279. swift: 'Swift',
  280. kotlin: 'Kotlin',
  281. dart: 'Dart',
  282. svelte: 'Svelte',
  283. vue: 'Vue',
  284. liquid: 'Liquid',
  285. pascal: 'Pascal / Delphi',
  286. scala: 'Scala',
  287. lua: 'Lua',
  288. luau: 'Luau',
  289. yaml: 'YAML',
  290. twig: 'Twig',
  291. unknown: 'Unknown',
  292. };
  293. return names[language] || language;
  294. }