Skip to main content

syntax/
syntax_editor.rs

1//! Syntax Tree editor
2//!
3//! Inspired by Roslyn's [`SyntaxEditor`].
4//!
5//! [`SyntaxEditor`]: https://github.com/dotnet/roslyn/blob/43b0b05cc4f492fd5de00f6f6717409091df8daa/src/Workspaces/Core/Portable/Editing/SyntaxEditor.cs
6
7use std::{
8    cell::RefCell,
9    fmt, iter,
10    num::NonZeroU32,
11    ops::RangeInclusive,
12    sync::atomic::{AtomicU32, Ordering},
13};
14
15use rowan::TextRange;
16use rustc_hash::FxHashMap;
17
18use crate::{
19    AstNode, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, T,
20    ast::{self, edit::IndentLevel, syntax_factory::SyntaxFactory},
21};
22
23mod edit_algo;
24mod edits;
25mod mapping;
26
27pub use edits::{GetOrCreateWhereClause, Removable};
28pub use mapping::{SyntaxMapping, SyntaxMappingBuilder};
29
30#[derive(Debug)]
31pub struct SyntaxEditor {
32    root: SyntaxNode,
33    changes: RefCell<Vec<Change>>,
34    annotations: RefCell<Vec<(SyntaxElement, SyntaxAnnotation)>>,
35    make: SyntaxFactory,
36}
37
38impl SyntaxEditor {
39    /// Creates a syntax editor from `root`.
40    ///
41    /// The returned `root` is guaranteed to be a detached, immutable node.
42    /// If the provided node is not a root (i.e., has a parent), it is cloned
43    /// into a fresh subtree to satisfy syntax editor invariants.
44    pub fn new(root: SyntaxNode) -> (Self, SyntaxNode) {
45        let mut root = root;
46
47        if root.parent().is_some() {
48            root = root.clone_subtree()
49        };
50
51        let editor = Self {
52            root: root.clone(),
53            changes: RefCell::new(Vec::new()),
54            annotations: RefCell::new(Vec::new()),
55            make: SyntaxFactory::with_mappings(),
56        };
57
58        (editor, root)
59    }
60
61    /// Typed-node variant of [`SyntaxEditor::new`].
62    pub fn with_ast_node<T>(root: &T) -> (Self, T)
63    where
64        T: AstNode,
65    {
66        let (editor, root) = Self::new(root.syntax().clone());
67
68        (editor, T::cast(root).unwrap())
69    }
70
71    pub fn make(&self) -> &SyntaxFactory {
72        &self.make
73    }
74
75    pub fn add_annotation(&self, element: impl Element, annotation: SyntaxAnnotation) {
76        self.annotations.borrow_mut().push((element.syntax_element(), annotation))
77    }
78
79    pub fn add_annotation_all(&self, elements: Vec<impl Element>, annotation: SyntaxAnnotation) {
80        self.annotations
81            .borrow_mut()
82            .extend(elements.into_iter().map(|e| e.syntax_element()).zip(iter::repeat(annotation)));
83    }
84
85    pub fn merge(&self, other: SyntaxEditor) {
86        debug_assert!(
87            self.root == other.root || other.root.ancestors().any(|node| node == self.root),
88            "{:?} is not in the same tree as {:?}",
89            other.root,
90            self.root
91        );
92
93        self.changes.borrow_mut().append(&mut other.changes.into_inner());
94        if let Some(mut m) = self.make.mappings() {
95            m.merge(other.make.take());
96        }
97        self.annotations.borrow_mut().append(&mut other.annotations.into_inner());
98    }
99
100    pub fn insert(&self, position: Position, element: impl Element) {
101        debug_assert!(is_ancestor_or_self(&position.parent(), &self.root));
102        self.changes.borrow_mut().push(Change::Insert(position, element.syntax_element()))
103    }
104
105    pub fn insert_all(&self, position: Position, elements: Vec<SyntaxElement>) {
106        debug_assert!(is_ancestor_or_self(&position.parent(), &self.root));
107        self.changes.borrow_mut().push(Change::InsertAll(position, elements))
108    }
109
110    pub fn insert_with_whitespace(&self, position: Position, element: impl Element) {
111        self.insert_all_with_whitespace(position, vec![element.syntax_element()])
112    }
113
114    pub fn insert_all_with_whitespace(&self, position: Position, mut elements: Vec<SyntaxElement>) {
115        if let Some(first) = elements.first()
116            && let Some(ws) = ws_before(&position, first, &self.make)
117        {
118            elements.insert(0, ws.into());
119        }
120        if let Some(last) = elements.last()
121            && let Some(ws) = ws_after(&position, last, &self.make)
122        {
123            elements.push(ws.into());
124        }
125        self.insert_all(position, elements)
126    }
127
128    pub fn delete(&self, element: impl Element) {
129        let element = element.syntax_element();
130        debug_assert!(is_ancestor_or_self_of_element(&element, &self.root));
131        debug_assert!(
132            !matches!(&element, SyntaxElement::Node(node) if node == &self.root),
133            "should not delete root node"
134        );
135        let mut changes = self.changes.borrow_mut();
136        for change in changes.iter_mut() {
137            if let Change::Replace(existing, replacement) = change
138                && *existing == element
139            {
140                if replacement.is_none() {
141                    return;
142                }
143                *replacement = None;
144                return;
145            }
146        }
147        changes.push(Change::Replace(element, None));
148    }
149
150    pub fn delete_all(&self, range: RangeInclusive<SyntaxElement>) {
151        if range.start() == range.end() {
152            self.delete(range.start());
153            return;
154        }
155
156        debug_assert!(is_ancestor_or_self_of_element(range.start(), &self.root));
157        self.changes.borrow_mut().push(Change::ReplaceAll(range, Vec::new()))
158    }
159
160    pub fn replace(&self, old: impl Element, new: impl Element) {
161        let old = old.syntax_element();
162        debug_assert!(is_ancestor_or_self_of_element(&old, &self.root));
163        let new = new.syntax_element();
164        let mut changes = self.changes.borrow_mut();
165        for change in changes.iter_mut() {
166            if let Change::Replace(existing, replacement) = change
167                && *existing == old
168            {
169                match replacement {
170                    None => return,
171                    Some(existing_new) if *existing_new == new => return,
172                    Some(existing_new) => {
173                        *existing_new = new;
174                        return;
175                    }
176                }
177            }
178        }
179        changes.push(Change::Replace(old, Some(new)));
180    }
181
182    pub fn replace_with_many(&self, old: impl Element, new: Vec<SyntaxElement>) {
183        let old = old.syntax_element();
184        debug_assert!(is_ancestor_or_self_of_element(&old, &self.root));
185        debug_assert!(
186            !(matches!(&old, SyntaxElement::Node(node) if node == &self.root) && new.len() > 1),
187            "cannot replace root node with many elements"
188        );
189        self.changes.borrow_mut().push(Change::ReplaceWithMany(old.syntax_element(), new));
190    }
191
192    pub fn replace_all(&self, range: RangeInclusive<SyntaxElement>, new: Vec<SyntaxElement>) {
193        if range.start() == range.end() {
194            self.replace_with_many(range.start(), new);
195            return;
196        }
197
198        debug_assert!(is_ancestor_or_self_of_element(range.start(), &self.root));
199        self.changes.borrow_mut().push(Change::ReplaceAll(range, new))
200    }
201
202    pub fn finish(self) -> SyntaxEdit {
203        edit_algo::apply_edits(self)
204    }
205
206    pub fn deleted(&self, element: impl Element) -> bool {
207        let element = element.syntax_element();
208        self.changes
209            .borrow()
210            .iter()
211            .any(|change| matches!(change, Change::Replace(existing, None) if *existing == element))
212    }
213}
214
215/// Represents a completed [`SyntaxEditor`] operation.
216pub struct SyntaxEdit {
217    old_root: SyntaxNode,
218    new_root: SyntaxNode,
219    changed_elements: Vec<SyntaxElement>,
220    annotations: FxHashMap<SyntaxAnnotation, Vec<SyntaxElement>>,
221}
222
223impl SyntaxEdit {
224    /// Root of the initial unmodified syntax tree.
225    pub fn old_root(&self) -> &SyntaxNode {
226        &self.old_root
227    }
228
229    /// Root of the modified syntax tree.
230    pub fn new_root(&self) -> &SyntaxNode {
231        &self.new_root
232    }
233
234    /// Which syntax elements in the modified syntax tree were inserted or
235    /// modified as part of the edit.
236    ///
237    /// Note that for syntax nodes, only the upper-most parent of a set of
238    /// changes is included, not any child elements that may have been modified.
239    pub fn changed_elements(&self) -> &[SyntaxElement] {
240        self.changed_elements.as_slice()
241    }
242
243    /// Finds which syntax elements have been annotated with the given
244    /// annotation.
245    ///
246    /// Note that an annotation might not appear in the modified syntax tree if
247    /// the syntax elements that were annotated did not make it into the final
248    /// syntax tree.
249    pub fn find_annotation(&self, annotation: SyntaxAnnotation) -> &[SyntaxElement] {
250        self.annotations.get(&annotation).as_ref().map_or(&[], |it| it.as_slice())
251    }
252
253    pub fn find_element(&self, old_node: &SyntaxNode) -> Option<SyntaxNode> {
254        let old_root_start = self.old_root.text_range().start();
255        let old_start = old_node.text_range().start() - old_root_start;
256        let new_root_start = self.new_root.text_range().start();
257        let kind = old_node.kind();
258
259        self.new_root
260            .descendants()
261            .find(|it| it.kind() == kind && it.text_range().start() - new_root_start == old_start)
262    }
263}
264
265#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
266#[repr(transparent)]
267pub struct SyntaxAnnotation(NonZeroU32);
268
269impl Default for SyntaxAnnotation {
270    fn default() -> Self {
271        static COUNTER: AtomicU32 = AtomicU32::new(1);
272
273        // Only consistency within a thread matters, as SyntaxElements are !Send
274        let id = COUNTER.fetch_add(1, Ordering::Relaxed);
275
276        Self(NonZeroU32::new(id).expect("syntax annotation id overflow"))
277    }
278}
279
280/// Position describing where to insert elements
281#[derive(Debug)]
282pub struct Position {
283    repr: PositionRepr,
284}
285
286impl Position {
287    pub(crate) fn parent(&self) -> SyntaxNode {
288        self.place().0
289    }
290
291    pub(crate) fn place(&self) -> (SyntaxNode, usize) {
292        match &self.repr {
293            PositionRepr::FirstChild(parent) => (parent.clone(), 0),
294            PositionRepr::After(child) => (child.parent().unwrap(), index_no_trivia(child) + 1),
295        }
296    }
297}
298
299pub fn index_no_trivia(element: &SyntaxElement) -> usize {
300    element.index().expect("the parser emits trivia as standalone tokens")
301}
302
303#[derive(Debug)]
304enum PositionRepr {
305    FirstChild(SyntaxNode),
306    After(SyntaxElement),
307}
308
309impl Position {
310    pub fn after(elem: impl Element) -> Position {
311        let repr = PositionRepr::After(elem.syntax_element());
312        Position { repr }
313    }
314
315    pub fn before(elem: impl Element) -> Position {
316        let elem = elem.syntax_element();
317        let repr = match elem.prev_sibling_or_token() {
318            Some(it) => PositionRepr::After(it),
319            None => PositionRepr::FirstChild(elem.parent().unwrap()),
320        };
321        Position { repr }
322    }
323
324    pub fn first_child_of(node: &(impl Into<SyntaxNode> + Clone)) -> Position {
325        let repr = PositionRepr::FirstChild(node.clone().into());
326        Position { repr }
327    }
328
329    pub fn last_child_of(node: &(impl Into<SyntaxNode> + Clone)) -> Position {
330        let node = node.clone().into();
331        let repr = match node.last_child_or_token() {
332            Some(it) => PositionRepr::After(it),
333            None => PositionRepr::FirstChild(node),
334        };
335        Position { repr }
336    }
337}
338
339#[derive(Debug)]
340enum Change {
341    /// Inserts a single element at the specified position.
342    Insert(Position, SyntaxElement),
343    /// Inserts many elements in-order at the specified position.
344    InsertAll(Position, Vec<SyntaxElement>),
345    /// Represents both a replace single element and a delete element operation.
346    Replace(SyntaxElement, Option<SyntaxElement>),
347    /// Replaces a single element with many elements.
348    ReplaceWithMany(SyntaxElement, Vec<SyntaxElement>),
349    /// Replaces a range of elements with another list of elements.
350    /// Range will always have start != end.
351    ReplaceAll(RangeInclusive<SyntaxElement>, Vec<SyntaxElement>),
352}
353
354impl Change {
355    fn target_range(&self) -> TextRange {
356        match self {
357            Change::Insert(target, _) | Change::InsertAll(target, _) => match &target.repr {
358                PositionRepr::FirstChild(parent) => TextRange::at(
359                    parent.first_child_or_token().unwrap().text_range().start(),
360                    0.into(),
361                ),
362                PositionRepr::After(child) => TextRange::at(child.text_range().end(), 0.into()),
363            },
364            Change::Replace(target, _) | Change::ReplaceWithMany(target, _) => target.text_range(),
365            Change::ReplaceAll(range, _) => {
366                range.start().text_range().cover(range.end().text_range())
367            }
368        }
369    }
370
371    fn target_parent(&self) -> SyntaxNode {
372        match self {
373            Change::Insert(target, _) | Change::InsertAll(target, _) => target.parent(),
374            Change::Replace(target, _) | Change::ReplaceWithMany(target, _) => match target {
375                SyntaxElement::Node(target) => target.parent().unwrap_or_else(|| target.clone()),
376                SyntaxElement::Token(target) => target.parent().unwrap(),
377            },
378            Change::ReplaceAll(target, _) => target.start().parent().unwrap(),
379        }
380    }
381
382    fn change_kind(&self) -> ChangeKind {
383        match self {
384            Change::Insert(_, _) | Change::InsertAll(_, _) => ChangeKind::Insert,
385            Change::Replace(_, _) | Change::ReplaceWithMany(_, _) => ChangeKind::Replace,
386            Change::ReplaceAll(_, _) => ChangeKind::ReplaceRange,
387        }
388    }
389}
390
391#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
392enum ChangeKind {
393    Insert,
394    ReplaceRange,
395    Replace,
396}
397
398impl fmt::Display for Change {
399    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400        match self {
401            Change::Insert(position, node_or_token) => {
402                let parent = position.parent();
403                let mut parent_str = parent.to_string();
404                let target_range = self.target_range().start() - parent.text_range().start();
405
406                parent_str.insert_str(
407                    target_range.into(),
408                    &format!("\x1b[42m{node_or_token}\x1b[0m\x1b[K"),
409                );
410                f.write_str(&parent_str)
411            }
412            Change::InsertAll(position, vec) => {
413                let parent = position.parent();
414                let mut parent_str = parent.to_string();
415                let target_range = self.target_range().start() - parent.text_range().start();
416                let insertion: String = vec.iter().map(|it| it.to_string()).collect();
417
418                parent_str
419                    .insert_str(target_range.into(), &format!("\x1b[42m{insertion}\x1b[0m\x1b[K"));
420                f.write_str(&parent_str)
421            }
422            Change::Replace(old, new) => {
423                if let Some(new) = new {
424                    write!(f, "\x1b[41m{old}\x1b[42m{new}\x1b[0m\x1b[K")
425                } else {
426                    write!(f, "\x1b[41m{old}\x1b[0m\x1b[K")
427                }
428            }
429            Change::ReplaceWithMany(old, vec) => {
430                let new: String = vec.iter().map(|it| it.to_string()).collect();
431                write!(f, "\x1b[41m{old}\x1b[42m{new}\x1b[0m\x1b[K")
432            }
433            Change::ReplaceAll(range, vec) => {
434                let parent = range.start().parent().unwrap();
435                let parent_str = parent.to_string();
436                let pre_range =
437                    TextRange::new(parent.text_range().start(), range.start().text_range().start());
438                let old_range = TextRange::new(
439                    range.start().text_range().start(),
440                    range.end().text_range().end(),
441                );
442                let post_range =
443                    TextRange::new(range.end().text_range().end(), parent.text_range().end());
444
445                let pre_str = &parent_str[pre_range - parent.text_range().start()];
446                let old_str = &parent_str[old_range - parent.text_range().start()];
447                let post_str = &parent_str[post_range - parent.text_range().start()];
448                let new: String = vec.iter().map(|it| it.to_string()).collect();
449
450                write!(f, "{pre_str}\x1b[41m{old_str}\x1b[42m{new}\x1b[0m\x1b[K{post_str}")
451            }
452        }
453    }
454}
455
456/// Utility trait to allow calling syntax editor functions with references or owned
457/// nodes. Do not use outside of this module.
458pub trait Element {
459    fn syntax_element(self) -> SyntaxElement;
460}
461
462impl<E: Element + Clone> Element for &'_ E {
463    fn syntax_element(self) -> SyntaxElement {
464        self.clone().syntax_element()
465    }
466}
467
468impl Element for SyntaxElement {
469    fn syntax_element(self) -> SyntaxElement {
470        self
471    }
472}
473
474impl Element for SyntaxNode {
475    fn syntax_element(self) -> SyntaxElement {
476        self.into()
477    }
478}
479
480impl Element for SyntaxToken {
481    fn syntax_element(self) -> SyntaxElement {
482        self.into()
483    }
484}
485
486fn ws_before(
487    position: &Position,
488    new: &SyntaxElement,
489    factory: &SyntaxFactory,
490) -> Option<SyntaxToken> {
491    let prev = match &position.repr {
492        PositionRepr::FirstChild(_) => return None,
493        PositionRepr::After(it) => it,
494    };
495
496    if prev.kind() == T!['{']
497        && new.kind() == SyntaxKind::USE
498        && let Some(item_list) = prev.parent().and_then(ast::ItemList::cast)
499    {
500        let mut indent = IndentLevel::from_element(&item_list.syntax().clone().into());
501        indent.0 += 1;
502        return Some(factory.whitespace(&format!("\n{indent}")));
503    }
504
505    if prev.kind() == T!['{']
506        && ast::Stmt::can_cast(new.kind())
507        && let Some(stmt_list) = prev.parent().and_then(ast::StmtList::cast)
508    {
509        let mut indent = IndentLevel::from_element(&stmt_list.syntax().clone().into());
510        indent.0 += 1;
511        return Some(factory.whitespace(&format!("\n{indent}")));
512    }
513
514    ws_between(prev, new, factory)
515}
516
517fn ws_after(
518    position: &Position,
519    new: &SyntaxElement,
520    factory: &SyntaxFactory,
521) -> Option<SyntaxToken> {
522    let next = match &position.repr {
523        PositionRepr::FirstChild(parent) => parent.first_child_or_token()?,
524        PositionRepr::After(sibling) => sibling.next_sibling_or_token()?,
525    };
526    ws_between(new, &next, factory)
527}
528
529fn ws_between(
530    left: &SyntaxElement,
531    right: &SyntaxElement,
532    factory: &SyntaxFactory,
533) -> Option<SyntaxToken> {
534    if left.kind() == SyntaxKind::WHITESPACE || right.kind() == SyntaxKind::WHITESPACE {
535        return None;
536    }
537    if right.kind() == T![;] || right.kind() == T![,] {
538        return None;
539    }
540    if left.kind() == T![<] || right.kind() == T![>] {
541        return None;
542    }
543    if left.kind() == T![&] && right.kind() == SyntaxKind::LIFETIME {
544        return None;
545    }
546    if right.kind() == SyntaxKind::GENERIC_ARG_LIST {
547        return None;
548    }
549    if right.kind() == SyntaxKind::USE {
550        let mut indent = IndentLevel::from_element(left);
551        if left.kind() == SyntaxKind::USE {
552            indent.0 = IndentLevel::from_element(right).0.max(indent.0);
553        }
554        return Some(factory.whitespace(&format!("\n{indent}")));
555    }
556    if left.kind() == SyntaxKind::ATTR {
557        let mut indent = IndentLevel::from_element(right);
558        if right.kind() == SyntaxKind::ATTR {
559            indent.0 = IndentLevel::from_element(left).0.max(indent.0);
560        }
561        return Some(factory.whitespace(&format!("\n{indent}")));
562    }
563    Some(factory.whitespace(" "))
564}
565
566fn is_ancestor_or_self(node: &SyntaxNode, ancestor: &SyntaxNode) -> bool {
567    node == ancestor || node.ancestors().any(|it| &it == ancestor)
568}
569
570fn is_ancestor_or_self_of_element(node: &SyntaxElement, ancestor: &SyntaxNode) -> bool {
571    matches!(node, SyntaxElement::Node(node) if node == ancestor)
572        || node.ancestors().any(|it| &it == ancestor)
573}
574
575#[cfg(test)]
576mod tests {
577    use expect_test::expect;
578
579    use crate::{
580        AstNode,
581        ast::{self, make},
582    };
583
584    use super::*;
585
586    #[test]
587    fn basic_usage() {
588        let root = make::match_arm(
589            make::wildcard_pat().into(),
590            None,
591            make::expr_tuple([
592                make::expr_bin_op(
593                    make::expr_literal("2").into(),
594                    ast::BinaryOp::ArithOp(ast::ArithOp::Add),
595                    make::expr_literal("2").into(),
596                ),
597                make::expr_literal("true").into(),
598            ])
599            .into(),
600        );
601
602        let (editor, root) = SyntaxEditor::with_ast_node(&root);
603        let make = editor.make();
604
605        let to_wrap = root.syntax().descendants().find_map(ast::TupleExpr::cast).unwrap();
606        let to_replace = root.syntax().descendants().find_map(ast::BinExpr::cast).unwrap();
607
608        let name = make::name("var_name");
609        let name_ref = make::name_ref("var_name");
610
611        let placeholder_snippet = SyntaxAnnotation::default();
612        editor.add_annotation(name.syntax(), placeholder_snippet);
613        editor.add_annotation(name_ref.syntax(), placeholder_snippet);
614
615        let new_block = make.block_expr(
616            [editor
617                .make()
618                .let_stmt(
619                    make.ident_pat(false, false, name.clone()).into(),
620                    None,
621                    Some(to_replace.clone().into()),
622                )
623                .into()],
624            Some(to_wrap.clone().into()),
625        );
626
627        editor.replace(to_replace.syntax(), name_ref.syntax());
628        editor.replace(to_wrap.syntax(), new_block.syntax());
629
630        let edit = editor.finish();
631
632        let expect = expect![[r#"
633            _ => {
634                let var_name = 2 + 2;
635                (var_name, true)
636            },"#]];
637        expect.assert_eq(&edit.new_root.to_string());
638
639        assert_eq!(edit.find_annotation(placeholder_snippet).len(), 2);
640        assert!(
641            edit.annotations
642                .values()
643                .flatten()
644                .all(|element| element.ancestors().any(|it| &it == edit.new_root()))
645        )
646    }
647
648    #[test]
649    fn test_insert_independent() {
650        let root = make::block_expr(
651            [make::let_stmt(
652                make::ext::simple_ident_pat(make::name("second")).into(),
653                None,
654                Some(make::expr_literal("2").into()),
655            )
656            .into()],
657            None,
658        );
659
660        let (editor, root) = SyntaxEditor::with_ast_node(&root);
661        let make = editor.make();
662        let second_let = root.syntax().descendants().find_map(ast::LetStmt::cast).unwrap();
663
664        editor.insert(
665            Position::first_child_of(root.stmt_list().unwrap().syntax()),
666            make.let_stmt(
667                make::ext::simple_ident_pat(make::name("first")).into(),
668                None,
669                Some(make::expr_literal("1").into()),
670            )
671            .syntax(),
672        );
673
674        editor.insert(
675            Position::after(second_let.syntax()),
676            make.let_stmt(
677                make::ext::simple_ident_pat(make::name("third")).into(),
678                None,
679                Some(make::expr_literal("3").into()),
680            )
681            .syntax(),
682        );
683
684        let edit = editor.finish();
685
686        let expect = expect![[r#"
687            let first = 1;{
688                let second = 2;let third = 3;
689            }"#]];
690        expect.assert_eq(&edit.new_root.to_string());
691    }
692
693    #[test]
694    fn test_insert_dependent() {
695        let root = make::block_expr(
696            [],
697            Some(
698                make::block_expr(
699                    [make::let_stmt(
700                        make::ext::simple_ident_pat(make::name("second")).into(),
701                        None,
702                        Some(make::expr_literal("2").into()),
703                    )
704                    .into()],
705                    None,
706                )
707                .into(),
708            ),
709        );
710
711        let (editor, root) = SyntaxEditor::with_ast_node(&root);
712        let make = editor.make();
713
714        let inner_block =
715            root.syntax().descendants().flat_map(ast::BlockExpr::cast).nth(1).unwrap();
716        let second_let = root.syntax().descendants().find_map(ast::LetStmt::cast).unwrap();
717
718        let new_block_expr = make.block_expr([], Some(ast::Expr::BlockExpr(inner_block.clone())));
719
720        let first_let = make.let_stmt(
721            make::ext::simple_ident_pat(make::name("first")).into(),
722            None,
723            Some(make::expr_literal("1").into()),
724        );
725
726        let third_let = make.let_stmt(
727            make::ext::simple_ident_pat(make::name("third")).into(),
728            None,
729            Some(make::expr_literal("3").into()),
730        );
731
732        editor.insert(
733            Position::first_child_of(inner_block.stmt_list().unwrap().syntax()),
734            first_let.syntax(),
735        );
736        editor.insert(Position::after(second_let.syntax()), third_let.syntax());
737        editor.replace(inner_block.syntax(), new_block_expr.syntax());
738
739        let edit = editor.finish();
740
741        let expect = expect![[r#"
742            {
743                {
744                let first = 1;{
745                let second = 2;let third = 3;
746            }
747            }
748            }"#]];
749        expect.assert_eq(&edit.new_root.to_string());
750    }
751
752    #[test]
753    fn test_dependent_change_prefers_nearest_changed_ancestor() {
754        let root = make::block_expr(
755            [],
756            Some(
757                make::block_expr(
758                    [make::let_stmt(
759                        make::ext::simple_ident_pat(make::name("second")).into(),
760                        None,
761                        Some(make::expr_literal("2").into()),
762                    )
763                    .into()],
764                    None,
765                )
766                .into(),
767            ),
768        );
769
770        let (editor, root) = SyntaxEditor::with_ast_node(&root);
771        let make = editor.make();
772
773        let inner_block =
774            root.syntax().descendants().flat_map(ast::BlockExpr::cast).nth(1).unwrap();
775
776        let outer_replacement = make.block_expr([], Some(ast::Expr::BlockExpr(root.clone())));
777        let inner_replacement =
778            make.block_expr([], Some(ast::Expr::BlockExpr(inner_block.clone())));
779
780        let first_let = make.let_stmt(
781            make::ext::simple_ident_pat(make::name("first")).into(),
782            None,
783            Some(make::expr_literal("1").into()),
784        );
785
786        editor.insert(
787            Position::first_child_of(inner_block.stmt_list().unwrap().syntax()),
788            first_let.syntax(),
789        );
790        editor.replace(inner_block.syntax(), inner_replacement.syntax());
791        editor.replace(root.syntax(), outer_replacement.syntax());
792
793        let edit = editor.finish();
794
795        let expect = expect![[r#"
796            {
797                {
798                {
799                let first = 1;{
800                let second = 2;
801            }
802            }
803            }
804            }"#]];
805        expect.assert_eq(&edit.new_root.to_string());
806    }
807
808    #[test]
809    fn test_replace_root_with_dependent() {
810        let root = make::block_expr(
811            [make::let_stmt(
812                make::ext::simple_ident_pat(make::name("second")).into(),
813                None,
814                Some(make::expr_literal("2").into()),
815            )
816            .into()],
817            None,
818        );
819
820        let (editor, root) = SyntaxEditor::with_ast_node(&root);
821        let make = editor.make();
822
823        let inner_block = root;
824
825        let new_block_expr = make.block_expr([], Some(ast::Expr::BlockExpr(inner_block.clone())));
826
827        let first_let = make.let_stmt(
828            make::ext::simple_ident_pat(make::name("first")).into(),
829            None,
830            Some(make::expr_literal("1").into()),
831        );
832
833        editor.insert(
834            Position::first_child_of(inner_block.stmt_list().unwrap().syntax()),
835            first_let.syntax(),
836        );
837        editor.replace(inner_block.syntax(), new_block_expr.syntax());
838
839        let edit = editor.finish();
840
841        let expect = expect![[r#"
842            {
843                let first = 1;{
844                let second = 2;
845            }
846            }"#]];
847        expect.assert_eq(&edit.new_root.to_string());
848    }
849
850    #[test]
851    fn test_replace_token_in_parent() {
852        let parent_fn = make::fn_(
853            None,
854            None,
855            make::name("it"),
856            None,
857            None,
858            make::param_list(None, []),
859            make::block_expr([], Some(make::ext::expr_unit())),
860            Some(make::ret_type(make::ty_unit())),
861            false,
862            false,
863            false,
864            false,
865        );
866
867        let (editor, parent_fn) = SyntaxEditor::with_ast_node(&parent_fn);
868
869        if let Some(ret_ty) = parent_fn.ret_type() {
870            editor.delete(ret_ty.syntax().clone());
871
872            if let Some(SyntaxElement::Token(token)) = ret_ty.syntax().next_sibling_or_token()
873                && token.kind().is_trivia()
874            {
875                editor.delete(token);
876            }
877        }
878
879        if let Some(tail) = parent_fn.body().unwrap().tail_expr() {
880            editor.delete(tail.syntax().clone());
881        }
882
883        let edit = editor.finish();
884
885        let expect = expect![["fn it() {\n    \n}"]];
886        expect.assert_eq(&edit.new_root.to_string());
887    }
888
889    #[test]
890    fn test_more_times_replace_node_to_same_token() {
891        let arg_list =
892            make::arg_list([make::expr_literal("1").into(), make::expr_literal("2").into()]);
893
894        let (editor, arg_list) = SyntaxEditor::with_ast_node(&arg_list);
895
896        let target_expr = make::token(parser::SyntaxKind::UNDERSCORE);
897
898        for arg in arg_list.args() {
899            editor.replace(arg.syntax(), &target_expr);
900        }
901
902        let edit = editor.finish();
903
904        let expect = expect![["(_, _)"]];
905        expect.assert_eq(&edit.new_root.to_string());
906    }
907
908    #[test]
909    fn test_more_times_replace_node_to_same_node() {
910        let arg_list =
911            make::arg_list([make::expr_literal("1").into(), make::expr_literal("2").into()]);
912
913        let (editor, arg_list) = SyntaxEditor::with_ast_node(&arg_list);
914
915        let target_expr = make::expr_literal("3");
916
917        for arg in arg_list.args() {
918            editor.replace(arg.syntax(), target_expr.syntax());
919        }
920
921        let edit = editor.finish();
922
923        let expect = expect![["(3, 3)"]];
924        expect.assert_eq(&edit.new_root.to_string());
925    }
926
927    #[test]
928    fn test_more_times_insert_node_to_same_node() {
929        let arg_list =
930            make::arg_list([make::expr_literal("1").into(), make::expr_literal("2").into()]);
931
932        let (editor, arg_list) = SyntaxEditor::with_ast_node(&arg_list);
933
934        let target_expr = make::ext::expr_unit();
935
936        for arg in arg_list.args() {
937            editor.insert(Position::before(arg.syntax()), target_expr.syntax());
938        }
939
940        let edit = editor.finish();
941
942        let expect = expect![["(()1, ()2)"]];
943        expect.assert_eq(&edit.new_root.to_string());
944    }
945}