1use 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 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 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 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(Self::next_created_addresses(storage, anonymous_links)?);
165 Ok(plan)
166 }
167
168 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 next_created_addresses(storage: &mut impl NamedTypeLinks, count: usize) -> Result<Vec<u32>> {
208 let addresses: Vec<u32> = (0..count).map(|_| storage.create(0, 0)).collect();
209 for &address in addresses.iter().rev() {
210 storage.delete(address)?;
211 }
212 Ok(addresses)
213 }
214
215 fn collect_missing_references(
216 &self,
217 storage: &mut impl NamedTypeLinks,
218 plan: &mut LinkReferencePlan,
219 patterns: &[LinoLink],
220 is_substitution: bool,
221 pattern_type: &'static str,
222 ) -> Result<()> {
223 for pattern in patterns {
224 self.collect_missing_references_in_pattern(
225 storage,
226 plan,
227 pattern,
228 is_substitution,
229 pattern_type,
230 )?;
231 }
232 Ok(())
233 }
234
235 fn collect_missing_references_in_pattern(
236 &self,
237 storage: &mut impl NamedTypeLinks,
238 plan: &mut LinkReferencePlan,
239 pattern: &LinoLink,
240 is_substitution: bool,
241 pattern_type: &'static str,
242 ) -> Result<()> {
243 let pattern_id_is_definition = is_substitution
244 && Self::is_composite_lino(pattern)
245 && Self::concrete_identifier(pattern.id.as_deref()).is_some();
246
247 if !pattern_id_is_definition {
248 if let Some(identifier) = Self::concrete_identifier(pattern.id.as_deref()) {
249 self.validate_reference_identifier(storage, plan, &identifier, pattern_type)?;
250 }
251 }
252
253 if let Some(values) = &pattern.values {
254 for sub_pattern in values {
255 self.collect_missing_references_in_pattern(
256 storage,
257 plan,
258 sub_pattern,
259 is_substitution,
260 pattern_type,
261 )?;
262 }
263 }
264 Ok(())
265 }
266
267 fn validate_reference_identifier(
268 &self,
269 storage: &mut impl NamedTypeLinks,
270 plan: &mut LinkReferencePlan,
271 identifier: &str,
272 pattern_type: &'static str,
273 ) -> Result<()> {
274 if let Ok(link_id) = identifier.parse::<u32>() {
275 if !storage.exists(link_id) && !plan.numeric_ids_to_be_created.contains(&link_id) {
276 plan.add_missing_reference(MissingLinkReference {
277 identifier: identifier.to_string(),
278 pattern_type,
279 numeric_id: Some(link_id),
280 });
281 return Ok(());
282 }
283 self.trace_msg(&format!(
284 "[ValidateReferencesInPattern] Link {link_id} reference validated in {pattern_type} pattern"
285 ));
286 return Ok(());
287 }
288
289 if storage.get_by_name(self.name(identifier))?.is_none()
290 && !plan.names_to_be_created.contains(identifier)
291 {
292 plan.add_missing_reference(MissingLinkReference {
293 identifier: identifier.to_string(),
294 pattern_type,
295 numeric_id: None,
296 });
297 return Ok(());
298 }
299
300 self.trace_msg(&format!(
301 "[ValidateReferencesInPattern] Named link '{identifier}' reference validated in {pattern_type} pattern"
302 ));
303 Ok(())
304 }
305
306 fn auto_create_missing_references(
315 &self,
316 storage: &mut impl NamedTypeLinks,
317 plan: &LinkReferencePlan,
318 ) -> Result<Changes> {
319 let missing_references = &plan.missing_references;
320 let mut created = Vec::new();
321 let mut numeric_references = missing_references
322 .iter()
323 .filter_map(|reference| reference.numeric_id)
324 .collect::<Vec<_>>();
325 numeric_references.sort_unstable();
326 numeric_references.dedup();
327
328 for link_id in numeric_references {
329 if storage.exists(link_id) {
330 continue;
331 }
332
333 self.trace_msg(&format!(
334 "[ValidateLinksExistOrWillBeCreated] Auto-creating missing numeric reference {link_id}."
335 ));
336 storage.try_ensure_created(link_id)?;
337 let placeholder = Link::new(link_id, 0, 0);
338 created.push((None, Some(placeholder)));
339 if plan
340 .composite_pairs_to_be_created
341 .contains(&(link_id, link_id))
342 {
343 self.trace_msg(&format!(
344 "[ValidateLinksExistOrWillBeCreated] Link {link_id} exists as a placeholder because ({link_id}, {link_id}) is defined by the substitution."
345 ));
346 continue;
347 }
348 storage.update(link_id, link_id, link_id)?;
349 created.push((Some(placeholder), storage.get_link(link_id)));
350 }
351
352 let mut named_references = missing_references
353 .iter()
354 .filter(|reference| reference.numeric_id.is_none())
355 .map(|reference| reference.identifier.clone())
356 .collect::<Vec<_>>();
357 named_references.sort();
358 named_references.dedup();
359
360 for name in named_references {
361 if storage.get_by_name(self.name(&name))?.is_some() {
362 continue;
363 }
364
365 self.trace_msg(&format!(
366 "[ValidateLinksExistOrWillBeCreated] Auto-creating missing named reference '{name}' as point link."
367 ));
368 let link_id = storage.get_or_create_named(self.name(&name))?;
369 created.push((None, storage.get_link(link_id)));
370 }
371
372 Ok(created)
373 }
374
375 fn is_composite_lino(lino_link: &LinoLink) -> bool {
376 lino_link.values_count() == 2
377 }
378
379 fn concrete_numeric_identifier(id: Option<&str>) -> Option<u32> {
380 Self::concrete_identifier(id).and_then(|identifier| identifier.parse::<u32>().ok())
381 }
382
383 fn concrete_identifier(id: Option<&str>) -> Option<String> {
384 let identifier = id?.trim_end_matches(':');
385 if identifier.is_empty() || identifier == "*" || identifier.starts_with('$') {
386 None
387 } else {
388 Some(identifier.to_string())
389 }
390 }
391
392 fn trace_msg(&self, msg: &str) {
393 if self.trace {
394 eprintln!("{}", msg);
395 }
396 }
397}