grammars.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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' | 'astro' | 'liquid' | 'razor' | '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. r: 'tree-sitter-r.wasm',
  37. luau: 'tree-sitter-luau.wasm',
  38. objc: 'tree-sitter-objc.wasm',
  39. cfml: 'tree-sitter-cfml.wasm',
  40. cfscript: 'tree-sitter-cfscript.wasm',
  41. cfquery: 'tree-sitter-cfquery.wasm',
  42. cobol: 'tree-sitter-cobol.wasm',
  43. vbnet: 'tree-sitter-vbnet.wasm',
  44. erlang: 'tree-sitter-erlang.wasm',
  45. solidity: 'tree-sitter-solidity.wasm',
  46. terraform: 'tree-sitter-terraform.wasm',
  47. arkts: 'tree-sitter-arkts.wasm',
  48. nix: 'tree-sitter-nix.wasm',
  49. };
  50. /**
  51. * File extension to Language mapping
  52. */
  53. export const EXTENSION_MAP: Record<string, Language> = {
  54. '.ts': 'typescript',
  55. '.tsx': 'tsx',
  56. // ESM/CJS TypeScript module extensions — parsed as TS (no JSX). (#366)
  57. '.mts': 'typescript',
  58. '.cts': 'typescript',
  59. // ArkTS (HarmonyOS / OpenHarmony) — a TypeScript superset with declarative
  60. // UI (`@Component struct` + `build()`). Own grammar (a tree-sitter-typescript
  61. // -style fork); plain `.ts` in an ArkTS project stays TypeScript. (#648)
  62. '.ets': 'arkts',
  63. '.js': 'javascript',
  64. '.mjs': 'javascript',
  65. '.cjs': 'javascript',
  66. // SAP HANA XS Classic server-side JavaScript. (#556)
  67. '.xsjs': 'javascript',
  68. '.xsjslib': 'javascript',
  69. '.jsx': 'jsx',
  70. '.py': 'python',
  71. '.pyw': 'python',
  72. '.go': 'go',
  73. '.rs': 'rust',
  74. '.java': 'java',
  75. '.c': 'c',
  76. '.h': 'c', // Could also be C++, defaulting to C
  77. '.cpp': 'cpp',
  78. '.cc': 'cpp',
  79. '.cxx': 'cpp',
  80. '.hpp': 'cpp',
  81. '.hxx': 'cpp',
  82. '.cs': 'csharp',
  83. // ASP.NET Razor / Blazor markup — custom RazorExtractor (links @model/@inject/
  84. // component tags to their C# types; markup isn't a tree-sitter grammar).
  85. '.cshtml': 'razor',
  86. '.razor': 'razor',
  87. '.php': 'php',
  88. // Drupal-specific PHP file extensions
  89. '.module': 'php',
  90. '.install': 'php',
  91. '.theme': 'php',
  92. '.inc': 'php',
  93. // YAML (used for Drupal routing files; no symbol extraction, file-level tracking only)
  94. '.yml': 'yaml',
  95. '.yaml': 'yaml',
  96. // Twig templates (file-level tracking only, no symbol extraction)
  97. '.twig': 'twig',
  98. '.rb': 'ruby',
  99. '.rake': 'ruby',
  100. '.swift': 'swift',
  101. '.kt': 'kotlin',
  102. '.kts': 'kotlin',
  103. '.dart': 'dart',
  104. '.liquid': 'liquid',
  105. '.svelte': 'svelte',
  106. '.vue': 'vue',
  107. '.astro': 'astro',
  108. '.r': 'r',
  109. '.pas': 'pascal',
  110. '.dpr': 'pascal',
  111. '.dpk': 'pascal',
  112. '.lpr': 'pascal',
  113. '.dfm': 'pascal',
  114. '.fmx': 'pascal',
  115. '.scala': 'scala',
  116. '.sc': 'scala',
  117. '.lua': 'lua',
  118. '.luau': 'luau',
  119. '.m': 'objc',
  120. '.mm': 'objc',
  121. '.sol': 'solidity',
  122. // CFML: .cfc/.cfm parse with the tag-aware `cfml` grammar (custom CfmlExtractor
  123. // dialect-switches to cfscript for bare-script content); .cfs is pure CFScript.
  124. '.cfc': 'cfml',
  125. '.cfm': 'cfml',
  126. '.cfs': 'cfscript',
  127. // Metal Shading Language ≈ C++14: the C++ grammar extracts its functions,
  128. // structs, and calls. MSL-specific `[[attribute]]` annotations are blanked
  129. // pre-parse for `.metal` files (see blankMetalAttributes in c-cpp.ts). (#1121)
  130. '.metal': 'cpp',
  131. // CUDA ≈ C++ plus execution-space specifiers (`__global__` …) and
  132. // `<<<grid, block>>>` kernel-launch syntax: the C++ grammar extracts its
  133. // functions/structs/classes/calls once blankCudaConstructs (pre-parse; gated
  134. // by these extensions OR by content for CUDA living in `.h`/`.hpp` headers —
  135. // see c-cpp.ts) blanks the CUDA-only tokens. (#387)
  136. '.cu': 'cpp',
  137. '.cuh': 'cpp',
  138. '.nix': 'nix',
  139. // XML: file-level tracking; the MyBatis extractor matches `<mapper namespace="...">`
  140. // shape and emits SQL-statement nodes (other XML returns empty).
  141. '.xml': 'xml',
  142. // COBOL: programs (.cbl/.cob) and copybooks (.cpy). Vendored grammar
  143. // (patched yutaro-sakamoto/tree-sitter-cobol) handles fixed-format column
  144. // rules, EXEC CICS/SQL blocks, and standalone copybook fragments.
  145. '.cbl': 'cobol',
  146. '.cob': 'cobol',
  147. '.cobol': 'cobol',
  148. '.cpy': 'cobol',
  149. // VB.NET: vendored grammar (patched govindbanura/tree-sitter-vbnet) — classes,
  150. // modules, interfaces, structures, properties, events, Handles clauses, LINQ.
  151. '.vb': 'vbnet',
  152. // Erlang: modules (.erl) and header files (.hrl). Vendored WhatsApp/
  153. // tree-sitter-erlang grammar (the ELP grammar).
  154. '.erl': 'erlang',
  155. '.hrl': 'erlang',
  156. // escripts parse natively — the grammar has a first-class `shebang` node.
  157. // (`.app`/`.app.src` resource files route via isErlangAppFile below: their
  158. // last-dot extension is too generic for this map.)
  159. '.escript': 'erlang',
  160. // Spring config: `application.properties` / `application-*.properties`. Same
  161. // shape as the `.yml` variants — the YAML/properties extractor emits one node
  162. // per leaf key, and the Spring resolver links `@Value("${k}")` references.
  163. '.properties': 'properties',
  164. // Terraform / OpenTofu / HCL config — tree-sitter-terraform dialect of HCL.
  165. '.tf': 'terraform',
  166. '.tfvars': 'terraform',
  167. '.tofu': 'terraform',
  168. };
  169. /**
  170. * Whether a file is one CodeGraph can parse, based purely on its extension.
  171. * This is the single source of truth for "should we index this file" — derived
  172. * from EXTENSION_MAP so parser support and indexing selection never drift.
  173. *
  174. * `overrides` is the project's validated custom extension → language map (from
  175. * `codegraph.json`); when present its extensions count as indexable in addition
  176. * to the built-ins. Omitting it is byte-identical to the zero-config behavior.
  177. */
  178. export function isSourceFile(filePath: string, overrides?: Record<string, Language>): boolean {
  179. if (isPlayRoutesFile(filePath)) return true; // Play `conf/routes` is extensionless
  180. if (isShopifyLiquidJson(filePath)) return true; // Shopify OS 2.0 JSON templates / section groups
  181. if (isErlangAppFile(filePath)) return true; // OTP `.app`/`.app.src` resource files
  182. const dot = filePath.lastIndexOf('.');
  183. if (dot < 0) return false;
  184. const ext = filePath.slice(dot).toLowerCase();
  185. return ext in EXTENSION_MAP || (!!overrides && ext in overrides);
  186. }
  187. /**
  188. * Shopify OS 2.0 JSON template (`templates/*.json`) or section group
  189. * (`sections/*.json`) — these reference sections by `"type"`, so the Liquid
  190. * extractor links them. (config/ + locales/ JSON have no section refs.)
  191. */
  192. export function isShopifyLiquidJson(filePath: string): boolean {
  193. // Allow nested template dirs (`templates/customers/login.json`), not just
  194. // top-level (`templates/product.json`).
  195. return /(^|\/)(templates|sections)\/.+\.json$/i.test(filePath);
  196. }
  197. /**
  198. * OTP application resource file: `<app>.app.src` (checked into every rebar3/
  199. * erlang.mk app) or its compiled `<app>.app`. Erlang TERMS, not forms — the
  200. * grammar parses them as top-level expressions, and the Erlang extractor's
  201. * application-tuple handler turns `{mod, {Mod, _}}` and `{applications, […]}`
  202. * into entry-module and dependency edges. Routed by full suffix because the
  203. * last-dot extension (`.src`) is far too generic for EXTENSION_MAP.
  204. */
  205. export function isErlangAppFile(filePath: string): boolean {
  206. return /\.app(?:\.src)?$/i.test(filePath);
  207. }
  208. /**
  209. * Play Framework routes file: the extensionless `conf/routes` (and included
  210. * `conf/*.routes`). No grammar — route extraction is done by the Play framework
  211. * resolver, so it's processed through the no-grammar (`yaml`-style) path.
  212. */
  213. export function isPlayRoutesFile(filePath: string): boolean {
  214. return (
  215. filePath === 'conf/routes' ||
  216. filePath.endsWith('/conf/routes') ||
  217. filePath.endsWith('.routes')
  218. );
  219. }
  220. /**
  221. * Caches for loaded grammars and parsers
  222. */
  223. const parserCache = new Map<Language, Parser>();
  224. const languageCache = new Map<Language, WasmLanguage>();
  225. const unavailableGrammarErrors = new Map<Language, string>();
  226. let parserInitialized = false;
  227. /**
  228. * Initialize the tree-sitter WASM runtime. Must be called before loading grammars.
  229. * Does NOT load any grammar WASM files — use loadGrammarsForLanguages() for that.
  230. * Idempotent — safe to call multiple times.
  231. */
  232. export async function initGrammars(): Promise<void> {
  233. if (parserInitialized) return;
  234. await Parser.init();
  235. parserInitialized = true;
  236. }
  237. /**
  238. * Load grammar WASM files for specific languages only.
  239. * Skips languages that are already loaded or have no WASM grammar.
  240. * Must be called after initGrammars().
  241. */
  242. export async function loadGrammarsForLanguages(languages: Language[]): Promise<void> {
  243. if (!parserInitialized) {
  244. await initGrammars();
  245. }
  246. // SFC languages (svelte/vue/astro) have no grammar of their own — their
  247. // extractors delegate <script>/frontmatter content to the TS/JS extractor,
  248. // so those grammars must be loaded even when no plain .ts/.js file is in
  249. // the index set (e.g. a pure-.astro content site).
  250. if (languages.some((l) => l === 'svelte' || l === 'vue' || l === 'astro')) {
  251. languages = [...languages, 'typescript', 'javascript'];
  252. }
  253. // CFML (.cfc/.cfm) delegates bare-script content, <cfscript> tag bodies, and
  254. // <cfquery> SQL bodies to the cfscript/cfquery grammars (see injections.scm in
  255. // tree-sitter-cfml) — load both even when no standalone .cfs file is in the
  256. // index set.
  257. if (languages.some((l) => l === 'cfml')) {
  258. languages = [...languages, 'cfscript', 'cfquery'];
  259. }
  260. // Deduplicate and filter to languages that have WASM grammars and aren't already loaded
  261. const toLoad = [...new Set(languages)].filter(
  262. (lang): lang is GrammarLanguage =>
  263. lang in WASM_GRAMMAR_FILES &&
  264. !languageCache.has(lang) &&
  265. !unavailableGrammarErrors.has(lang)
  266. );
  267. // Load grammars sequentially to avoid web-tree-sitter WASM race condition on Node 20+
  268. // See: https://github.com/tree-sitter/tree-sitter/issues/2338
  269. for (const lang of toLoad) {
  270. const wasmFile = WASM_GRAMMAR_FILES[lang];
  271. try {
  272. // Some grammars ship their own WASMs (not in tree-sitter-wasms, or the
  273. // tree-sitter-wasms build is too old). Lua: tree-sitter-wasms ships an
  274. // ABI-13 build that corrupts the shared WASM heap under web-tree-sitter
  275. // 0.25 (drops nested calls/imports on every file after the first); we
  276. // vendor the upstream ABI-15 wasm instead. C#: the tree-sitter-wasms
  277. // build (ABI 13) has no primary-constructor support and parses
  278. // `class Foo(...)` as an ERROR that swallows the whole class (#237); we
  279. // vendor the upstream ABI-15 tree-sitter-c-sharp 0.23.5 wasm, which parses
  280. // primary constructors natively. Terraform: tree-sitter-wasms does not
  281. // ship HCL/Terraform at all, so we vendor the prebuilt
  282. // tree-sitter-terraform.wasm from @tree-sitter-grammars/tree-sitter-hcl
  283. // 1.2.0 (Apache-2.0) — byte-identical to the npm package's artifact.
  284. // ArkTS: tree-sitter-wasms doesn't ship it either; we vendor the prebuilt
  285. // tree-sitter-arkts.wasm from the tree-sitter-arkts 0.2.0 npm package
  286. // (harmony-contrib/tree-sitter-arkts, MIT) — byte-identical to the npm
  287. // tarball's artifact. It extends the tree-sitter-javascript grammar the
  288. // same way tree-sitter-typescript does, adding `struct_declaration` and
  289. // the `arkui_component_expression` build() DSL.
  290. // Nix: tree-sitter-wasms doesn't ship it; we vendor a wasm built from
  291. // nix-community/tree-sitter-nix @ 3d0173d (MIT) with tree-sitter-cli
  292. // 0.25.10 (`generate` + `build --wasm`, ABI 15 — upstream's checked-in
  293. // parser.c is still ABI 13; all 54 upstream corpus tests pass on the
  294. // regenerated parser).
  295. const wasmPath = (lang === 'pascal' || lang === 'scala' || lang === 'lua' || lang === 'luau' || lang === 'csharp' || lang === 'r' || lang === 'cfml' || lang === 'cfscript' || lang === 'cfquery' || lang === 'cobol' || lang === 'vbnet' || lang === 'erlang' || lang === 'terraform' || lang === 'arkts' || lang === 'nix')
  296. ? path.join(__dirname, 'wasm', wasmFile)
  297. : require.resolve(`tree-sitter-wasms/out/${wasmFile}`);
  298. const language = await WasmLanguage.load(wasmPath);
  299. languageCache.set(lang, language);
  300. } catch (error) {
  301. const message = error instanceof Error ? error.message : String(error);
  302. console.warn(`[CodeGraph] Failed to load ${lang} grammar — parsing will be unavailable: ${message}`);
  303. unavailableGrammarErrors.set(lang, message);
  304. }
  305. }
  306. }
  307. /**
  308. * Load ALL grammar WASM files. Convenience function for tests and
  309. * backward compatibility. Prefer loadGrammarsForLanguages() in production.
  310. */
  311. export async function loadAllGrammars(): Promise<void> {
  312. const allLanguages = Object.keys(WASM_GRAMMAR_FILES) as GrammarLanguage[];
  313. await loadGrammarsForLanguages(allLanguages);
  314. }
  315. /**
  316. * Check if grammars have been initialized
  317. */
  318. export function isGrammarsInitialized(): boolean {
  319. return parserInitialized;
  320. }
  321. /**
  322. * Get a parser for the specified language.
  323. * Returns synchronously from pre-loaded cache.
  324. */
  325. export function getParser(language: Language): Parser | null {
  326. if (parserCache.has(language)) {
  327. return parserCache.get(language)!;
  328. }
  329. const lang = languageCache.get(language);
  330. if (!lang) {
  331. return null;
  332. }
  333. const parser = new Parser();
  334. parser.setLanguage(lang);
  335. parserCache.set(language, parser);
  336. return parser;
  337. }
  338. /**
  339. * Detect language from file extension.
  340. *
  341. * `overrides` is the project's validated custom extension → language map (from
  342. * `codegraph.json`); when present its mappings take precedence over the built-in
  343. * `EXTENSION_MAP`. Omitting it is byte-identical to the zero-config behavior.
  344. */
  345. export function detectLanguage(filePath: string, source?: string, overrides?: Record<string, Language>): Language {
  346. // Play `conf/routes` has no grammar — route through the no-symbol path; the
  347. // Play framework resolver extracts route nodes from it.
  348. if (isPlayRoutesFile(filePath)) return 'yaml';
  349. const ext = filePath.substring(filePath.lastIndexOf('.')).toLowerCase();
  350. // Shopify OS 2.0 JSON templates / section groups → the Liquid extractor (it
  351. // links each section `"type"` to its `sections/<type>.liquid`).
  352. if (isShopifyLiquidJson(filePath)) return 'liquid';
  353. // OTP `.app`/`.app.src` resource files — Erlang terms the grammar parses as
  354. // top-level expressions (last-dot ext `.src` is too generic for the map).
  355. if (isErlangAppFile(filePath)) return 'erlang';
  356. const lang = (overrides && overrides[ext]) || EXTENSION_MAP[ext] || 'unknown';
  357. // .h files could be C, C++, or Objective-C — check source content
  358. if (lang === 'c' && ext === '.h' && source) {
  359. if (looksLikeCpp(source)) return 'cpp';
  360. if (looksLikeObjc(source)) return 'objc';
  361. }
  362. return lang;
  363. }
  364. /**
  365. * Heuristic: does a .h file contain C++ constructs?
  366. * Checks the first ~8KB for patterns that are unique to C++ and never valid C.
  367. */
  368. function looksLikeCpp(source: string): boolean {
  369. const sample = source.substring(0, 8192);
  370. return /\bnamespace\b|\bclass\s+\w+\s*[:{]|\btemplate\s*<|\b(?:public|private|protected)\s*:|\bvirtual\b|\busing\s+(?:namespace\b|\w+\s*=)/.test(sample);
  371. }
  372. /**
  373. * Heuristic: does a .h file contain Objective-C constructs?
  374. */
  375. function looksLikeObjc(source: string): boolean {
  376. const sample = source.substring(0, 8192);
  377. return /@(?:interface|implementation|protocol|synthesize)\b/.test(sample);
  378. }
  379. /**
  380. * Check if a language is supported (has a grammar defined).
  381. * Returns true if the grammar exists, even if not yet loaded.
  382. */
  383. export function isLanguageSupported(language: Language): boolean {
  384. if (language === 'svelte') return true; // custom extractor (script block delegation)
  385. if (language === 'vue') return true; // custom extractor (script block delegation)
  386. if (language === 'astro') return true; // custom extractor (frontmatter/script block delegation)
  387. if (language === 'liquid') return true; // custom regex extractor
  388. if (language === 'razor') return true; // custom RazorExtractor (.cshtml/.razor markup)
  389. if (language === 'yaml') return true; // file-level tracking only; Drupal routing extraction via framework resolver
  390. if (language === 'twig') return true; // file-level tracking only
  391. if (language === 'xml') return true; // MyBatis mapper extractor
  392. if (language === 'properties') return true; // Spring config keys
  393. if (language === 'unknown') return false;
  394. return language in WASM_GRAMMAR_FILES;
  395. }
  396. /**
  397. * Check if a grammar has been loaded and is ready for parsing.
  398. */
  399. export function isGrammarLoaded(language: Language): boolean {
  400. if (language === 'svelte' || language === 'vue' || language === 'astro' || language === 'liquid' || language === 'razor') return true;
  401. if (language === 'yaml' || language === 'twig') return true; // no WASM grammar needed
  402. if (language === 'xml' || language === 'properties') return true; // no WASM grammar needed
  403. return languageCache.has(language);
  404. }
  405. /**
  406. * Languages tracked at the file-record level only: parsing emits zero symbol
  407. * nodes, but the file is still stored (and framework resolvers may add per-file
  408. * references later, e.g. Drupal routing yml, Spring `@Value` against
  409. * application.properties). This is the canonical set behind the no-symbol
  410. * branch in `tree-sitter.ts`; `xml` is intentionally excluded because its
  411. * MyBatis extractor emits a file node. Callers use this to count such files as
  412. * indexed rather than skipped, so it must stay in sync with that branch.
  413. */
  414. export function isFileLevelOnlyLanguage(language: Language): boolean {
  415. return language === 'yaml' || language === 'twig' || language === 'properties';
  416. }
  417. /**
  418. * Get all supported languages (those with grammar definitions).
  419. */
  420. export function getSupportedLanguages(): Language[] {
  421. return [...(Object.keys(WASM_GRAMMAR_FILES) as GrammarLanguage[]), 'svelte', 'vue', 'astro', 'liquid'];
  422. }
  423. /**
  424. * Reset the cached parser for a language to reclaim WASM heap memory.
  425. * The tree-sitter WASM runtime accumulates fragmented memory over thousands
  426. * of parses. Deleting and recreating the Parser instance forces the WASM
  427. * heap to reset, preventing "memory access out of bounds" crashes in
  428. * large repos.
  429. */
  430. export function resetParser(language: Language): void {
  431. const old = parserCache.get(language);
  432. if (old) {
  433. old.delete();
  434. parserCache.delete(language);
  435. }
  436. }
  437. /**
  438. * Clear parser/grammar caches (useful for testing)
  439. */
  440. export function clearParserCache(): void {
  441. for (const parser of parserCache.values()) {
  442. parser.delete();
  443. }
  444. parserCache.clear();
  445. // Note: languageCache is NOT cleared — WASM languages persist.
  446. // To fully re-init, set parserInitialized = false and call initGrammars() again.
  447. unavailableGrammarErrors.clear();
  448. }
  449. /**
  450. * Report grammars that failed to load.
  451. */
  452. export function getUnavailableGrammarErrors(): Partial<Record<Language, string>> {
  453. const out: Partial<Record<Language, string>> = {};
  454. for (const [language, message] of unavailableGrammarErrors.entries()) {
  455. out[language] = message;
  456. }
  457. return out;
  458. }
  459. /**
  460. * Get language display name
  461. */
  462. export function getLanguageDisplayName(language: Language): string {
  463. const names: Record<Language, string> = {
  464. typescript: 'TypeScript',
  465. javascript: 'JavaScript',
  466. tsx: 'TypeScript (TSX)',
  467. jsx: 'JavaScript (JSX)',
  468. python: 'Python',
  469. go: 'Go',
  470. rust: 'Rust',
  471. r: 'R',
  472. java: 'Java',
  473. c: 'C',
  474. cpp: 'C++',
  475. csharp: 'C#',
  476. razor: 'Razor/Blazor',
  477. php: 'PHP',
  478. ruby: 'Ruby',
  479. swift: 'Swift',
  480. kotlin: 'Kotlin',
  481. dart: 'Dart',
  482. svelte: 'Svelte',
  483. vue: 'Vue',
  484. astro: 'Astro',
  485. liquid: 'Liquid',
  486. pascal: 'Pascal / Delphi',
  487. scala: 'Scala',
  488. lua: 'Lua',
  489. luau: 'Luau',
  490. objc: 'Objective-C',
  491. solidity: 'Solidity',
  492. nix: 'Nix',
  493. yaml: 'YAML',
  494. twig: 'Twig',
  495. xml: 'XML',
  496. properties: 'Java properties',
  497. cfml: 'CFML',
  498. cfscript: 'CFScript',
  499. cfquery: 'CFQuery (SQL)',
  500. cobol: 'COBOL',
  501. vbnet: 'Visual Basic .NET',
  502. erlang: 'Erlang',
  503. terraform: 'Terraform',
  504. arkts: 'ArkTS',
  505. unknown: 'Unknown',
  506. };
  507. return names[language] || language;
  508. }