Skip to main content

link_cli/
named_type_links.rs

1//! [`NamedTypeLinks`], the storage interface every layer of the CLI is written
2//! against, and its implementations for the plain store and for each decorator.
3//!
4//! A store that implements this trait can be dropped anywhere in the stack, so
5//! an application can add its own layer -- a cache, a permission check, a
6//! remote store -- without the query processor knowing about it.
7
8use anyhow::{Context, Result};
9use std::collections::HashSet;
10use std::fs::OpenOptions;
11use std::io::{BufWriter, Write};
12use std::path::Path;
13
14use crate::error::LinkError;
15use crate::link::Link;
16use crate::link_storage::{ChangeObserver, LinkStorage};
17use crate::named_types::{NamedTypes, NamedTypesDecorator};
18
19pub trait NamedTypeLinks {
20    fn create(&mut self, source: u32, target: u32) -> u32;
21    fn ensure_created(&mut self, id: u32) -> u32;
22    fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
23        if id == 0 || id == u32::MAX {
24            return Err(LinkError::InvalidFormat(format!(
25                "Cannot ensure unsupported link address {id}"
26            ))
27            .into());
28        }
29
30        Ok(self.ensure_created(id))
31    }
32    fn get_link(&mut self, id: u32) -> Option<Link>;
33    fn exists(&mut self, id: u32) -> bool;
34    /// [`Self::create`] for a layer that may refuse it, as a
35    /// [`PermissionsDecorator`](crate::permissions::PermissionsDecorator)
36    /// does: the query processor and the type hierarchy create through it.
37    fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
38        Ok(self.create(source, target))
39    }
40    /// [`Self::get_or_create`] for a layer that may refuse it.
41    fn try_get_or_create(&mut self, source: u32, target: u32) -> Result<u32> {
42        match self.search(source, target) {
43            Some(found) => Ok(found),
44            None => self.try_create(source, target),
45        }
46    }
47    /// Whether a reference of a query to `id` names a link that exists.
48    ///
49    /// The same as [`Self::exists`], but for a view that hides links: a
50    /// reference is a right of its own, so a link the subject cannot read
51    /// exists for a reference when the subject may refer to it, and otherwise
52    /// answers as a missing one (issue #161).
53    fn reference_exists(&mut self, id: u32) -> bool {
54        self.exists(id)
55    }
56    /// Whether `id` is an address of this store, so a link created there
57    /// ([`Self::ensure_created`], the undo of a delete) belongs in it; `None`
58    /// for a plain store, which has no addresses of its own.
59    ///
60    /// A store made of others answers: a [`RemapLinks`](crate::RemapLinks)
61    /// claims the addresses of its map, and a [`UnionLinks`](crate::UnionLinks)
62    /// creates a link at an address in the first member that claims it, the
63    /// primary one when none does, so a union recreates a link in the member
64    /// its address is of (issue #149). The C# twin is `IComposedLinks.Claims`.
65    fn claims(&mut self, id: u32) -> Option<bool> {
66        let _ = id;
67        None
68    }
69    /// The addresses the next `count` links created in the store get.
70    ///
71    /// A store reuses the address freed last first, so the lowest free one is
72    /// not necessarily next. Creating the links and deleting them again in
73    /// reverse leaves the store exactly as it was, and is the one way to ask
74    /// any store, a remote one included. A view that may not create asks the
75    /// store below.
76    fn next_created_addresses(&mut self, count: usize) -> Result<Vec<u32>> {
77        let mut addresses = Vec::with_capacity(count);
78        for _ in 0..count {
79            addresses.push(self.try_create(0, 0)?);
80        }
81        for &address in addresses.iter().rev() {
82            self.delete(address)?;
83        }
84        Ok(addresses)
85    }
86    fn update(&mut self, id: u32, source: u32, target: u32) -> Result<Link> {
87        self.update_observed(id, source, target, &mut |_, _| {})
88    }
89    /// [`Self::update`], reporting every change the update caused.
90    ///
91    /// An update that would duplicate an existing doublet is resolved into a
92    /// merge: the updated link is deleted and its usages are moved to the
93    /// duplicate, so one call can make several changes. The C# CLI sees them
94    /// because `AdvancedMixedQueryProcessor` hands a handler to the store:
95    ///
96    /// ```csharp
97    /// links.Update(before, after, (beforeState, afterState) =>
98    ///     options.ChangesHandler?.Invoke(beforeState, afterState) ?? links.Constants.Continue);
99    /// ```
100    fn update_observed(
101        &mut self,
102        id: u32,
103        source: u32,
104        target: u32,
105        observer: ChangeObserver<'_>,
106    ) -> Result<Link>;
107    fn delete(&mut self, id: u32) -> Result<Link> {
108        self.delete_observed(id, &mut |_, _| {})
109    }
110    /// [`Self::delete`], reporting every change the deletion caused.
111    ///
112    /// Deleting a link cascades into every link that still used it, and each of
113    /// those removals is a change in its own right, reported the way
114    /// `AdvancedMixedQueryProcessor.RemoveLinks` reports them in C#:
115    ///
116    /// ```csharp
117    /// links.Delete(link, (before, after) =>
118    ///     options.ChangesHandler?.Invoke(before, after) ?? links.Constants.Continue);
119    /// ```
120    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link>;
121    fn all_links(&mut self) -> Vec<Link>;
122    /// The links that match a pattern, where `None` matches any value, in
123    /// the order of their addresses.
124    ///
125    /// The default filters [`Self::all_links`]; a store with a lookup index
126    /// overrides it.
127    fn query_links(
128        &mut self,
129        index: Option<u32>,
130        source: Option<u32>,
131        target: Option<u32>,
132    ) -> Vec<Link> {
133        let mut links: Vec<Link> = self
134            .all_links()
135            .into_iter()
136            .filter(|link| {
137                index.is_none_or(|index| link.index == index)
138                    && source.is_none_or(|source| link.source == source)
139                    && target.is_none_or(|target| link.target == target)
140            })
141            .collect();
142        links.sort_unstable_by_key(|link| link.index);
143        links
144    }
145    fn search(&mut self, source: u32, target: u32) -> Option<u32>;
146    fn get_or_create(&mut self, source: u32, target: u32) -> u32;
147    fn get_name(&mut self, id: u32) -> Result<Option<String>>;
148    fn set_name(&mut self, id: u32, name: &str) -> Result<u32>;
149    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>>;
150    fn remove_name(&mut self, id: u32) -> Result<()>;
151    fn save(&mut self) -> Result<()>;
152
153    fn get_or_create_named(&mut self, name: &str) -> Result<u32> {
154        if let Some(id) = self.get_by_name(name)? {
155            return Ok(id);
156        }
157
158        let id = self.try_create(0, 0)?;
159        self.set_name(id, name)?;
160        self.update(id, id, id)?;
161        Ok(id)
162    }
163
164    fn format_reference(&mut self, id: u32) -> Result<String> {
165        Ok(self
166            .get_name(id)?
167            .map(|name| escape_lino_reference(&name))
168            .unwrap_or_else(|| id.to_string()))
169    }
170
171    fn format_lino(&mut self, link: &Link) -> Result<String> {
172        Ok(format!(
173            "({}: {} {})",
174            self.format_reference(link.index)?,
175            self.format_reference(link.source)?,
176            self.format_reference(link.target)?
177        ))
178    }
179
180    fn lino_lines(&mut self) -> Result<Vec<String>> {
181        let mut links = self.all_links();
182        links.sort_by_key(|link| link.index);
183
184        links
185            .iter()
186            .map(|link| self.format_lino(link))
187            .collect::<Result<Vec<_>>>()
188    }
189
190    fn write_lino_output<P: AsRef<Path>>(&mut self, path: P) -> Result<()>
191    where
192        Self: Sized,
193    {
194        let path = path.as_ref();
195        let file = OpenOptions::new()
196            .write(true)
197            .create(true)
198            .truncate(true)
199            .open(path)
200            .with_context(|| format!("Failed to create LiNo output: {}", path.display()))?;
201
202        let mut writer = BufWriter::new(file);
203        for line in self.lino_lines()? {
204            writeln!(writer, "{line}")?;
205        }
206        writer.flush()?;
207        Ok(())
208    }
209
210    fn print_all_lino(&mut self) -> Result<()> {
211        for line in self.lino_lines()? {
212            println!("{line}");
213        }
214        Ok(())
215    }
216
217    fn print_change_lino(&mut self, before: &Option<Link>, after: &Option<Link>) -> Result<()> {
218        let before_text = before
219            .map(|link| self.format_lino(&link))
220            .transpose()?
221            .unwrap_or_default();
222        let after_text = after
223            .map(|link| self.format_lino(&link))
224            .transpose()?
225            .unwrap_or_default();
226        println!("({before_text}) ({after_text})");
227        Ok(())
228    }
229
230    fn format_structure(&mut self, id: u32) -> Result<String> {
231        let mut visited = HashSet::new();
232        self.format_structure_recursive(id, &mut visited)
233    }
234
235    fn format_structure_recursive(
236        &mut self,
237        id: u32,
238        visited: &mut HashSet<u32>,
239    ) -> Result<String> {
240        let link = self.get_link(id).ok_or(LinkError::not_found(id))?;
241        if !visited.insert(id) {
242            return self.format_reference(id);
243        }
244
245        let source = if self.exists(link.source) && !visited.contains(&link.source) {
246            self.format_structure_recursive(link.source, visited)?
247        } else {
248            self.format_reference(link.source)?
249        };
250        let target = self.format_reference(link.target)?;
251        let index = self.format_reference(link.index)?;
252        visited.remove(&id);
253
254        Ok(format!("({index}: {source} {target})"))
255    }
256}
257
258impl NamedTypeLinks for LinkStorage {
259    fn create(&mut self, source: u32, target: u32) -> u32 {
260        LinkStorage::create(self, source, target)
261    }
262
263    fn ensure_created(&mut self, id: u32) -> u32 {
264        LinkStorage::ensure_created(self, id)
265    }
266
267    fn get_link(&mut self, id: u32) -> Option<Link> {
268        self.get(id).copied()
269    }
270
271    fn exists(&mut self, id: u32) -> bool {
272        LinkStorage::exists(self, id)
273    }
274
275    fn update_observed(
276        &mut self,
277        id: u32,
278        source: u32,
279        target: u32,
280        observer: ChangeObserver<'_>,
281    ) -> Result<Link> {
282        LinkStorage::update_observed(self, id, source, target, observer)
283    }
284
285    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
286        LinkStorage::delete_observed(self, id, observer)
287    }
288
289    fn all_links(&mut self) -> Vec<Link> {
290        self.all().into_iter().copied().collect()
291    }
292
293    fn query_links(
294        &mut self,
295        index: Option<u32>,
296        source: Option<u32>,
297        target: Option<u32>,
298    ) -> Vec<Link> {
299        let mut links: Vec<Link> = LinkStorage::query(self, index, source, target)
300            .into_iter()
301            .copied()
302            .collect();
303        links.sort_unstable_by_key(|link| link.index);
304        links
305    }
306
307    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
308        LinkStorage::search(self, source, target)
309    }
310
311    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
312        LinkStorage::get_or_create(self, source, target)
313    }
314
315    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
316        Ok(LinkStorage::get_name(self, id).cloned())
317    }
318
319    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
320        LinkStorage::set_name(self, id, name);
321        Ok(id)
322    }
323
324    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
325        Ok(LinkStorage::get_by_name(self, name))
326    }
327
328    fn remove_name(&mut self, id: u32) -> Result<()> {
329        LinkStorage::remove_name(self, id);
330        Ok(())
331    }
332
333    fn save(&mut self) -> Result<()> {
334        LinkStorage::save(self)
335    }
336
337    fn get_or_create_named(&mut self, name: &str) -> Result<u32> {
338        Ok(LinkStorage::get_or_create_named(self, name))
339    }
340}
341
342impl NamedTypeLinks for NamedTypesDecorator {
343    fn create(&mut self, source: u32, target: u32) -> u32 {
344        NamedTypesDecorator::create(self, source, target)
345    }
346
347    fn ensure_created(&mut self, id: u32) -> u32 {
348        NamedTypesDecorator::ensure_created(self, id)
349    }
350
351    fn get_link(&mut self, id: u32) -> Option<Link> {
352        self.get(id).copied()
353    }
354
355    fn exists(&mut self, id: u32) -> bool {
356        NamedTypesDecorator::exists(self, id)
357    }
358
359    fn update_observed(
360        &mut self,
361        id: u32,
362        source: u32,
363        target: u32,
364        observer: ChangeObserver<'_>,
365    ) -> Result<Link> {
366        NamedTypesDecorator::update_observed(self, id, source, target, observer)
367    }
368
369    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
370        NamedTypesDecorator::delete_observed(self, id, observer)
371    }
372
373    fn all_links(&mut self) -> Vec<Link> {
374        self.all().into_iter().copied().collect()
375    }
376
377    fn query_links(
378        &mut self,
379        index: Option<u32>,
380        source: Option<u32>,
381        target: Option<u32>,
382    ) -> Vec<Link> {
383        let mut links: Vec<Link> = NamedTypesDecorator::query(self, index, source, target)
384            .into_iter()
385            .copied()
386            .collect();
387        links.sort_unstable_by_key(|link| link.index);
388        links
389    }
390
391    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
392        NamedTypesDecorator::search(self, source, target)
393    }
394
395    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
396        NamedTypesDecorator::get_or_create(self, source, target)
397    }
398
399    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
400        NamedTypes::get_name(self, id)
401    }
402
403    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
404        NamedTypes::set_name(self, id, name)
405    }
406
407    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
408        NamedTypes::get_by_name(self, name)
409    }
410
411    fn remove_name(&mut self, id: u32) -> Result<()> {
412        NamedTypes::remove_name(self, id)
413    }
414
415    fn save(&mut self) -> Result<()> {
416        NamedTypesDecorator::save(self)
417    }
418}
419
420impl NamedTypeLinks for crate::transactions::TransactionsDecorator {
421    fn create(&mut self, source: u32, target: u32) -> u32 {
422        crate::transactions::TransactionsDecorator::create(self, source, target)
423            .expect("TransactionsDecorator::create failed in NamedTypeLinks bridge")
424    }
425
426    fn ensure_created(&mut self, id: u32) -> u32 {
427        crate::transactions::TransactionsDecorator::ensure_created(self, id)
428            .expect("TransactionsDecorator::ensure_created failed in NamedTypeLinks bridge")
429    }
430
431    fn get_link(&mut self, id: u32) -> Option<Link> {
432        self.get(id).copied()
433    }
434
435    fn exists(&mut self, id: u32) -> bool {
436        crate::transactions::TransactionsDecorator::exists(self, id)
437    }
438
439    fn update_observed(
440        &mut self,
441        id: u32,
442        source: u32,
443        target: u32,
444        observer: ChangeObserver<'_>,
445    ) -> Result<Link> {
446        Ok(crate::transactions::TransactionsDecorator::update_observed(
447            self, id, source, target, observer,
448        )?)
449    }
450
451    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
452        Ok(crate::transactions::TransactionsDecorator::delete_observed(
453            self, id, observer,
454        )?)
455    }
456
457    fn all_links(&mut self) -> Vec<Link> {
458        self.all().into_iter().copied().collect()
459    }
460
461    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
462        crate::transactions::TransactionsDecorator::search(self, source, target)
463    }
464
465    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
466        crate::transactions::TransactionsDecorator::get_or_create(self, source, target)
467            .expect("TransactionsDecorator::get_or_create failed in NamedTypeLinks bridge")
468    }
469
470    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
471        NamedTypes::get_name(self.inner_mut(), id)
472    }
473
474    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
475        NamedTypes::set_name(self.inner_mut(), id, name)
476    }
477
478    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
479        NamedTypes::get_by_name(self.inner_mut(), name)
480    }
481
482    fn remove_name(&mut self, id: u32) -> Result<()> {
483        NamedTypes::remove_name(self.inner_mut(), id)
484    }
485
486    fn save(&mut self) -> Result<()> {
487        Ok(crate::transactions::TransactionsDecorator::save(self)?)
488    }
489}
490
491impl NamedTypeLinks for crate::version_control::VersionControlDecorator {
492    fn create(&mut self, source: u32, target: u32) -> u32 {
493        crate::version_control::VersionControlDecorator::create(self, source, target)
494            .expect("VersionControlDecorator::create failed in NamedTypeLinks bridge")
495    }
496
497    fn ensure_created(&mut self, id: u32) -> u32 {
498        crate::version_control::VersionControlDecorator::ensure_created(self, id)
499    }
500
501    fn get_link(&mut self, id: u32) -> Option<Link> {
502        self.get(id).copied()
503    }
504
505    fn exists(&mut self, id: u32) -> bool {
506        crate::version_control::VersionControlDecorator::exists(self, id)
507    }
508
509    fn update_observed(
510        &mut self,
511        id: u32,
512        source: u32,
513        target: u32,
514        observer: ChangeObserver<'_>,
515    ) -> Result<Link> {
516        crate::version_control::VersionControlDecorator::update_observed(
517            self, id, source, target, observer,
518        )
519    }
520
521    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
522        crate::version_control::VersionControlDecorator::delete_observed(self, id, observer)
523    }
524
525    fn all_links(&mut self) -> Vec<Link> {
526        self.all().into_iter().copied().collect()
527    }
528
529    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
530        crate::version_control::VersionControlDecorator::search(self, source, target)
531    }
532
533    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
534        crate::version_control::VersionControlDecorator::get_or_create(self, source, target)
535            .expect("VersionControlDecorator::get_or_create failed in NamedTypeLinks bridge")
536    }
537
538    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
539        NamedTypes::get_name(self.transactions_mut().inner_mut(), id)
540    }
541
542    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
543        NamedTypes::set_name(self.transactions_mut().inner_mut(), id, name)
544    }
545
546    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
547        NamedTypes::get_by_name(self.transactions_mut().inner_mut(), name)
548    }
549
550    fn remove_name(&mut self, id: u32) -> Result<()> {
551        NamedTypes::remove_name(self.transactions_mut().inner_mut(), id)
552    }
553
554    fn save(&mut self) -> Result<()> {
555        crate::version_control::VersionControlDecorator::save(self)
556    }
557}
558
559/// A borrowed store is a store: a layer can wrap `&mut store` and leave the
560/// store with its owner, as the permission policy does when it reads the
561/// types of the data through a [`TypesDecorator`](crate::types::TypesDecorator).
562impl<L: NamedTypeLinks + ?Sized> NamedTypeLinks for &mut L {
563    fn create(&mut self, source: u32, target: u32) -> u32 {
564        (**self).create(source, target)
565    }
566
567    fn ensure_created(&mut self, id: u32) -> u32 {
568        (**self).ensure_created(id)
569    }
570
571    fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
572        (**self).try_ensure_created(id)
573    }
574
575    fn get_link(&mut self, id: u32) -> Option<Link> {
576        (**self).get_link(id)
577    }
578
579    fn exists(&mut self, id: u32) -> bool {
580        (**self).exists(id)
581    }
582
583    fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
584        (**self).try_create(source, target)
585    }
586
587    fn try_get_or_create(&mut self, source: u32, target: u32) -> Result<u32> {
588        (**self).try_get_or_create(source, target)
589    }
590
591    fn reference_exists(&mut self, id: u32) -> bool {
592        (**self).reference_exists(id)
593    }
594
595    fn claims(&mut self, id: u32) -> Option<bool> {
596        (**self).claims(id)
597    }
598
599    fn next_created_addresses(&mut self, count: usize) -> Result<Vec<u32>> {
600        (**self).next_created_addresses(count)
601    }
602
603    fn update_observed(
604        &mut self,
605        id: u32,
606        source: u32,
607        target: u32,
608        observer: ChangeObserver<'_>,
609    ) -> Result<Link> {
610        (**self).update_observed(id, source, target, observer)
611    }
612
613    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
614        (**self).delete_observed(id, observer)
615    }
616
617    fn all_links(&mut self) -> Vec<Link> {
618        (**self).all_links()
619    }
620
621    fn query_links(
622        &mut self,
623        index: Option<u32>,
624        source: Option<u32>,
625        target: Option<u32>,
626    ) -> Vec<Link> {
627        (**self).query_links(index, source, target)
628    }
629
630    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
631        (**self).search(source, target)
632    }
633
634    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
635        (**self).get_or_create(source, target)
636    }
637
638    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
639        (**self).get_name(id)
640    }
641
642    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
643        (**self).set_name(id, name)
644    }
645
646    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
647        (**self).get_by_name(name)
648    }
649
650    fn remove_name(&mut self, id: u32) -> Result<()> {
651        (**self).remove_name(id)
652    }
653
654    fn save(&mut self) -> Result<()> {
655        (**self).save()
656    }
657
658    fn get_or_create_named(&mut self, name: &str) -> Result<u32> {
659        (**self).get_or_create_named(name)
660    }
661}
662
663pub fn escape_lino_reference(reference: &str) -> String {
664    if reference.is_empty() || reference.trim().is_empty() {
665        return String::new();
666    }
667
668    let has_single_quote = reference.contains('\'');
669    let has_double_quote = reference.contains('"');
670    let needs_quoting = reference.parse::<u32>().is_ok()
671        || reference.contains(':')
672        || reference.contains('(')
673        || reference.contains(')')
674        || reference.contains(' ')
675        || reference.contains('\t')
676        || reference.contains('\n')
677        || reference.contains('\r')
678        || has_single_quote
679        || has_double_quote;
680
681    if has_single_quote && has_double_quote {
682        return format!("'{}'", reference.replace('\'', "\\'"));
683    }
684
685    if has_double_quote {
686        return format!("'{reference}'");
687    }
688
689    if has_single_quote {
690        return format!("\"{reference}\"");
691    }
692
693    if needs_quoting {
694        return format!("'{reference}'");
695    }
696
697    reference.to_string()
698}