grammars.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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' | 'xml' | 'properties' | '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. objc: 'tree-sitter-objc.wasm',
  38. };
  39. /**
  40. * File extension to Language mapping
  41. */
  42. export const EXTENSION_MAP: Record<string, Language> = {
  43. '.ts': 'typescript',
  44. '.tsx': 'tsx',
  45. '.js': 'javascript',
  46. '.mjs': 'javascript',
  47. '.cjs': 'javascript',
  48. '.jsx': 'jsx',
  49. '.py': 'python',
  50. '.pyw': 'python',
  51. '.go': 'go',
  52. '.rs': 'rust',
  53. '.java': 'java',
  54. '.c': 'c',
  55. '.h': 'c', // Could also be C++, defaulting to C
  56. '.cpp': 'cpp',
  57. '.cc': 'cpp',
  58. '.cxx': 'cpp',
  59. '.hpp': 'cpp',
  60. '.hxx': 'cpp',
  61. '.cs': 'csharp',
  62. '.php': 'php',
  63. // Drupal-specific PHP file extensions
  64. '.module': 'php',
  65. '.install': 'php',
  66. '.theme': 'php',
  67. '.inc': 'php',
  68. // YAML (used for Drupal routing files; no symbol extraction, file-level tracking only)
  69. '.yml': 'yaml',
  70. '.yaml': 'yaml',
  71. // Twig templates (file-level tracking only, no symbol extraction)
  72. '.twig': 'twig',
  73. '.rb': 'ruby',
  74. '.rake': 'ruby',
  75. '.swift': 'swift',
  76. '.kt': 'kotlin',
  77. '.kts': 'kotlin',
  78. '.dart': 'dart',
  79. '.liquid': 'liquid',
  80. '.svelte': 'svelte',
  81. '.vue': 'vue',
  82. '.pas': 'pascal',
  83. '.dpr': 'pascal',
  84. '.dpk': 'pascal',
  85. '.lpr': 'pascal',
  86. '.dfm': 'pascal',
  87. '.fmx': 'pascal',
  88. '.scala': 'scala',
  89. '.sc': 'scala',
  90. '.lua': 'lua',
  91. '.luau': 'luau',
  92. '.m': 'objc',
  93. '.mm': 'objc',
  94. // XML: file-level tracking; the MyBatis extractor matches `<mapper namespace="...">`
  95. // shape and emits SQL-statement nodes (other XML returns empty).
  96. '.xml': 'xml',
  97. // Spring config: `application.properties` / `application-*.properties`. Same
  98. // shape as the `.yml` variants — the YAML/properties extractor emits one node
  99. // per leaf key, and the Spring resolver links `@Value("${k}")` references.
  100. '.properties': 'properties',
  101. };
  102. /**
  103. * Whether a file is one CodeGraph can parse, based purely on its extension.
  104. * This is the single source of truth for "should we index this file" — derived
  105. * from EXTENSION_MAP so parser support and indexing selection never drift.
  106. */
  107. export function isSourceFile(filePath: string): boolean {
  108. if (isPlayRoutesFile(filePath)) return true; // Play `conf/routes` is extensionless
  109. const dot = filePath.lastIndexOf('.');
  110. if (dot < 0) return false;
  111. return filePath.slice(dot).toLowerCase() in EXTENSION_MAP;
  112. }
  113. /**
  114. * Play Framework routes file: the extensionless `conf/routes` (and included
  115. * `conf/*.routes`). No grammar — route extraction is done by the Play framework
  116. * resolver, so it's processed through the no-grammar (`yaml`-style) path.
  117. */
  118. export function isPlayRoutesFile(filePath: string): boolean {
  119. return (
  120. filePath === 'conf/routes' ||
  121. filePath.endsWith('/conf/routes') ||
  122. filePath.endsWith('.routes')
  123. );
  124. }
  125. /**
  126. * Caches for loaded grammars and parsers
  127. */
  128. const parserCache = new Map<Language, Parser>();
  129. const languageCache = new Map<Language, WasmLanguage>();
  130. const unavailableGrammarErrors = new Map<Language, string>();
  131. let parserInitialized = false;
  132. /**
  133. * Initialize the tree-sitter WASM runtime. Must be called before loading grammars.
  134. * Does NOT load any grammar WASM files — use loadGrammarsForLanguages() for that.
  135. * Idempotent — safe to call multiple times.
  136. */
  137. export async function initGrammars(): Promise<void> {
  138. if (parserInitialized) return;
  139. await Parser.init();
  140. parserInitialized = true;
  141. }
  142. /**
  143. * Load grammar WASM files for specific languages only.
  144. * Skips languages that are already loaded or have no WASM grammar.
  145. * Must be called after initGrammars().
  146. */
  147. export async function loadGrammarsForLanguages(languages: Language[]): Promise<void> {
  148. if (!parserInitialized) {
  149. await initGrammars();
  150. }
  151. // Deduplicate and filter to languages that have WASM grammars and aren't already loaded
  152. const toLoad = [...new Set(languages)].filter(
  153. (lang): lang is GrammarLanguage =>
  154. lang in WASM_GRAMMAR_FILES &&
  155. !languageCache.has(lang) &&
  156. !unavailableGrammarErrors.has(lang)
  157. );
  158. // Load grammars sequentially to avoid web-tree-sitter WASM race condition on Node 20+
  159. // See: https://github.com/tree-sitter/tree-sitter/issues/2338
  160. for (const lang of toLoad) {
  161. const wasmFile = WASM_GRAMMAR_FILES[lang];
  162. try {
  163. // Some grammars ship their own WASMs (not in tree-sitter-wasms, or the
  164. // tree-sitter-wasms build is too old). Lua: tree-sitter-wasms ships an
  165. // ABI-13 build that corrupts the shared WASM heap under web-tree-sitter
  166. // 0.25 (drops nested calls/imports on every file after the first); we
  167. // vendor the upstream ABI-15 wasm instead.
  168. const wasmPath = (lang === 'pascal' || lang === 'scala' || lang === 'lua' || lang === 'luau')
  169. ? path.join(__dirname, 'wasm', wasmFile)
  170. : require.resolve(`tree-sitter-wasms/out/${wasmFile}`);
  171. const language = await WasmLanguage.load(wasmPath);
  172. languageCache.set(lang, language);
  173. } catch (error) {
  174. const message = error instanceof Error ? error.message : String(error);
  175. console.warn(`[CodeGraph] Failed to load ${lang} grammar — parsing will be unavailable: ${message}`);
  176. unavailableGrammarErrors.set(lang, message);
  177. }
  178. }
  179. }
  180. /**
  181. * Load ALL grammar WASM files. Convenience function for tests and
  182. * backward compatibility. Prefer loadGrammarsForLanguages() in production.
  183. */
  184. export async function loadAllGrammars(): Promise<void> {
  185. const allLanguages = Object.keys(WASM_GRAMMAR_FILES) as GrammarLanguage[];
  186. await loadGrammarsForLanguages(allLanguages);
  187. }
  188. /**
  189. * Check if grammars have been initialized
  190. */
  191. export function isGrammarsInitialized(): boolean {
  192. return parserInitialized;
  193. }
  194. /**
  195. * Get a parser for the specified language.
  196. * Returns synchronously from pre-loaded cache.
  197. */
  198. export function getParser(language: Language): Parser | null {
  199. if (parserCache.has(language)) {
  200. return parserCache.get(language)!;
  201. }
  202. const lang = languageCache.get(language);
  203. if (!lang) {
  204. return null;
  205. }
  206. const parser = new Parser();
  207. parser.setLanguage(lang);
  208. parserCache.set(language, parser);
  209. return parser;
  210. }
  211. /**
  212. * Detect language from file extension
  213. */
  214. export function detectLanguage(filePath: string, source?: string): Language {
  215. // Play `conf/routes` has no grammar — route through the no-symbol path; the
  216. // Play framework resolver extracts route nodes from it.
  217. if (isPlayRoutesFile(filePath)) return 'yaml';
  218. const ext = filePath.substring(filePath.lastIndexOf('.')).toLowerCase();
  219. const lang = EXTENSION_MAP[ext] || 'unknown';
  220. // .h files could be C, C++, or Objective-C — check source content
  221. if (lang === 'c' && ext === '.h' && source) {
  222. if (looksLikeCpp(source)) return 'cpp';
  223. if (looksLikeObjc(source)) return 'objc';
  224. }
  225. return lang;
  226. }
  227. /**
  228. * Heuristic: does a .h file contain C++ constructs?
  229. * Checks the first ~8KB for patterns that are unique to C++ and never valid C.
  230. */
  231. function looksLikeCpp(source: string): boolean {
  232. const sample = source.substring(0, 8192);
  233. return /\bnamespace\b|\bclass\s+\w+\s*[:{]|\btemplate\s*<|\b(?:public|private|protected)\s*:|\bvirtual\b|\busing\s+(?:namespace\b|\w+\s*=)/.test(sample);
  234. }
  235. /**
  236. * Heuristic: does a .h file contain Objective-C constructs?
  237. */
  238. function looksLikeObjc(source: string): boolean {
  239. const sample = source.substring(0, 8192);
  240. return /@(?:interface|implementation|protocol|synthesize)\b/.test(sample);
  241. }
  242. /**
  243. * Check if a language is supported (has a grammar defined).
  244. * Returns true if the grammar exists, even if not yet loaded.
  245. */
  246. export function isLanguageSupported(language: Language): boolean {
  247. if (language === 'svelte') return true; // custom extractor (script block delegation)
  248. if (language === 'vue') return true; // custom extractor (script block delegation)
  249. if (language === 'liquid') return true; // custom regex extractor
  250. if (language === 'yaml') return true; // file-level tracking only; Drupal routing extraction via framework resolver
  251. if (language === 'twig') return true; // file-level tracking only
  252. if (language === 'xml') return true; // MyBatis mapper extractor
  253. if (language === 'properties') return true; // Spring config keys
  254. if (language === 'unknown') return false;
  255. return language in WASM_GRAMMAR_FILES;
  256. }
  257. /**
  258. * Check if a grammar has been loaded and is ready for parsing.
  259. */
  260. export function isGrammarLoaded(language: Language): boolean {
  261. if (language === 'svelte' || language === 'vue' || language === 'liquid') return true;
  262. if (language === 'yaml' || language === 'twig') return true; // no WASM grammar needed
  263. if (language === 'xml' || language === 'properties') return true; // no WASM grammar needed
  264. return languageCache.has(language);
  265. }
  266. /**
  267. * Get all supported languages (those with grammar definitions).
  268. */
  269. export function getSupportedLanguages(): Language[] {
  270. return [...(Object.keys(WASM_GRAMMAR_FILES) as GrammarLanguage[]), 'svelte', 'vue', 'liquid'];
  271. }
  272. /**
  273. * Reset the cached parser for a language to reclaim WASM heap memory.
  274. * The tree-sitter WASM runtime accumulates fragmented memory over thousands
  275. * of parses. Deleting and recreating the Parser instance forces the WASM
  276. * heap to reset, preventing "memory access out of bounds" crashes in
  277. * large repos.
  278. */
  279. export function resetParser(language: Language): void {
  280. const old = parserCache.get(language);
  281. if (old) {
  282. old.delete();
  283. parserCache.delete(language);
  284. }
  285. }
  286. /**
  287. * Clear parser/grammar caches (useful for testing)
  288. */
  289. export function clearParserCache(): void {
  290. for (const parser of parserCache.values()) {
  291. parser.delete();
  292. }
  293. parserCache.clear();
  294. // Note: languageCache is NOT cleared — WASM languages persist.
  295. // To fully re-init, set parserInitialized = false and call initGrammars() again.
  296. unavailableGrammarErrors.clear();
  297. }
  298. /**
  299. * Report grammars that failed to load.
  300. */
  301. export function getUnavailableGrammarErrors(): Partial<Record<Language, string>> {
  302. const out: Partial<Record<Language, string>> = {};
  303. for (const [language, message] of unavailableGrammarErrors.entries()) {
  304. out[language] = message;
  305. }
  306. return out;
  307. }
  308. /**
  309. * Get language display name
  310. */
  311. export function getLanguageDisplayName(language: Language): string {
  312. const names: Record<Language, string> = {
  313. typescript: 'TypeScript',
  314. javascript: 'JavaScript',
  315. tsx: 'TypeScript (TSX)',
  316. jsx: 'JavaScript (JSX)',
  317. python: 'Python',
  318. go: 'Go',
  319. rust: 'Rust',
  320. java: 'Java',
  321. c: 'C',
  322. cpp: 'C++',
  323. csharp: 'C#',
  324. php: 'PHP',
  325. ruby: 'Ruby',
  326. swift: 'Swift',
  327. kotlin: 'Kotlin',
  328. dart: 'Dart',
  329. svelte: 'Svelte',
  330. vue: 'Vue',
  331. liquid: 'Liquid',
  332. pascal: 'Pascal / Delphi',
  333. scala: 'Scala',
  334. lua: 'Lua',
  335. luau: 'Luau',
  336. objc: 'Objective-C',
  337. yaml: 'YAML',
  338. twig: 'Twig',
  339. xml: 'XML',
  340. properties: 'Java properties',
  341. unknown: 'Unknown',
  342. };
  343. return names[language] || language;
  344. }