Skip to main content

meta_language/link_network/
structure.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fmt::Write as _;
3
4use super::{LinkId, LinkMetadata, LinkNetwork, LinkType};
5
6const MAXIMUM_WORK: usize = 4_000_000;
7
8struct Node {
9    role: Role,
10    references: Vec<usize>,
11}
12
13#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
14enum Role {
15    Known(Option<LinkType>),
16    Missing,
17}
18
19struct Partition {
20    nodes: Vec<Node>,
21    classes: Vec<usize>,
22    root_positions: Vec<usize>,
23}
24
25fn charge(work: &mut usize, amount: usize) -> Result<(), String> {
26    *work = work.saturating_add(amount);
27    if *work > MAXIMUM_WORK {
28        return Err("link structure work limit exceeded".to_owned());
29    }
30    Ok(())
31}
32
33fn position_of(
34    id: LinkId,
35    positions: &mut BTreeMap<LinkId, usize>,
36    pending: &mut Vec<LinkId>,
37    work: &mut usize,
38) -> Result<usize, String> {
39    let position = match positions.entry(id) {
40        std::collections::btree_map::Entry::Occupied(entry) => *entry.get(),
41        std::collections::btree_map::Entry::Vacant(entry) => {
42            charge(work, 1)?;
43            pending.push(id);
44            *entry.insert(pending.len() - 1)
45        }
46    };
47    Ok(position)
48}
49
50fn connect(
51    role: Option<LinkType>,
52    references: &[LinkId],
53    positions: &mut BTreeMap<LinkId, usize>,
54    pending: &mut Vec<LinkId>,
55    work: &mut usize,
56) -> Result<Node, String> {
57    charge(work, references.len())?;
58    let references = references
59        .iter()
60        .map(|&id| position_of(id, positions, pending, work))
61        .collect::<Result<_, _>>()?;
62    Ok(Node {
63        role: Role::Known(role),
64        references,
65    })
66}
67
68fn connect_pending(
69    network: &LinkNetwork,
70    positions: &mut BTreeMap<LinkId, usize>,
71    pending: &mut Vec<LinkId>,
72    nodes: &mut Vec<Node>,
73    work: &mut usize,
74    allow_missing: bool,
75) -> Result<(), String> {
76    while let Some(&id) = pending.get(nodes.len()) {
77        let node = match network.link(id) {
78            Some(link) => connect(
79                link.metadata().link_type(),
80                link.references(),
81                positions,
82                pending,
83                work,
84            )?,
85            None if allow_missing => Node {
86                role: Role::Missing,
87                references: Vec::new(),
88            },
89            None => return Err(format!("unresolved link reference {id}")),
90        };
91        nodes.push(node);
92    }
93    Ok(())
94}
95
96fn partition(
97    network: &LinkNetwork,
98    roots: &[LinkId],
99    proposed: Option<(LinkType, &[LinkId])>,
100) -> Result<Partition, String> {
101    let mut positions = BTreeMap::new();
102    let mut pending = Vec::new();
103    let mut nodes = Vec::new();
104    let mut work = 0;
105    let proposal = proposed
106        .map(|(role, references)| {
107            connect(
108                Some(role),
109                references,
110                &mut positions,
111                &mut pending,
112                &mut work,
113            )
114        })
115        .transpose()?;
116    if proposal.is_some() {
117        connect_pending(
118            network,
119            &mut positions,
120            &mut pending,
121            &mut nodes,
122            &mut work,
123            false,
124        )?;
125    }
126    let root_positions = roots
127        .iter()
128        .map(|&id| position_of(id, &mut positions, &mut pending, &mut work))
129        .collect::<Result<_, _>>()?;
130    connect_pending(
131        network,
132        &mut positions,
133        &mut pending,
134        &mut nodes,
135        &mut work,
136        proposal.is_some(),
137    )?;
138    nodes.extend(proposal);
139    let pass_cost = nodes.iter().map(|node| 1 + node.references.len()).sum();
140    let mut classes = vec![0; nodes.len()];
141    let mut count = 0;
142    loop {
143        charge(&mut work, pass_cost)?;
144        let mut ranks = BTreeMap::new();
145        classes = nodes
146            .iter()
147            .zip(&classes)
148            .map(|(node, &class)| {
149                let successors: Vec<_> = node
150                    .references
151                    .iter()
152                    .map(|&index| classes[index])
153                    .collect();
154                let rank = ranks.len();
155                *ranks.entry((node.role, class, successors)).or_insert(rank)
156            })
157            .collect();
158        if count == ranks.len() {
159            return Ok(Partition {
160                nodes,
161                classes,
162                root_positions,
163            });
164        }
165        count = ranks.len();
166    }
167}
168
169impl LinkNetwork {
170    /// Returns the ordered rooted bisimulation quotient independently of names
171    /// and storage identifiers. Link roles and ordered reference slots are observed.
172    ///
173    /// # Errors
174    ///
175    /// Returns an error for an unresolved reachable reference or exhausted work.
176    pub fn structural_identity(&self, id: LinkId) -> Result<String, String> {
177        let Partition { nodes, classes, .. } = partition(self, &[id], None)?;
178        let mut numbers = BTreeMap::from([(classes[0], 0)]);
179        let mut pending = vec![0];
180        let mut output = String::from("link structure 1 [");
181        let mut cursor = 0;
182        while let Some(&position) = pending.get(cursor) {
183            let node = &nodes[position];
184            if cursor != 0 {
185                output.push(',');
186            }
187            output.push_str("[\"");
188            if let Role::Known(Some(role)) = node.role {
189                write!(output, "{role}").expect("writing to a String never fails");
190            }
191            output.push('"');
192            for &reference in &node.references {
193                let number = *numbers.entry(classes[reference]).or_insert_with(|| {
194                    pending.push(reference);
195                    pending.len() - 1
196                });
197                write!(output, ",{number}").expect("writing to a String never fails");
198            }
199            output.push(']');
200            cursor += 1;
201        }
202        output.push(']');
203        Ok(output)
204    }
205
206    /// Finds an anonymous link with the given ordered structure.
207    ///
208    /// # Errors
209    ///
210    /// Returns an error for an unresolved reference or exhausted work.
211    pub fn find_structural_link(
212        &self,
213        references: &[LinkId],
214        link_type: LinkType,
215    ) -> Result<Option<LinkId>, String> {
216        let metadata = LinkMetadata::new().with_link_type(link_type);
217        let declared: BTreeSet<_> = self.declared_names.values().copied().collect();
218        let candidates: Vec<_> = self
219            .links()
220            .filter(|link| {
221                link.metadata() == &metadata
222                    && link.references().len() == references.len()
223                    && !declared.contains(&link.id())
224            })
225            .map(super::Link::id)
226            .collect();
227        let Partition {
228            classes,
229            root_positions,
230            ..
231        } = partition(self, &candidates, Some((link_type, references)))?;
232        let proposed = classes.last().expect("proposed structure has a class");
233        Ok(candidates
234            .into_iter()
235            .zip(root_positions)
236            .find(|(_, position)| classes[*position] == *proposed)
237            .map(|(id, _)| id))
238    }
239
240    /// Interns a closed anonymous structure, retaining named and sourced occurrences.
241    ///
242    /// # Errors
243    /// Returns an error before insertion for an unresolved reference or exhausted work.
244    pub fn insert_structural_link(
245        &mut self,
246        references: &[LinkId],
247        link_type: LinkType,
248    ) -> Result<LinkId, String> {
249        if let Some(id) = self.find_structural_link(references, link_type)? {
250            return Ok(id);
251        }
252        if self.next_id == u64::MAX {
253            return Err("link identifier space exhausted".to_owned());
254        }
255        Ok(self.insert_dynamic_link(references, LinkMetadata::new().with_link_type(link_type)))
256    }
257
258    /// Inserts a labeled relation whose label role is expressed by two self references.
259    ///
260    /// # Errors
261    ///
262    /// Returns an error when the label name already identifies a different link.
263    pub fn insert_structural_field(
264        &mut self,
265        parent: LinkId,
266        label: &str,
267        child: LinkId,
268    ) -> Result<LinkId, String> {
269        let label_link = self
270            .find_term(label)
271            .unwrap_or_else(|| self.insert_typed_point(label, LinkType::Field, None));
272        let point = self
273            .link(label_link)
274            .ok_or_else(|| format!("missing field label: {label}"))?;
275        let references = point.references();
276        if point.metadata().link_type() != Some(LinkType::Field)
277            || point.metadata().term() != Some(label)
278            || references.is_empty()
279            || references.len() > 2
280            || !references.iter().all(|&reference| reference == label_link)
281        {
282            return Err(format!("name already identifies a different link: {label}"));
283        }
284        if references.len() == 1 {
285            self.set_references(label_link, &[label_link, label_link]);
286        }
287        Ok(self.insert_link(
288            [parent, label_link, child],
289            LinkMetadata::new().with_link_type(LinkType::Field),
290        ))
291    }
292}