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
221fn solve<T: Triplets + ?Sized>(
224 triplets: &mut T,
225 patterns: &[Pattern],
226 bindings: Bindings,
227 matched: &mut Vec<u32>,
228 solutions: &mut Vec<(Bindings, Vec<u32>)>,
229) {
230 let Some((pattern, rest)) = patterns.split_first() else {
231 solutions.push((bindings, matched.clone()));
232 return;
233 };
234 let any = Reference::Any;
235 let references = [
236 pattern.index.as_ref().unwrap_or(&any),
237 &pattern.parts[0],
238 &pattern.parts[1],
239 &pattern.parts[2],
240 ];
241 let mut values = [None; 4];
242 for (slot, reference) in values.iter_mut().zip(references) {
243 match restriction_of(triplets, reference, &bindings) {
244 Restriction::Any => {}
245 Restriction::Value(value) => *slot = Some(value),
246 Restriction::Impossible => return,
247 }
248 }
249 let query = TripletQuery::new(values[0], values[1], values[2], values[3]);
250 for triplet in triplets.each_triplet(query) {
251 let mut next = bindings.clone();
252 let found = [triplet.index, triplet.type_id, triplet.from, triplet.to];
253 if references
254 .iter()
255 .zip(found)
256 .all(|(reference, value)| bind(&mut next, reference, value))
257 {
258 matched.push(triplet.index);
259 solve(triplets, rest, next, matched, solutions);
260 matched.pop();
261 }
262 }
263}
264
265enum Target {
267 Existing(u32),
268 Address(u32),
269 New(Option<Reference>),
270}
271
272pub(super) fn substitute<T: Triplets + ?Sized>(
280 triplets: &mut T,
281 patterns: &[Pattern],
282 mut bindings: Bindings,
283 changes: &mut Vec<TripletChange>,
284) -> Result<Vec<u32>> {
285 let mut targets = Vec::with_capacity(patterns.len());
286 let mut defined_names = HashSet::new();
287 let mut defined_variables = HashSet::new();
288 let mut defined_addresses = HashSet::new();
289 for pattern in patterns {
290 let target = match &pattern.index {
291 None => Target::New(None),
292 Some(Reference::Any) => bail!("A substitution cannot create or update the index *."),
293 Some(Reference::Variable(name)) => match bindings.get(name) {
294 Some(&bound) => Target::Existing(bound),
295 None => {
296 defined_variables.insert(name.clone());
297 Target::New(pattern.index.clone())
298 }
299 },
300 Some(Reference::Name(name)) => match name_of(triplets, name) {
301 Some(id) => Target::Existing(id),
302 None => {
303 defined_names.insert(name.clone());
304 Target::New(pattern.index.clone())
305 }
306 },
307 Some(Reference::Address(address)) => {
308 if *address == 0 {
309 bail!("A triplet cannot be at address 0.");
310 }
311 if triplets.is_triplet(*address) {
312 Target::Existing(*address)
313 } else if triplets.exists(*address) {
314 bail!("Link {address} is a doublet, not a triplet.");
315 } else {
316 defined_addresses.insert(*address);
317 Target::Address(*address)
318 }
319 }
320 };
321 if let Target::Existing(index) = target {
322 if !triplets.is_triplet(index) {
323 bail!("Link {index} is not a triplet.");
324 }
325 }
326 targets.push(target);
327 }
328 for (pattern, target) in patterns.iter().zip(&targets) {
329 for (position, part) in pattern.parts.iter().enumerate() {
330 let known = match part {
331 Reference::Any => matches!(target, Target::Existing(_)),
332 Reference::Variable(name) => {
333 bindings.contains_key(name) || defined_variables.contains(name)
334 }
335 Reference::Name(name) => {
336 name_of(triplets, name).is_some() || defined_names.contains(name)
337 }
338 Reference::Address(0) => position > 0,
339 Reference::Address(address) => {
340 triplets.is_triplet(*address) || defined_addresses.contains(address)
341 }
342 };
343 if !known {
344 bail!(
345 "The {} part {} of a substitution is not a triplet.",
346 ["type", "from", "to"][position],
347 describe_reference(part)
348 );
349 }
350 }
351 }
352
353 let mut indices = Vec::with_capacity(targets.len());
354 let mut created = HashSet::new();
355 for target in targets {
356 let index = match target {
357 Target::Existing(index) => index,
358 Target::Address(address) => {
359 if !triplets.is_triplet(address) {
360 triplets.create_triplet_point_at(address)?;
361 created.insert(address);
362 }
363 address
364 }
365 Target::New(reference) => {
366 let known = match &reference {
368 Some(Reference::Name(name)) => name_of(triplets, name),
369 Some(Reference::Variable(name)) => bindings.get(name).copied(),
370 _ => None,
371 };
372 match known {
373 Some(index) => index,
374 None => {
375 let index = triplets.create_triplet_point()?;
376 match &reference {
377 Some(Reference::Name(name)) => {
378 triplets.set_name(index, name)?;
379 }
380 Some(Reference::Variable(name)) => {
381 bindings.insert(name.clone(), index);
382 }
383 _ => {}
384 }
385 created.insert(index);
386 index
387 }
388 }
389 }
390 };
391 indices.push(index);
392 }
393
394 let mut kept = HashSet::new();
395 for (pattern, &index) in patterns.iter().zip(&indices) {
396 let before = triplets.get_triplet(index);
397 let current = before.unwrap_or(Triplet::new(index, index, 0, 0));
398 let currents = [current.type_id, current.from, current.to];
399 let mut parts = [0; 3];
400 for (position, part) in pattern.parts.iter().enumerate() {
401 parts[position] = match part {
402 Reference::Any => currents[position],
403 Reference::Variable(name) => bindings[name],
404 Reference::Address(address) => *address,
405 Reference::Name(name) => match name_of(triplets, name) {
406 Some(id) => id,
407 None => bail!("The name {name} is not a triplet."),
408 },
409 };
410 }
411 triplets.update_triplet(index, parts[0], parts[1], parts[2])?;
412 let after = triplets.get_triplet(index);
413 let before = if created.contains(&index) {
414 None
415 } else {
416 before
417 };
418 if let Some(change) = changes.iter_mut().rev().find(|change| {
420 change.after.is_some_and(|after| after.index == index) && kept.contains(&index)
421 }) {
422 change.after = after;
423 } else {
424 changes.push(TripletChange { before, after });
425 }
426 kept.insert(index);
427 }
428 Ok(indices)
429}
430
431fn describe_reference(reference: &Reference) -> String {
432 match reference {
433 Reference::Any => "*".to_string(),
434 Reference::Variable(name) | Reference::Name(name) => name.clone(),
435 Reference::Address(address) => address.to_string(),
436 }
437}