Skip to main content

syntax/syntax_editor/
edit_algo.rs

1//! Implementation of applying changes to a syntax tree.
2
3use std::{cmp::Ordering, ops::Range};
4
5use rowan::TextRange;
6use rustc_hash::FxHashMap;
7use stdx::format_to;
8
9use crate::{NodeOrToken, SyntaxElement, SyntaxNode};
10
11use super::{
12    Change, ChangeKind, PositionRepr, SyntaxAnnotation, SyntaxEdit, SyntaxEditor, SyntaxMapping,
13    index_no_trivia, mapping::MissingMapping,
14};
15
16/// A validated batch of changes in the exact order in which it must execute.
17///
18/// Planning is deliberately separate from tree mutation. Once an `EditPlan`
19/// exists, execution does not need to reason about overlaps, dependencies, or
20/// source ordering.
21struct EditPlan {
22    changes: Vec<PlannedChange>,
23}
24
25/// A change whose target tree and output tracking are fully known.
26struct PlannedChange {
27    tree: SyntaxNode,
28    change: Change,
29    record_as_changed: bool,
30}
31
32impl PlannedChange {
33    /// Returns the immutable source elements that this change will slice in.
34    fn replacement_elements(&self) -> &[SyntaxElement] {
35        match &self.change {
36            Change::Insert(_, element) | Change::Replace(_, Some(element)) => {
37                std::slice::from_ref(element)
38            }
39            Change::InsertAll(_, elements)
40            | Change::ReplaceWithMany(_, elements)
41            | Change::ReplaceAll(_, elements) => elements,
42            Change::Replace(_, None) => &[],
43        }
44    }
45}
46
47/// The dependency info accumulated from one source ordered changes.
48///
49/// `parent` is an edge to the nearest containing node replacement. A discarded
50/// entry has no executable graph node because an ancestor deletion or ambiguous
51/// range replacement has mde its target unavailable.
52#[derive(Clone, Copy, Default)]
53struct PlanEntry {
54    parent: Option<usize>,
55    discarded: bool,
56}
57
58/// Planning failure containing the source-ordered changes use for diag.
59struct InvalidEditPlan {
60    changes: Vec<Change>,
61}
62
63impl EditPlan {
64    /// Validates raw editor changes and turns them into an execution schedule.
65    ///
66    /// The input is first sorted in source order, dependent targets are then
67    /// rewritten from their input trees into ancestor replacement trees. Finally,
68    /// discarded changes are removed and the dependency forest is traversed in
69    /// postorder.
70    /// Independent roots and sibling changes are prioritized right to left.
71    fn build(
72        mut changes: Vec<Change>,
73        mappings: &SyntaxMapping,
74        mut node_depth: impl FnMut(SyntaxNode) -> usize,
75    ) -> Result<Self, InvalidEditPlan> {
76        changes.sort_by(|left, right| {
77            left.target_range()
78                .start()
79                .cmp(&right.target_range().start())
80                .then_with(|| {
81                    let left_target = left.target_parent();
82                    let right_target = right.target_parent();
83                    if left_target == right_target {
84                        Ordering::Equal
85                    } else {
86                        node_depth(left_target).cmp(&node_depth(right_target))
87                    }
88                })
89                .then(left.change_kind().cmp(&right.change_kind()))
90        });
91
92        if !Self::replacements_are_disjoint(&changes, &mut node_depth) {
93            return Err(InvalidEditPlan { changes });
94        }
95
96        let mut entries = vec![PlanEntry::default(); changes.len()];
97        let mut regions_by_tree = FxHashMap::<SyntaxNode, Vec<ChangedRegion>>::default();
98
99        for (index, change) in changes.iter().enumerate() {
100            let target_tree = change.target_parent().tree_top();
101            let regions = regions_by_tree.entry(target_tree).or_default();
102            if let Some(region_index) = regions
103                .iter()
104                .rposition(|region| region.range.contains_range(change.target_range()))
105            {
106                regions.truncate(region_index + 1);
107                match regions[region_index].nested_changes {
108                    NestedChanges::Remap => {
109                        entries[index].parent = Some(regions[region_index].change_index);
110                    }
111                    NestedChanges::Discard => entries[index].discarded = true,
112                }
113            } else {
114                regions.clear();
115            }
116
117            if let Some(region) = ChangedRegion::for_change(change, index, entries[index].discarded)
118            {
119                regions.push(region);
120            }
121        }
122
123        // Work from the innermost dependency towards the outermost one. This
124        // lets a chain A -> B -> C rewrite C into B before B itself is mapped
125        // into A's replacement tree.
126        for (child, entry) in entries.iter().enumerate().rev() {
127            if let Some(parent) = entry.parent {
128                Self::rewrite_dependent_target(&mut changes, parent, child, mappings);
129            }
130        }
131
132        let mut children = vec![Vec::new(); changes.len()];
133        for (child, entry) in entries.iter().enumerate() {
134            if let Some(parent) = entry.parent {
135                children[parent].push(child);
136            }
137        }
138        for siblings in &mut children {
139            siblings.sort_by(|&left, &right| {
140                Self::execution_priority(&changes[left], &changes[right], &mut node_depth)
141            });
142        }
143
144        let mut roots = entries
145            .iter()
146            .enumerate()
147            .filter_map(|(index, entry)| {
148                (!entry.discarded && entry.parent.is_none()).then_some(index)
149            })
150            .collect::<Vec<_>>();
151        roots.sort_by(|&left, &right| {
152            Self::execution_priority(&changes[left], &changes[right], &mut node_depth)
153        });
154
155        let mut planned = changes
156            .into_iter()
157            .zip(entries)
158            .map(|(change, entry)| {
159                (!entry.discarded).then_some(PlannedChange {
160                    tree: change.target_parent().tree_top(),
161                    change,
162                    record_as_changed: entry.parent.is_none(),
163                })
164            })
165            .collect::<Vec<_>>();
166
167        let mut ordered = Vec::new();
168        for root in roots {
169            Self::append_postorder(root, &children, &mut planned, &mut ordered);
170        }
171
172        Ok(Self { changes: ordered })
173    }
174
175    /// Orders disjoint changes from right to left, with deeper ties first.
176    fn execution_priority(
177        left: &Change,
178        right: &Change,
179        node_depth: &mut impl FnMut(SyntaxNode) -> usize,
180    ) -> Ordering {
181        right
182            .target_range()
183            .start()
184            .cmp(&left.target_range().start())
185            .then_with(|| node_depth(right.target_parent()).cmp(&node_depth(left.target_parent())))
186            .then(right.change_kind().cmp(&left.change_kind()))
187    }
188
189    /// Appends a dependency subtree in post order fashion.
190    fn append_postorder(
191        index: usize,
192        children: &[Vec<usize>],
193        planned: &mut [Option<PlannedChange>],
194        ordered: &mut Vec<PlannedChange>,
195    ) {
196        for &child in &children[index] {
197            Self::append_postorder(child, children, planned, ordered);
198        }
199        ordered.push(planned[index].take().expect("reachable plan nodes are not discarded"));
200    }
201
202    /// Checks that replacement at the same tree depth do not overlap
203    ///
204    /// `changes` is sorted by range start, so overlap is a single comparison against the
205    /// last range at that key, and `insert` can throw away the range it evicts.
206    fn replacements_are_disjoint(
207        changes: &[Change],
208        mut node_depth: impl FnMut(SyntaxNode) -> usize,
209    ) -> bool {
210        let mut previous = FxHashMap::<(SyntaxNode, usize), TextRange>::default();
211        for change in changes {
212            if !matches!(change.change_kind(), ChangeKind::Replace | ChangeKind::ReplaceRange) {
213                continue;
214            }
215
216            let parent = change.target_parent();
217            let key = (parent.tree_top(), node_depth(parent));
218            if previous
219                .insert(key, change.target_range())
220                .is_some_and(|range| range.end() > change.target_range().start())
221            {
222                return false;
223            }
224        }
225        true
226    }
227
228    /// Maps one dependent change into its ancestor replacement tree.
229    fn rewrite_dependent_target(
230        changes: &mut [Change],
231        parent: usize,
232        child: usize,
233        mappings: &SyntaxMapping,
234    ) {
235        let (input_ancestor, output_ancestor) = match &changes[parent] {
236            Change::Replace(
237                SyntaxElement::Node(target),
238                Some(SyntaxElement::Node(replacement)),
239            ) => (target.clone(), replacement.clone()),
240            _ => unreachable!("only node replacements can own dependent changes"),
241        };
242
243        let upmap_node = |target: &SyntaxNode| {
244            mappings.upmap_child(target, &input_ancestor, &output_ancestor).unwrap_or_else(
245                |MissingMapping(current)| {
246                    panic!(
247                        "no mappings exist between {current:?} (ancestor of {input_ancestor:?}) and {output_ancestor:?}"
248                    )
249                },
250            )
251        };
252        let upmap_element = |target: &SyntaxElement| {
253            mappings.upmap_child_element(target, &input_ancestor, &output_ancestor).unwrap_or_else(
254                |MissingMapping(current)| {
255                    panic!(
256                        "no mappings exist between {current:?} (ancestor of {input_ancestor:?}) and {output_ancestor:?}"
257                    )
258                },
259            )
260        };
261
262        match &mut changes[child] {
263            Change::Insert(position, _) | Change::InsertAll(position, _) => {
264                match &mut position.repr {
265                    PositionRepr::FirstChild(parent) => *parent = upmap_node(parent),
266                    PositionRepr::After(child) => *child = upmap_element(child),
267                }
268            }
269            Change::Replace(target, _) | Change::ReplaceWithMany(target, _) => {
270                *target = upmap_element(target);
271            }
272            Change::ReplaceAll(range, _) => {
273                *range = upmap_element(range.start())..=upmap_element(range.end());
274            }
275        }
276    }
277}
278
279/// A stable structural address expressed as `children_with_token` indices.
280#[derive(Clone)]
281struct SyntaxPath {
282    child_indices: Vec<usize>,
283}
284
285impl SyntaxPath {
286    /// Builds the root-relative path of element in its current tree.
287    fn new(element: &SyntaxElement) -> Self {
288        let mut child_indices = Vec::new();
289        let mut node = match element {
290            SyntaxElement::Node(node) => node.clone(),
291            SyntaxElement::Token(token) => {
292                child_indices.push(index_no_trivia(element));
293                token.parent().unwrap()
294            }
295        };
296
297        while let Some(parent) = node.parent() {
298            child_indices.push(node.index());
299            node = parent;
300        }
301        child_indices.reverse();
302        Self { child_indices }
303    }
304
305    /// Follows this path from root, returning None if the structure differs.
306    fn resolve(&self, root: &SyntaxNode) -> Option<SyntaxElement> {
307        let mut current = SyntaxElement::Node(root.clone());
308        for &index in &self.child_indices {
309            current = current.into_node()?.children_with_tokens().nth(index)?;
310        }
311        Some(current)
312    }
313
314    /// Removes `ancestor`'s prefix, yielding this path within that subtree.
315    ///
316    /// Could have used LCA?
317    fn relative_to(&self, ancestor: &SyntaxPath) -> Option<SyntaxPath> {
318        self.child_indices
319            .strip_prefix(ancestor.child_indices.as_slice())
320            .map(|relative| SyntaxPath { child_indices: relative.to_vec() })
321    }
322
323    /// Appends an inserted child slot and a path relative to that child.
324    fn in_child(&self, index: usize, relative: &SyntaxPath) -> SyntaxPath {
325        let mut child_indices =
326            Vec::with_capacity(self.child_indices.len() + relative.child_indices.len() + 1);
327        child_indices.extend_from_slice(&self.child_indices);
328        child_indices.push(index);
329        child_indices.extend_from_slice(&relative.child_indices);
330        SyntaxPath { child_indices }
331    }
332
333    /// Updates this path for a splice and reports whether its element survives.
334    fn adjust_for_splice(
335        &mut self,
336        parent: &SyntaxPath,
337        deleted: &Range<usize>,
338        inserted: usize,
339    ) -> bool {
340        let Some(relative) = self.child_indices.strip_prefix(parent.child_indices.as_slice())
341        else {
342            return true;
343        };
344        let Some((&child, _)) = relative.split_first() else { return true };
345
346        if deleted.contains(&child) {
347            return false;
348        }
349        if child >= deleted.end {
350            let new_child = child + inserted;
351            self.child_indices[parent.child_indices.len()] =
352                new_child - (deleted.end - deleted.start);
353        }
354        true
355    }
356}
357
358/// An annotation paired with its structural location and registration order.
359#[derive(Clone)]
360struct TrackedAnnotation {
361    path: SyntaxPath,
362    annotation: SyntaxAnnotation,
363    order: usize,
364}
365
366/// A structural edit used to translate original paths into a current tree.
367enum PathEdit {
368    /// A child-list splice with all coordinates relative to the pre-edit tree.
369    Splice { parent: SyntaxPath, deleted: Range<usize>, inserted: usize },
370    /// A root replacement, after which no path into the old root survives.
371    ReplaceRoot,
372}
373
374/// The evolving immutable root and location metadata for one source tree.
375///
376/// A syntax edit can involve the editor root plus several detached factory
377/// trees. Each receives an independent state so dependent edits can be applied
378/// before a generated tree is inserted elsewhere.
379struct TreeState {
380    root: SyntaxNode,
381    edits: Vec<PathEdit>,
382    changed: Vec<SyntaxPath>,
383    original_annotations: Vec<TrackedAnnotation>,
384    annotations: Vec<TrackedAnnotation>,
385}
386
387impl TreeState {
388    /// Starts tracking an unmodified immutable root.
389    fn new(root: SyntaxNode) -> Self {
390        Self {
391            root,
392            edits: Vec::new(),
393            changed: Vec::new(),
394            original_annotations: Vec::new(),
395            annotations: Vec::new(),
396        }
397    }
398
399    /// Replay structural edits to translate an original path into this state.
400    fn map_original_path(&self, mut path: SyntaxPath) -> Option<SyntaxPath> {
401        for edit in &self.edits {
402            match edit {
403                PathEdit::Splice { parent, deleted, inserted } => {
404                    if !path.adjust_for_splice(parent, deleted, *inserted) {
405                        return None;
406                    }
407                }
408                PathEdit::ReplaceRoot => return None,
409            }
410        }
411        Some(path)
412    }
413
414    /// Finds a change target in the current root.
415    fn map_original_element(&self, element: &SyntaxElement) -> SyntaxElement {
416        self.map_original_path(SyntaxPath::new(element))
417            .and_then(|path| path.resolve(&self.root))
418            .expect("an edit target must still be present")
419    }
420
421    /// Applies one child-list splice and updates tracked structural path.
422    fn splice(
423        &mut self,
424        parent_path: SyntaxPath,
425        deleted: Range<usize>,
426        inserted: Vec<PreparedElement>,
427        track_as_changed: bool,
428    ) {
429        let inserted_count = inserted.len();
430        self.changed
431            .retain_mut(|path| path.adjust_for_splice(&parent_path, &deleted, inserted_count));
432        self.annotations
433            .retain_mut(|it| it.path.adjust_for_splice(&parent_path, &deleted, inserted_count));
434
435        for (offset, element) in inserted.iter().enumerate() {
436            let index = deleted.start + offset;
437            if track_as_changed {
438                self.changed
439                    .push(parent_path.in_child(index, &SyntaxPath { child_indices: Vec::new() }));
440            }
441            self.annotations.extend(element.annotations.iter().map(|annotation| {
442                TrackedAnnotation {
443                    path: parent_path.in_child(index, &annotation.path),
444                    annotation: annotation.annotation,
445                    order: annotation.order,
446                }
447            }));
448        }
449
450        let parent = parent_path.resolve(&self.root).and_then(SyntaxElement::into_node).unwrap();
451        let green = rowan::GreenNodeData::splice_children(
452            parent.green(),
453            deleted.clone(),
454            inserted.into_iter().map(PreparedElement::into_green),
455        );
456        self.root = SyntaxNode::new_root(parent.replace_with(green));
457        self.edits.push(PathEdit::Splice {
458            parent: parent_path,
459            deleted,
460            inserted: inserted_count,
461        });
462    }
463
464    /// Replaces the tree's root with a prepared node payload.
465    fn replace_root(&mut self, replacement: PreparedElement, track_as_changed: bool) {
466        let NodeOrToken::Node(node) = replacement.syntax else {
467            panic!("root node replacement should be a node")
468        };
469        self.root = SyntaxNode::new_root(node.green().to_owned());
470        self.changed.clear();
471        if track_as_changed {
472            self.changed.push(SyntaxPath { child_indices: Vec::new() });
473        }
474        self.annotations = replacement.annotations;
475        self.edits.push(PathEdit::ReplaceRoot);
476    }
477
478    /// Applies a planned change to this tree using already prepared payloads.
479    fn apply(
480        &mut self,
481        change: &Change,
482        replacement: Vec<PreparedElement>,
483        record_as_changed: bool,
484    ) {
485        match change {
486            Change::Insert(position, _) | Change::InsertAll(position, _) => {
487                let (parent, index) = match &position.repr {
488                    PositionRepr::FirstChild(parent) => {
489                        let parent = self.map_original_element(&parent.clone().into());
490                        (parent.into_node().unwrap(), 0)
491                    }
492                    PositionRepr::After(child) => {
493                        let child = self.map_original_element(child);
494                        (child.parent().unwrap(), index_no_trivia(&child) + 1)
495                    }
496                };
497                self.splice(
498                    SyntaxPath::new(&parent.into()),
499                    index..index,
500                    replacement,
501                    record_as_changed,
502                );
503            }
504            Change::Replace(SyntaxElement::Node(target), Some(_)) if target.parent().is_none() => {
505                self.replace_root(replacement.into_iter().next().unwrap(), record_as_changed);
506            }
507            Change::Replace(target, _) | Change::ReplaceWithMany(target, _) => {
508                let target = self.map_original_element(target);
509                let parent = target.parent().unwrap();
510                let index = index_no_trivia(&target);
511                self.splice(
512                    SyntaxPath::new(&parent.into()),
513                    index..index + 1,
514                    replacement,
515                    record_as_changed,
516                );
517            }
518            Change::ReplaceAll(range, _) => {
519                let start = self.map_original_element(range.start());
520                let end = self.map_original_element(range.end());
521                let parent = start.parent().unwrap();
522                self.splice(
523                    SyntaxPath::new(&parent.into()),
524                    index_no_trivia(&start)..index_no_trivia(&end) + 1,
525                    replacement,
526                    record_as_changed,
527                );
528            }
529        }
530    }
531}
532
533/// A replacement payload paired with the annotation below it.
534///
535/// The syntax element remains an immutable snapshot of its source tree.
536/// Annotation paths are relative to the payload root and are rebased by
537/// splice
538struct PreparedElement {
539    syntax: SyntaxElement,
540    annotations: Vec<TrackedAnnotation>,
541}
542
543impl PreparedElement {
544    fn into_green(self) -> rowan::NodeOrToken<rowan::GreenNode, rowan::GreenToken> {
545        match self.syntax {
546            SyntaxElement::Node(node) => NodeOrToken::Node(node.green().to_owned()),
547            SyntaxElement::Token(token) => NodeOrToken::Token(token.green().to_owned()),
548        }
549    }
550}
551
552/// Owns all evolving trees involved in executing an edit plan.
553struct TreeStore {
554    states: FxHashMap<SyntaxNode, TreeState>,
555}
556
557impl TreeStore {
558    /// Creates per tree state for annotations after following factory mapping.
559    fn with_annotations(
560        annotations: Vec<(SyntaxElement, SyntaxAnnotation)>,
561        mappings: &SyntaxMapping,
562    ) -> Self {
563        let mut states = FxHashMap::<SyntaxNode, TreeState>::default();
564        for (order, (element, annotation)) in annotations.into_iter().enumerate() {
565            let element = mappings.upmap_element(&element);
566            let tree = element.tree_top();
567            let tracked = TrackedAnnotation { path: SyntaxPath::new(&element), annotation, order };
568            let state = states.entry(tree.clone()).or_insert_with(|| TreeState::new(tree));
569            state.original_annotations.push(tracked.clone());
570            state.annotations.push(tracked);
571        }
572        Self { states }
573    }
574
575    /// Execute an already ordered plan without performing further analysis.
576    fn execute(&mut self, plan: EditPlan) {
577        for planned in plan.changes {
578            self.states
579                .entry(planned.tree.clone())
580                .or_insert_with(|| TreeState::new(planned.tree.clone()));
581            let replacement = planned
582                .replacement_elements()
583                .iter()
584                .map(|element| self.prepare_element(element))
585                .collect();
586            self.states.get_mut(&planned.tree).unwrap().apply(
587                &planned.change,
588                replacement,
589                planned.record_as_changed,
590            );
591        }
592    }
593
594    /// Captures the source element and annotations used by a replacement.
595    fn prepare_element(&self, element: &SyntaxElement) -> PreparedElement {
596        let tree = element.tree_top();
597        let original_path = SyntaxPath::new(element);
598        let (element, annotations) = match self.states.get(&tree) {
599            Some(state) => {
600                let annotations_below =
601                    |annotations: &[TrackedAnnotation], ancestor: &SyntaxPath| {
602                        annotations
603                            .iter()
604                            .filter_map(|annotation| {
605                                annotation.path.relative_to(ancestor).map(|path| {
606                                    TrackedAnnotation {
607                                        path,
608                                        annotation: annotation.annotation,
609                                        order: annotation.order,
610                                    }
611                                })
612                            })
613                            .collect()
614                    };
615                match state.map_original_path(original_path.clone()) {
616                    Some(path) => {
617                        let element = path.resolve(&state.root).unwrap();
618                        let annotations = annotations_below(&state.annotations, &path);
619                        (element, annotations)
620                    }
621                    None => {
622                        let annotations =
623                            annotations_below(&state.original_annotations, &original_path);
624                        (element.clone(), annotations)
625                    }
626                }
627            }
628            None => (element.clone(), Vec::new()),
629        };
630        PreparedElement { syntax: element, annotations }
631    }
632
633    /// Resolves the editor roots tracked paths and constructs the public edit.
634    fn finish(mut self, old_root: SyntaxNode) -> SyntaxEdit {
635        let state =
636            self.states.remove(&old_root).unwrap_or_else(|| TreeState::new(old_root.clone()));
637        let new_root = state.root;
638
639        let mut changed_elements = state
640            .changed
641            .into_iter()
642            .filter_map(|path| path.resolve(&new_root))
643            .collect::<Vec<_>>();
644        changed_elements.sort_by_key(|element| element.text_range().start());
645
646        let mut annotations = FxHashMap::<SyntaxAnnotation, Vec<(usize, SyntaxElement)>>::default();
647        for annotation in state.annotations {
648            if let Some(element) = annotation.path.resolve(&new_root) {
649                annotations
650                    .entry(annotation.annotation)
651                    .or_default()
652                    .push((annotation.order, element));
653            }
654        }
655        let annotations = annotations
656            .into_iter()
657            .map(|(annotation, mut elements)| {
658                elements.sort_by_key(|(order, element)| (*order, element.text_range().start()));
659                (annotation, elements.into_iter().map(|(_, element)| element).collect())
660            })
661            .collect();
662
663        SyntaxEdit { old_root, new_root, changed_elements, annotations }
664    }
665}
666
667/// Plans and executes all changes recorded by a SyntaxEditor.
668pub(super) fn apply_edits(editor: SyntaxEditor) -> SyntaxEdit {
669    let SyntaxEditor { root, changes, annotations, make } = editor;
670    let mappings = make.take();
671    let mut node_depths = FxHashMap::<SyntaxNode, usize>::default();
672    let mut node_depth = |node: SyntaxNode| {
673        *node_depths.entry(node).or_insert_with_key(|node| node.ancestors().count())
674    };
675
676    let plan = match EditPlan::build(changes.into_inner(), &mappings, &mut node_depth) {
677        Ok(plan) => plan,
678        Err(InvalidEditPlan { changes }) => {
679            report_intersecting_changes(&changes, &mut node_depth, &root);
680            return SyntaxEdit {
681                old_root: root.clone(),
682                new_root: root,
683                annotations: FxHashMap::default(),
684                changed_elements: Vec::new(),
685            };
686        }
687    };
688
689    let mut trees = TreeStore::with_annotations(annotations.into_inner(), &mappings);
690    trees.execute(plan);
691    trees.finish(root)
692}
693
694fn report_intersecting_changes(
695    changes: &[Change],
696    mut get_node_depth: impl FnMut(SyntaxNode) -> usize,
697    root: &SyntaxNode,
698) {
699    let intersecting_changes = changes
700        .iter()
701        .zip(changes.iter().skip(1))
702        .filter(|(l, r)| {
703            // We only care about checking for disjoint replace ranges.
704            matches!(
705                (l.change_kind(), r.change_kind()),
706                (
707                    ChangeKind::Replace | ChangeKind::ReplaceRange,
708                    ChangeKind::Replace | ChangeKind::ReplaceRange
709                )
710            )
711        })
712        .filter(|(l, r)| {
713            get_node_depth(l.target_parent()) == get_node_depth(r.target_parent())
714                && (l.target_range().end() > r.target_range().start())
715        });
716
717    let mut error_msg = String::from("some replace change ranges intersect!\n");
718
719    let parent_str = root.to_string();
720
721    for (l, r) in intersecting_changes {
722        let mut highlighted_str = parent_str.clone();
723        let l_range = l.target_range();
724        let r_range = r.target_range();
725
726        let i_range = l_range.intersect(r_range).unwrap();
727        let i_str = format!("\x1b[46m{}", &parent_str[i_range]);
728
729        let pre_range: Range<usize> = l_range.start().into()..i_range.start().into();
730        let pre_str = format!("\x1b[44m{}", &parent_str[pre_range]);
731
732        let (highlight_range, highlight_str) = if l_range == r_range {
733            format_to!(error_msg, "\x1b[46mleft change:\x1b[0m  {l:?} {l}\n");
734            format_to!(error_msg, "\x1b[46mequals\x1b[0m\n");
735            format_to!(error_msg, "\x1b[46mright change:\x1b[0m {r:?} {r}\n");
736            let i_highlighted = format!("{i_str}\x1b[0m\x1b[K");
737            let total_range: Range<usize> = i_range.into();
738            (total_range, i_highlighted)
739        } else {
740            format_to!(error_msg, "\x1b[44mleft change:\x1b[0m  {l:?} {l}\n");
741            let range_end = if l_range.contains_range(r_range) {
742                format_to!(error_msg, "\x1b[46mcovers\x1b[0m\n");
743                format_to!(error_msg, "\x1b[46mright change:\x1b[0m {r:?} {r}\n");
744                l_range.end()
745            } else {
746                format_to!(error_msg, "\x1b[46mintersects\x1b[0m\n");
747                format_to!(error_msg, "\x1b[42mright change:\x1b[0m {r:?} {r}\n");
748                r_range.end()
749            };
750
751            let post_range: Range<usize> = i_range.end().into()..range_end.into();
752
753            let post_str = format!("\x1b[42m{}", &parent_str[post_range]);
754            let result = format!("{pre_str}{i_str}{post_str}\x1b[0m\x1b[K");
755            let total_range: Range<usize> = l_range.start().into()..range_end.into();
756            (total_range, result)
757        };
758        highlighted_str.replace_range(highlight_range, &highlight_str);
759
760        format_to!(error_msg, "{highlighted_str}\n");
761    }
762
763    stdx::always!(false, "{}", error_msg);
764}
765
766/// A replacement region that can contain later source ordered changeds
767struct ChangedRegion {
768    range: TextRange,
769    change_index: usize,
770    nested_changes: NestedChanges,
771}
772
773/// How changes nested within a replacement region are handled.
774enum NestedChanges {
775    /// Map nested targets into a one-to-one node replacement.
776    Remap,
777    /// Drop nested changes because the replacement has no unique counterpart.
778    Discard,
779}
780
781impl ChangedRegion {
782    /// Describes a region replaced by change, if it can contain changes.
783    fn for_change(change: &Change, change_index: usize, discarded: bool) -> Option<Self> {
784        match change {
785            Change::Replace(SyntaxElement::Node(target), replacement) => Some(Self {
786                range: target.text_range(),
787                change_index,
788                nested_changes: if !discarded && matches!(replacement, Some(SyntaxElement::Node(_)))
789                {
790                    NestedChanges::Remap
791                } else {
792                    NestedChanges::Discard
793                },
794            }),
795            Change::ReplaceWithMany(SyntaxElement::Node(target), _) => Some(Self {
796                range: target.text_range(),
797                change_index,
798                nested_changes: NestedChanges::Discard,
799            }),
800            Change::ReplaceAll(elements, _) => Some(Self {
801                range: TextRange::new(
802                    elements.start().text_range().start(),
803                    elements.end().text_range().end(),
804                ),
805                change_index,
806                nested_changes: NestedChanges::Discard,
807            }),
808            _ => None,
809        }
810    }
811}