Skip to main content

link_cli/triplets/
lino.rs

1//! Triplets in Links Notation: one `(index: type from to)` per line.
2//!
3//! The export lists every triplet in the order of its address, a part by its
4//! name when it has one and `0` for an empty from or to. The import reads the
5//! same lines back: a numeric index is kept, a named index is the triplet of
6//! that name (created when there is none), and a line without an index is a
7//! new triplet. Lines may refer to each other in any order, since every
8//! triplet is reserved before any of them gets its parts.
9
10use anyhow::{bail, Result};
11
12use super::query::{pattern_of, substitute, Reference};
13use super::{Triplet, TripletQuery, Triplets};
14use crate::query_parser;
15
16/// Every triplet as a line `(index: type from to)`, in the order of the
17/// addresses.
18pub fn triplets_to_lino<T: Triplets + ?Sized>(triplets: &mut T) -> Result<String> {
19    let mut text = String::new();
20    for Triplet {
21        index,
22        type_id,
23        from,
24        to,
25    } in triplets.each_triplet(TripletQuery::any())
26    {
27        text.push_str(&format!(
28            "({}: {} {} {})\n",
29            reference(triplets, index)?,
30            reference(triplets, type_id)?,
31            reference(triplets, from)?,
32            reference(triplets, to)?
33        ));
34    }
35    Ok(text)
36}
37
38fn reference<T: Triplets + ?Sized>(triplets: &mut T, id: u32) -> Result<String> {
39    if id == 0 {
40        return Ok("0".to_string());
41    }
42    Ok(match triplets.get_name(id)? {
43        Some(name) => query_parser::format_identifier(&format!("\"{name}\"")),
44        None => id.to_string(),
45    })
46}
47
48/// Writes the triplets of `text` and returns their indices, one per line.
49pub fn import_triplets_lino<T: Triplets + ?Sized>(
50    triplets: &mut T,
51    text: &str,
52) -> Result<Vec<u32>> {
53    let parsed = query_parser::parse(text)?;
54    let mut patterns = Vec::with_capacity(parsed.len());
55    for line in &parsed {
56        // A document of one line is that line wrapped once more.
57        let line = match line.values.as_deref() {
58            Some([only]) if line.id.is_none() && only.has_values() => only,
59            _ => line,
60        };
61        let pattern = pattern_of(line)?;
62        let references = pattern.index.iter().chain(pattern.parts.iter());
63        for reference in references {
64            if matches!(reference, Reference::Any | Reference::Variable(_)) {
65                bail!("A triplet in Links Notation has no variables or wildcards.");
66            }
67        }
68        patterns.push(pattern);
69    }
70    let mut changes = Vec::new();
71    substitute(triplets, &patterns, Default::default(), &mut changes)
72}