aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/handlers/replace_let_with_if_let.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/handlers/replace_let_with_if_let.rs')
-rw-r--r--crates/ra_assists/src/handlers/replace_let_with_if_let.rs108
1 files changed, 108 insertions, 0 deletions
diff --git a/crates/ra_assists/src/handlers/replace_let_with_if_let.rs b/crates/ra_assists/src/handlers/replace_let_with_if_let.rs
new file mode 100644
index 000000000..10e41f97e
--- /dev/null
+++ b/crates/ra_assists/src/handlers/replace_let_with_if_let.rs
@@ -0,0 +1,108 @@
1use hir::Adt;
2use ra_syntax::{
3 ast::{self, make},
4 AstNode, T,
5};
6
7use crate::{
8 assist_ctx::{Assist, AssistCtx},
9 AssistId,
10};
11use ast::edit::{AstNodeEdit, IndentLevel};
12use std::iter::once;
13
14// Assist: replace_let_with_if_let
15//
16// Replaces `if let` with an else branch with a `match` expression.
17//
18// ```
19// # enum Option<T> { Some(T), None }
20//
21// fn main(action: Action) {
22// <|>let x = compute();
23// }
24//
25// fn compute() -> Option<i32> { None }
26// ```
27// ->
28// ```
29// # enum Option<T> { Some(T), None }
30//
31// fn main(action: Action) {
32// if let Some(x) = compute() {
33// }
34// }
35//
36// fn compute() -> Option<i32> { None }
37// ```
38pub(crate) fn replace_let_with_if_let(ctx: AssistCtx) -> Option<Assist> {
39 let let_kw = ctx.find_token_at_offset(T![let])?;
40 let let_stmt = let_kw.ancestors().find_map(ast::LetStmt::cast)?;
41 let init = let_stmt.initializer()?;
42 let original_pat = let_stmt.pat()?;
43 let ty = ctx.sema.type_of_expr(&init)?;
44 let enum_ = match ty.as_adt() {
45 Some(Adt::Enum(it)) => it,
46 _ => return None,
47 };
48 let happy_case =
49 [("Result", "Ok"), ("Option", "Some")].iter().find_map(|(known_type, happy_case)| {
50 if &enum_.name(ctx.db).to_string() == known_type {
51 return Some(happy_case);
52 }
53 None
54 });
55
56 ctx.add_assist(AssistId("replace_let_with_if_let"), "Replace with if-let", |edit| {
57 let with_placeholder: ast::Pat = match happy_case {
58 None => make::placeholder_pat().into(),
59 Some(var_name) => make::tuple_struct_pat(
60 make::path_unqualified(make::path_segment(make::name_ref(var_name))),
61 once(make::placeholder_pat().into()),
62 )
63 .into(),
64 };
65 let block =
66 IndentLevel::from_node(let_stmt.syntax()).increase_indent(make::block_expr(None, None));
67 let if_ = make::expr_if(make::condition(init, Some(with_placeholder)), block);
68 let stmt = make::expr_stmt(if_);
69
70 let placeholder = stmt.syntax().descendants().find_map(ast::PlaceholderPat::cast).unwrap();
71 let target_offset =
72 let_stmt.syntax().text_range().start() + placeholder.syntax().text_range().start();
73 let stmt = stmt.replace_descendant(placeholder.into(), original_pat);
74
75 edit.replace_ast(ast::Stmt::from(let_stmt), ast::Stmt::from(stmt));
76 edit.target(let_kw.text_range());
77 edit.set_cursor(target_offset);
78 })
79}
80
81#[cfg(test)]
82mod tests {
83 use crate::helpers::check_assist;
84
85 use super::*;
86
87 #[test]
88 fn replace_let_unknown_enum() {
89 check_assist(
90 replace_let_with_if_let,
91 r"
92enum E<T> { X(T), Y(T) }
93
94fn main() {
95 <|>let x = E::X(92);
96}
97 ",
98 r"
99enum E<T> { X(T), Y(T) }
100
101fn main() {
102 if let <|>x = E::X(92) {
103 }
104}
105 ",
106 )
107 }
108}