(grammarDir: string)
| 50 | ) => { start: number; end: number; scopes: string[] }[][] |
| 51 | |
| 52 | export const createOracle = async (grammarDir: string): Promise<Tokenize> => { |
| 53 | const engine = await createOnigurumaEngine( |
| 54 | import("@shikijs/engine-oniguruma/wasm-inlined") |
| 55 | ) |
| 56 | const index: GrammarIndex = JSON.parse( |
| 57 | readFileSync(join(grammarDir, "index.json"), "utf8") |
| 58 | ) |
| 59 | const raw = new Map<string, IRawGrammar>() |
| 60 | const loadGrammar = (scopeName: string): IRawGrammar | null => { |
| 61 | const file = index.grammars[scopeName] |
| 62 | if (!file) return null |
| 63 | let grammar = raw.get(scopeName) |
| 64 | if (!grammar) { |
| 65 | grammar = JSON.parse(readFileSync(join(grammarDir, file), "utf8")) |
| 66 | raw.set(scopeName, grammar!) |
| 67 | } |
| 68 | return grammar! |
| 69 | } |
| 70 | const grammars = new Map<string, IGrammar>() |
| 71 | const grammarFor = async (ext: string, ark: boolean) => { |
| 72 | const key = `${ext}:${ark}` |
| 73 | const cached = grammars.get(key) |
| 74 | if (cached) return cached |
| 75 | const host = index.hosts[ext] |
| 76 | if (!host) throw new Error(`No TextMate host for .${ext}`) |
| 77 | const injections = new Map( |
| 78 | Object.entries(host.injections).map(([target, scopes]) => [ |
| 79 | target, |
| 80 | ark ? scopes : scopes.filter(s => s !== arkInjectionScope) |
| 81 | ]) |
| 82 | ) |
| 83 | const registry = new Registry({ |
| 84 | onigLib: { |
| 85 | createOnigScanner: sources => engine.createScanner(sources), |
| 86 | createOnigString: s => engine.createString(s) |
| 87 | }, |
| 88 | loadGrammar, |
| 89 | // VS Code's TMGrammarFactory: a grammar injected into `a.b` also |
| 90 | // applies to `a.b.c`, so every prefix of the scope is looked up |
| 91 | getInjections: scopeName => { |
| 92 | const parts = scopeName.split(".") |
| 93 | return parts.flatMap( |
| 94 | (_, i) => injections.get(parts.slice(0, i + 1).join(".")) ?? [] |
| 95 | ) |
| 96 | } |
| 97 | }) |
| 98 | const grammar = await registry.loadGrammar(host.scopeName) |
| 99 | if (!grammar) throw new Error(`Couldn't load ${host.scopeName}`) |
| 100 | grammars.set(key, grammar) |
| 101 | return grammar |
| 102 | } |
| 103 | for (const ext of Object.keys(index.hosts)) { |
| 104 | await grammarFor(ext, true) |
| 105 | await grammarFor(ext, false) |
| 106 | } |
| 107 | return (source, ext, ark) => { |
| 108 | const grammar = grammars.get(`${ext}:${ark}`) |
| 109 | if (!grammar) throw new Error(`No TextMate host for .${ext}`) |
no test coverage detected