Skip to content

Commit d477979

Browse files
committed
Add tests for LetStmt::set_ty
1 parent 787ca88 commit d477979

File tree

1 file changed

+44
-14
lines changed

1 file changed

+44
-14
lines changed

crates/syntax/src/ast/edit_in_place.rs

+44-14
Original file line numberDiff line numberDiff line change
@@ -663,25 +663,26 @@ impl ast::LetStmt {
663663

664664
ted::remove(existing_ty.syntax());
665665
}
666+
667+
// Remove any trailing ws
668+
if let Some(last) = self.syntax().last_token().filter(|it| it.kind() == WHITESPACE)
669+
{
670+
last.detach();
671+
}
666672
}
667673
Some(new_ty) => {
668674
if self.colon_token().is_none() {
669-
let mut to_insert: Vec<SyntaxElement> = vec![];
670-
671-
let position = match self.pat() {
672-
Some(pat) => Position::after(pat.syntax()),
673-
None => {
674-
to_insert.push(make::tokens::single_space().into());
675-
Position::after(self.let_token().unwrap())
676-
}
677-
};
678-
679-
to_insert.push(make::token(T![:]).into());
680-
681-
ted::insert_all_raw(position, to_insert);
675+
ted::insert_raw(
676+
Position::after(self.pat().unwrap().syntax()),
677+
make::token(T![:]),
678+
);
682679
}
683680

684-
ted::insert(Position::after(self.colon_token().unwrap()), new_ty.syntax());
681+
if let Some(old_ty) = self.ty() {
682+
ted::replace(old_ty.syntax(), new_ty.syntax());
683+
} else {
684+
ted::insert(Position::after(self.colon_token().unwrap()), new_ty.syntax());
685+
}
685686
}
686687
}
687688
}
@@ -1022,6 +1023,35 @@ mod tests {
10221023
check("let a @ ", "let a", None);
10231024
}
10241025

1026+
#[test]
1027+
fn test_let_stmt_set_ty() {
1028+
#[track_caller]
1029+
fn check(before: &str, expected: &str, ty: Option<ast::Type>) {
1030+
let ty = ty.map(|it| it.clone_for_update());
1031+
1032+
let let_stmt = ast_mut_from_text::<ast::LetStmt>(&format!("fn f() {{ {before} }}"));
1033+
let_stmt.set_ty(ty);
1034+
1035+
let after = ast_mut_from_text::<ast::LetStmt>(&format!("fn f() {{ {expected} }}"));
1036+
assert_eq!(let_stmt.to_string(), after.to_string(), "{let_stmt:#?}\n!=\n{after:#?}");
1037+
}
1038+
1039+
// adding
1040+
check("let a;", "let a: ();", Some(make::ty_tuple([])));
1041+
// no semicolon due to it being eaten during error recovery
1042+
check("let a:", "let a: ()", Some(make::ty_tuple([])));
1043+
1044+
// replacing
1045+
check("let a: u8;", "let a: ();", Some(make::ty_tuple([])));
1046+
1047+
// removing
1048+
check("let a: u8;", "let a;", None);
1049+
check("let a:;", "let a;", None);
1050+
1051+
check("let a: u8 = 3;", "let a = 3;", None);
1052+
check("let a: = 3;", "let a = 3;", None);
1053+
}
1054+
10251055
#[test]
10261056
fn add_variant_to_empty_enum() {
10271057
let variant = make::variant(make::name("Bar"), None).clone_for_update();

0 commit comments

Comments
 (0)