|
1 | 1 | use ide_db::ty_filter::TryEnum; |
2 | 2 | use syntax::{ |
3 | 3 | AstNode, T, |
4 | | - ast::{self, edit::IndentLevel, edit_in_place::Indent, syntax_factory::SyntaxFactory}, |
| 4 | + ast::{self, edit::AstNodeEdit, edit::IndentLevel, syntax_factory::SyntaxFactory}, |
5 | 5 | }; |
6 | 6 |
|
7 | 7 | use crate::{AssistContext, AssistId, Assists}; |
@@ -35,6 +35,11 @@ pub(crate) fn replace_let_with_if_let(acc: &mut Assists, ctx: &AssistContext<'_> |
35 | 35 | let let_stmt = let_kw.parent().and_then(ast::LetStmt::cast)?; |
36 | 36 | let init = let_stmt.initializer()?; |
37 | 37 | let original_pat = let_stmt.pat()?; |
| 38 | + let statements = |
| 39 | + std::iter::successors(let_stmt.syntax().next_sibling(), |it| it.next_sibling()) |
| 40 | + .filter_map(ast::Stmt::cast) |
| 41 | + .filter(|stmt| crate::utils::is_selected(stmt, ctx.selection_trimmed(), false)) |
| 42 | + .collect::<Vec<_>>(); |
38 | 43 |
|
39 | 44 | let target = let_kw.text_range(); |
40 | 45 | acc.add( |
@@ -63,16 +68,23 @@ pub(crate) fn replace_let_with_if_let(acc: &mut Assists, ctx: &AssistContext<'_> |
63 | 68 | let init_expr = |
64 | 69 | if let_expr_needs_paren(&init) { make.expr_paren(init).into() } else { init }; |
65 | 70 |
|
66 | | - let block = make.block_expr([], None); |
67 | | - block.indent(IndentLevel::from_node(let_stmt.syntax())); |
| 71 | + let block = make.block_expr(statements.iter().map(AstNodeEdit::reset_indent), None); |
68 | 72 | let if_expr = make.expr_if( |
69 | 73 | make.expr_let(pat, init_expr).into(), |
70 | | - block, |
| 74 | + block.indent(IndentLevel::from_node(let_stmt.syntax())), |
71 | 75 | let_stmt |
72 | 76 | .let_else() |
73 | 77 | .and_then(|let_else| let_else.block_expr().map(ast::ElseBranch::from)), |
74 | 78 | ); |
75 | 79 | let if_stmt = make.expr_stmt(if_expr.into()); |
| 80 | + for stmt in statements { |
| 81 | + if let Some(prev) = stmt.syntax().prev_sibling_or_token() |
| 82 | + && prev.kind() == syntax::SyntaxKind::WHITESPACE |
| 83 | + { |
| 84 | + editor.delete(prev); |
| 85 | + } |
| 86 | + editor.delete(stmt.syntax()); |
| 87 | + } |
76 | 88 |
|
77 | 89 | editor.replace(let_stmt.syntax(), if_stmt.syntax()); |
78 | 90 | editor.add_mappings(make.finish_with_mappings()); |
@@ -119,6 +131,32 @@ fn main() { |
119 | 131 | ) |
120 | 132 | } |
121 | 133 |
|
| 134 | + #[test] |
| 135 | + fn replace_let_with_stmts() { |
| 136 | + check_assist( |
| 137 | + replace_let_with_if_let, |
| 138 | + r" |
| 139 | +enum E<T> { X(T), Y(T) } |
| 140 | +
|
| 141 | +fn main() { |
| 142 | + $0let x = E::X(92); |
| 143 | + let y = x;$0 |
| 144 | + let _ = (); |
| 145 | +} |
| 146 | + ", |
| 147 | + r" |
| 148 | +enum E<T> { X(T), Y(T) } |
| 149 | +
|
| 150 | +fn main() { |
| 151 | + if let x = E::X(92) { |
| 152 | + let y = x; |
| 153 | + } |
| 154 | + let _ = (); |
| 155 | +} |
| 156 | + ", |
| 157 | + ) |
| 158 | + } |
| 159 | + |
122 | 160 | #[test] |
123 | 161 | fn replace_let_logic_and() { |
124 | 162 | check_assist( |
|
0 commit comments