Skip to main content

link_cli/
types.rs

1//! A type hierarchy with recursive sub-typing and multiple inheritance, kept
2//! in the links themselves (issue #148).
3//!
4//! - The type of a link is its source: `(v: S x)` is a value of type `S`.
5//! - A type points at itself: the root `(Type: Type Type)` is a point, and a
6//!   sub-type of `T` is `(S: T S)`, a value of `T` whose target is itself.
7//! - More parents (multiple inheritance) are pairs `(p: S T2)` marked by
8//!   `(m: Extends p)`.
9//!
10//! So `Type -> SubType -> … -> Value` is a chain of sources of any depth, and
11//! every query below walks it with a set of visited links, so cycles end.
12//!
13//! [`Types`] is the interface, with every query and write as a default method
14//! over [`NamedTypeLinks`], and [`TypesDecorator`] is the decorator that
15//! implements it over any other layer. It is the Rust port of `typeSystem`
16//! of `@link-foundation/ui-links`; the C# counterpart is
17//! `Foundation.Data.Doublets.Cli.TypesDecorator<TLinkAddress>`.
18//!
19//! The pinned types of [`PinnedTypes`](crate::pinned_types::PinnedTypes) are
20//! `(1: 1 1)`, `(2: 1 2)`, `(3: 1 3)`, …: with the root at address 1 they are
21//! sub-types of it, so a pinned store is already a hierarchy.
22
23use std::collections::HashSet;
24
25use anyhow::{bail, Result};
26
27use crate::link::Link;
28use crate::link_storage::ChangeObserver;
29use crate::named_type_links::NamedTypeLinks;
30
31/// The name of the root type point.
32pub const ROOT_TYPE_NAME: &str = "Type";
33
34/// The name of the `Extends` marker point.
35pub const EXTENDS_NAME: &str = "Extends";
36
37/// The two points a type hierarchy needs: the root type `(Type: Type Type)`
38/// and the `Extends` marker of extra parents, `None` when the hierarchy has
39/// no multiple inheritance.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub struct TypeMarkers {
42    pub root: u32,
43    pub extends: Option<u32>,
44}
45
46impl TypeMarkers {
47    /// The points named `Type` and `Extends`, each created as a point
48    /// `(x: x x)` and named when missing.
49    pub fn ensure<L: NamedTypeLinks + ?Sized>(links: &mut L) -> Result<Self> {
50        Ok(Self {
51            root: ensure_point(links, ROOT_TYPE_NAME)?,
52            extends: Some(ensure_point(links, EXTENDS_NAME)?),
53        })
54    }
55}
56
57/// The point named `name`, created and named when missing.
58///
59/// A name whose link no longer exists is given to a new point.
60pub fn ensure_point<L: NamedTypeLinks + ?Sized>(links: &mut L, name: &str) -> Result<u32> {
61    if let Some(known) = links.get_by_name(name)? {
62        if known != 0 && links.exists(known) {
63            return Ok(known);
64        }
65    }
66    let id = links.try_create(0, 0)?;
67    links.update(id, id, id)?;
68    links.set_name(id, name)?;
69    Ok(id)
70}
71
72/// The queries and writes of a type hierarchy.
73///
74/// Only [`root`](Self::root) and [`extends`](Self::extends) are required;
75/// everything else is a default method that reads and writes through `Self`,
76/// so a layer that wraps a [`TypesDecorator`] -- a permission check, say --
77/// implements this trait by forwarding the two markers and sees every write
78/// the hierarchy makes. Any default can be overridden.
79pub trait Types: NamedTypeLinks {
80    /// The root type, `(Type: Type Type)`.
81    fn root(&self) -> u32;
82
83    /// The `Extends` marker, or `None` when there is none.
84    fn extends(&self) -> Option<u32>;
85
86    /// The type of a link: its source; `None` for a missing link.
87    fn type_of(&mut self, link: u32) -> Option<u32> {
88        stored(self, link).map(|link| link.source)
89    }
90
91    /// Whether `link` is a type: it exists and points at itself.
92    fn is_type(&mut self, link: u32) -> bool {
93        stored(self, link).is_some_and(|stored| stored.target == link)
94    }
95
96    /// The direct parents of a type: its source (unless it is a point) and
97    /// what it extends, in the order the extensions were added.
98    fn parents_of(&mut self, type_id: u32) -> Vec<u32> {
99        let mut parents = Vec::new();
100        let Some(link) = stored(self, type_id) else {
101            return parents;
102        };
103        if link.source != type_id && link.source != 0 {
104            parents.push(link.source);
105        }
106        add_extended_types(self, type_id, &mut parents);
107        parents
108    }
109
110    /// Every type `type_id` is, itself first, breadth first, without repeats.
111    fn ancestors_of(&mut self, type_id: u32) -> Vec<u32> {
112        let mut ancestors = vec![type_id];
113        let mut seen = HashSet::from([type_id]);
114        let mut i = 0;
115        while i < ancestors.len() {
116            for parent in self.parents_of(ancestors[i]) {
117                if seen.insert(parent) {
118                    ancestors.push(parent);
119                }
120            }
121            i += 1;
122        }
123        ancestors
124    }
125
126    /// Whether `link` is a pair that gives a type one more parent.
127    fn is_extension(&mut self, link: u32) -> bool {
128        match self.extends() {
129            Some(extends) if link != 0 => self.search(extends, link).is_some(),
130            _ => false,
131        }
132    }
133
134    /// Whether `link` is strictly of `type_id`: starting from its source and
135    /// the types the link itself extends, through any depth of sub-types and
136    /// parents, cycles included. A type is not of itself; [`is_a`](Self::is_a) is.
137    fn is_of(&mut self, link: u32, type_id: u32) -> bool {
138        match stored(self, link) {
139            Some(link) => self.is_of_link(&link, type_id),
140            None => false,
141        }
142    }
143
144    /// [`is_of`](Self::is_of) for a link given as `(index, source, target)`,
145    /// stored or not.
146    fn is_of_link(&mut self, link: &Link, type_id: u32) -> bool {
147        // A link is of its source and of every type it extends itself; the
148        // pairs that give a type more parents are of type Extends, not values
149        // of the type they extend.
150        let mut starts = Vec::new();
151        match self.extends() {
152            Some(extends) if self.is_extension(link.index) => starts.push(extends),
153            _ => {
154                starts.push(link.source);
155                if link.index != 0 && self.exists(link.index) {
156                    add_extended_types(self, link.index, &mut starts);
157                }
158            }
159        }
160        let mut stack: Vec<u32> = starts.into_iter().rev().collect();
161        let mut seen = HashSet::new();
162        while let Some(at) = stack.pop() {
163            if at == type_id {
164                return true;
165            }
166            if at == 0 || !seen.insert(at) {
167                continue;
168            }
169            stack.extend(self.parents_of(at));
170        }
171        false
172    }
173
174    /// Whether `link` is `type_id` itself or of it.
175    fn is_a(&mut self, link: u32, type_id: u32) -> bool {
176        stored(self, link).is_some() && (link == type_id || self.is_of(link, type_id))
177    }
178
179    /// [`is_a`](Self::is_a) for a link given as `(index, source, target)`,
180    /// stored or not.
181    fn is_a_link(&mut self, link: &Link, type_id: u32) -> bool {
182        link.index == type_id || self.is_of_link(link, type_id)
183    }
184
185    /// Defines a type `(S: parent S)` that also extends every type in `more`.
186    fn define(&mut self, parent: u32, more: &[u32]) -> Result<u32> {
187        if !more.is_empty() && self.extends().is_none() {
188            bail!("Multiple parents need an Extends marker.");
189        }
190        ensure_exists(self, parent)?;
191        for &other in more {
192            ensure_exists(self, other)?;
193        }
194        let id = self.try_create(0, 0)?;
195        self.update(id, parent, id)?;
196        for &other in more {
197            self.extend(id, other)?;
198        }
199        Ok(id)
200    }
201
202    /// Defines a direct sub-type of [`root`](Self::root).
203    fn define_root(&mut self) -> Result<u32> {
204        let root = self.root();
205        self.define(root, &[])
206    }
207
208    /// Makes `type_id` extend `parent`: the pair `(p: type parent)` marked by
209    /// `(m: Extends p)`. Returns the pair.
210    ///
211    /// Refused when `parent` is a direct sub-type `(parent: type parent)` of
212    /// `type_id`, whose definition is that very doublet.
213    fn extend(&mut self, type_id: u32, parent: u32) -> Result<u32> {
214        let Some(extends) = self.extends() else {
215            bail!("Multiple parents need an Extends marker.");
216        };
217        ensure_exists(self, type_id)?;
218        let parent_link = ensure_exists(self, parent)?;
219        if parent_link.source == type_id && parent_link.target == parent {
220            // (parent: type parent) is already the doublet (type parent):
221            // marking it would turn the definition of parent into a pair.
222            bail!(
223                "Type {parent} is a direct sub-type of {type_id}: the pair ({type_id} {parent}) would be its definition."
224            );
225        }
226        let pair = self.try_get_or_create(type_id, parent)?;
227        self.try_get_or_create(extends, pair)?;
228        Ok(pair)
229    }
230
231    /// A value `(v: type v)` of `type_id`.
232    fn instance(&mut self, type_id: u32) -> Result<u32> {
233        ensure_exists(self, type_id)?;
234        let id = self.try_create(0, 0)?;
235        self.update(id, type_id, id)?;
236        Ok(id)
237    }
238
239    /// A value `(v: type target)` of `type_id`.
240    fn instance_with_target(&mut self, type_id: u32, target: u32) -> Result<u32> {
241        ensure_exists(self, type_id)?;
242        ensure_exists(self, target)?;
243        self.try_get_or_create(type_id, target)
244    }
245}
246
247fn stored<L: NamedTypeLinks + ?Sized>(links: &mut L, link: u32) -> Option<Link> {
248    if link == 0 {
249        return None;
250    }
251    links.get_link(link)
252}
253
254fn ensure_exists<L: NamedTypeLinks + ?Sized>(links: &mut L, link: u32) -> Result<Link> {
255    match stored(links, link) {
256        Some(stored) => Ok(stored),
257        None => bail!("Link {link} does not exist."),
258    }
259}
260
261/// Adds the targets of the pairs `(p: type T)` marked by `(m: Extends p)`, in
262/// the order of the pairs' addresses.
263fn add_extended_types<T: Types + ?Sized>(types: &mut T, type_id: u32, parents: &mut Vec<u32>) {
264    if types.extends().is_none() || type_id == 0 {
265        return;
266    }
267    for pair in types.query_links(None, Some(type_id), None) {
268        if pair.index != type_id && pair.target != 0 && types.is_extension(pair.index) {
269            parents.push(pair.target);
270        }
271    }
272}
273
274/// A decorator that keeps a type hierarchy with recursive sub-typing and
275/// multiple inheritance in the links of the layer it wraps; see the
276/// [module documentation](self).
277pub struct TypesDecorator<L: NamedTypeLinks> {
278    links: L,
279    markers: TypeMarkers,
280}
281
282impl<L: NamedTypeLinks> TypesDecorator<L> {
283    /// A hierarchy rooted at `root`, with `extends` as the marker of extra
284    /// parents, or without multiple inheritance when it is `None`.
285    pub fn new(links: L, root: u32, extends: Option<u32>) -> Self {
286        Self::with_markers(links, TypeMarkers { root, extends })
287    }
288
289    pub fn with_markers(links: L, markers: TypeMarkers) -> Self {
290        Self { links, markers }
291    }
292
293    /// A hierarchy whose markers are the points named `Type` and `Extends`,
294    /// created when missing.
295    pub fn with_named_markers(mut links: L) -> Result<Self> {
296        let markers = TypeMarkers::ensure(&mut links)?;
297        Ok(Self::with_markers(links, markers))
298    }
299
300    pub fn markers(&self) -> TypeMarkers {
301        self.markers
302    }
303
304    pub fn links(&self) -> &L {
305        &self.links
306    }
307
308    pub fn links_mut(&mut self) -> &mut L {
309        &mut self.links
310    }
311
312    pub fn into_inner(self) -> L {
313        self.links
314    }
315}
316
317impl<L: NamedTypeLinks> Types for TypesDecorator<L> {
318    fn root(&self) -> u32 {
319        self.markers.root
320    }
321
322    fn extends(&self) -> Option<u32> {
323        self.markers.extends
324    }
325}
326
327impl<L: NamedTypeLinks> NamedTypeLinks for TypesDecorator<L> {
328    fn create(&mut self, source: u32, target: u32) -> u32 {
329        self.links.create(source, target)
330    }
331
332    fn ensure_created(&mut self, id: u32) -> u32 {
333        self.links.ensure_created(id)
334    }
335
336    fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
337        self.links.try_ensure_created(id)
338    }
339
340    fn get_link(&mut self, id: u32) -> Option<Link> {
341        self.links.get_link(id)
342    }
343
344    fn exists(&mut self, id: u32) -> bool {
345        self.links.exists(id)
346    }
347
348    fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
349        self.links.try_create(source, target)
350    }
351
352    fn try_get_or_create(&mut self, source: u32, target: u32) -> Result<u32> {
353        self.links.try_get_or_create(source, target)
354    }
355
356    fn reference_exists(&mut self, id: u32) -> bool {
357        self.links.reference_exists(id)
358    }
359
360    fn next_created_addresses(&mut self, count: usize) -> Result<Vec<u32>> {
361        self.links.next_created_addresses(count)
362    }
363
364    fn update_observed(
365        &mut self,
366        id: u32,
367        source: u32,
368        target: u32,
369        observer: ChangeObserver<'_>,
370    ) -> Result<Link> {
371        self.links.update_observed(id, source, target, observer)
372    }
373
374    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
375        self.links.delete_observed(id, observer)
376    }
377
378    fn all_links(&mut self) -> Vec<Link> {
379        self.links.all_links()
380    }
381
382    fn query_links(
383        &mut self,
384        index: Option<u32>,
385        source: Option<u32>,
386        target: Option<u32>,
387    ) -> Vec<Link> {
388        self.links.query_links(index, source, target)
389    }
390
391    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
392        self.links.search(source, target)
393    }
394
395    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
396        self.links.get_or_create(source, target)
397    }
398
399    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
400        self.links.get_name(id)
401    }
402
403    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
404        self.links.set_name(id, name)
405    }
406
407    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
408        self.links.get_by_name(name)
409    }
410
411    fn remove_name(&mut self, id: u32) -> Result<()> {
412        self.links.remove_name(id)
413    }
414
415    fn save(&mut self) -> Result<()> {
416        self.links.save()
417    }
418
419    fn get_or_create_named(&mut self, name: &str) -> Result<u32> {
420        self.links.get_or_create_named(name)
421    }
422}