Skip to main content

link_cli/
query_processor.rs

1//! QueryProcessor - Handles LiNo query parsing and execution
2//!
3//! This module provides the QueryProcessor for processing LiNo queries.
4//! Corresponds to BasicQueryProcessor, MixedQueryProcessor, and AdvancedMixedQueryProcessor in C#
5
6use anyhow::Result;
7use std::collections::{HashMap, HashSet};
8
9use crate::changes_simplifier::simplify_changes;
10use crate::error::LinkError;
11use crate::link::Link;
12use crate::link_reference_validator::LinkReferenceValidator;
13use crate::lino_link::LinoLink;
14use crate::named_type_links::NamedTypeLinks;
15use crate::query_types::{Pattern, ResolvedLink};
16
17// Pattern matching lives in a submodule; see query_processor/matching.rs.
18mod matching;
19// Write-side operations live in a submodule; see query_processor/mutations.rs.
20mod mutations;
21
22/// The `(before, after)` states a query reports, where `None` is no link:
23/// `(None, Some(link))` is a creation and `(Some(link), None)` a deletion.
24pub type Changes = Vec<(Option<Link>, Option<Link>)>;
25
26/// QueryProcessor handles LiNo query parsing and execution
27/// Corresponds to AdvancedMixedQueryProcessor in C#
28pub struct QueryProcessor {
29    trace: bool,
30    auto_create_missing_references: bool,
31}
32
33impl QueryProcessor {
34    /// Creates a new QueryProcessor
35    pub fn new(trace: bool) -> Self {
36        Self {
37            trace,
38            auto_create_missing_references: false,
39        }
40    }
41
42    pub fn with_auto_create_missing_references(
43        mut self,
44        auto_create_missing_references: bool,
45    ) -> Self {
46        self.auto_create_missing_references = auto_create_missing_references;
47        self
48    }
49
50    /// Processes a LiNo query and returns the list of changes.
51    ///
52    /// Every scenario is simplified on the way out, matching the C# CLI, which
53    /// collects the raw handler calls and runs `SimplifyChanges` over them once
54    /// in `Program.cs` regardless of which branch of the processor produced
55    /// them.
56    pub fn process_query(&self, storage: &mut impl NamedTypeLinks, query: &str) -> Result<Changes> {
57        let changes = self.process_query_raw(storage, query)?;
58        Ok(self.simplify_changes_list(&changes))
59    }
60
61    /// The processor proper: applies `query` and reports the raw
62    /// `(before, after)` states, in the order they happened.
63    fn process_query_raw(&self, storage: &mut impl NamedTypeLinks, query: &str) -> Result<Changes> {
64        self.trace_msg(&format!("[ProcessQuery] Query: \"{}\"", query));
65
66        let query = query.trim();
67        if query.is_empty() {
68            self.trace_msg("[ProcessQuery] Query is empty, returning.");
69            return Ok(vec![]);
70        }
71
72        let parsed_links = crate::query_parser::parse(query)?;
73
74        self.trace_msg(&format!(
75            "[ProcessQuery] Parser returned {} top-level link(s).",
76            parsed_links.len()
77        ));
78
79        if parsed_links.is_empty() {
80            self.trace_msg("[ProcessQuery] No top-level parsed links found, returning.");
81            return Ok(vec![]);
82        }
83
84        // Accept both the wrapped form `((restriction) (substitution))` and
85        // the C# parser-compatible form `restriction substitution`.
86        let (restriction_link, substitution_link) = match &parsed_links[0].values {
87            Some(values) if values.len() >= 2 => (&values[0], &values[1]),
88            _ if parsed_links.len() >= 2 => (&parsed_links[0], &parsed_links[1]),
89            _ => {
90                self.trace_msg("[ProcessQuery] Query has fewer than 2 links, returning.");
91                return Ok(vec![]);
92            }
93        };
94
95        self.trace_msg(&format!(
96            "[ProcessQuery] Restriction link => Id={:?} Values.Count={}",
97            restriction_link.id,
98            restriction_link.values_count()
99        ));
100        self.trace_msg(&format!(
101            "[ProcessQuery] Substitution link => Id={:?} Values.Count={}",
102            substitution_link.id,
103            substitution_link.values_count()
104        ));
105
106        let mut changes_list = Vec::new();
107
108        // If both restriction and substitution are empty, do nothing
109        if restriction_link.is_empty() && substitution_link.is_empty() {
110            self.trace_msg(
111                "[ProcessQuery] Restriction & substitution both empty => no operation, returning.",
112            );
113            return Ok(vec![]);
114        }
115
116        // Creation scenario: no restriction, only substitution
117        if restriction_link.is_empty() && !substitution_link.is_empty() {
118            self.trace_msg(
119                "[ProcessQuery] No restriction, but substitution is non-empty => creation scenario.",
120            );
121            if let Some(values) = &substitution_link.values {
122                changes_list.extend(self.validate_links_exist_or_will_be_created(
123                    storage,
124                    &[],
125                    values,
126                )?);
127
128                for link_to_create in values {
129                    let created_id =
130                        self.ensure_link_created(storage, link_to_create, &mut changes_list)?;
131                    self.trace_msg(&format!(
132                        "[ProcessQuery] Created link ID #{} from substitution pattern.",
133                        created_id
134                    ));
135                }
136            }
137            storage.save()?;
138            return Ok(changes_list);
139        }
140
141        // Deletion scenario: restriction but no substitution
142        if !restriction_link.is_empty() && substitution_link.is_empty() {
143            self.trace_msg(
144                "[ProcessQuery] Restriction non-empty, substitution empty => deletion scenario.",
145            );
146            let restriction_values = restriction_link.values.as_deref().unwrap_or(&[]);
147            changes_list.extend(self.validate_links_exist_or_will_be_created(
148                storage,
149                restriction_values,
150                &[],
151            )?);
152
153            let restriction_patterns = self.patterns_from_lino(restriction_link);
154            let mut links_to_delete = Vec::new();
155            for pattern in &restriction_patterns {
156                links_to_delete.extend(self.matched_links(storage, pattern, &HashMap::new())?);
157            }
158            links_to_delete.sort_by_key(|link| link.index);
159            links_to_delete.dedup_by_key(|link| link.index);
160
161            for link in links_to_delete {
162                if storage.exists(link.index) {
163                    self.delete_observed(storage, link.index, &mut changes_list)?;
164                    self.trace_msg(&format!("[ProcessQuery] Deleted link ID #{}.", link.index));
165                }
166            }
167            storage.save()?;
168            return Ok(changes_list);
169        }
170
171        // Update/Mixed scenario: both restriction and substitution have values
172        self.trace_msg(
173            "[ProcessQuery] Both restriction and substitution non-empty => update/mixed scenario.",
174        );
175
176        let restriction_patterns = self.patterns_from_lino(restriction_link);
177        let substitution_patterns = self.patterns_from_lino(substitution_link);
178        let restriction_values = restriction_link.values.as_deref().unwrap_or(&[]);
179        let substitution_values = substitution_link.values.as_deref().unwrap_or(&[]);
180        changes_list.extend(self.validate_links_exist_or_will_be_created(
181            storage,
182            restriction_values,
183            substitution_values,
184        )?);
185        let solutions = self.find_all_solutions(storage, &restriction_patterns)?;
186
187        if solutions.is_empty() {
188            self.trace_msg("[ProcessQuery] No solutions found => returning.");
189            if !changes_list.is_empty() {
190                storage.save()?;
191            }
192            return Ok(changes_list);
193        }
194
195        let mut all_solutions_no_operation = true;
196        for solution in &solutions {
197            if !self.solution_is_no_operation(
198                storage,
199                solution,
200                &restriction_patterns,
201                &substitution_patterns,
202            )? {
203                all_solutions_no_operation = false;
204                break;
205            }
206        }
207
208        if all_solutions_no_operation {
209            for solution in &solutions {
210                for pattern in &restriction_patterns {
211                    for link in self.matched_links(storage, pattern, solution)? {
212                        if !changes_list.contains(&(Some(link), Some(link))) {
213                            changes_list.push((Some(link), Some(link)));
214                        }
215                    }
216                }
217            }
218            return Ok(changes_list);
219        }
220
221        let mut all_planned_operations = Vec::new();
222        for solution in &solutions {
223            let restriction_links = self.resolve_patterns(
224                storage,
225                &restriction_patterns,
226                solution,
227                false,
228                &mut changes_list,
229            )?;
230            let substitution_links = self.resolve_patterns(
231                storage,
232                &substitution_patterns,
233                solution,
234                true,
235                &mut changes_list,
236            )?;
237            all_planned_operations
238                .extend(self.determine_operations(&restriction_links, &substitution_links));
239        }
240
241        let intended_final_states = Self::intended_final_states(&all_planned_operations);
242
243        for (before, after) in all_planned_operations {
244            self.apply_operation(storage, before, after, &mut changes_list)?;
245        }
246
247        self.restore_unexpected_deletions(storage, &intended_final_states, &mut changes_list)?;
248
249        storage.save()?;
250
251        Ok(changes_list)
252    }
253
254    fn validate_links_exist_or_will_be_created(
255        &self,
256        storage: &mut impl NamedTypeLinks,
257        restriction_patterns: &[LinoLink],
258        substitution_patterns: &[LinoLink],
259    ) -> Result<Changes> {
260        LinkReferenceValidator::for_query(self.trace, self.auto_create_missing_references)
261            .validate_links_exist_or_will_be_created(
262                storage,
263                restriction_patterns,
264                substitution_patterns,
265            )
266    }
267
268    fn patterns_from_lino(&self, lino_link: &LinoLink) -> Vec<Pattern> {
269        let mut patterns = lino_link
270            .values
271            .as_ref()
272            .map(|values| {
273                values
274                    .iter()
275                    .map(Self::create_pattern_from_lino)
276                    .collect::<Vec<_>>()
277            })
278            .unwrap_or_default();
279
280        if lino_link.id.is_some() {
281            patterns.insert(0, Self::create_pattern_from_lino(lino_link));
282        }
283
284        patterns
285    }
286
287    fn create_pattern_from_lino(lino_link: &LinoLink) -> Pattern {
288        let index = lino_link.id.clone().unwrap_or_default();
289        match &lino_link.values {
290            Some(values) if values.len() == 2 => Pattern::new(
291                index,
292                Some(Self::create_pattern_from_lino(&values[0])),
293                Some(Self::create_pattern_from_lino(&values[1])),
294            ),
295            _ => Pattern::new(index, None, None),
296        }
297    }
298
299    fn find_all_solutions(
300        &self,
301        storage: &mut impl NamedTypeLinks,
302        patterns: &[Pattern],
303    ) -> Result<Vec<HashMap<String, u32>>> {
304        let mut partial_solutions = vec![HashMap::new()];
305
306        for pattern in patterns {
307            let mut new_solutions = Vec::new();
308            for solution in &partial_solutions {
309                for match_solution in self.match_pattern(storage, pattern, solution)? {
310                    if Self::solutions_are_compatible(solution, &match_solution) {
311                        let mut combined = solution.clone();
312                        combined.extend(match_solution);
313                        new_solutions.push(combined);
314                    }
315                }
316            }
317            partial_solutions = new_solutions;
318            if partial_solutions.is_empty() {
319                break;
320            }
321        }
322
323        Ok(partial_solutions)
324    }
325
326    fn solutions_are_compatible(
327        existing: &HashMap<String, u32>,
328        new_assignments: &HashMap<String, u32>,
329    ) -> bool {
330        new_assignments
331            .iter()
332            .all(|(key, value)| existing.get(key).is_none_or(|existing| existing == value))
333    }
334
335    fn resolve_patterns_readonly(
336        &self,
337        storage: &mut impl NamedTypeLinks,
338        patterns: &[Pattern],
339        solution: &HashMap<String, u32>,
340        is_substitution: bool,
341    ) -> Result<Vec<ResolvedLink>> {
342        let mut resolved = Vec::new();
343        for pattern in patterns {
344            if let Some(link) =
345                self.resolve_pattern_readonly(storage, pattern, solution, is_substitution)?
346            {
347                resolved.push(link);
348            }
349        }
350        Ok(resolved)
351    }
352
353    fn resolve_pattern_readonly(
354        &self,
355        storage: &mut impl NamedTypeLinks,
356        pattern: &Pattern,
357        solution: &HashMap<String, u32>,
358        is_substitution: bool,
359    ) -> Result<Option<ResolvedLink>> {
360        if pattern.is_leaf() {
361            let index = self.resolve_identifier_readonly(
362                storage,
363                &pattern.index,
364                solution,
365                if is_substitution { 0 } else { u32::MAX },
366            )?;
367            return Ok(Some(ResolvedLink::new(index, u32::MAX, u32::MAX, None)));
368        }
369
370        let source_pattern = pattern
371            .source
372            .as_deref()
373            .ok_or_else(|| LinkError::InvalidFormat("Invalid source pattern".to_string()))?;
374        let target_pattern = pattern
375            .target
376            .as_deref()
377            .ok_or_else(|| LinkError::InvalidFormat("Invalid target pattern".to_string()))?;
378
379        let source = self
380            .resolve_pattern_readonly(storage, source_pattern, solution, is_substitution)?
381            .ok_or_else(|| LinkError::InvalidFormat("Invalid source pattern".to_string()))?
382            .index;
383        let target = self
384            .resolve_pattern_readonly(storage, target_pattern, solution, is_substitution)?
385            .ok_or_else(|| LinkError::InvalidFormat("Invalid target pattern".to_string()))?
386            .index;
387        let default_index = if is_substitution { 0 } else { u32::MAX };
388        let index =
389            self.resolve_identifier_readonly(storage, &pattern.index, solution, default_index)?;
390
391        Ok(Some(ResolvedLink::new(index, source, target, None)))
392    }
393
394    fn resolve_identifier_readonly(
395        &self,
396        storage: &mut impl NamedTypeLinks,
397        identifier: &str,
398        solution: &HashMap<String, u32>,
399        default_value: u32,
400    ) -> Result<u32> {
401        if identifier.is_empty() {
402            return Ok(default_value);
403        }
404        if identifier == "*" {
405            return Ok(u32::MAX);
406        }
407        if let Some(value) = solution.get(identifier) {
408            return Ok(*value);
409        }
410        if Self::is_variable(identifier) {
411            return Ok(default_value);
412        }
413        if let Ok(parsed) = identifier.parse::<u32>() {
414            return Ok(parsed);
415        }
416        Ok(storage
417            .get_by_name(crate::query_parser::name(identifier))?
418            .unwrap_or(default_value))
419    }
420
421    fn resolve_patterns(
422        &self,
423        storage: &mut impl NamedTypeLinks,
424        patterns: &[Pattern],
425        solution: &HashMap<String, u32>,
426        is_substitution: bool,
427        changes: &mut Changes,
428    ) -> Result<Vec<ResolvedLink>> {
429        let mut working_solution = solution.clone();
430        let mut visited_indexes = HashSet::new();
431        let mut resolved = Vec::new();
432        for pattern in patterns {
433            resolved.push(self.resolve_pattern(
434                storage,
435                pattern,
436                &mut working_solution,
437                is_substitution,
438                &mut visited_indexes,
439                changes,
440            )?);
441        }
442        Ok(resolved)
443    }
444
445    fn resolve_pattern(
446        &self,
447        storage: &mut impl NamedTypeLinks,
448        pattern: &Pattern,
449        solution: &mut HashMap<String, u32>,
450        is_substitution: bool,
451        visited_indexes: &mut HashSet<u32>,
452        changes: &mut Changes,
453    ) -> Result<ResolvedLink> {
454        if pattern.is_leaf() {
455            let index = self.resolve_identifier(
456                storage,
457                &pattern.index,
458                solution,
459                if is_substitution { 0 } else { u32::MAX },
460                is_substitution,
461                changes,
462            )?;
463            return Ok(ResolvedLink::new(index, u32::MAX, u32::MAX, None));
464        }
465
466        let mut source = self
467            .resolve_pattern(
468                storage,
469                pattern.source.as_deref().unwrap(),
470                solution,
471                is_substitution,
472                visited_indexes,
473                changes,
474            )?
475            .index;
476        let mut target = self
477            .resolve_pattern(
478                storage,
479                pattern.target.as_deref().unwrap(),
480                solution,
481                is_substitution,
482                visited_indexes,
483                changes,
484            )?
485            .index;
486        let default_index = if is_substitution { 0 } else { u32::MAX };
487        let mut index = self.resolve_identifier(
488            storage,
489            &pattern.index,
490            solution,
491            default_index,
492            false,
493            changes,
494        )?;
495        let mut name = None;
496
497        if is_substitution
498            && !pattern.index.is_empty()
499            && !Self::is_numeric_or_wildcard(&pattern.index)
500            && !Self::is_variable(&pattern.index)
501        {
502            name = Some(pattern.index.clone());
503            if index == 0 {
504                if let Some(existing_id) = storage.search(source, target) {
505                    index = existing_id;
506                }
507            }
508        }
509
510        if is_substitution {
511            Self::preserve_existing_substitution_parts(
512                storage,
513                pattern,
514                solution,
515                index,
516                &mut source,
517                &mut target,
518                visited_indexes,
519            )?;
520        }
521
522        Ok(ResolvedLink::new(index, source, target, name))
523    }
524
525    fn resolve_identifier(
526        &self,
527        storage: &mut impl NamedTypeLinks,
528        identifier: &str,
529        solution: &HashMap<String, u32>,
530        default_value: u32,
531        create_named_leaf: bool,
532        changes: &mut Changes,
533    ) -> Result<u32> {
534        if identifier.is_empty() {
535            return Ok(default_value);
536        }
537        if identifier == "*" {
538            return Ok(u32::MAX);
539        }
540        if let Some(value) = solution.get(identifier) {
541            return Ok(*value);
542        }
543        if Self::is_variable(identifier) {
544            return Ok(default_value);
545        }
546        if let Ok(parsed) = identifier.parse::<u32>() {
547            return Ok(parsed);
548        }
549        if create_named_leaf {
550            return self.ensure_named_point_link(storage, identifier, changes);
551        }
552        Ok(storage
553            .get_by_name(crate::query_parser::name(identifier))?
554            .unwrap_or(default_value))
555    }
556
557    fn determine_operations(
558        &self,
559        restrictions: &[ResolvedLink],
560        substitutions: &[ResolvedLink],
561    ) -> Vec<(Option<ResolvedLink>, Option<ResolvedLink>)> {
562        let mut operations = Vec::new();
563        let mut restriction_by_index = HashMap::new();
564        let mut substitution_by_index = HashMap::new();
565        let mut wildcard_restrictions = Vec::new();
566        let mut wildcard_substitutions = Vec::new();
567
568        for restriction in restrictions {
569            if Self::is_normal_index(restriction.index) {
570                restriction_by_index.insert(restriction.index, restriction.clone());
571            } else {
572                wildcard_restrictions.push(restriction.clone());
573            }
574        }
575
576        for substitution in substitutions {
577            if Self::is_normal_index(substitution.index) {
578                substitution_by_index.insert(substitution.index, substitution.clone());
579            } else {
580                wildcard_substitutions.push(substitution.clone());
581            }
582        }
583
584        let mut all_indices = restriction_by_index
585            .keys()
586            .chain(substitution_by_index.keys())
587            .copied()
588            .collect::<Vec<_>>();
589        all_indices.sort_unstable();
590        all_indices.dedup();
591
592        for index in all_indices {
593            match (
594                restriction_by_index.get(&index),
595                substitution_by_index.get(&index),
596            ) {
597                (Some(before), Some(after)) => {
598                    operations.push((Some(before.clone()), Some(after.clone())));
599                }
600                (Some(before), None) => operations.push((Some(before.clone()), None)),
601                (None, Some(after)) => operations.push((None, Some(after.clone()))),
602                (None, None) => {}
603            }
604        }
605
606        operations.extend(
607            wildcard_restrictions
608                .into_iter()
609                .map(|restriction| (Some(restriction), None)),
610        );
611        operations.extend(
612            wildcard_substitutions
613                .into_iter()
614                .map(|substitution| (None, Some(substitution))),
615        );
616
617        operations
618    }
619
620    fn apply_operation(
621        &self,
622        storage: &mut impl NamedTypeLinks,
623        before: Option<ResolvedLink>,
624        after: Option<ResolvedLink>,
625        changes: &mut Changes,
626    ) -> Result<()> {
627        match (before, after) {
628            (Some(before), None) => {
629                let mut links = self.links_matching_definition(storage, &before)?;
630                links.sort_by_key(|link| link.index);
631                links.dedup_by_key(|link| link.index);
632                for link in links {
633                    if storage.exists(link.index) {
634                        self.delete_observed(storage, link.index, changes)?;
635                    }
636                }
637            }
638            (None, Some(after)) => {
639                self.create_or_update_resolved_link(storage, &after, changes)?;
640            }
641            (Some(before), Some(after)) => {
642                if before.index == after.index && storage.exists(before.index) {
643                    let stored = storage.get_link(before.index).unwrap();
644                    if stored.source != after.source || stored.target != after.target {
645                        // A merge into a duplicate deletes `before.index`;
646                        // `restore_unexpected_deletions` puts it back when the
647                        // query asked for it, exactly as the C# processor does.
648                        self.update_observed(
649                            storage,
650                            before.index,
651                            after.source,
652                            after.target,
653                            changes,
654                        )?;
655                    } else {
656                        changes.push((Some(stored), Some(stored)));
657                    }
658                    if let Some(name) = &after.name {
659                        storage.set_name(before.index, crate::query_parser::name(name))?;
660                    }
661                } else {
662                    self.apply_operation(storage, Some(before), None, changes)?;
663                    self.apply_operation(storage, None, Some(after), changes)?;
664                }
665            }
666            (None, None) => {}
667        }
668
669        Ok(())
670    }
671
672    fn links_matching_definition(
673        &self,
674        storage: &mut impl NamedTypeLinks,
675        definition: &ResolvedLink,
676    ) -> Result<Vec<Link>> {
677        Ok(storage
678            .all_links()
679            .into_iter()
680            .filter(|link| {
681                (definition.index == 0
682                    || Self::is_any(definition.index)
683                    || link.index == definition.index)
684                    && (Self::is_any(definition.source) || link.source == definition.source)
685                    && (Self::is_any(definition.target) || link.target == definition.target)
686            })
687            .collect())
688    }
689
690    fn assign_variable(id: &str, value: u32, assignments: &mut HashMap<String, u32>) {
691        if Self::is_variable(id) && value != 0 {
692            assignments.insert(id.to_string(), value);
693        }
694    }
695
696    fn is_variable(identifier: &str) -> bool {
697        !identifier.is_empty() && identifier.starts_with('$')
698    }
699
700    fn is_any(value: u32) -> bool {
701        value == u32::MAX
702    }
703
704    /// Resolves a half a query left unspecified against the half already
705    /// stored, the way C# resolves its `any` constant on the way into the
706    /// store.
707    ///
708    /// The C# processor marks an unbound substitution variable — and a `*` — with
709    /// `links.Constants.Any`, which is a value the *store* understands:
710    /// `Update` leaves a half substituted with `any` exactly as it was, and a
711    /// link created from one gets `null` there. This processor marks the same
712    /// thing with [`u32::MAX`], which the store underneath does not recognise
713    /// (its `any` is `2147483644`, the hybrid-aware constant), so `() (($a $a))`
714    /// used to store the literal `4294967295` in both halves where C# stores
715    /// `(1: 0 0)`. Resolving at the write boundary keeps [`u32::MAX`] as this
716    /// crate's single internal marker while writing what C# writes.
717    fn resolve_unspecified(value: u32, existing: u32) -> u32 {
718        if Self::is_any(value) {
719            existing
720        } else {
721            value
722        }
723    }
724
725    /// Looks a doublet up with unspecified halves treated as wildcards, the way
726    /// C#'s `SearchOrDefault` does.
727    ///
728    /// `SearchOrDefault` runs through `Each`, which reads `any` in a query as
729    /// "every value" rather than as a literal address, so `() ((1 $a))` finds a
730    /// stored `(1: 1 1)` instead of creating a second link beside it.
731    /// [`NamedTypeLinks::search`] matches literally on purpose — it backs
732    /// uniqueness resolution — so the wildcard pass belongs here.
733    fn search_unspecified(
734        storage: &mut impl NamedTypeLinks,
735        source: u32,
736        target: u32,
737    ) -> Option<u32> {
738        if !Self::is_any(source) && !Self::is_any(target) {
739            return storage.search(source, target);
740        }
741        storage
742            .all_links()
743            .into_iter()
744            .filter(|link| {
745                (Self::is_any(source) || link.source == source)
746                    && (Self::is_any(target) || link.target == target)
747            })
748            .map(|link| link.index)
749            .min()
750    }
751
752    fn is_normal_index(value: u32) -> bool {
753        value != 0 && !Self::is_any(value)
754    }
755
756    fn is_numeric_or_wildcard(identifier: &str) -> bool {
757        identifier == "*" || identifier.parse::<u32>().is_ok()
758    }
759
760    /// Simplifies the changes list.
761    ///
762    /// A missing side — the state before a creation, or the state after a
763    /// deletion — becomes the null link `(0: 0 0)` on the way in and turns back
764    /// into `None` on the way out. C# has no option type here and feeds the
765    /// simplifier `default(Link<uint>)` for both, so routing the null states
766    /// around the simplifier (as this used to) both reported creations and
767    /// deletions in a different order than C# and hid them from the chain
768    /// collapsing that is the whole point of the pass.
769    fn simplify_changes_list(&self, changes: &[(Option<Link>, Option<Link>)]) -> Changes {
770        let to_simplify: Vec<(Link, Link)> = changes
771            .iter()
772            .map(|(before, after)| {
773                (
774                    before.unwrap_or_else(Link::null),
775                    after.unwrap_or_else(Link::null),
776                )
777            })
778            .collect();
779
780        simplify_changes(to_simplify)
781            .into_iter()
782            .map(|(before, after)| {
783                (
784                    (!before.is_null()).then_some(before),
785                    (!after.is_null()).then_some(after),
786                )
787            })
788            .collect()
789    }
790
791    /// Logs a trace message if tracing is enabled
792    fn trace_msg(&self, msg: &str) {
793        if self.trace {
794            eprintln!("{}", msg);
795        }
796    }
797}