Skip to main content

meta_language/
language_catalog.rs

1//! The registered language catalog shared with the JavaScript runtime.
2//!
3//! `src/data/language-catalog.lino` is generated from
4//! `parity/language-grammar-inventory.json` by
5//! `js/scripts/build-language-catalog.mjs`; the npm package ships the same
6//! file, so both runtimes agree on every alias, file extension, and default
7//! grammar.
8
9use std::collections::BTreeMap;
10use std::sync::OnceLock;
11
12use serde_json::Value;
13
14pub use crate::language_identification::{
15    InvalidLanguageIdentificationThreshold, LanguageCandidate, LanguageIdentification,
16    LanguageIdentificationSpan, identify_language_with_threshold,
17};
18
19const LANGUAGE_CATALOG_LINKS: &str = include_str!("data/language-catalog.lino");
20
21/// A grammar that parses a registered language by default.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct GrammarProvenance {
24    /// Grammar id in the grammar lock, such as `javascript` or `markdown_inline`,
25    /// or a native grammar id of the catalog, such as `native-json`.
26    pub id: String,
27    /// Exact grammar version (crate version or pinned upstream revision).
28    pub version: String,
29    /// SHA-256 of the generated `parser.c` both runtimes compile, or of a
30    /// native grammar's Links Notation text.
31    pub parser_sha256: String,
32}
33
34/// One registered language.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct LanguageEntry {
37    /// Canonical inventory name, such as `JavaScript` or `sql-postgres`.
38    pub name: String,
39    /// Inventory family, such as `programming`, `sql`, or `natural`.
40    pub family: String,
41    /// Case-insensitive aliases accepted wherever a language name is.
42    pub aliases: Vec<String>,
43    /// File extensions (lowercase, with the leading dot) that dispatch here.
44    pub extensions: Vec<String>,
45    /// Grammars that parse the language by default, primary grammar first.
46    pub grammars: Vec<GrammarProvenance>,
47    /// Pinned grammar sources, licenses, scanners and independent corpora.
48    pub grammar_sources: Vec<Value>,
49    /// Language targets embedded in this host language's native regions.
50    pub embedded_languages: Vec<String>,
51    /// Explicit inventoried language versions, separate from grammar releases.
52    pub versions: Option<Value>,
53    /// Explicit inventoried editions, retained without joining their coverage.
54    pub editions: Option<Value>,
55    /// Explicit inventoried dialect boundaries.
56    pub dialects: Option<Value>,
57}
58
59/// Returns every registered language in inventory order.
60#[must_use]
61pub fn language_catalog() -> &'static [LanguageEntry] {
62    static CATALOG: OnceLock<Vec<LanguageEntry>> = OnceLock::new();
63    CATALOG.get_or_init(parse_catalog)
64}
65
66/// Returns the catalog entry for a language name or alias (case-insensitive).
67#[must_use]
68pub fn language_entry(language: &str) -> Option<&'static LanguageEntry> {
69    language_catalog().iter().find(|entry| {
70        entry.name.eq_ignore_ascii_case(language)
71            || entry
72                .aliases
73                .iter()
74                .any(|alias| alias.eq_ignore_ascii_case(language))
75    })
76}
77
78/// Returns the canonical inventory name for a language name or alias.
79#[must_use]
80pub fn canonical_language_name(language: &str) -> Option<&'static str> {
81    language_entry(language).map(|entry| entry.name.as_str())
82}
83
84/// Returns every language registered for a file path, most specific first:
85/// languages whose extension is a longer case-insensitive suffix of the path
86/// come before shorter ones, and ties keep catalog order.
87#[must_use]
88pub fn language_candidates_for_path(path: &str) -> Vec<&'static str> {
89    let lower = path.to_lowercase();
90    let mut candidates: Vec<(usize, usize, &'static str)> = language_catalog()
91        .iter()
92        .enumerate()
93        .filter_map(|(index, entry)| {
94            entry
95                .extensions
96                .iter()
97                .filter(|extension| lower.ends_with(extension.as_str()))
98                .map(String::len)
99                .max()
100                .map(|length| (length, index, entry.name.as_str()))
101        })
102        .collect();
103    candidates.sort_by(|left, right| right.0.cmp(&left.0).then(left.1.cmp(&right.1)));
104    candidates.into_iter().map(|(_, _, name)| name).collect()
105}
106
107/// Returns the language a file path dispatches to.
108#[must_use]
109pub fn language_for_path(path: &str) -> Option<&'static str> {
110    language_candidates_for_path(path).into_iter().next()
111}
112
113/// Returns the grammars that parse a language by default.
114#[must_use]
115pub fn grammar_provenance(language: &str) -> &'static [GrammarProvenance] {
116    language_entry(language).map_or(&[], |entry| entry.grammars.as_slice())
117}
118
119/// Returns the pinned tree-sitter grammars a language's native default
120/// grammar replaced, which stay its oracles; empty for a language without a
121/// native default grammar.
122#[must_use]
123pub fn oracle_grammar_provenance(language: &str) -> &'static [GrammarProvenance] {
124    static ORACLES: OnceLock<Vec<(String, Vec<GrammarProvenance>)>> = OnceLock::new();
125    let Some(entry) = language_entry(language) else {
126        return &[];
127    };
128    ORACLES
129        .get_or_init(|| {
130            catalog_value()["languages"]
131                .as_array()
132                .expect("language catalog lists languages")
133                .iter()
134                .filter(|language| language["oracleGrammars"].is_array())
135                .map(|language| {
136                    (
137                        string(&language["name"]),
138                        provenance(&language["oracleGrammars"]),
139                    )
140                })
141                .collect()
142        })
143        .iter()
144        .find(|(name, _)| *name == entry.name)
145        .map_or(&[], |(_, grammars)| grammars.as_slice())
146}
147
148/// A native Links Notation grammar of the catalog, which parses its languages
149/// by default, with the kinds its tree places as its tree-sitter oracle does.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct NativeGrammarEntry {
152    /// Grammar id, such as `native-json`.
153    pub id: String,
154    /// The grammar file below `src/data/`, such as `native-grammars/json.lino`.
155    pub file: String,
156    /// Leaf kinds the oracle drops, such as a byte order mark.
157    pub hidden: Vec<String>,
158    /// Leaf kinds the oracle keeps inside a node without a node of their own.
159    pub anonymous: Vec<String>,
160    /// Node kinds the oracle marks as extras.
161    pub extras: Vec<String>,
162    /// Whether the root span includes trivia before its first token.
163    pub root_includes_leading_trivia: bool,
164    /// The tree-sitter kind of each rule renamed from it, by rule name.
165    pub oracle_kinds: BTreeMap<String, String>,
166}
167
168/// Returns every native grammar of the catalog.
169#[must_use]
170pub fn native_grammars() -> &'static [NativeGrammarEntry] {
171    static NATIVE: OnceLock<Vec<NativeGrammarEntry>> = OnceLock::new();
172    NATIVE.get_or_init(|| {
173        catalog_value()["nativeGrammars"]
174            .as_object()
175            .map(|grammars| {
176                grammars
177                    .iter()
178                    .map(|(id, grammar)| NativeGrammarEntry {
179                        id: id.clone(),
180                        file: string(&grammar["file"]),
181                        hidden: strings(&grammar["hidden"]),
182                        anonymous: strings(&grammar["anonymous"]),
183                        extras: strings(&grammar["extras"]),
184                        root_includes_leading_trivia: grammar["rootIncludesLeadingTrivia"]
185                            .as_bool()
186                            .unwrap_or(false),
187                        oracle_kinds: grammar["oracleKinds"]
188                            .as_object()
189                            .map(|kinds| {
190                                kinds
191                                    .iter()
192                                    .map(|(name, kind)| (name.clone(), string(kind)))
193                                    .collect()
194                            })
195                            .unwrap_or_default(),
196                    })
197                    .collect()
198            })
199            .unwrap_or_default()
200    })
201}
202
203/// Returns the native grammar of the catalog with id `id`.
204#[must_use]
205pub fn native_grammar(id: &str) -> Option<&'static NativeGrammarEntry> {
206    native_grammars().iter().find(|grammar| grammar.id == id)
207}
208
209fn catalog_value() -> &'static Value {
210    static VALUE: OnceLock<Value> = OnceLock::new();
211    VALUE.get_or_init(|| {
212        crate::structured_data_links::read_structured_data_lino(LANGUAGE_CATALOG_LINKS)
213            .expect("language catalog is valid Links Notation")
214    })
215}
216
217fn provenance(grammars: &Value) -> Vec<GrammarProvenance> {
218    grammars
219        .as_array()
220        .expect("language grammars")
221        .iter()
222        .map(|grammar| GrammarProvenance {
223            id: string(&grammar["id"]),
224            version: string(&grammar["version"]),
225            parser_sha256: string(&grammar["parserSha256"]),
226        })
227        .collect()
228}
229
230fn parse_catalog() -> Vec<LanguageEntry> {
231    catalog_value()["languages"]
232        .as_array()
233        .expect("language catalog lists languages")
234        .iter()
235        .map(|language| LanguageEntry {
236            name: string(&language["name"]),
237            family: string(&language["family"]),
238            aliases: strings(&language["aliases"]),
239            extensions: strings(&language["extensions"]),
240            grammars: provenance(&language["grammars"]),
241            grammar_sources: language["grammarSources"]
242                .as_array()
243                .cloned()
244                .unwrap_or_default(),
245            embedded_languages: language["embeddedLanguages"]
246                .as_array()
247                .map_or_else(Vec::new, |_| strings(&language["embeddedLanguages"])),
248            versions: language.get("versions").cloned(),
249            editions: language.get("editions").cloned(),
250            dialects: language.get("dialects").cloned(),
251        })
252        .collect()
253}
254
255fn string(value: &Value) -> String {
256    value.as_str().expect("language catalog string").to_string()
257}
258
259fn strings(value: &Value) -> Vec<String> {
260    value
261        .as_array()
262        .expect("language catalog array")
263        .iter()
264        .map(string)
265        .collect()
266}