Skip to main content

meta_language/
concept_distinctions.rs

1//! Which concepts are shared across languages, and which must stay distinct.
2//!
3//! Two source spellings name one concept only under a one-to-one
4//! correspondence of meaning: each spelling resolves to exactly one concept
5//! record or foundation model, and it is the same one. The same spelling with
6//! different meanings, such as `|` in pest (ordered choice) and in BNF
7//! (unordered choice), or `panic!` in Rust (abort) and in Lean (a default
8//! value), never merges. Ordered and unordered choice, lexical and syntactic
9//! precedence, binding and assignment, and the integer, overflow, effect,
10//! universe, proof and logic models the foundation register keeps apart are
11//! required distinctions the check below enforces. The JavaScript twin is
12//! `js/src/concept-distinctions.js`.
13
14use std::collections::BTreeSet;
15
16use crate::concept_records::{
17    ConceptRecord, SourceAlias, concept_record, concept_records, concept_records_for_source_name,
18};
19use crate::foundation_models::{FoundationRegister, foundation_register};
20use crate::grammar::{Grammar, GrammarExpr, RuleKind};
21
22/// Two concepts that must never be merged, with the reason.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct RequiredDistinction {
25    /// The identities of the two concepts.
26    pub concepts: [&'static str; 2],
27    /// What distinguishes them.
28    pub reason: &'static str,
29}
30
31/// The concept pairs that stay distinct in every grammar and program.
32pub const REQUIRED_CONCEPT_DISTINCTIONS: &[RequiredDistinction] =
33    include!("data/required-concept-distinctions.rs");
34
35/// The foundation model pairs that stay distinct; the register records the reason for each.
36pub const REQUIRED_FOUNDATION_DISTINCTIONS: &[[&str; 2]] = &[
37    [
38        "integer-model.natural-number",
39        "integer-model.unbounded-integer",
40    ],
41    ["overflow-model.abort", "overflow-model.wrapping"],
42    [
43        "effect-model.abort",
44        "effect-model.panic-with-default-value",
45    ],
46    [
47        "universe-model.non-cumulative-sort-hierarchy",
48        "universe-model.cumulative-type-hierarchy",
49    ],
50    [
51        "proof-system.bounded-property-check",
52        "proof-system.lean-kernel",
53    ],
54    [
55        "logic-model.constructive-propositions",
56        "logic-model.classical-propositions",
57    ],
58];
59
60/// How two source spellings relate.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum CorrespondenceRelation {
63    /// Both spellings mean exactly one concept, and it is the same concept.
64    Shared,
65    /// Both spellings mean exactly one concept, and the concepts differ.
66    Distinct,
67    /// A spelling means more than one concept, so no correspondence follows from the spelling alone.
68    Ambiguous,
69    /// A spelling means no recorded concept.
70    Unknown,
71}
72
73impl CorrespondenceRelation {
74    /// The relation's name, the same string the JavaScript runtime reports.
75    #[must_use]
76    pub const fn as_str(self) -> &'static str {
77        match self {
78            Self::Shared => "shared",
79            Self::Distinct => "distinct",
80            Self::Ambiguous => "ambiguous",
81            Self::Unknown => "unknown",
82        }
83    }
84}
85
86/// The relation between two source spellings and what justifies it.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct ConceptCorrespondence {
89    /// How the two spellings relate.
90    pub relation: CorrespondenceRelation,
91    /// The concepts and models the first spelling means.
92    pub first: Vec<String>,
93    /// The concepts and models the second spelling means.
94    pub second: Vec<String>,
95    /// The concept both spellings mean, when the relation is shared.
96    pub shared: Option<String>,
97    /// The definition of the shared concept, or the recorded reason two distinct concepts differ.
98    pub justification: Option<String>,
99    /// The kind of the recorded correspondence between two distinct foundation models.
100    pub correspondence: Option<String>,
101}
102
103/// A way the records fail to keep required distinctions or justify a shared concept.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct ConceptDistinctionProblem {
106    /// The problem kind, the same string the JavaScript runtime reports, such as `indistinct-concepts`.
107    pub kind: &'static str,
108    /// The concept, model or pair the problem is about.
109    pub subject: String,
110    /// A readable explanation.
111    pub message: String,
112}
113
114/// One use of precedence in a grammar and the concept it expresses.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct PrecedenceUse {
117    /// The rule the precedence appears in.
118    pub rule: String,
119    /// The precedence label, such as `prec=1` or `prec_left=2`.
120    pub label: String,
121    /// `grammar.lexical-precedence` inside a token, `grammar.syntactic-precedence` elsewhere.
122    pub concept: &'static str,
123}
124
125fn within_matches(id: &str, within: Option<&str>) -> bool {
126    within.is_none_or(|prefix| {
127        id == prefix
128            || id
129                .strip_prefix(prefix)
130                .is_some_and(|rest| rest.starts_with('.'))
131    })
132}
133
134/// Returns the concepts and foundation models a source spelling means, optionally only those under `within`.
135///
136/// A concept record matches an alias with the same source and name; a
137/// foundation model matches when its alias for the source lists the name among
138/// its comma-separated spellings.
139#[must_use]
140pub fn source_meanings_in(
141    records: &[ConceptRecord],
142    register: &FoundationRegister,
143    alias: &SourceAlias,
144    within: Option<&str>,
145) -> Vec<String> {
146    // Only the immutable embedded register has a process-local alias index.
147    // Caller-owned slices are inspected anew, including nested alias changes.
148    let concepts: Vec<&ConceptRecord> = if std::ptr::eq(records, concept_records()) {
149        concept_records_for_source_name(&alias.source, &alias.name)
150    } else {
151        records
152            .iter()
153            .filter(|record| {
154                record.source_aliases.iter().any(|candidate| {
155                    candidate.source == alias.source && candidate.name == alias.name
156                })
157            })
158            .collect()
159    };
160    let models = register.models.iter().filter(|model| {
161        model.source_aliases.iter().any(|candidate| {
162            candidate.source == alias.source
163                && candidate
164                    .name
165                    .split(", ")
166                    .any(|spelling| spelling == alias.name)
167        })
168    });
169    concepts
170        .into_iter()
171        .map(|record| record.id.clone())
172        .chain(models.map(|model| model.id.clone()))
173        .filter(|id| within_matches(id, within))
174        .collect()
175}
176
177fn same_pair(pair: &[impl AsRef<str>], first: &str, second: &str) -> bool {
178    pair.len() == 2
179        && ((pair[0].as_ref() == first && pair[1].as_ref() == second)
180            || (pair[0].as_ref() == second && pair[1].as_ref() == first))
181}
182
183fn meaning_definition(
184    records: &[ConceptRecord],
185    register: &FoundationRegister,
186    id: &str,
187) -> Option<String> {
188    let concept = if std::ptr::eq(records, concept_records()) {
189        concept_record(id).filter(|record| record.id == id)
190    } else {
191        records.iter().find(|record| record.id == id)
192    };
193    concept.map(|record| record.definition.clone()).or_else(|| {
194        register
195            .models
196            .iter()
197            .find(|model| model.id == id)
198            .map(|model| model.definition.clone())
199    })
200}
201
202/// Relates two source spellings through the given records and foundation register.
203#[must_use]
204pub fn concept_correspondence_in(
205    records: &[ConceptRecord],
206    register: &FoundationRegister,
207    first: &SourceAlias,
208    second: &SourceAlias,
209    within: Option<&str>,
210) -> ConceptCorrespondence {
211    let first_meanings = source_meanings_in(records, register, first, within);
212    let second_meanings = source_meanings_in(records, register, second, within);
213    let mut result = ConceptCorrespondence {
214        relation: CorrespondenceRelation::Unknown,
215        first: first_meanings.clone(),
216        second: second_meanings.clone(),
217        shared: None,
218        justification: None,
219        correspondence: None,
220    };
221    if first_meanings.is_empty() || second_meanings.is_empty() {
222        return result;
223    }
224    if first_meanings.len() > 1 || second_meanings.len() > 1 {
225        result.relation = CorrespondenceRelation::Ambiguous;
226        return result;
227    }
228    let (one, other) = (&first_meanings[0], &second_meanings[0]);
229    if one == other {
230        result.relation = CorrespondenceRelation::Shared;
231        result.shared = Some(one.clone());
232        result.justification = meaning_definition(records, register, one);
233        return result;
234    }
235    result.relation = CorrespondenceRelation::Distinct;
236    result.justification = REQUIRED_CONCEPT_DISTINCTIONS
237        .iter()
238        .find(|entry| same_pair(&entry.concepts, one, other))
239        .map(|entry| entry.reason.to_owned())
240        .or_else(|| {
241            register
242                .distinctions
243                .iter()
244                .find(|entry| same_pair(&entry.models, one, other))
245                .map(|entry| entry.reason.clone())
246        });
247    result.correspondence = register
248        .correspondences
249        .iter()
250        .find(|entry| same_pair(&[&entry.from, &entry.to], one, other))
251        .map(|entry| entry.kind.clone());
252    result
253}
254
255/// Relates two source spellings through the embedded concept records and foundation register.
256#[must_use]
257pub fn concept_correspondence(
258    first: &SourceAlias,
259    second: &SourceAlias,
260    within: Option<&str>,
261) -> ConceptCorrespondence {
262    concept_correspondence_in(
263        concept_records(),
264        foundation_register(),
265        first,
266        second,
267        within,
268    )
269}
270
271fn shared_sources(aliases: &[SourceAlias]) -> usize {
272    aliases
273        .iter()
274        .map(|alias| alias.source.as_str())
275        .filter(|source| *source != "meta-language" && !source.ends_with(" grammar surface"))
276        .collect::<BTreeSet<_>>()
277        .len()
278}
279
280/// A justification is a sentence of at least three words.
281fn is_justification(text: &str) -> bool {
282    let text = text.trim();
283    text.ends_with('.') && text.split_whitespace().count() >= 3
284}
285
286/// Checks that the records keep every required distinction and justify every shared concept.
287///
288/// A required pair must name two recorded concepts (or models) with different
289/// definitions (or properties) that do not record one another as a former name
290/// or as what they represent, and every required foundation pair must carry a
291/// distinction with its reason in the register. A concept or model several
292/// sources share must state the meaning that justifies sharing it. The kinds
293/// match the JavaScript runtime's `checkConceptDistinctions`; an empty result
294/// means the distinctions hold.
295#[must_use]
296pub fn check_concept_distinctions(
297    records: &[ConceptRecord],
298    register: &FoundationRegister,
299) -> Vec<ConceptDistinctionProblem> {
300    let mut problems = Vec::new();
301    let mut report = |kind, subject: &str, message: String| {
302        problems.push(ConceptDistinctionProblem {
303            kind,
304            subject: subject.to_owned(),
305            message,
306        });
307    };
308    for entry in REQUIRED_CONCEPT_DISTINCTIONS {
309        let subject = entry.concepts.join(" / ");
310        let found: Vec<_> = entry
311            .concepts
312            .iter()
313            .map(|id| records.iter().find(|record| record.id == *id))
314            .collect();
315        for (id, record) in entry.concepts.iter().zip(&found) {
316            if record.is_none() {
317                report(
318                    "unknown-concept",
319                    &subject,
320                    format!("{subject} must stay distinct, but {id} is not recorded"),
321                );
322            }
323        }
324        let [Some(first), Some(second)] = found[..] else {
325            continue;
326        };
327        if first.definition.trim().to_lowercase() == second.definition.trim().to_lowercase() {
328            report(
329                "indistinct-concepts",
330                &subject,
331                format!("{subject} record the same definition, which merges two meanings"),
332            );
333        }
334        for (record, other) in [(first, second), (second, first)] {
335            if record.former_names.contains(&other.id)
336                || record.represents.as_deref() == Some(other.id.as_str())
337            {
338                report(
339                    "conflated-distinction",
340                    &subject,
341                    format!(
342                        "{} records {} as itself, which merges two meanings",
343                        record.id, other.id
344                    ),
345                );
346            }
347        }
348    }
349    for pair in REQUIRED_FOUNDATION_DISTINCTIONS {
350        let subject = pair.join(" / ");
351        let found: Vec<_> = pair
352            .iter()
353            .map(|id| register.models.iter().find(|model| model.id == *id))
354            .collect();
355        for (id, model) in pair.iter().zip(&found) {
356            if model.is_none() {
357                report(
358                    "unknown-model",
359                    &subject,
360                    format!("{subject} must stay distinct, but {id} is not recorded"),
361                );
362            }
363        }
364        if let [Some(first), Some(second)] = found[..]
365            && first.properties == second.properties
366        {
367            report(
368                "indistinct-concepts",
369                &subject,
370                format!("{subject} record the same properties, which merges two meanings"),
371            );
372        }
373        let recorded = register.distinctions.iter().any(|entry| {
374            same_pair(&entry.models, pair[0], pair[1]) && is_justification(&entry.reason)
375        });
376        if !recorded {
377            report(
378                "unrecorded-distinction",
379                &subject,
380                format!("the foundation register records no reason why {subject} differ"),
381            );
382        }
383    }
384    for record in records {
385        if shared_sources(&record.source_aliases) > 1
386            && (!is_justification(&record.definition) || record.constraints.is_empty())
387        {
388            report(
389                "unjustified-sharing",
390                &record.id,
391                format!(
392                    "{} is shared by several sources but states no meaning that justifies the correspondence",
393                    record.id
394                ),
395            );
396        }
397    }
398    for model in &register.models {
399        if shared_sources(&model.source_aliases) > 1
400            && (!is_justification(&model.definition) || model.properties.is_empty())
401        {
402            report(
403                "unjustified-sharing",
404                &model.id,
405                format!(
406                    "{} is shared by several languages but states no meaning that justifies the correspondence",
407                    model.id
408                ),
409            );
410        }
411    }
412    problems
413}
414
415fn is_precedence_label(label: &str) -> bool {
416    ["prec", "prec_left", "prec_right", "prec_dynamic"]
417        .iter()
418        .any(|name| {
419            label == *name
420                || label
421                    .strip_prefix(name)
422                    .is_some_and(|rest| rest.starts_with('='))
423        })
424}
425
426fn collect_precedence(
427    rule: &str,
428    expr: &GrammarExpr,
429    in_token: bool,
430    uses: &mut Vec<PrecedenceUse>,
431) {
432    match expr {
433        GrammarExpr::Capture { label, expr } => {
434            let label = label.as_deref().unwrap_or_default();
435            if is_precedence_label(label) {
436                let lexical = in_token && !label.starts_with("prec_dynamic");
437                uses.push(PrecedenceUse {
438                    rule: rule.to_owned(),
439                    label: label.to_owned(),
440                    concept: if lexical {
441                        "grammar.lexical-precedence"
442                    } else {
443                        "grammar.syntactic-precedence"
444                    },
445                });
446            }
447            let token = in_token || label == "token" || label == "immediate_token";
448            collect_precedence(rule, expr, token, uses);
449        }
450        GrammarExpr::Choice { alternatives, .. } => {
451            for alternative in alternatives {
452                collect_precedence(rule, alternative, in_token, uses);
453            }
454        }
455        GrammarExpr::Sequence(items) => {
456            for item in items {
457                collect_precedence(rule, item, in_token, uses);
458            }
459        }
460        GrammarExpr::Optional(item)
461        | GrammarExpr::ZeroOrMore(item)
462        | GrammarExpr::OneOrMore(item)
463        | GrammarExpr::Repeat { expr: item, .. }
464        | GrammarExpr::And(item)
465        | GrammarExpr::Not(item) => collect_precedence(rule, item, in_token, uses),
466        _ => {}
467    }
468}
469
470/// Returns every precedence use in `grammar` with the concept it expresses.
471///
472/// Precedence inside a token rule or a `token` capture decides between tokens
473/// (lexical precedence); anywhere else, and dynamic precedence everywhere, it
474/// decides between parse alternatives (syntactic precedence). Both runtimes
475/// read tree-sitter's `prec` the same way, so the two never merge.
476#[must_use]
477pub fn grammar_precedence_concepts(grammar: &Grammar) -> Vec<PrecedenceUse> {
478    let mut uses = Vec::new();
479    for rule in grammar.rules() {
480        collect_precedence(
481            rule.name(),
482            rule.expr(),
483            rule.kind() == RuleKind::Token,
484            &mut uses,
485        );
486    }
487    uses
488}