link-cli 3.1.2

A CLI tool and reusable library for links manipulation backed by a LiNo-notation doublet storage engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! [`NamedTypeLinks`], the storage interface every layer of the CLI is written
//! against, and its implementations for the plain store and for each decorator.
//!
//! A store that implements this trait can be dropped anywhere in the stack, so
//! an application can add its own layer -- a cache, a permission check, a
//! remote store -- without the query processor knowing about it.

use anyhow::{Context, Result};
use std::collections::HashSet;
use std::fs::OpenOptions;
use std::io::{BufWriter, Write};
use std::path::Path;

use crate::error::LinkError;
use crate::link::{GenericLink, Link};
use crate::link_storage::{ChangeObserver, LinkStorage};
use crate::named_types::{NamedTypes, NamedTypesDecorator};
use crate::query_address::QueryAddress;

fn validate_ensure_address<T: QueryAddress>(id: T) -> Result<()> {
    if id == T::from_byte(0) || id == T::MAX {
        return Err(LinkError::InvalidFormat(format!(
            "Cannot ensure unsupported link address {id}"
        ))
        .into());
    }
    Ok(())
}

pub trait NamedTypeLinks<T: QueryAddress = u32> {
    /// A checked transport may restrict numeric input and query expansion.
    fn query_limits(&self) -> Option<crate::query_options::QueryLimits> {
        None
    }
    /// Reserve the actual allocation sequence without staging observable rows.
    /// Backends with a recycling allocator may retain the legacy probe path.
    fn reserve_query_allocations(
        &mut self,
        _processor: &crate::query_processor::GenericQueryProcessor<T>,
        _restriction: &crate::lino_link::LinoLink,
        _substitution: &crate::lino_link::LinoLink,
    ) -> Result<Option<HashSet<T>>> {
        Ok(None)
    }
    fn create(&mut self, source: T, target: T) -> T;
    /// Fallible allocation for backends that can report transaction/address errors.
    fn try_create(&mut self, source: T, target: T) -> Result<T> {
        Ok(self.create(source, target))
    }
    fn ensure_created(&mut self, id: T) -> T;
    fn try_ensure_created(&mut self, id: T) -> Result<T> {
        validate_ensure_address(id)?;
        Ok(self.ensure_created(id))
    }
    /// Whether a reference of a query to `id` names a link that exists.
    ///
    /// The same as [`Self::exists`], but for a view that hides links: a
    /// reference is a right of its own, so a link the subject cannot read
    /// exists for a reference when the subject may refer to it, and otherwise
    /// answers as a missing one (issue #161).
    fn reference_exists(&mut self, id: T) -> bool {
        self.exists(id)
    }
    /// Whether `id` is an address of this store, so a link created there
    /// ([`Self::ensure_created`], the undo of a delete) belongs in it; `None`
    /// for a plain store, which has no addresses of its own.
    ///
    /// A store made of others answers: a [`RemapLinks`](crate::RemapLinks)
    /// claims the addresses of its map, and a [`UnionLinks`](crate::UnionLinks)
    /// creates a link at an address in the first member that claims it, the
    /// primary one when none does, so a union recreates a link in the member
    /// its address is of (issue #149). The C# twin is `IComposedLinks.Claims`.
    fn claims(&mut self, id: T) -> Option<bool> {
        let _ = id;
        None
    }
    /// The addresses the next `count` links created in the store get.
    ///
    /// A store reuses the address freed last first, so the lowest free one is
    /// not necessarily next. Creating the links and deleting them again in
    /// reverse leaves the store exactly as it was, and is the one way to ask
    /// any store, a remote one included. A view that may not create asks the
    /// store below.
    fn next_created_addresses(&mut self, count: usize) -> Result<Vec<T>> {
        let mut addresses = Vec::with_capacity(count);
        for _ in 0..count {
            addresses.push(self.try_create(T::from_byte(0), T::from_byte(0))?);
        }
        for &address in addresses.iter().rev() {
            self.delete(address)?;
        }
        Ok(addresses)
    }
    fn get_link(&mut self, id: T) -> Option<GenericLink<T>>;
    fn exists(&mut self, id: T) -> bool;
    fn update(&mut self, id: T, source: T, target: T) -> Result<GenericLink<T>> {
        self.update_observed(id, source, target, &mut |_, _| {})
    }
    /// [`Self::update`], reporting every change the update caused.
    ///
    /// An update that would duplicate an existing doublet is resolved into a
    /// merge: the updated link is deleted and its usages are moved to the
    /// duplicate, so one call can make several changes. The C# CLI sees them
    /// because `AdvancedMixedQueryProcessor` hands a handler to the store:
    ///
    /// ```csharp
    /// links.Update(before, after, (beforeState, afterState) =>
    ///     options.ChangesHandler?.Invoke(beforeState, afterState) ?? links.Constants.Continue);
    /// ```
    fn update_observed(
        &mut self,
        id: T,
        source: T,
        target: T,
        observer: ChangeObserver<'_, T>,
    ) -> Result<GenericLink<T>>;
    fn delete(&mut self, id: T) -> Result<GenericLink<T>> {
        self.delete_observed(id, &mut |_, _| {})
    }
    /// [`Self::delete`], reporting every change the deletion caused.
    ///
    /// Deleting a link cascades into every link that still used it, and each of
    /// those removals is a change in its own right, reported the way
    /// `AdvancedMixedQueryProcessor.RemoveLinks` reports them in C#:
    ///
    /// ```csharp
    /// links.Delete(link, (before, after) =>
    ///     options.ChangesHandler?.Invoke(before, after) ?? links.Constants.Continue);
    /// ```
    fn delete_observed(&mut self, id: T, observer: ChangeObserver<'_, T>)
        -> Result<GenericLink<T>>;
    fn all_links(&mut self) -> Vec<GenericLink<T>>;
    /// The links that match a pattern, where `None` matches any value, in
    /// the order of their addresses.
    ///
    /// The default filters [`Self::all_links`]; a store with a lookup index
    /// overrides it.
    fn query_links(
        &mut self,
        index: Option<T>,
        source: Option<T>,
        target: Option<T>,
    ) -> Vec<GenericLink<T>> {
        let mut links: Vec<GenericLink<T>> = self
            .all_links()
            .into_iter()
            .filter(|link| {
                index.is_none_or(|index| link.index == index)
                    && source.is_none_or(|source| link.source == source)
                    && target.is_none_or(|target| link.target == target)
            })
            .collect();
        links.sort_unstable_by_key(|link| link.index);
        links
    }
    fn search(&mut self, source: T, target: T) -> Option<T>;
    fn get_or_create(&mut self, source: T, target: T) -> T;
    /// Fallible pair lookup/allocation for composable query and decorator writes.
    fn try_get_or_create(&mut self, source: T, target: T) -> Result<T> {
        if let Some(id) = self.search(source, target) {
            return Ok(id);
        }
        self.try_create(source, target)
    }
    fn get_name(&mut self, id: T) -> Result<Option<String>>;
    fn set_name(&mut self, id: T, name: &str) -> Result<T>;
    fn get_by_name(&mut self, name: &str) -> Result<Option<T>>;
    fn remove_name(&mut self, id: T) -> Result<()>;
    fn save(&mut self) -> Result<()>;

    fn get_or_create_named(&mut self, name: &str) -> Result<T> {
        if let Some(id) = self.get_by_name(name)? {
            return Ok(id);
        }

        let id = self.try_create(T::from_byte(0), T::from_byte(0))?;
        self.set_name(id, name)?;
        self.update(id, id, id)?;
        Ok(id)
    }

    fn format_reference(&mut self, id: T) -> Result<String> {
        Ok(self
            .get_name(id)?
            .map(|name| {
                if name.parse::<T>().is_ok() && name.parse::<u32>().is_err() {
                    links_notation::encode_reference_literal(&name)
                } else {
                    escape_lino_reference(&name)
                }
            })
            .unwrap_or_else(|| id.to_string()))
    }

    fn format_lino(&mut self, link: &GenericLink<T>) -> Result<String> {
        Ok(format!(
            "({}: {} {})",
            self.format_reference(link.index)?,
            self.format_reference(link.source)?,
            self.format_reference(link.target)?
        ))
    }

    fn lino_lines(&mut self) -> Result<Vec<String>> {
        let mut links = self.all_links();
        links.sort_by_key(|link| link.index);

        links
            .iter()
            .map(|link| self.format_lino(link))
            .collect::<Result<Vec<_>>>()
    }

    fn write_lino_output<P: AsRef<Path>>(&mut self, path: P) -> Result<()>
    where
        Self: Sized,
    {
        let path = path.as_ref();
        let file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)
            .with_context(|| format!("Failed to create LiNo output: {}", path.display()))?;

        let mut writer = BufWriter::new(file);
        for line in self.lino_lines()? {
            writeln!(writer, "{line}")?;
        }
        writer.flush()?;
        Ok(())
    }

    fn print_all_lino(&mut self) -> Result<()> {
        for line in self.lino_lines()? {
            println!("{line}");
        }
        Ok(())
    }

    fn print_change_lino(
        &mut self,
        before: &Option<GenericLink<T>>,
        after: &Option<GenericLink<T>>,
    ) -> Result<()> {
        let before_text = before
            .map(|link| self.format_lino(&link))
            .transpose()?
            .unwrap_or_default();
        let after_text = after
            .map(|link| self.format_lino(&link))
            .transpose()?
            .unwrap_or_default();
        println!("({before_text}) ({after_text})");
        Ok(())
    }

    fn format_structure(&mut self, id: T) -> Result<String> {
        let mut visited = HashSet::new();
        self.format_structure_recursive(id, &mut visited)
    }

    fn format_structure_recursive(&mut self, id: T, visited: &mut HashSet<T>) -> Result<String> {
        crate::structure_format::format_structure(
            self,
            id,
            visited,
            |store, address| store.get_link(address),
            |store, address| store.exists(address),
            |store, address| store.format_reference(address),
        )
    }
}

impl NamedTypeLinks for LinkStorage {
    fn reserve_query_allocations(
        &mut self,
        processor: &crate::QueryProcessor,
        restriction: &crate::lino_link::LinoLink,
        substitution: &crate::lino_link::LinoLink,
    ) -> Result<Option<HashSet<u32>>> {
        preview_recycling_query(self.query_copy(), processor, restriction, substitution)
    }

    fn create(&mut self, source: u32, target: u32) -> u32 {
        LinkStorage::create(self, source, target)
    }

    fn ensure_created(&mut self, id: u32) -> u32 {
        LinkStorage::ensure_created(self, id)
    }

    fn get_link(&mut self, id: u32) -> Option<Link> {
        self.get(id).copied()
    }

    fn exists(&mut self, id: u32) -> bool {
        LinkStorage::exists(self, id)
    }

    fn update_observed(
        &mut self,
        id: u32,
        source: u32,
        target: u32,
        observer: ChangeObserver<'_>,
    ) -> Result<Link> {
        LinkStorage::update_observed(self, id, source, target, observer)
    }

    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
        LinkStorage::delete_observed(self, id, observer)
    }

    fn all_links(&mut self) -> Vec<Link> {
        self.all().into_iter().copied().collect()
    }

    fn query_links(
        &mut self,
        index: Option<u32>,
        source: Option<u32>,
        target: Option<u32>,
    ) -> Vec<Link> {
        let mut links: Vec<Link> = LinkStorage::query(self, index, source, target)
            .into_iter()
            .copied()
            .collect();
        links.sort_unstable_by_key(|link| link.index);
        links
    }

    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
        LinkStorage::search(self, source, target)
    }

    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
        LinkStorage::get_or_create(self, source, target)
    }

    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
        Ok(LinkStorage::get_name(self, id).cloned())
    }

    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
        LinkStorage::set_name(self, id, name);
        Ok(id)
    }

    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
        Ok(LinkStorage::get_by_name(self, name))
    }

    fn remove_name(&mut self, id: u32) -> Result<()> {
        LinkStorage::remove_name(self, id);
        Ok(())
    }

    fn save(&mut self) -> Result<()> {
        LinkStorage::save(self)
    }

    fn get_or_create_named(&mut self, name: &str) -> Result<u32> {
        Ok(LinkStorage::get_or_create_named(self, name))
    }
}

impl NamedTypeLinks for NamedTypesDecorator {
    fn reserve_query_allocations(
        &mut self,
        processor: &crate::QueryProcessor,
        restriction: &crate::lino_link::LinoLink,
        substitution: &crate::lino_link::LinoLink,
    ) -> Result<Option<HashSet<u32>>> {
        preview_recycling_query(self.query_copy(), processor, restriction, substitution)
    }

    fn create(&mut self, source: u32, target: u32) -> u32 {
        NamedTypesDecorator::create(self, source, target)
    }

    fn ensure_created(&mut self, id: u32) -> u32 {
        NamedTypesDecorator::ensure_created(self, id)
    }

    fn get_link(&mut self, id: u32) -> Option<Link> {
        self.get(id).copied()
    }

    fn exists(&mut self, id: u32) -> bool {
        NamedTypesDecorator::exists(self, id)
    }

    fn update_observed(
        &mut self,
        id: u32,
        source: u32,
        target: u32,
        observer: ChangeObserver<'_>,
    ) -> Result<Link> {
        NamedTypesDecorator::update_observed(self, id, source, target, observer)
    }

    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
        NamedTypesDecorator::delete_observed(self, id, observer)
    }

    fn all_links(&mut self) -> Vec<Link> {
        self.all().into_iter().copied().collect()
    }

    fn query_links(
        &mut self,
        index: Option<u32>,
        source: Option<u32>,
        target: Option<u32>,
    ) -> Vec<Link> {
        let mut links: Vec<Link> = NamedTypesDecorator::query(self, index, source, target)
            .into_iter()
            .copied()
            .collect();
        links.sort_unstable_by_key(|link| link.index);
        links
    }

    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
        NamedTypesDecorator::search(self, source, target)
    }

    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
        NamedTypesDecorator::get_or_create(self, source, target)
    }

    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
        NamedTypes::get_name(self, id)
    }

    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
        NamedTypes::set_name(self, id, name)
    }

    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
        NamedTypes::get_by_name(self, name)
    }

    fn remove_name(&mut self, id: u32) -> Result<()> {
        NamedTypes::remove_name(self, id)
    }

    fn save(&mut self) -> Result<()> {
        NamedTypesDecorator::save(self)
    }
}

impl NamedTypeLinks for crate::transactions::TransactionsDecorator {
    fn reserve_query_allocations(
        &mut self,
        processor: &crate::QueryProcessor,
        restriction: &crate::lino_link::LinoLink,
        substitution: &crate::lino_link::LinoLink,
    ) -> Result<Option<HashSet<u32>>> {
        self.ensure_write_allowed()?;
        self.inner_mut()
            .reserve_query_allocations(processor, restriction, substitution)
    }

    fn try_get_or_create(&mut self, source: u32, target: u32) -> Result<u32> {
        Ok(crate::transactions::TransactionsDecorator::get_or_create(
            self, source, target,
        )?)
    }

    fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
        Ok(crate::transactions::TransactionsDecorator::create(
            self, source, target,
        )?)
    }

    fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
        validate_ensure_address(id)?;
        Ok(crate::transactions::TransactionsDecorator::ensure_created(
            self, id,
        )?)
    }

    fn create(&mut self, source: u32, target: u32) -> u32 {
        crate::transactions::TransactionsDecorator::create(self, source, target)
            .expect("TransactionsDecorator::create failed in NamedTypeLinks bridge")
    }

    fn ensure_created(&mut self, id: u32) -> u32 {
        crate::transactions::TransactionsDecorator::ensure_created(self, id)
            .expect("TransactionsDecorator::ensure_created failed in NamedTypeLinks bridge")
    }

    fn get_link(&mut self, id: u32) -> Option<Link> {
        self.get(id).copied()
    }

    fn exists(&mut self, id: u32) -> bool {
        crate::transactions::TransactionsDecorator::exists(self, id)
    }

    fn update_observed(
        &mut self,
        id: u32,
        source: u32,
        target: u32,
        observer: ChangeObserver<'_>,
    ) -> Result<Link> {
        Ok(crate::transactions::TransactionsDecorator::update_observed(
            self, id, source, target, observer,
        )?)
    }

    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
        Ok(crate::transactions::TransactionsDecorator::delete_observed(
            self, id, observer,
        )?)
    }

    fn all_links(&mut self) -> Vec<Link> {
        self.all().into_iter().copied().collect()
    }

    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
        crate::transactions::TransactionsDecorator::search(self, source, target)
    }

    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
        crate::transactions::TransactionsDecorator::get_or_create(self, source, target)
            .expect("TransactionsDecorator::get_or_create failed in NamedTypeLinks bridge")
    }

    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
        NamedTypes::get_name(self.inner_mut(), id)
    }

    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
        Ok(crate::transactions::TransactionsDecorator::set_name(
            self, id, name,
        )?)
    }

    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
        NamedTypes::get_by_name(self.inner_mut(), name)
    }

    fn remove_name(&mut self, id: u32) -> Result<()> {
        Ok(crate::transactions::TransactionsDecorator::remove_name(
            self, id,
        )?)
    }

    fn save(&mut self) -> Result<()> {
        Ok(crate::transactions::TransactionsDecorator::save(self)?)
    }
}

impl<B: NamedTypeLinks> NamedTypeLinks
    for crate::version_control::GenericVersionControlDecorator<B>
{
    fn reserve_query_allocations(
        &mut self,
        processor: &crate::QueryProcessor,
        restriction: &crate::lino_link::LinoLink,
        substitution: &crate::lino_link::LinoLink,
    ) -> Result<Option<HashSet<u32>>> {
        self.ensure_write_allowed()?;
        self.transactions_mut()
            .reserve_query_allocations(processor, restriction, substitution)
    }

    fn try_get_or_create(&mut self, source: u32, target: u32) -> Result<u32> {
        crate::version_control::GenericVersionControlDecorator::get_or_create(self, source, target)
    }

    fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
        crate::version_control::GenericVersionControlDecorator::create(self, source, target)
    }

    fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
        validate_ensure_address(id)?;
        crate::version_control::GenericVersionControlDecorator::try_ensure_created(self, id)
    }

    fn create(&mut self, source: u32, target: u32) -> u32 {
        crate::version_control::GenericVersionControlDecorator::create(self, source, target)
            .expect("VersionControlDecorator::create failed in NamedTypeLinks bridge")
    }

    fn ensure_created(&mut self, id: u32) -> u32 {
        crate::version_control::GenericVersionControlDecorator::ensure_created(self, id)
    }

    fn get_link(&mut self, id: u32) -> Option<Link> {
        self.get(id).copied()
    }

    fn exists(&mut self, id: u32) -> bool {
        crate::version_control::GenericVersionControlDecorator::exists(self, id)
    }

    fn update_observed(
        &mut self,
        id: u32,
        source: u32,
        target: u32,
        observer: ChangeObserver<'_>,
    ) -> Result<Link> {
        crate::version_control::GenericVersionControlDecorator::update_observed(
            self, id, source, target, observer,
        )
    }

    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
        crate::version_control::GenericVersionControlDecorator::delete_observed(self, id, observer)
    }

    fn all_links(&mut self) -> Vec<Link> {
        self.all().into_iter().copied().collect()
    }

    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
        crate::version_control::GenericVersionControlDecorator::search(self, source, target)
    }

    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
        crate::version_control::GenericVersionControlDecorator::get_or_create(self, source, target)
            .expect("VersionControlDecorator::get_or_create failed in NamedTypeLinks bridge")
    }

    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
        NamedTypes::get_name(self.transactions_mut().inner_mut(), id)
    }

    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
        crate::version_control::GenericVersionControlDecorator::set_name(self, id, name)
    }

    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
        NamedTypes::get_by_name(self.transactions_mut().inner_mut(), name)
    }

    fn remove_name(&mut self, id: u32) -> Result<()> {
        crate::version_control::GenericVersionControlDecorator::remove_name(self, id)
    }

    fn save(&mut self) -> Result<()> {
        crate::version_control::GenericVersionControlDecorator::save(self)
    }
}

fn preview_recycling_query(
    mut scratch: impl NamedTypeLinks,
    processor: &crate::QueryProcessor,
    restriction: &crate::lino_link::LinoLink,
    substitution: &crate::lino_link::LinoLink,
) -> Result<Option<HashSet<u32>>> {
    processor.preview(&mut scratch, restriction, substitution)?;
    Ok(Some(
        scratch
            .all_links()
            .into_iter()
            .map(|row| row.index)
            .collect(),
    ))
}

/// A borrowed store is a store: a layer can wrap `&mut store` and leave the
/// store with its owner, as the permission policy does when it reads the
/// types of the data through a [`TypesDecorator`](crate::types::TypesDecorator).
impl<T: QueryAddress, L: NamedTypeLinks<T> + ?Sized> NamedTypeLinks<T> for &mut L {
    fn query_limits(&self) -> Option<crate::query_options::QueryLimits> {
        (**self).query_limits()
    }
    fn reserve_query_allocations(
        &mut self,
        processor: &crate::query_processor::GenericQueryProcessor<T>,
        restriction: &crate::lino_link::LinoLink,
        substitution: &crate::lino_link::LinoLink,
    ) -> Result<Option<HashSet<T>>> {
        (**self).reserve_query_allocations(processor, restriction, substitution)
    }
    fn create(&mut self, source: T, target: T) -> T {
        (**self).create(source, target)
    }

    fn ensure_created(&mut self, id: T) -> T {
        (**self).ensure_created(id)
    }

    fn try_ensure_created(&mut self, id: T) -> Result<T> {
        (**self).try_ensure_created(id)
    }

    fn get_link(&mut self, id: T) -> Option<GenericLink<T>> {
        (**self).get_link(id)
    }

    fn exists(&mut self, id: T) -> bool {
        (**self).exists(id)
    }

    fn try_create(&mut self, source: T, target: T) -> Result<T> {
        (**self).try_create(source, target)
    }

    fn try_get_or_create(&mut self, source: T, target: T) -> Result<T> {
        (**self).try_get_or_create(source, target)
    }

    fn reference_exists(&mut self, id: T) -> bool {
        (**self).reference_exists(id)
    }

    fn claims(&mut self, id: T) -> Option<bool> {
        (**self).claims(id)
    }

    fn next_created_addresses(&mut self, count: usize) -> Result<Vec<T>> {
        (**self).next_created_addresses(count)
    }

    fn update_observed(
        &mut self,
        id: T,
        source: T,
        target: T,
        observer: ChangeObserver<'_, T>,
    ) -> Result<GenericLink<T>> {
        (**self).update_observed(id, source, target, observer)
    }

    fn delete_observed(
        &mut self,
        id: T,
        observer: ChangeObserver<'_, T>,
    ) -> Result<GenericLink<T>> {
        (**self).delete_observed(id, observer)
    }

    fn all_links(&mut self) -> Vec<GenericLink<T>> {
        (**self).all_links()
    }

    fn query_links(
        &mut self,
        index: Option<T>,
        source: Option<T>,
        target: Option<T>,
    ) -> Vec<GenericLink<T>> {
        (**self).query_links(index, source, target)
    }

    fn search(&mut self, source: T, target: T) -> Option<T> {
        (**self).search(source, target)
    }

    fn get_or_create(&mut self, source: T, target: T) -> T {
        (**self).get_or_create(source, target)
    }

    fn get_name(&mut self, id: T) -> Result<Option<String>> {
        (**self).get_name(id)
    }

    fn set_name(&mut self, id: T, name: &str) -> Result<T> {
        (**self).set_name(id, name)
    }

    fn get_by_name(&mut self, name: &str) -> Result<Option<T>> {
        (**self).get_by_name(name)
    }

    fn remove_name(&mut self, id: T) -> Result<()> {
        (**self).remove_name(id)
    }

    fn save(&mut self) -> Result<()> {
        (**self).save()
    }

    fn get_or_create_named(&mut self, name: &str) -> Result<T> {
        (**self).get_or_create_named(name)
    }
}

/// The text of a name used as a reference. The notation decides how to delimit
/// it, except for digits that would otherwise read as an address and for mixed
/// quotes, whose literal form the C# port has always written.
pub fn escape_lino_reference(reference: &str) -> String {
    if reference.is_empty() {
        return String::new();
    }
    if reference.parse::<u32>().is_ok() {
        return format!("'{reference}'");
    }
    if reference.contains('\'') && reference.contains('"') {
        return links_notation::encode_reference_literal(reference);
    }
    links_notation::LiNo::Ref(reference).to_string()
}