1use std::collections::{HashMap, HashSet};
19
20use anyhow::{bail, Result};
21
22use super::{Triplet, TripletQuery, Triplets};
23use crate::lino_link::LinoLink;
24use crate::query_parser;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct TripletChange {
30 pub before: Option<Triplet>,
31 pub after: Option<Triplet>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
36pub(super) enum Reference {
37 Any,
38 Variable(String),
39 Address(u32),
40 Name(String),
41}
42
43impl Reference {
44 fn parse(text: &str) -> Self {
45 let name = query_parser::name(text);
46 if name != text {
47 Self::Name(name.to_string())
48 } else if text == "*" {
49 Self::Any
50 } else if text.starts_with('$') {
51 Self::Variable(text.to_string())
52 } else if let Ok(address) = text.parse::<u32>() {
53 Self::Address(address)
54 } else {
55 Self::Name(text.to_string())
56 }
57 }
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
62pub(super) struct Pattern {
63 pub(super) index: Option<Reference>,
64 pub(super) parts: [Reference; 3],
65}
66
67type Bindings = HashMap<String, u32>;
68
69pub(super) fn patterns_of(link: &LinoLink) -> Result<Vec<Pattern>> {
72 let values = link.values.as_deref().unwrap_or(&[]);
73 if link.id.is_some() || values.iter().any(|value| !value.has_values()) {
74 return Ok(vec![pattern_of(link)?]);
75 }
76 values.iter().map(pattern_of).collect()
77}
78
79pub(super) fn pattern_of(link: &LinoLink) -> Result<Pattern> {
81 let values = link.values.as_deref().unwrap_or(&[]);
82 if values.len() != 3 {
83 bail!(
84 "A triplet pattern has three parts, type, from and to: {} has {}.",
85 describe(link),
86 values.len()
87 );
88 }
89 let mut parts = Vec::with_capacity(3);
90 for value in values {
91 match (&value.id, value.has_values()) {
92 (Some(id), false) => parts.push(Reference::parse(id)),
93 _ => bail!(
94 "A part of a triplet pattern is a reference, not {}.",
95 describe(value)
96 ),
97 }
98 }
99 let [type_part, from, to]: [Reference; 3] =
100 parts.try_into().expect("a pattern has exactly three parts");
101 Ok(Pattern {
102 index: link.id.as_deref().map(Reference::parse),
103 parts: [type_part, from, to],
104 })
105}
106
107fn describe(link: &LinoLink) -> String {
108 let values = link
109 .values
110 .as_deref()
111 .unwrap_or(&[])
112 .iter()
113 .map(describe)
114 .collect::<Vec<_>>()
115 .join(" ");
116 match (&link.id, link.has_values()) {
117 (Some(id), true) => format!("({id}: {values})"),
118 (Some(id), false) => id.clone(),
119 (None, _) => format!("({values})"),
120 }
121}
122
123fn name_of<T: Triplets + ?Sized>(triplets: &mut T, name: &str) -> Option<u32> {
124 triplets
125 .get_by_name(name)
126 .ok()
127 .flatten()
128 .filter(|&id| id != 0)
129}
130
131pub fn process_triplets_query<T: Triplets + ?Sized>(
134 triplets: &mut T,
135 query: &str,
136) -> Result<Vec<TripletChange>> {
137 let parsed = query_parser::parse(query)?;
138 let (restriction, substitution) = match parsed.as_slice() {
139 [] => return Ok(Vec::new()),
140 [only] => match only.values.as_deref() {
141 Some([restriction, substitution]) if only.id.is_none() => (restriction, substitution),
142 _ => bail!("A triplets query is ((restriction) (substitution))."),
143 },
144 [restriction, substitution] => (restriction, substitution),
145 _ => bail!("A triplets query is ((restriction) (substitution))."),
146 };
147 let restrictions = patterns_of(restriction)?;
148 let substitutions = patterns_of(substitution)?;
149 let mut solutions = Vec::new();
150 if restrictions.is_empty() {
151 solutions.push((Bindings::new(), Vec::new()));
152 } else {
153 let mut matched = Vec::new();
154 solve(
155 triplets,
156 &restrictions,
157 Bindings::new(),
158 &mut matched,
159 &mut solutions,
160 );
161 }
162 let mut changes = Vec::new();
163 let mut deletes = Vec::new();
164 for (bindings, matched) in solutions {
165 let kept = substitute(triplets, &substitutions, bindings, &mut changes)?;
166 let kept: HashSet<u32> = kept.into_iter().collect();
167 for index in matched {
168 if !kept.contains(&index) && !deletes.contains(&index) {
169 deletes.push(index);
170 }
171 }
172 }
173 for index in deletes {
174 if triplets.is_triplet(index) {
175 for deleted in triplets.delete_triplet(index)? {
176 changes.push(TripletChange {
177 before: Some(deleted),
178 after: None,
179 });
180 }
181 }
182 }
183 Ok(changes)
184}
185
186enum Restriction {
187 Any,
188 Value(u32),
189 Impossible,
190}
191
192fn restriction_of<T: Triplets + ?Sized>(
193 triplets: &mut T,
194 reference: &Reference,
195 bindings: &Bindings,
196) -> Restriction {
197 match reference {
198 Reference::Any => Restriction::Any,
199 Reference::Variable(name) => match bindings.get(name) {
200 Some(&value) => Restriction::Value(value),
201 None => Restriction::Any,
202 },
203 Reference::Address(address) => Restriction::Value(*address),
204 Reference::Name(name) => match name_of(triplets, name) {
205 Some(id) => Restriction::Value(id),
206 None => Restriction::Impossible,
207 },
208 }
209}
210
211fn bind(bindings: &mut Bindings, reference: &Reference, value: u32) -> bool {
212 match reference {
213 Reference::Variable(name) => match bindings.get(name) {
214 Some(&bound) => bound == value,
215 None => {
216 bindings.insert(name.clone(), value);
217 true
218 }
219 },
220 _ => true,
221 }
222}
223
224pub fn match_triplets_query<T: Triplets + ?Sized>(
228 triplets: &mut T,
229 restriction: &str,
230 variable: &str,
231) -> Result<Vec<u32>> {
232 let parsed = query_parser::parse(restriction)?;
233 let [link] = parsed.as_slice() else {
234 bail!("A restriction is one link of patterns: {restriction}");
235 };
236 let patterns = patterns_of(link)?;
237 let mut solutions = Vec::new();
238 solve(
239 triplets,
240 &patterns,
241 Bindings::new(),
242 &mut Vec::new(),
243 &mut solutions,
244 );
245 let mut seen = HashSet::new();
246 Ok(solutions
247 .iter()
248 .filter_map(|(bindings, _)| bindings.get(variable).copied())
249 .filter(|value| seen.insert(*value))
250 .collect())
251}
252
253fn solve<T: Triplets + ?Sized>(
256 triplets: &mut T,
257 patterns: &[Pattern],
258 bindings: Bindings,
259 matched: &mut Vec<u32>,
260 solutions: &mut Vec<(Bindings, Vec<u32>)>,
261) {
262 let Some((pattern, rest)) = patterns.split_first() else {
263 solutions.push((bindings, matched.clone()));
264 return;
265 };
266 let any = Reference::Any;
267 let references = [
268 pattern.index.as_ref().unwrap_or(&any),
269 &pattern.parts[0],
270 &pattern.parts[1],
271 &pattern.parts[2],
272 ];
273 let mut values = [None; 4];
274 for (slot, reference) in values.iter_mut().zip(references) {
275 match restriction_of(triplets, reference, &bindings) {
276 Restriction::Any => {}
277 Restriction::Value(value) => *slot = Some(value),
278 Restriction::Impossible => return,
279 }
280 }
281 let query = TripletQuery::new(values[0], values[1], values[2], values[3]);
282 for triplet in triplets.each_triplet(query) {
283 let mut next = bindings.clone();
284 let found = [triplet.index, triplet.type_id, triplet.from, triplet.to];
285 if references
286 .iter()
287 .zip(found)
288 .all(|(reference, value)| bind(&mut next, reference, value))
289 {
290 matched.push(triplet.index);
291 solve(triplets, rest, next, matched, solutions);
292 matched.pop();
293 }
294 }
295}
296
297enum Target {
299 Existing(u32),
300 Address(u32),
301 New(Option<Reference>),
302}
303
304pub(super) fn substitute<T: Triplets + ?Sized>(
312 triplets: &mut T,
313 patterns: &[Pattern],
314 mut bindings: Bindings,
315 changes: &mut Vec<TripletChange>,
316) -> Result<Vec<u32>> {
317 let mut targets = Vec::with_capacity(patterns.len());
318 let mut defined_names = HashSet::new();
319 let mut defined_variables = HashSet::new();
320 let mut defined_addresses = HashSet::new();
321 for pattern in patterns {
322 let target = match &pattern.index {
323 None => Target::New(None),
324 Some(Reference::Any) => bail!("A substitution cannot create or update the index *."),
325 Some(Reference::Variable(name)) => match bindings.get(name) {
326 Some(&bound) => Target::Existing(bound),
327 None => {
328 defined_variables.insert(name.clone());
329 Target::New(pattern.index.clone())
330 }
331 },
332 Some(Reference::Name(name)) => match name_of(triplets, name) {
333 Some(id) => Target::Existing(id),
334 None => {
335 defined_names.insert(name.clone());
336 Target::New(pattern.index.clone())
337 }
338 },
339 Some(Reference::Address(address)) => {
340 if *address == 0 {
341 bail!("A triplet cannot be at address 0.");
342 }
343 if triplets.is_triplet(*address) {
344 Target::Existing(*address)
345 } else if triplets.exists(*address) {
346 bail!("Link {address} is a doublet, not a triplet.");
347 } else {
348 defined_addresses.insert(*address);
349 Target::Address(*address)
350 }
351 }
352 };
353 if let Target::Existing(index) = target {
354 if !triplets.is_triplet(index) {
355 bail!("Link {index} is not a triplet.");
356 }
357 }
358 targets.push(target);
359 }
360 for (pattern, target) in patterns.iter().zip(&targets) {
361 for (position, part) in pattern.parts.iter().enumerate() {
362 let known = match part {
363 Reference::Any => matches!(target, Target::Existing(_)),
364 Reference::Variable(name) => {
365 bindings.contains_key(name) || defined_variables.contains(name)
366 }
367 Reference::Name(name) => {
368 name_of(triplets, name).is_some() || defined_names.contains(name)
369 }
370 Reference::Address(0) => position > 0,
371 Reference::Address(address) => {
372 triplets.reference_is_triplet(*address) || defined_addresses.contains(address)
373 }
374 };
375 if !known {
376 bail!(
377 "The {} part {} of a substitution is not a triplet.",
378 ["type", "from", "to"][position],
379 describe_reference(part)
380 );
381 }
382 }
383 }
384
385 let mut indices = Vec::with_capacity(targets.len());
386 let mut created = HashSet::new();
387 for target in targets {
388 let index = match target {
389 Target::Existing(index) => index,
390 Target::Address(address) => {
391 if !triplets.is_triplet(address) {
392 triplets.create_triplet_point_at(address)?;
393 created.insert(address);
394 }
395 address
396 }
397 Target::New(reference) => {
398 let known = match &reference {
400 Some(Reference::Name(name)) => name_of(triplets, name),
401 Some(Reference::Variable(name)) => bindings.get(name).copied(),
402 _ => None,
403 };
404 match known {
405 Some(index) => index,
406 None => {
407 let index = triplets.create_triplet_point()?;
408 match &reference {
409 Some(Reference::Name(name)) => {
410 triplets.set_name(index, name)?;
411 }
412 Some(Reference::Variable(name)) => {
413 bindings.insert(name.clone(), index);
414 }
415 _ => {}
416 }
417 created.insert(index);
418 index
419 }
420 }
421 }
422 };
423 indices.push(index);
424 }
425
426 let mut kept = HashSet::new();
427 for (pattern, &index) in patterns.iter().zip(&indices) {
428 let before = triplets.get_triplet(index);
429 let current = before.unwrap_or(Triplet::new(index, index, 0, 0));
430 let currents = [current.type_id, current.from, current.to];
431 let mut parts = [0; 3];
432 for (position, part) in pattern.parts.iter().enumerate() {
433 parts[position] = match part {
434 Reference::Any => currents[position],
435 Reference::Variable(name) => bindings[name],
436 Reference::Address(address) => *address,
437 Reference::Name(name) => match name_of(triplets, name) {
438 Some(id) => id,
439 None => bail!("The name {name} is not a triplet."),
440 },
441 };
442 }
443 triplets.update_triplet(index, parts[0], parts[1], parts[2])?;
444 let after = triplets.get_triplet(index);
445 let before = if created.contains(&index) {
446 None
447 } else {
448 before
449 };
450 if let Some(change) = changes.iter_mut().rev().find(|change| {
452 change.after.is_some_and(|after| after.index == index) && kept.contains(&index)
453 }) {
454 change.after = after;
455 } else {
456 changes.push(TripletChange { before, after });
457 }
458 kept.insert(index);
459 }
460 Ok(indices)
461}
462
463fn describe_reference(reference: &Reference) -> String {
464 match reference {
465 Reference::Any => "*".to_string(),
466 Reference::Variable(name) | Reference::Name(name) => name.clone(),
467 Reference::Address(address) => address.to_string(),
468 }
469}