Skip to main content

link_cli/
link_reference_validator.rs

1//! Checking that every link a query refers to exists, and creating the ones
2//! that do not when the caller asked for that.
3//!
4//! Ported from the C# `LinkReferenceValidator`, and public for the same reason
5//! the query processor is: a custom front end that resolves references its own
6//! way needs to be able to reuse, or replace, exactly this step.
7
8use anyhow::Result;
9use std::collections::HashSet;
10
11use crate::error::LinkError;
12use crate::link::Link;
13use crate::lino_link::LinoLink;
14use crate::named_type_links::NamedTypeLinks;
15use crate::query_processor::Changes;
16
17pub struct LinkReferenceValidator {
18    trace: bool,
19    auto_create_missing_references: bool,
20    enveloped_names: bool,
21}
22
23#[derive(Debug, Default)]
24struct LinkReferencePlan {
25    numeric_ids_to_be_created: HashSet<u32>,
26    names_to_be_created: HashSet<String>,
27    /// `(source, target)` pairs the substitution itself defines.
28    ///
29    /// A missing numeric reference whose own point pair `(id, id)` appears
30    /// here is left as a `(id: 0 0)` placeholder instead of being turned into
31    /// a point link, so that the substitution which is about to write that
32    /// exact pair does not collide with it under uniqueness resolution.
33    composite_pairs_to_be_created: HashSet<(u32, u32)>,
34    missing_references: Vec<MissingLinkReference>,
35    missing_reference_keys: HashSet<String>,
36}
37
38impl LinkReferencePlan {
39    fn add_missing_reference(&mut self, reference: MissingLinkReference) {
40        let key = reference.key();
41        if self.missing_reference_keys.insert(key) {
42            self.missing_references.push(reference);
43        }
44    }
45}
46
47#[derive(Debug, Clone)]
48struct MissingLinkReference {
49    identifier: String,
50    pattern_type: &'static str,
51    numeric_id: Option<u32>,
52}
53
54impl MissingLinkReference {
55    fn key(&self) -> String {
56        self.numeric_id
57            .map(|id| format!("id:{id}"))
58            .unwrap_or_else(|| format!("name:{}", self.identifier))
59    }
60}
61
62impl LinkReferenceValidator {
63    pub fn new(trace: bool, auto_create_missing_references: bool) -> Self {
64        Self {
65            trace,
66            auto_create_missing_references,
67            enveloped_names: false,
68        }
69    }
70
71    pub(crate) fn for_query(trace: bool, auto_create_missing_references: bool) -> Self {
72        Self {
73            enveloped_names: true,
74            ..Self::new(trace, auto_create_missing_references)
75        }
76    }
77
78    fn name<'a>(&self, identifier: &'a str) -> &'a str {
79        if self.enveloped_names {
80            crate::query_parser::name(identifier)
81        } else {
82            identifier
83        }
84    }
85
86    /// Validate already-decoded identifiers supplied by a custom front end.
87    pub fn validate_links_exist_or_will_be_created(
88        &self,
89        storage: &mut impl NamedTypeLinks,
90        restriction_patterns: &[LinoLink],
91        substitution_patterns: &[LinoLink],
92    ) -> Result<Changes> {
93        self.trace_msg("[ValidateLinksExistOrWillBeCreated] Starting validation");
94
95        let mut created = Vec::new();
96        loop {
97            let plan =
98                self.plan_references(storage, restriction_patterns, substitution_patterns)?;
99            if plan.missing_references.is_empty() {
100                self.trace_msg("[ValidateLinksExistOrWillBeCreated] Validation completed");
101                return Ok(created);
102            }
103
104            if !self.auto_create_missing_references {
105                let missing = &plan.missing_references[0];
106                return Err(LinkError::QueryError(format!(
107                    "Invalid reference to non-existent link '{}' in {} pattern. Link '{}' does not exist and will not be created by this operation. Use --auto-create-missing-references to create missing references as point links.",
108                    self.name(&missing.identifier), missing.pattern_type, self.name(&missing.identifier)
109                ))
110                .into());
111            }
112
113            // Creating a reference frees addresses on the way, which changes
114            // the ones the query's new links get, so the plan is made again
115            // until every reference is accounted for.
116            created.extend(self.auto_create_missing_references(storage, &plan)?);
117        }
118    }
119
120    fn plan_references(
121        &self,
122        storage: &mut impl NamedTypeLinks,
123        restriction_patterns: &[LinoLink],
124        substitution_patterns: &[LinoLink],
125    ) -> Result<LinkReferencePlan> {
126        let mut plan = self.build_link_reference_plan(storage, substitution_patterns)?;
127        self.trace_msg(&format!(
128            "[ValidateLinksExistOrWillBeCreated] Numeric links to be created: {:?}",
129            plan.numeric_ids_to_be_created
130        ));
131        self.trace_msg(&format!(
132            "[ValidateLinksExistOrWillBeCreated] Named links to be created: {:?}",
133            plan.names_to_be_created
134        ));
135
136        self.collect_missing_references(
137            storage,
138            &mut plan,
139            restriction_patterns,
140            false,
141            "restriction",
142        )?;
143        self.collect_missing_references(
144            storage,
145            &mut plan,
146            substitution_patterns,
147            true,
148            "substitution",
149        )?;
150        Ok(plan)
151    }
152
153    fn build_link_reference_plan(
154        &self,
155        storage: &mut impl NamedTypeLinks,
156        substitution_patterns: &[LinoLink],
157    ) -> Result<LinkReferencePlan> {
158        let mut plan = LinkReferencePlan::default();
159        let mut anonymous_links = 0;
160        for pattern in substitution_patterns {
161            Self::collect_definitions(pattern, &mut plan, &mut anonymous_links);
162        }
163        plan.numeric_ids_to_be_created
164            .extend(storage.next_created_addresses(anonymous_links)?);
165        Ok(plan)
166    }
167
168    /// Collects the ids and names the substitution defines, the `(source,
169    /// target)` pairs it writes under them, and how many links it writes
170    /// without an id.
171    fn collect_definitions(
172        pattern: &LinoLink,
173        plan: &mut LinkReferencePlan,
174        anonymous_links: &mut usize,
175    ) {
176        if let Some(values) = &pattern.values {
177            for sub_pattern in values {
178                Self::collect_definitions(sub_pattern, plan, anonymous_links);
179            }
180        }
181        if !Self::is_composite_lino(pattern) {
182            return;
183        }
184        let Some(identifier) = Self::concrete_identifier(pattern.id.as_deref()) else {
185            *anonymous_links += 1;
186            return;
187        };
188        match identifier.parse::<u32>() {
189            Ok(link_id) => plan.numeric_ids_to_be_created.insert(link_id),
190            Err(_) => plan.names_to_be_created.insert(identifier),
191        };
192        let values = pattern.values.as_deref().unwrap_or_default();
193        if let (Some(source), Some(target)) = (
194            Self::concrete_numeric_identifier(values[0].id.as_deref()),
195            Self::concrete_numeric_identifier(values[1].id.as_deref()),
196        ) {
197            plan.composite_pairs_to_be_created.insert((source, target));
198        }
199    }
200
201    fn collect_missing_references(
202        &self,
203        storage: &mut impl NamedTypeLinks,
204        plan: &mut LinkReferencePlan,
205        patterns: &[LinoLink],
206        is_substitution: bool,
207        pattern_type: &'static str,
208    ) -> Result<()> {
209        for pattern in patterns {
210            self.collect_missing_references_in_pattern(
211                storage,
212                plan,
213                pattern,
214                is_substitution,
215                pattern_type,
216            )?;
217        }
218        Ok(())
219    }
220
221    fn collect_missing_references_in_pattern(
222        &self,
223        storage: &mut impl NamedTypeLinks,
224        plan: &mut LinkReferencePlan,
225        pattern: &LinoLink,
226        is_substitution: bool,
227        pattern_type: &'static str,
228    ) -> Result<()> {
229        let pattern_id_is_definition = is_substitution
230            && Self::is_composite_lino(pattern)
231            && Self::concrete_identifier(pattern.id.as_deref()).is_some();
232
233        if !pattern_id_is_definition {
234            if let Some(identifier) = Self::concrete_identifier(pattern.id.as_deref()) {
235                self.validate_reference_identifier(storage, plan, &identifier, pattern_type)?;
236            }
237        }
238
239        if let Some(values) = &pattern.values {
240            for sub_pattern in values {
241                self.collect_missing_references_in_pattern(
242                    storage,
243                    plan,
244                    sub_pattern,
245                    is_substitution,
246                    pattern_type,
247                )?;
248            }
249        }
250        Ok(())
251    }
252
253    fn validate_reference_identifier(
254        &self,
255        storage: &mut impl NamedTypeLinks,
256        plan: &mut LinkReferencePlan,
257        identifier: &str,
258        pattern_type: &'static str,
259    ) -> Result<()> {
260        if let Ok(link_id) = identifier.parse::<u32>() {
261            if !storage.reference_exists(link_id)
262                && !plan.numeric_ids_to_be_created.contains(&link_id)
263            {
264                plan.add_missing_reference(MissingLinkReference {
265                    identifier: identifier.to_string(),
266                    pattern_type,
267                    numeric_id: Some(link_id),
268                });
269                return Ok(());
270            }
271            self.trace_msg(&format!(
272                "[ValidateReferencesInPattern] Link {link_id} reference validated in {pattern_type} pattern"
273            ));
274            return Ok(());
275        }
276
277        if storage.get_by_name(self.name(identifier))?.is_none()
278            && !plan.names_to_be_created.contains(identifier)
279        {
280            plan.add_missing_reference(MissingLinkReference {
281                identifier: identifier.to_string(),
282                pattern_type,
283                numeric_id: None,
284            });
285            return Ok(());
286        }
287
288        self.trace_msg(&format!(
289            "[ValidateReferencesInPattern] Named link '{identifier}' reference validated in {pattern_type} pattern"
290        ));
291        Ok(())
292    }
293
294    /// Creates every missing reference as a point link and reports each
295    /// creation the way it happens: a numeric reference is first filled in as
296    /// the empty `(id: 0 0)` and then pointed at itself, a named one is created
297    /// as `(name: name name)` directly. The simplified `--changes` report of
298    /// both is the creation of the point link, `() ((2: 2 2))`.
299    ///
300    /// A numeric reference the substitution defines as `(id: id id)` itself
301    /// is only filled in: the query writes the point link.
302    fn auto_create_missing_references(
303        &self,
304        storage: &mut impl NamedTypeLinks,
305        plan: &LinkReferencePlan,
306    ) -> Result<Changes> {
307        let missing_references = &plan.missing_references;
308        let mut created = Vec::new();
309        let mut numeric_references = missing_references
310            .iter()
311            .filter_map(|reference| reference.numeric_id)
312            .collect::<Vec<_>>();
313        numeric_references.sort_unstable();
314        numeric_references.dedup();
315
316        for link_id in numeric_references {
317            if storage.reference_exists(link_id) {
318                continue;
319            }
320
321            self.trace_msg(&format!(
322                "[ValidateLinksExistOrWillBeCreated] Auto-creating missing numeric reference {link_id}."
323            ));
324            storage.try_ensure_created(link_id)?;
325            let placeholder = Link::new(link_id, 0, 0);
326            created.push((None, Some(placeholder)));
327            if plan
328                .composite_pairs_to_be_created
329                .contains(&(link_id, link_id))
330            {
331                self.trace_msg(&format!(
332                    "[ValidateLinksExistOrWillBeCreated] Link {link_id} exists as a placeholder because ({link_id}, {link_id}) is defined by the substitution."
333                ));
334                continue;
335            }
336            storage.update(link_id, link_id, link_id)?;
337            created.push((Some(placeholder), storage.get_link(link_id)));
338        }
339
340        let mut named_references = missing_references
341            .iter()
342            .filter(|reference| reference.numeric_id.is_none())
343            .map(|reference| reference.identifier.clone())
344            .collect::<Vec<_>>();
345        named_references.sort();
346        named_references.dedup();
347
348        for name in named_references {
349            if storage.get_by_name(self.name(&name))?.is_some() {
350                continue;
351            }
352
353            self.trace_msg(&format!(
354                "[ValidateLinksExistOrWillBeCreated] Auto-creating missing named reference '{name}' as point link."
355            ));
356            let link_id = storage.get_or_create_named(self.name(&name))?;
357            created.push((None, storage.get_link(link_id)));
358        }
359
360        Ok(created)
361    }
362
363    fn is_composite_lino(lino_link: &LinoLink) -> bool {
364        lino_link.values_count() == 2
365    }
366
367    fn concrete_numeric_identifier(id: Option<&str>) -> Option<u32> {
368        Self::concrete_identifier(id).and_then(|identifier| identifier.parse::<u32>().ok())
369    }
370
371    fn concrete_identifier(id: Option<&str>) -> Option<String> {
372        let identifier = id?.trim_end_matches(':');
373        if identifier.is_empty() || identifier == "*" || identifier.starts_with('$') {
374            None
375        } else {
376            Some(identifier.to_string())
377        }
378    }
379
380    fn trace_msg(&self, msg: &str) {
381        if self.trace {
382            eprintln!("{}", msg);
383        }
384    }
385}