Skip to main content

meta_language/
formal_concept_definition.rs

1//! Linked operational definitions and closed equivalence certificates.
2//! Primitive declarations are shared data. Equality decisions reuse the
3//! verifier automatically translated from JavaScript; this adapter preserves
4//! network identities, ordered references and labeled relations.
5
6use std::collections::BTreeSet;
7use std::sync::OnceLock;
8
9use serde_json::{Value, json};
10
11use crate::link_network::{LinkId, LinkMetadata, LinkNetwork, LinkType};
12use crate::shared_numeric_function_model::{
13    BOOLEAN_FUNCTION_DECLARATION_VALUE_MODEL, SHARED_BOOLEAN_FUNCTION_MODEL,
14    SHARED_NUMERIC_FUNCTION_MODEL, create_shared_numeric_function_meaning,
15    read_boolean_function_declaration_value_model, read_shared_boolean_function_model,
16    read_shared_numeric_function_model,
17};
18use crate::translation::boolean_declaration_value_rules::accept_boolean_declaration_value_selector;
19use crate::translation::ir::Program;
20use crate::typed_program_links::{
21    emit_typed_program_links, encode_typed_program_links_with_provenance,
22    read_typed_program_binding_identities,
23};
24
25mod graph;
26mod relation_rules;
27use graph::{
28    Graph, correspondence, data, exclude_binding_names, fields, graph, snapshot, verify_pairs,
29};
30
31const LANGUAGE: &str = "meta-language formal definition";
32const SCHEMA: &str = "1";
33const ROOT: &str = "formal concept definition";
34const CERTIFICATE: &str = "formal equivalence certificate";
35const PAIRS: &str = "formal node correspondence list";
36const PAIR: &str = "formal node correspondence";
37
38/// A linked definition or certificate with its explicit root identity.
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct FormalConceptArchive {
41    /// Complete graph, including shared identities and cyclic references.
42    pub network: LinkNetwork,
43    /// Root of the definition or certificate.
44    pub root: LinkId,
45}
46
47impl FormalConceptArchive {
48    /// Restore a serialized archive without interpreting its proof premises.
49    ///
50    /// # Errors
51    /// Refuses malformed links or a missing numeric root.
52    pub fn from_json(value: &Value) -> Result<Self, String> {
53        let links = value["links"]
54            .as_str()
55            .ok_or("a formal definition needs a linked archive and a root")?;
56        let root = value["root"]
57            .as_u64()
58            .ok_or("a formal definition needs a linked archive and a root")?;
59        Ok(Self {
60            network: LinkNetwork::from_lino(links).map_err(|error| error.to_string())?,
61            root: LinkId::from_u64(root),
62        })
63    }
64
65    /// Serialize the full graph and its root, preserving identities.
66    #[must_use]
67    pub fn to_json(&self) -> Value {
68        json!({"links": self.network.to_lino(), "root": self.root.as_u64()})
69    }
70}
71
72/// Host inputs for the same three supported linked interpretation models.
73#[derive(Clone, Copy)]
74pub enum FormalConceptDefinitionInput<'a> {
75    /// An operational program already checked by the portable core.
76    Program(&'a Program),
77    /// An existing typed-program graph, rechecked before accepting its basis.
78    LinkedProgram {
79        network: &'a LinkNetwork,
80        root: LinkId,
81    },
82    /// Exact shared source primitive declaration, or its implicit declaration.
83    Declaration(Option<&'a Value>),
84}
85
86/// Supported interpretation model and separately inspectable provenance.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct FormalConceptDefinitionOptions {
89    /// Exact key in the shared primitive declarations.
90    pub model: String,
91    /// Provenance recorded as linked data but excluded from semantic equality.
92    pub provenance: Option<Value>,
93}
94
95impl Default for FormalConceptDefinitionOptions {
96    fn default() -> Self {
97        Self {
98            model: "checked typed program".to_owned(),
99            provenance: None,
100        }
101    }
102}
103
104impl From<&str> for FormalConceptDefinitionOptions {
105    fn from(model: &str) -> Self {
106        Self {
107            model: model.to_owned(),
108            provenance: None,
109        }
110    }
111}
112
113fn models() -> &'static Value {
114    static MODELS: OnceLock<Value> = OnceLock::new();
115    MODELS.get_or_init(|| {
116        crate::structured_data_links::read_structured_data_lino(include_str!(
117            "data/formal-concept-models.lino"
118        ))
119        .expect("shared formal primitive declarations are Links Notation")
120    })
121}
122
123fn metadata(term: &str, definition: Option<&str>) -> LinkMetadata {
124    let value = LinkMetadata::new()
125        .with_link_type(LinkType::Semantic)
126        .with_language(LANGUAGE)
127        .with_named(true)
128        .with_term(term);
129    if let Some(definition) = definition {
130        value.with_definition(definition)
131    } else {
132        value
133    }
134}
135
136struct Checked {
137    model: String,
138    graph: Graph,
139}
140
141fn checked(value: &FormalConceptArchive) -> Result<Checked, String> {
142    let network = &value.network;
143    let wrapper = network
144        .link(value.root)
145        .ok_or("unsupported or missing formal definition basis")?;
146    let meta = wrapper.metadata();
147    if meta.language() != Some(LANGUAGE)
148        || meta.term() != Some(ROOT)
149        || meta.definition() != Some(SCHEMA)
150        || wrapper.references().len() != 2
151    {
152        return Err("unsupported or missing formal definition basis".to_owned());
153    }
154    let body = wrapper.references()[0];
155    let basis = wrapper.references()[1];
156    let model_link = network
157        .link(basis)
158        .ok_or("unsupported or counterfeit formal primitive model")?;
159    let model = model_link
160        .metadata()
161        .definition()
162        .ok_or("unsupported or counterfeit formal primitive model")?;
163    let declaration = models()
164        .get(model)
165        .ok_or("unsupported or counterfeit formal primitive model")?;
166    if model_link.metadata().language() != Some(LANGUAGE)
167        || model_link.metadata().term() != Some("formal primitive model")
168        || model_link.references().len() != 1
169    {
170        return Err("unsupported or counterfeit formal primitive model".to_owned());
171    }
172    let mut expected = LinkNetwork::new();
173    let expected_root = data(&mut expected, declaration)?;
174    let expected_graph = graph(&expected, expected_root, &BTreeSet::default())?;
175    if correspondence(
176        &graph(network, model_link.references()[0], &BTreeSet::default())?,
177        &expected_graph,
178    )
179    .is_none()
180    {
181        return Err("the formal primitive model differs from its supported declaration".to_owned());
182    }
183    let mut exclusions = BTreeSet::from([(value.root, "provenance".to_owned())]);
184    let mut meaning = None;
185    if model == "checked typed program"
186        || model == SHARED_NUMERIC_FUNCTION_MODEL
187        || model == SHARED_BOOLEAN_FUNCTION_MODEL
188        || model == BOOLEAN_FUNCTION_DECLARATION_VALUE_MODEL
189    {
190        let bindings = read_typed_program_binding_identities(network, body)
191            .map_err(|error| error.to_string())?;
192        // Supported operations must have both actual target interpretations.
193        // The existing adapters diagnose unknown constructs, rather than
194        // granting equality from matching but uninterpretable host payloads.
195        emit_typed_program_links(network, body, "JavaScript").map_err(|error| error.to_string())?;
196        emit_typed_program_links(network, body, "Rust").map_err(|error| error.to_string())?;
197        for (parent, relations) in fields(network) {
198            for relation in relations {
199                if relation.label == "source span"
200                    || (parent == body && relation.label == "provenance")
201                {
202                    exclusions.insert((parent, relation.label));
203                }
204            }
205        }
206        // Alpha equivalence applies only to actual owned binders established
207        // by the checked scope walk. Unreachable relation links cannot mark
208        // semantic field names or public declarations as lexical bindings.
209        exclude_binding_names(network, body, &mut exclusions, &bindings)?;
210        if model == SHARED_NUMERIC_FUNCTION_MODEL
211            || model == SHARED_BOOLEAN_FUNCTION_MODEL
212            || model == BOOLEAN_FUNCTION_DECLARATION_VALUE_MODEL
213        {
214            let declaration_value = model == BOOLEAN_FUNCTION_DECLARATION_VALUE_MODEL;
215            let boolean_value = model == SHARED_BOOLEAN_FUNCTION_MODEL || declaration_value;
216            let shared = if declaration_value {
217                let entries = fields(network).remove(&value.root).unwrap_or_default();
218                let selectors: Vec<_> = entries
219                    .iter()
220                    .filter(|field| field.label == "selected function declaration")
221                    .collect();
222                if !accept_boolean_declaration_value_selector(selectors.len() == 1, true) {
223                    return Err(
224                        "the direct declaration basis requires exactly one owned entry selector"
225                            .to_owned(),
226                    );
227                }
228                let shared = read_boolean_function_declaration_value_model(
229                    network,
230                    body,
231                    selectors[0].child,
232                )?;
233                exclusions.insert((value.root, "selected function declaration".to_owned()));
234                exclusions.extend(shared.qualification_fields.iter().cloned());
235                shared
236            } else if boolean_value {
237                read_shared_boolean_function_model(network, body)?
238            } else {
239                read_shared_numeric_function_model(network, body, false)?
240            };
241            let mut view = create_shared_numeric_function_meaning(network, &shared)?;
242            if boolean_value {
243                // The explicit callable observation retains names in the archive.
244                for id in &shared.declaration_ids {
245                    exclusions.insert((*id, "name".to_owned()));
246                    exclusions.insert((*id, "full name".to_owned()));
247                }
248                let mut references = wrapper.references().to_vec();
249                references[0] = shared.entry_target;
250                if !view.set_references(value.root, &references) {
251                    return Err("missing Boolean callable meaning root".to_owned());
252                }
253            }
254            meaning = Some(view);
255            exclusions.extend(shared.signature_fields);
256            exclusions.insert((shared.language_parent, shared.language_label));
257        }
258    } else if correspondence(
259        &graph(network, body, &BTreeSet::default())?,
260        &expected_graph,
261    )
262    .is_none()
263    {
264        return Err(
265            "a source interpretation differs from its declared primitive meaning".to_owned(),
266        );
267    }
268    Ok(Checked {
269        model: model.to_owned(),
270        graph: graph(meaning.as_ref().unwrap_or(network), value.root, &exclusions)?,
271    })
272}
273
274/// Copy an operational definition with its exact supported shared basis.
275///
276/// # Errors
277/// Refuses unknown models, counterfeit primitive data or unsupported programs.
278pub fn encode_formal_concept_definition(
279    value: FormalConceptDefinitionInput<'_>,
280    options: impl Into<FormalConceptDefinitionOptions>,
281) -> Result<FormalConceptArchive, String> {
282    let options = options.into();
283    let model = options.model.as_str();
284    if model == BOOLEAN_FUNCTION_DECLARATION_VALUE_MODEL {
285        return Err(
286            "the direct declaration basis requires an actual owned entry selector".to_owned(),
287        );
288    }
289    let declaration = models()
290        .get(model)
291        .ok_or("unsupported formal primitive model")?;
292    let (mut network, body) = if model == "checked typed program"
293        || model == SHARED_NUMERIC_FUNCTION_MODEL
294        || model == SHARED_BOOLEAN_FUNCTION_MODEL
295    {
296        match value {
297            FormalConceptDefinitionInput::Program(program) => {
298                let archive = encode_typed_program_links_with_provenance(
299                    program,
300                    options.provenance.as_ref(),
301                )
302                .map_err(|error| error.to_string())?;
303                (archive.network, archive.root)
304            }
305            FormalConceptDefinitionInput::LinkedProgram { network, root } => {
306                (network.clone(), root)
307            }
308            FormalConceptDefinitionInput::Declaration(_) => {
309                return Err("a checked model needs a typed operational program".to_owned());
310            }
311        }
312    } else {
313        let FormalConceptDefinitionInput::Declaration(value) = value else {
314            return Err("a source primitive has no declared formal interpretation".to_owned());
315        };
316        if value.is_some_and(|value| value != declaration) {
317            return Err("a source primitive has no declared formal interpretation".to_owned());
318        }
319        let mut network = LinkNetwork::new();
320        let body = data(&mut network, declaration)?;
321        (network, body)
322    };
323    let declaration_root = data(&mut network, declaration)?;
324    let basis = network.insert_link(
325        [declaration_root],
326        metadata("formal primitive model", Some(model)),
327    );
328    let root = network.insert_link([body, basis], metadata(ROOT, Some(SCHEMA)));
329    if let Some(provenance) = options.provenance.as_ref() {
330        let provenance = data(&mut network, provenance)?;
331        network.insert_field(root, "provenance", provenance);
332    }
333    let result = FormalConceptArchive { network, root };
334    checked(&result)?;
335    Ok(result)
336}
337
338// Private graph constructor for the additive declaration-value entry API.
339// The public options type and original wrapper constructor remain unchanged.
340pub fn encode_formal_function_declaration_context(
341    network: &LinkNetwork,
342    typed_root: LinkId,
343    entry_declaration: LinkId,
344    provenance: Option<&Value>,
345) -> Result<FormalConceptArchive, String> {
346    let mut network = network.clone();
347    let model = BOOLEAN_FUNCTION_DECLARATION_VALUE_MODEL;
348    let declaration = models()
349        .get(model)
350        .ok_or("unsupported formal primitive model")?;
351    let declaration_root = data(&mut network, declaration)?;
352    let basis = network.insert_link(
353        [declaration_root],
354        metadata("formal primitive model", Some(model)),
355    );
356    let root = network.insert_link([typed_root, basis], metadata(ROOT, Some(SCHEMA)));
357    network.insert_field(root, "selected function declaration", entry_declaration);
358    if let Some(provenance) = provenance {
359        let provenance = data(&mut network, provenance)?;
360        network.insert_field(root, "provenance", provenance);
361    }
362    let archive = FormalConceptArchive { network, root };
363    checked(&archive)?;
364    Ok(archive)
365}
366
367/// Portable preparation for the generated closed-bijection verifier.
368///
369/// # Errors
370/// Refuses every unsupported or invalid basis before returning graph data.
371pub fn read_formal_concept_definition(value: &Value) -> Result<Value, String> {
372    let archive = FormalConceptArchive::from_json(value)?;
373    let result = checked(&archive)?;
374    Ok(
375        json!({"schemaVersion": 1, "model": result.model, "shapes": result.graph.shapes, "offsets": result.graph.offsets, "edges": result.graph.edges}),
376    )
377}
378
379/// Prove equality under one supported model using a closed correspondence.
380#[must_use]
381pub fn prove_formal_concept_equivalence(
382    first: &FormalConceptArchive,
383    second: &FormalConceptArchive,
384) -> Option<FormalConceptArchive> {
385    let one = checked(first).ok()?;
386    let other = checked(second).ok()?;
387    if one.model != other.model {
388        return None;
389    }
390    let pairs = correspondence(&one.graph, &other.graph)?;
391    let mut network = LinkNetwork::new();
392    let left = snapshot(&mut network, &one.graph)?;
393    let right = snapshot(&mut network, &other.graph)?;
394    let entries = pairs
395        .into_iter()
396        .map(|(a, b)| network.insert_link([left[a], right[b]], metadata(PAIR, None)))
397        .collect::<Vec<_>>();
398    let list = network.insert_dynamic_link(&entries, metadata(PAIRS, None));
399    let root = network.insert_link(
400        [left[0], right[0], list],
401        metadata(CERTIFICATE, Some(SCHEMA)),
402    );
403    Some(FormalConceptArchive { network, root })
404}
405
406fn verify(
407    first: &FormalConceptArchive,
408    second: &FormalConceptArchive,
409    certificate: &FormalConceptArchive,
410) -> Result<bool, String> {
411    let one = checked(first)?;
412    let other = checked(second)?;
413    if one.model != other.model {
414        return Ok(false);
415    }
416    let network = &certificate.network;
417    let link = network
418        .link(certificate.root)
419        .ok_or("missing formal equivalence certificate")?;
420    if link.metadata().language() != Some(LANGUAGE)
421        || link.metadata().term() != Some(CERTIFICATE)
422        || link.metadata().definition() != Some(SCHEMA)
423        || link.references().len() != 3
424    {
425        return Ok(false);
426    }
427    let left = graph(network, link.references()[0], &BTreeSet::default())?;
428    let right = graph(network, link.references()[1], &BTreeSet::default())?;
429    if !left.same_shape(&one.graph) || !right.same_shape(&other.graph) {
430        return Ok(false);
431    }
432    let list = network
433        .link(link.references()[2])
434        .ok_or("missing formal node correspondence list")?;
435    if list.metadata().language() != Some(LANGUAGE)
436        || list.metadata().term() != Some(PAIRS)
437        || list.references().len() != left.shapes.len()
438        || left.shapes.len() != right.shapes.len()
439    {
440        return Ok(false);
441    }
442    let mut pairs = Vec::new();
443    for id in list.references() {
444        let pair = network
445            .link(*id)
446            .ok_or("missing formal node correspondence")?;
447        if pair.metadata().language() != Some(LANGUAGE)
448            || pair.metadata().term() != Some(PAIR)
449            || pair.references().len() != 2
450        {
451            return Ok(false);
452        }
453        let Some(a) = left.indices.get(&pair.references()[0]) else {
454            return Ok(false);
455        };
456        let Some(b) = right.indices.get(&pair.references()[1]) else {
457            return Ok(false);
458        };
459        pairs.push((*a, *b));
460    }
461    Ok(pairs.first() == Some(&(0, 0)) && verify_pairs(&left, &right, &pairs))
462}
463
464/// Recheck the certificate's copied premises and every correspondence pair.
465#[must_use]
466pub fn verify_formal_concept_equivalence(
467    first: &FormalConceptArchive,
468    second: &FormalConceptArchive,
469    certificate: &FormalConceptArchive,
470) -> bool {
471    verify(first, second, certificate).unwrap_or(false)
472}