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