Skip to main content

meta_language/
grammar_concepts.rs

1//! The concepts of the native grammars (requirement
2//! I195-GRAMMAR-SHARED-CONCEPTS): every rule of every native grammar names a
3//! canonical concept record with `(concept ID)`, and the record carries a
4//! `native:<language>` source alias for each rule that names it. A concept
5//! that two or more native grammars name is shared; a concept that one grammar
6//! names is specific to that language. A construct translates from one native
7//! grammar to another through its concept record alone, with no rule for the
8//! pair of languages. This is the port of `js/src/grammar-concepts.js`.
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::sync::{Mutex, OnceLock};
12
13use crate::concept_records::concept_records_for_source_name;
14use crate::decorators::{
15    DecoratorError, DecoratorLevel, DecoratorSet, decorator_record, record_field,
16};
17use crate::language_catalog::{native_grammar, native_grammars};
18use crate::native_grammar_parser::{native_grammar_text, native_parser};
19use crate::{ConceptRecord, FeatureParseOptions, SyntaxTree, concept_records, parse_grammar_links};
20
21const NATIVE_SOURCE_PREFIX: &str = "native:";
22
23/// A rule of a native grammar and the concept it names.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct NativeRuleConcept {
26    /// The rule name.
27    pub rule: String,
28    /// The concept identity the rule names, or `None` when it names none.
29    pub concept: Option<String>,
30}
31
32/// What is wrong with the concept of a native grammar rule.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum NativeConceptProblemKind {
35    /// The rule names no concept.
36    RuleWithoutConcept,
37    /// No record has the concept the rule names.
38    ConceptWithoutRecord,
39    /// The record of the rule's concept has no source alias for the rule.
40    RuleWithoutAlias,
41    /// A record has a source alias for a rule that does not name it.
42    AliasWithoutRule,
43    /// The rule names a concept in another language's namespace.
44    NamespaceMismatch,
45}
46
47impl NativeConceptProblemKind {
48    /// The kebab-case name the JavaScript runtime uses.
49    #[must_use]
50    pub const fn as_str(self) -> &'static str {
51        match self {
52            Self::RuleWithoutConcept => "rule-without-concept",
53            Self::ConceptWithoutRecord => "concept-without-record",
54            Self::RuleWithoutAlias => "rule-without-alias",
55            Self::AliasWithoutRule => "alias-without-rule",
56            Self::NamespaceMismatch => "namespace-mismatch",
57        }
58    }
59}
60
61/// One problem `check_native_grammar_concepts` finds.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct NativeConceptProblem {
64    /// What is wrong.
65    pub kind: NativeConceptProblemKind,
66    /// The native grammar id, such as `native-json`.
67    pub grammar: String,
68    /// The rule name.
69    pub rule: String,
70    /// The concept identity involved, if any.
71    pub concept: Option<String>,
72}
73
74/// The id of every native grammar of the catalog, sorted.
75#[must_use]
76pub fn native_grammar_ids() -> Vec<&'static str> {
77    let mut ids: Vec<&'static str> = native_grammars()
78        .iter()
79        .map(|grammar| grammar.id.as_str())
80        .collect();
81    ids.sort_unstable();
82    ids
83}
84
85/// The language of the native grammar `id`, its file name: `json` for
86/// `native-json`.
87#[must_use]
88pub fn native_grammar_language(id: &str) -> Option<&'static str> {
89    let file = native_grammar(id)?.file.as_str();
90    let name = file.rsplit('/').next().unwrap_or(file);
91    Some(name.strip_suffix(".lino").unwrap_or(name))
92}
93
94/// The source concept records name the rules of the native grammar `id`
95/// under: `native:json`.
96#[must_use]
97pub fn native_grammar_source(id: &str) -> Option<String> {
98    native_grammar_language(id).map(|language| format!("{NATIVE_SOURCE_PREFIX}{language}"))
99}
100
101/// Every rule of the native grammar `id` with the concept it names, in
102/// grammar order; empty for an id that names no native grammar.
103#[must_use]
104pub fn native_grammar_rule_concepts(id: &str) -> Vec<NativeRuleConcept> {
105    static RULES: OnceLock<Mutex<BTreeMap<String, Vec<NativeRuleConcept>>>> = OnceLock::new();
106    let Some(text) = native_grammar_text(id) else {
107        return Vec::new();
108    };
109    let rules = RULES.get_or_init(|| Mutex::new(BTreeMap::new()));
110    if let Some(found) = rules
111        .lock()
112        .expect("the rule summary cache is available")
113        .get(id)
114    {
115        return found.clone();
116    }
117    let found = parse_grammar_links(text)
118        .map(|grammar| {
119            grammar
120                .rules()
121                .iter()
122                .map(|rule| NativeRuleConcept {
123                    rule: rule.name.clone(),
124                    concept: rule.concept.clone(),
125                })
126                .collect::<Vec<_>>()
127        })
128        .unwrap_or_default();
129    rules
130        .lock()
131        .expect("the rule summary cache is available")
132        .insert(id.to_owned(), found.clone());
133    found
134}
135
136// The language a concept identity is specific to by its namespace:
137// `grammar.diff.hunk` belongs to diff.
138fn namespace_language<'a>(concept: &'a str, languages: &BTreeSet<&str>) -> Option<&'a str> {
139    let parts: Vec<&str> = concept.split('.').collect();
140    (parts.len() > 2 && languages.contains(parts[1])).then(|| parts[1])
141}
142
143/// Checks the concepts of every rule of every native grammar.
144///
145/// Every rule names a concept that has a record, the records' native source
146/// aliases are exactly the rules that name them, and a concept in a language
147/// namespace (`grammar.diff.…`) is named by that language alone.
148#[must_use]
149pub fn check_native_grammar_concepts() -> Vec<NativeConceptProblem> {
150    check_native_grammar_concepts_in(
151        concept_records(),
152        &native_grammar_ids(),
153        &native_grammar_rule_concepts,
154    )
155}
156
157/// `check_native_grammar_concepts` over the records `records`, the native
158/// grammars `grammars` and the rule concepts `rule_concepts` gives each.
159#[must_use]
160pub fn check_native_grammar_concepts_in(
161    records: &[ConceptRecord],
162    grammars: &[&str],
163    rule_concepts: &dyn Fn(&str) -> Vec<NativeRuleConcept>,
164) -> Vec<NativeConceptProblem> {
165    let by_id: BTreeMap<&str, &ConceptRecord> = records
166        .iter()
167        .map(|record| (record.id.as_str(), record))
168        .collect();
169    let languages: BTreeSet<&str> = grammars
170        .iter()
171        .filter_map(|id| native_grammar_language(id))
172        .collect();
173    let mut problems = Vec::new();
174    for &grammar in grammars {
175        let (Some(source), Some(language)) = (
176            native_grammar_source(grammar),
177            native_grammar_language(grammar),
178        ) else {
179            continue;
180        };
181        let problem = |kind, rule: &str, concept: Option<&str>| NativeConceptProblem {
182            kind,
183            grammar: grammar.to_owned(),
184            rule: rule.to_owned(),
185            concept: concept.map(str::to_owned),
186        };
187        let mut named = BTreeMap::new();
188        for NativeRuleConcept { rule, concept } in rule_concepts(grammar) {
189            let Some(concept) = concept else {
190                problems.push(problem(
191                    NativeConceptProblemKind::RuleWithoutConcept,
192                    &rule,
193                    None,
194                ));
195                continue;
196            };
197            let Some(record) = by_id.get(concept.as_str()) else {
198                problems.push(problem(
199                    NativeConceptProblemKind::ConceptWithoutRecord,
200                    &rule,
201                    Some(&concept),
202                ));
203                named.insert(rule, concept);
204                continue;
205            };
206            if !record
207                .source_aliases
208                .iter()
209                .any(|alias| alias.source == source && alias.name == rule)
210            {
211                problems.push(problem(
212                    NativeConceptProblemKind::RuleWithoutAlias,
213                    &rule,
214                    Some(&concept),
215                ));
216            }
217            if namespace_language(&concept, &languages).is_some_and(|owner| owner != language) {
218                problems.push(problem(
219                    NativeConceptProblemKind::NamespaceMismatch,
220                    &rule,
221                    Some(&concept),
222                ));
223            }
224            named.insert(rule, concept);
225        }
226        for record in records {
227            for alias in &record.source_aliases {
228                if alias.source == source && named.get(&alias.name) != Some(&record.id) {
229                    problems.push(problem(
230                        NativeConceptProblemKind::AliasWithoutRule,
231                        &alias.name,
232                        Some(&record.id),
233                    ));
234                }
235            }
236        }
237    }
238    problems
239}
240
241/// A rule that names a concept two or more native grammars name.
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub struct SharedRule {
244    /// The rule name.
245    pub rule: String,
246    /// The shared concept identity.
247    pub concept: String,
248    /// The languages whose native grammars name the concept, sorted.
249    pub languages: Vec<String>,
250}
251
252/// A rule that names a concept only its own native grammar names.
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub struct SpecificRule {
255    /// The rule name.
256    pub rule: String,
257    /// The language-specific concept identity.
258    pub concept: String,
259}
260
261/// The reuse of one native grammar: its rules split into shared and
262/// language-specific ones.
263#[derive(Debug, Clone, PartialEq, Eq)]
264pub struct GrammarConceptReuse {
265    /// The native grammar id.
266    pub grammar: String,
267    /// The language of the grammar.
268    pub language: String,
269    /// The number of rules.
270    pub rules: usize,
271    /// The rules that name a shared concept.
272    pub shared: Vec<SharedRule>,
273    /// The rules that name a language-specific concept.
274    pub specific: Vec<SpecificRule>,
275}
276
277/// A concept the native grammars name, with the languages that name it.
278#[derive(Debug, Clone, PartialEq, Eq)]
279pub struct ConceptReuse {
280    /// The concept identity.
281    pub concept: String,
282    /// The languages whose native grammars name the concept, sorted.
283    pub languages: Vec<String>,
284    /// Whether two or more languages name the concept.
285    pub shared: bool,
286}
287
288/// The per-language reuse report of the native grammars.
289#[derive(Debug, Clone, PartialEq, Eq)]
290pub struct NativeConceptReuse {
291    /// The reuse of each native grammar, by grammar id.
292    pub grammars: Vec<GrammarConceptReuse>,
293    /// Every concept the native grammars name, by identity.
294    pub concepts: Vec<ConceptReuse>,
295}
296
297/// The per-language reuse report of the native grammars.
298///
299/// For every native grammar, its rules split into those that name a shared
300/// concept (one two or more native grammars name, listed with those
301/// languages) and those that name a concept specific to that language; and
302/// every concept the native grammars name with the languages that name it.
303#[must_use]
304pub fn native_grammar_concept_reuse() -> NativeConceptReuse {
305    let grammars = native_grammar_ids();
306    let language_of: BTreeMap<String, &str> = grammars
307        .iter()
308        .filter_map(|id| Some((native_grammar_source(id)?, native_grammar_language(id)?)))
309        .collect();
310    let mut languages: BTreeMap<&str, Vec<String>> = BTreeMap::new();
311    for record in concept_records() {
312        let named: BTreeSet<&str> = record
313            .source_aliases
314            .iter()
315            .filter_map(|alias| language_of.get(&alias.source).copied())
316            .collect();
317        if !named.is_empty() {
318            languages.insert(&record.id, named.into_iter().map(str::to_owned).collect());
319        }
320    }
321    let report = grammars
322        .iter()
323        .map(|&grammar| {
324            let mut shared = Vec::new();
325            let mut specific = Vec::new();
326            for NativeRuleConcept { rule, concept } in native_grammar_rule_concepts(grammar) {
327                let concept = concept.unwrap_or_default();
328                match languages.get(concept.as_str()) {
329                    Some(named) if named.len() > 1 => shared.push(SharedRule {
330                        rule,
331                        concept,
332                        languages: named.clone(),
333                    }),
334                    _ => specific.push(SpecificRule { rule, concept }),
335                }
336            }
337            GrammarConceptReuse {
338                grammar: grammar.to_owned(),
339                language: native_grammar_language(grammar)
340                    .unwrap_or_default()
341                    .to_owned(),
342                rules: shared.len() + specific.len(),
343                shared,
344                specific,
345            }
346        })
347        .collect();
348    let concepts = languages
349        .into_iter()
350        .map(|(concept, named)| ConceptReuse {
351            concept: concept.to_owned(),
352            shared: named.len() > 1,
353            languages: named,
354        })
355        .collect();
356    NativeConceptReuse {
357        grammars: report,
358        concepts,
359    }
360}
361
362/// How a construct translates from one native grammar to another.
363#[derive(Debug, Clone, Copy, PartialEq, Eq)]
364pub enum ConstructTranslationRelation {
365    /// The target grammar names one rule with the construct's concept.
366    Translated,
367    /// The target grammar names no rule with the construct's concept.
368    Untranslatable,
369    /// Several records name the rule, or the target names several rules.
370    Ambiguous,
371    /// No record names the rule.
372    Unknown,
373}
374
375impl ConstructTranslationRelation {
376    /// The name the JavaScript runtime uses.
377    #[must_use]
378    pub const fn as_str(self) -> &'static str {
379        match self {
380            Self::Translated => "translated",
381            Self::Untranslatable => "untranslatable",
382            Self::Ambiguous => "ambiguous",
383            Self::Unknown => "unknown",
384        }
385    }
386
387    /// The relation the JavaScript runtime names `name`.
388    #[must_use]
389    pub fn parse(name: &str) -> Option<Self> {
390        [
391            Self::Translated,
392            Self::Untranslatable,
393            Self::Ambiguous,
394            Self::Unknown,
395        ]
396        .into_iter()
397        .find(|relation| relation.as_str() == name)
398    }
399}
400
401/// The translation of one construct between native grammars.
402#[derive(Debug, Clone, PartialEq, Eq)]
403pub struct ConstructTranslation {
404    /// How the construct translates.
405    pub relation: ConstructTranslationRelation,
406    /// The concept the translation went through.
407    pub concept: Option<String>,
408    /// The rules of the target grammar that name the concept.
409    pub rules: Vec<String>,
410}
411
412/// Translates the rule `rule` of the native grammar `from` to `to`.
413///
414/// The translation goes through the concept record whose source alias names
415/// the rule, then that record's alias in the target grammar. No rule for the
416/// pair of languages takes part.
417#[must_use]
418pub fn translate_native_construct(from: &str, rule: &str, to: &str) -> ConstructTranslation {
419    translate_native_construct_in(concept_records(), from, rule, to)
420}
421
422/// `translate_native_construct` over the records `records`.
423#[must_use]
424pub fn translate_native_construct_in(
425    records: &[ConceptRecord],
426    from: &str,
427    rule: &str,
428    to: &str,
429) -> ConstructTranslation {
430    let unknown = ConstructTranslation {
431        relation: ConstructTranslationRelation::Unknown,
432        concept: None,
433        rules: Vec::new(),
434    };
435    let (Some(source), Some(target)) = (native_grammar_source(from), native_grammar_source(to))
436    else {
437        return unknown;
438    };
439    let meanings: Vec<&ConceptRecord> = if std::ptr::eq(records, concept_records()) {
440        concept_records_for_source_name(&source, rule)
441    } else {
442        records
443            .iter()
444            .filter(|record| {
445                record
446                    .source_aliases
447                    .iter()
448                    .any(|alias| alias.source == source && alias.name == rule)
449            })
450            .collect()
451    };
452    let record = match meanings.as_slice() {
453        [] => return unknown,
454        [record] => record,
455        _ => {
456            return ConstructTranslation {
457                relation: ConstructTranslationRelation::Ambiguous,
458                ..unknown
459            };
460        }
461    };
462    let rules: Vec<String> = record
463        .source_aliases
464        .iter()
465        .filter(|alias| alias.source == target)
466        .map(|alias| alias.name.clone())
467        .collect();
468    ConstructTranslation {
469        relation: relation_of(&rules),
470        concept: Some(record.id.clone()),
471        rules,
472    }
473}
474
475const fn relation_of(rules: &[String]) -> ConstructTranslationRelation {
476    match rules.len() {
477        1 => ConstructTranslationRelation::Translated,
478        0 => ConstructTranslationRelation::Untranslatable,
479        _ => ConstructTranslationRelation::Ambiguous,
480    }
481}
482
483/// [`translate_native_construct`] after the `concept-mapping` decorators of
484/// `decorators`.
485///
486/// They see the result as `{ from, to, rule, relation,
487/// concept, rules }` (rules joined by spaces): they may change the concept or
488/// the target rules, whose relation then follows from their number unless a
489/// decorator set it, and `drop` makes the construct `unknown`.
490///
491/// # Errors
492///
493/// A [`DecoratorError`] when a decorator sets an unknown relation.
494pub fn translate_native_construct_decorated(
495    from: &str,
496    rule: &str,
497    to: &str,
498    decorators: &DecoratorSet,
499) -> Result<ConstructTranslation, DecoratorError> {
500    let found = translate_native_construct(from, rule, to);
501    if !decorators.has(DecoratorLevel::ConceptMapping) {
502        return Ok(found);
503    }
504    let joined = found.rules.join(" ");
505    let record = decorator_record([
506        ("from", from),
507        ("to", to),
508        ("rule", rule),
509        ("relation", found.relation.as_str()),
510        ("concept", found.concept.as_deref().unwrap_or_default()),
511        ("rules", &joined),
512    ]);
513    let Some(decorated) = decorators.decorate(DecoratorLevel::ConceptMapping, &record) else {
514        return Ok(ConstructTranslation {
515            relation: ConstructTranslationRelation::Unknown,
516            concept: None,
517            rules: Vec::new(),
518        });
519    };
520    let rules: Vec<String> = record_field(&decorated, "rules")
521        .split(' ')
522        .filter(|name| !name.is_empty())
523        .map(str::to_owned)
524        .collect();
525    let relation = record_field(&decorated, "relation");
526    let relation =
527        if relation != found.relation.as_str() || record_field(&decorated, "rules") == joined {
528            ConstructTranslationRelation::parse(relation).ok_or_else(|| {
529                DecoratorError::new(format!("a decorator set the unknown relation {relation:?}"))
530            })?
531        } else {
532            relation_of(&rules)
533        };
534    let concept = record_field(&decorated, "concept");
535    Ok(ConstructTranslation {
536        relation,
537        concept: (!concept.is_empty()).then(|| concept.to_owned()),
538        rules,
539    })
540}
541
542/// A node of a construct tree: a node of a native parse tree whose kind is a
543/// rule of the grammar.
544#[derive(Debug, Clone, PartialEq, Eq)]
545pub struct ConstructTree {
546    /// The rule name.
547    pub kind: String,
548    /// The concept the rule names.
549    pub concept: String,
550    /// The constructs inside it.
551    pub children: Vec<Self>,
552}
553
554/// The construct tree of `source` under the native grammar `id`.
555///
556/// It keeps the nodes of the parse tree whose kind is a rule of the grammar,
557/// without trivia, literals and token kinds that are not rules. `None` when
558/// the grammar does not accept the input.
559#[must_use]
560pub fn native_construct_tree(id: &str, source: &str) -> Option<ConstructTree> {
561    let concepts: BTreeMap<String, String> = native_grammar_rule_concepts(id)
562        .into_iter()
563        .filter_map(|NativeRuleConcept { rule, concept }| Some((rule, concept?)))
564        .collect();
565    let outcome = native_parser(id)?
566        .parse_tree(source.as_bytes(), &FeatureParseOptions::default())
567        .ok()?;
568    let tree = outcome.tree?;
569    if !matches!(tree, SyntaxTree::Node { .. }) {
570        return None;
571    }
572    constructs(&tree, &concepts)?.into_iter().next()
573}
574
575fn constructs(
576    node: &SyntaxTree,
577    concepts: &BTreeMap<String, String>,
578) -> Option<Vec<ConstructTree>> {
579    let (kind, children) = match node {
580        SyntaxTree::Node { kind, children, .. } => {
581            let mut inner = Vec::new();
582            for child in children {
583                inner.extend(constructs(child, concepts)?);
584            }
585            (Some(kind), inner)
586        }
587        SyntaxTree::Token {
588            kind,
589            trivia: false,
590            ..
591        } => (kind.as_ref(), Vec::new()),
592        SyntaxTree::Token { .. } | SyntaxTree::Embed { .. } => (None, Vec::new()),
593        SyntaxTree::Error { .. } | SyntaxTree::Missing { .. } => return None,
594    };
595    match kind.and_then(|kind| Some((kind, concepts.get(kind)?))) {
596        Some((kind, concept)) => Some(vec![ConstructTree {
597            kind: kind.clone(),
598            concept: concept.clone(),
599            children,
600        }]),
601        None => Some(children),
602    }
603}
604
605/// A construct of a tree that does not translate.
606#[derive(Debug, Clone, PartialEq, Eq)]
607pub struct ConstructTranslationProblem {
608    /// The rule name in the source grammar.
609    pub kind: String,
610    /// The concept of the construct, if a record names it.
611    pub concept: Option<String>,
612    /// Why it does not translate.
613    pub relation: ConstructTranslationRelation,
614}
615
616/// The translation of a construct tree between native grammars.
617#[derive(Debug, Clone, PartialEq, Eq)]
618pub struct ConstructTreeTranslation {
619    /// The tree with the target rule names, or `None` when a construct does
620    /// not translate.
621    pub tree: Option<ConstructTree>,
622    /// Every construct that does not translate, children first.
623    pub problems: Vec<ConstructTranslationProblem>,
624}
625
626/// Translates a construct tree of the native grammar `from` to the native
627/// grammar `to`, every node through `translate_native_construct`.
628#[must_use]
629pub fn translate_native_construct_tree(
630    tree: &ConstructTree,
631    from: &str,
632    to: &str,
633) -> ConstructTreeTranslation {
634    fn translate(
635        node: &ConstructTree,
636        from: &str,
637        to: &str,
638        problems: &mut Vec<ConstructTranslationProblem>,
639    ) -> Option<ConstructTree> {
640        let translation = translate_native_construct(from, &node.kind, to);
641        let children: Vec<Option<ConstructTree>> = node
642            .children
643            .iter()
644            .map(|child| translate(child, from, to, problems))
645            .collect();
646        if translation.relation != ConstructTranslationRelation::Translated {
647            problems.push(ConstructTranslationProblem {
648                kind: node.kind.clone(),
649                concept: translation.concept,
650                relation: translation.relation,
651            });
652            return None;
653        }
654        Some(ConstructTree {
655            kind: translation.rules[0].clone(),
656            concept: translation.concept.unwrap_or_default(),
657            children: children.into_iter().collect::<Option<Vec<_>>>()?,
658        })
659    }
660    let mut problems = Vec::new();
661    let translated = translate(tree, from, to, &mut problems);
662    ConstructTreeTranslation {
663        tree: if problems.is_empty() {
664            translated
665        } else {
666            None
667        },
668        problems,
669    }
670}