Skip to main content

link_cli/
lino_database_input.rs

1//! LiNo database import helpers.
2
3use anyhow::{bail, Context, Result};
4use std::fs;
5use std::path::Path;
6
7use crate::lino_link::LinoLink;
8use crate::named_type_links::NamedTypeLinks;
9use crate::parser::Parser;
10
11/// Default nesting limit for a LiNo text import.
12pub const DEFAULT_IMPORT_DEPTH: usize = links_notation::parser::DEFAULT_MAX_DEPTH;
13/// Highest nesting limit supported by the recursive import path.
14pub const MAX_IMPORT_DEPTH: usize = 128;
15
16/// Imports and saves a LiNo file with a nesting limit of 64 levels.
17pub fn import_lino_file<T, P>(storage: &mut T, path: P) -> Result<()>
18where
19    T: NamedTypeLinks,
20    P: AsRef<Path>,
21{
22    import_lino_file_with_max_depth(storage, path, DEFAULT_IMPORT_DEPTH)
23}
24
25/// Imports and saves a LiNo file with a nesting limit from 1 to 128.
26pub fn import_lino_file_with_max_depth<T, P>(
27    storage: &mut T,
28    path: P,
29    max_depth: usize,
30) -> Result<()>
31where
32    T: NamedTypeLinks,
33    P: AsRef<Path>,
34{
35    let path = path.as_ref();
36    let text = fs::read_to_string(path)
37        .with_context(|| format!("Failed to read LiNo input: {}", path.display()))?;
38    import_lino_text_with_max_depth(storage, &text, max_depth)?;
39    storage.save()?;
40    Ok(())
41}
42
43/// Imports LiNo text with a nesting limit of 64 levels, without saving.
44pub fn import_lino_text<T>(storage: &mut T, links_notation: &str) -> Result<()>
45where
46    T: NamedTypeLinks,
47{
48    import_lino_text_with_max_depth(storage, links_notation, DEFAULT_IMPORT_DEPTH)
49}
50
51/// Imports LiNo text with a nesting limit from 1 to 128, without saving.
52pub fn import_lino_text_with_max_depth<T>(
53    storage: &mut T,
54    links_notation: &str,
55    max_depth: usize,
56) -> Result<()>
57where
58    T: NamedTypeLinks,
59{
60    if !(1..=MAX_IMPORT_DEPTH).contains(&max_depth) {
61        bail!("LiNo import nesting limit must be an integer from 1 to {MAX_IMPORT_DEPTH}");
62    }
63    let normalized_links_notation = normalize_links_notation(links_notation);
64    let links = parse_import(&normalized_links_notation, max_depth)?;
65
66    // Parsing accepts more shapes than database import does. Validate the whole
67    // tree before resolving references, which may create links and names.
68    for link in links.iter().filter(|link| !link.is_empty()) {
69        validate_link(link, false)?;
70    }
71
72    for link in links.iter().filter(|link| !link.is_empty()) {
73        import_link(storage, link)?;
74    }
75
76    Ok(())
77}
78
79#[cfg(not(target_arch = "wasm32"))]
80fn parse_import(text: &str, max_depth: usize) -> Result<Vec<LinoLink>> {
81    // The notation parser's recursive frames can exceed a native caller's
82    // stack budget, especially in debug builds. Only parsing needs this stack.
83    std::thread::scope(|scope| {
84        let parser = std::thread::Builder::new()
85            .stack_size(8 * 1024 * 1024)
86            .spawn_scoped(scope, || {
87                Parser::new().parse_with_max_depth(text, max_depth)
88            })
89            .context("Failed to start the LiNo import parser")?;
90        match parser.join() {
91            Ok(parsed) => Ok(parsed?),
92            Err(panic) => std::panic::resume_unwind(panic),
93        }
94    })
95}
96
97// WebAssembly has no threads, so the parse uses the module's shadow stack.
98// The wasm wrapper (rust/wasm/build.rs) links with an 8 MiB stack to match the
99// native parse thread; other wasm32 embedders need a similar `-zstack-size`.
100#[cfg(target_arch = "wasm32")]
101fn parse_import(text: &str, max_depth: usize) -> Result<Vec<LinoLink>> {
102    Ok(Parser::new().parse_with_max_depth(text, max_depth)?)
103}
104
105fn validate_link(link: &LinoLink, allow_anonymous_index: bool) -> Result<()> {
106    let values = link
107        .values
108        .as_ref()
109        .filter(|values| values.len() == 2)
110        .ok_or_else(|| anyhow::anyhow!("LiNo import supports links with exactly two values"))?;
111
112    for reference in values {
113        match reference.values_count() {
114            2 => validate_link(reference, true)?,
115            0 => {
116                if normalize_identifier(reference.id.as_deref()).is_empty() {
117                    bail!("LiNo import references must have a value");
118                }
119            }
120            _ => bail!(
121                "LiNo import references must be scalar values or nested links with exactly two values"
122            ),
123        }
124    }
125
126    if !allow_anonymous_index && normalize_identifier(link.id.as_deref()).is_empty() {
127        bail!("Top-level LiNo import links must have an index or name");
128    }
129    Ok(())
130}
131
132/// Imports a link `validate_link` accepted, as every entry to this module does first.
133fn import_link<T>(storage: &mut T, link: &LinoLink) -> Result<u32>
134where
135    T: NamedTypeLinks,
136{
137    let values = link
138        .values
139        .as_ref()
140        .filter(|values| values.len() == 2)
141        .ok_or_else(|| anyhow::anyhow!("LiNo import supports links with exactly two values"))?;
142
143    let source = resolve_reference(storage, &values[0])?;
144    let target = resolve_reference(storage, &values[1])?;
145    let identifier = normalize_identifier(link.id.as_deref());
146
147    if identifier.is_empty() {
148        return storage.try_get_or_create(source, target);
149    }
150
151    let index = resolve_index(storage, &identifier)?;
152    update_link(storage, index, source, target)?;
153    Ok(index)
154}
155
156fn resolve_reference<T>(storage: &mut T, reference: &LinoLink) -> Result<u32>
157where
158    T: NamedTypeLinks,
159{
160    if reference.values_count() == 2 {
161        return import_link(storage, reference);
162    }
163
164    let identifier = normalize_identifier(reference.id.as_deref());
165    if let Some(id) = parse_reference_number(&identifier, true) {
166        return Ok(id);
167    }
168
169    storage.get_or_create_named(&identifier)
170}
171
172fn resolve_index<T>(storage: &mut T, identifier: &str) -> Result<u32>
173where
174    T: NamedTypeLinks,
175{
176    if let Some(id) = parse_reference_number(identifier, false) {
177        if !storage.exists(id) {
178            storage.try_ensure_created(id)?;
179        }
180
181        return Ok(id);
182    }
183
184    storage.get_or_create_named(identifier)
185}
186
187pub(crate) fn update_link<T>(storage: &mut T, index: u32, source: u32, target: u32) -> Result<()>
188where
189    T: NamedTypeLinks,
190{
191    if !storage.exists(index) {
192        storage.try_ensure_created(index)?;
193    }
194
195    if let Some(current) = storage.get_link(index) {
196        if current.source == source && current.target == target {
197            return Ok(());
198        }
199    }
200
201    storage.update(index, source, target)?;
202    Ok(())
203}
204
205fn parse_reference_number(identifier: &str, allow_zero: bool) -> Option<u32> {
206    let id = identifier.parse::<u32>().ok()?;
207    if id == 0 && !allow_zero {
208        return None;
209    }
210
211    Some(id)
212}
213
214fn normalize_identifier(identifier: Option<&str>) -> String {
215    let normalized = identifier
216        .unwrap_or_default()
217        .trim()
218        .trim_end_matches(':')
219        .to_string();
220
221    if normalized.len() >= 2 && normalized.starts_with('\'') && normalized.ends_with('\'') {
222        return normalized[1..normalized.len() - 1].replace("\\'", "'");
223    }
224
225    if normalized.len() >= 2 && normalized.starts_with('"') && normalized.ends_with('"') {
226        return normalized[1..normalized.len() - 1].replace("\\\"", "\"");
227    }
228
229    normalized
230}
231
232fn normalize_links_notation(links_notation: &str) -> String {
233    links_notation
234        .lines()
235        .map(str::trim)
236        .filter(|line| !line.is_empty())
237        .collect::<Vec<_>>()
238        .join("\n")
239}