Skip to main content

meta_language/
foundation_models.rs

1//! The foundations meta-language knows, as data.
2//!
3//! `src/data/foundation-models.lino` is written from
4//! `parity/foundation-models.lino` by `js/scripts/build-foundation-models.mjs`;
5//! the npm package ships the same file. It records integer, overflow,
6//! universe, effect, proof and logic models, the models each language uses,
7//! and the explicit correspondences between distinct models. No model is the
8//! universal logic every other model reduces to: a consumer brings its own
9//! foundation and proof authority and relates it to these models through
10//! correspondences.
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::sync::OnceLock;
14
15use serde::Deserialize;
16use serde_json::{Map, Value};
17
18use crate::SourceAlias;
19
20const FOUNDATION_MODELS_LINKS: &str = include_str!("data/foundation-models.lino");
21
22/// The kinds of correspondence between two distinct models; none of them claims the models are the same.
23pub const CORRESPONDENCE_KINDS: [&str; 4] = ["embedding", "conditional", "encoding", "restatement"];
24
25/// The families whose models are logics or proof authorities.
26///
27/// A model of one of them that every other model of its family embeds into, or (beyond the
28/// booleans every language has) that every language is made to use, would be
29/// a hard-coded universal logic.
30pub const LOGIC_FAMILIES: [&str; 3] = ["logic-model", "proof-system", "universe-model"];
31
32/// A family of foundation models, such as `integer-model` or `proof-system`.
33#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
34#[serde(deny_unknown_fields)]
35pub struct FoundationFamily {
36    /// Stable identity of the family.
37    pub id: String,
38    /// What the family's models describe.
39    pub definition: String,
40}
41
42/// One foundation model: a meaning, not a spelling.
43#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
44#[serde(rename_all = "camelCase", deny_unknown_fields)]
45pub struct FoundationModel {
46    /// Stable identity, `<family>.<name>`, such as `overflow-model.wrapping`.
47    pub id: String,
48    /// The family the model belongs to.
49    pub family: String,
50    /// What the model means.
51    pub definition: String,
52    /// The properties that distinguish the model from the other models of its family.
53    pub properties: Map<String, Value>,
54    /// The names languages give the model.
55    pub source_aliases: Vec<SourceAlias>,
56}
57
58/// A recorded relation between two distinct models and the condition under which it holds.
59#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
60#[serde(rename_all = "camelCase", deny_unknown_fields)]
61pub struct FoundationCorrespondence {
62    /// The model the correspondence starts from.
63    pub from: String,
64    /// The model the correspondence leads to.
65    pub to: String,
66    /// One of [`CORRESPONDENCE_KINDS`].
67    pub kind: String,
68    /// When the two models agree.
69    pub condition: String,
70    /// The translation encodings and assumptions this correspondence justifies.
71    #[serde(default)]
72    pub translation_encodings: Vec<String>,
73}
74
75/// Two models that must never be merged, with the reason.
76#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
77#[serde(rename_all = "camelCase", deny_unknown_fields)]
78pub struct FoundationDistinction {
79    /// The two models.
80    pub models: Vec<String>,
81    /// What distinguishes them.
82    pub reason: String,
83    /// The translation encodings and assumptions this distinction justifies.
84    #[serde(default)]
85    pub translation_encodings: Vec<String>,
86}
87
88/// The models one language uses.
89#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
90#[serde(deny_unknown_fields)]
91pub struct LanguageFoundation {
92    /// The language, such as `Rust` or `Lean`.
93    pub language: String,
94    /// The identities of the models the language uses, one or more per family.
95    pub models: Vec<String>,
96}
97
98/// A foundation register: the shape of `parity/foundation-models.lino`.
99#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
100#[serde(deny_unknown_fields)]
101pub struct FoundationRegister {
102    /// What the register records.
103    pub description: String,
104    /// The model families.
105    pub families: Vec<FoundationFamily>,
106    /// The models.
107    pub models: Vec<FoundationModel>,
108    /// The correspondences between distinct models.
109    pub correspondences: Vec<FoundationCorrespondence>,
110    /// The models that must stay distinct.
111    pub distinctions: Vec<FoundationDistinction>,
112    /// The models each language uses.
113    pub languages: Vec<LanguageFoundation>,
114}
115
116/// A way a register fails to keep foundations neutral.
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct FoundationProblem {
119    /// The problem kind, the same string the JavaScript runtime reports, such as `universal-model`.
120    pub kind: &'static str,
121    /// The model, correspondence or language the problem is about.
122    pub subject: String,
123    /// A readable explanation.
124    pub message: String,
125}
126
127/// Returns the embedded foundation register.
128#[must_use]
129pub fn foundation_register() -> &'static FoundationRegister {
130    static REGISTER: OnceLock<FoundationRegister> = OnceLock::new();
131    REGISTER.get_or_init(|| {
132        serde_json::from_value(
133            crate::structured_data_links::read_structured_data_lino(FOUNDATION_MODELS_LINKS)
134                .expect("the embedded foundation links are valid"),
135        )
136        .expect("the embedded foundation models are valid")
137    })
138}
139
140/// Returns the model named `id`.
141#[must_use]
142pub fn foundation_model(id: &str) -> Option<&'static FoundationModel> {
143    foundation_register()
144        .models
145        .iter()
146        .find(|model| model.id == id)
147}
148
149/// Returns the models `language` uses, optionally only those of one family.
150#[must_use]
151pub fn language_foundation_models(
152    language: &str,
153    family: Option<&str>,
154) -> Vec<&'static FoundationModel> {
155    foundation_register()
156        .languages
157        .iter()
158        .filter(|entry| entry.language == language)
159        .flat_map(|entry| entry.models.iter().filter_map(|id| foundation_model(id)))
160        .filter(|model| family.is_none_or(|family| model.family == family))
161        .collect()
162}
163
164/// Returns the recorded correspondences between two models, in either direction.
165#[must_use]
166pub fn foundation_correspondences(a: &str, b: &str) -> Vec<&'static FoundationCorrespondence> {
167    foundation_register()
168        .correspondences
169        .iter()
170        .filter(|entry| (entry.from == a && entry.to == b) || (entry.from == b && entry.to == a))
171        .collect()
172}
173
174/// Checks that a register keeps foundations neutral.
175///
176/// Every model belongs to a declared family, distinct models are not merged or
177/// claimed equal, every correspondence states its condition, every language
178/// names its own models, and no model is a universal logic. Unknown fields such
179/// as `universal` are rejected when the register is parsed. An empty result
180/// means the register is neutral; the kinds match the JavaScript runtime's
181/// `checkFoundationModels`.
182#[must_use]
183pub fn check_foundation_models(register: &FoundationRegister) -> Vec<FoundationProblem> {
184    let mut problems = Vec::new();
185    let mut report = |kind, subject: &str, message: String| {
186        problems.push(FoundationProblem {
187            kind,
188            subject: subject.to_owned(),
189            message,
190        });
191    };
192    let mut families = BTreeSet::new();
193    for family in &register.families {
194        if !families.insert(family.id.as_str()) {
195            report(
196                "duplicate",
197                &family.id,
198                format!("family {} is declared twice", family.id),
199            );
200        }
201    }
202    let mut models = BTreeMap::new();
203    for model in &register.models {
204        if models.insert(model.id.as_str(), model).is_some() {
205            report(
206                "duplicate",
207                &model.id,
208                format!("model {} is declared twice", model.id),
209            );
210        }
211        if !families.contains(model.family.as_str()) {
212            report(
213                "unknown-family",
214                &model.id,
215                format!("{} belongs to undeclared family {}", model.id, model.family),
216            );
217        } else if !model.id.starts_with(&format!("{}.", model.family)) {
218            report(
219                "identity",
220                &model.id,
221                format!(
222                    "{} is not named under its family {}",
223                    model.id, model.family
224                ),
225            );
226        }
227        if model.definition.is_empty() {
228            report(
229                "definition",
230                &model.id,
231                format!("{} has no definition", model.id),
232            );
233        }
234        if model.properties.is_empty() {
235            report(
236                "properties",
237                &model.id,
238                format!(
239                    "{} records no properties, so its distinctness cannot be checked",
240                    model.id
241                ),
242            );
243        }
244    }
245    for (index, model) in register.models.iter().enumerate() {
246        for other in &register.models[index + 1..] {
247            // Map equality ignores key order, like the JavaScript runtime's canonical JSON comparison.
248            if model.family == other.family && model.properties == other.properties {
249                report(
250                    "indistinct-models",
251                    &model.id,
252                    format!(
253                        "{} and {} record the same properties: one meaning must be one model with source aliases",
254                        model.id, other.id
255                    ),
256                );
257            }
258        }
259    }
260    let mut pairs = BTreeSet::new();
261    for entry in &register.correspondences {
262        let subject = format!("{} -> {}", entry.from, entry.to);
263        for end in [&entry.from, &entry.to] {
264            if !models.contains_key(end.as_str()) {
265                report(
266                    "unknown-model",
267                    &subject,
268                    format!("{subject} names undeclared model {end}"),
269                );
270            }
271        }
272        if entry.from == entry.to {
273            report(
274                "self-correspondence",
275                &subject,
276                format!("{subject} relates a model to itself"),
277            );
278        }
279        if !CORRESPONDENCE_KINDS.contains(&entry.kind.as_str()) {
280            report(
281                "correspondence-kind",
282                &subject,
283                format!(
284                    "{subject} has kind {}; two distinct models never correspond exactly, and the same meaning must be one model",
285                    entry.kind
286                ),
287            );
288        }
289        if entry.condition.trim().chars().count() < 20 {
290            report(
291                "unconditioned-correspondence",
292                &subject,
293                format!("{subject} does not state the condition under which the models agree"),
294            );
295        }
296        let key = if entry.from <= entry.to {
297            (&entry.from, &entry.to)
298        } else {
299            (&entry.to, &entry.from)
300        };
301        if !pairs.insert(key) {
302            report(
303                "duplicate",
304                &subject,
305                format!("{subject} is recorded twice"),
306            );
307        }
308    }
309    for entry in &register.distinctions {
310        let subject = entry.models.join(" / ");
311        if entry.models.len() != 2 {
312            report(
313                "distinction",
314                &subject,
315                "a distinction names exactly two models".to_owned(),
316            );
317        }
318        for id in &entry.models {
319            if !models.contains_key(id.as_str()) {
320                report(
321                    "unknown-model",
322                    &subject,
323                    format!("distinction {subject} names undeclared model {id}"),
324                );
325            }
326        }
327        if entry.reason.trim().chars().count() < 20 {
328            report(
329                "distinction",
330                &subject,
331                format!("distinction {subject} gives no reason"),
332            );
333        }
334    }
335    for entry in &register.languages {
336        let mut used = BTreeSet::new();
337        for id in &entry.models {
338            match models.get(id.as_str()) {
339                Some(model) => {
340                    used.insert(model.family.as_str());
341                }
342                None => report(
343                    "unknown-model",
344                    &entry.language,
345                    format!("{} uses undeclared model {id}", entry.language),
346                ),
347            }
348        }
349        for family in &families {
350            if !used.contains(family) {
351                report(
352                    "language-family",
353                    &entry.language,
354                    format!("{} does not record its {family}", entry.language),
355                );
356            }
357        }
358    }
359    for family in LOGIC_FAMILIES
360        .into_iter()
361        .filter(|family| families.contains(family))
362    {
363        let members: Vec<_> = register
364            .models
365            .iter()
366            .filter(|model| model.family == family)
367            .collect();
368        if members.len() < 2 {
369            continue;
370        }
371        for model in &members {
372            let embedded = members
373                .iter()
374                .filter(|other| other.id != model.id)
375                .all(|other| {
376                    register.correspondences.iter().any(|entry| {
377                        entry.kind == "embedding" && entry.from == other.id && entry.to == model.id
378                    })
379                });
380            if embedded {
381                report(
382                    "universal-model",
383                    &model.id,
384                    format!(
385                        "every other {family} embeds into {}, which makes it a hard-coded universal logic",
386                        model.id
387                    ),
388                );
389            }
390            if family != "logic-model"
391                && register.languages.len() > 1
392                && register
393                    .languages
394                    .iter()
395                    .all(|entry| entry.models.contains(&model.id))
396            {
397                report(
398                    "universal-model",
399                    &model.id,
400                    format!(
401                        "every language is made to use {}, which makes it a hard-coded universal foundation",
402                        model.id
403                    ),
404                );
405            }
406        }
407    }
408    problems
409}