Skip to content

Commit e28f551

Browse files
committed
Add AssocItemList::add_item_at_start
Needed to recreate the behavior of `generate_new` addding the `new` method at the start of the impl
1 parent e011715 commit e28f551

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

crates/syntax/src/ast/edit_in_place.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,8 @@ impl ast::Impl {
627627
}
628628

629629
impl ast::AssocItemList {
630+
/// Adds a new associated item after all of the existing associated items.
631+
///
630632
/// Attention! This function does align the first line of `item` with respect to `self`,
631633
/// but it does _not_ change indentation of other lines (if any).
632634
pub fn add_item(&self, item: ast::AssocItem) {
@@ -650,6 +652,46 @@ impl ast::AssocItemList {
650652
];
651653
ted::insert_all(position, elements);
652654
}
655+
656+
/// Adds a new associated item at the start of the associated item list.
657+
///
658+
/// Attention! This function does align the first line of `item` with respect to `self`,
659+
/// but it does _not_ change indentation of other lines (if any).
660+
pub fn add_item_at_start(&self, item: ast::AssocItem) {
661+
match self.assoc_items().next() {
662+
Some(first_item) => {
663+
let indent = IndentLevel::from_node(first_item.syntax());
664+
let before = Position::before(first_item.syntax());
665+
666+
ted::insert_all(
667+
before,
668+
vec![
669+
item.syntax().clone().into(),
670+
make::tokens::whitespace(&format!("\n\n{indent}")).into(),
671+
],
672+
)
673+
}
674+
None => {
675+
let (indent, position, whitespace) = match self.l_curly_token() {
676+
Some(l_curly) => {
677+
normalize_ws_between_braces(self.syntax());
678+
(IndentLevel::from_token(&l_curly) + 1, Position::after(&l_curly), "\n")
679+
}
680+
None => (IndentLevel::single(), Position::first_child_of(self.syntax()), ""),
681+
};
682+
683+
let mut elements = vec![];
684+
685+
// Avoid pushing an empty whitespace token
686+
if !indent.is_zero() || !whitespace.is_empty() {
687+
elements.push(make::tokens::whitespace(&format!("{whitespace}{indent}")).into())
688+
}
689+
elements.push(item.syntax().clone().into());
690+
691+
ted::insert_all(position, elements)
692+
}
693+
};
694+
}
653695
}
654696

655697
impl ast::Fn {

0 commit comments

Comments
 (0)