Skip to content

Commit c3dfeba

Browse files
bors[bot]matklad
andauthored
Merge #4204
4204: Use specific pattern when translating if-let-else to match r=matklad a=matklad We *probably* should actually use the same machinery here, as we do for fill match arms, but just special-casing options and results seems to be a good first step. bors r+ 🤖 Co-authored-by: Aleksey Kladov <[email protected]>
2 parents b140827 + 7c3c289 commit c3dfeba

File tree

4 files changed

+144
-54
lines changed

4 files changed

+144
-54
lines changed

crates/ra_assists/src/handlers/replace_if_let_with_match.rs

Lines changed: 72 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
use ra_fmt::unwrap_trivial_block;
22
use ra_syntax::{
3-
ast::{self, make},
3+
ast::{self, edit::IndentLevel, make},
44
AstNode,
55
};
66

7-
use crate::{Assist, AssistCtx, AssistId};
8-
use ast::edit::IndentLevel;
7+
use crate::{utils::TryEnum, Assist, AssistCtx, AssistId};
98

109
// Assist: replace_if_let_with_match
1110
//
@@ -44,15 +43,21 @@ pub(crate) fn replace_if_let_with_match(ctx: AssistCtx) -> Option<Assist> {
4443
ast::ElseBranch::IfExpr(_) => return None,
4544
};
4645

47-
ctx.add_assist(AssistId("replace_if_let_with_match"), "Replace with match", |edit| {
46+
let sema = ctx.sema;
47+
ctx.add_assist(AssistId("replace_if_let_with_match"), "Replace with match", move |edit| {
4848
let match_expr = {
4949
let then_arm = {
5050
let then_expr = unwrap_trivial_block(then_block);
51-
make::match_arm(vec![pat], then_expr)
51+
make::match_arm(vec![pat.clone()], then_expr)
5252
};
5353
let else_arm = {
54+
let pattern = sema
55+
.type_of_pat(&pat)
56+
.and_then(|ty| TryEnum::from_ty(sema, &ty))
57+
.map(|it| it.sad_pattern())
58+
.unwrap_or_else(|| make::placeholder_pat().into());
5459
let else_expr = unwrap_trivial_block(else_block);
55-
make::match_arm(vec![make::placeholder_pat().into()], else_expr)
60+
make::match_arm(vec![pattern], else_expr)
5661
};
5762
make::expr_match(expr, make::match_arm_list(vec![then_arm, else_arm]))
5863
};
@@ -68,6 +73,7 @@ pub(crate) fn replace_if_let_with_match(ctx: AssistCtx) -> Option<Assist> {
6873
#[cfg(test)]
6974
mod tests {
7075
use super::*;
76+
7177
use crate::helpers::{check_assist, check_assist_target};
7278

7379
#[test]
@@ -145,4 +151,64 @@ impl VariantData {
145151
}",
146152
);
147153
}
154+
155+
#[test]
156+
fn special_case_option() {
157+
check_assist(
158+
replace_if_let_with_match,
159+
r#"
160+
enum Option<T> { Some(T), None }
161+
use Option::*;
162+
163+
fn foo(x: Option<i32>) {
164+
<|>if let Some(x) = x {
165+
println!("{}", x)
166+
} else {
167+
println!("none")
168+
}
169+
}
170+
"#,
171+
r#"
172+
enum Option<T> { Some(T), None }
173+
use Option::*;
174+
175+
fn foo(x: Option<i32>) {
176+
<|>match x {
177+
Some(x) => println!("{}", x),
178+
None => println!("none"),
179+
}
180+
}
181+
"#,
182+
);
183+
}
184+
185+
#[test]
186+
fn special_case_result() {
187+
check_assist(
188+
replace_if_let_with_match,
189+
r#"
190+
enum Result<T, E> { Ok(T), Err(E) }
191+
use Result::*;
192+
193+
fn foo(x: Result<i32, ()>) {
194+
<|>if let Ok(x) = x {
195+
println!("{}", x)
196+
} else {
197+
println!("none")
198+
}
199+
}
200+
"#,
201+
r#"
202+
enum Result<T, E> { Ok(T), Err(E) }
203+
use Result::*;
204+
205+
fn foo(x: Result<i32, ()>) {
206+
<|>match x {
207+
Ok(x) => println!("{}", x),
208+
Err(_) => println!("none"),
209+
}
210+
}
211+
"#,
212+
);
213+
}
148214
}

crates/ra_assists/src/handlers/replace_let_with_if_let.rs

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::iter::once;
22

3-
use hir::Adt;
43
use ra_syntax::{
54
ast::{
65
self,
@@ -12,6 +11,7 @@ use ra_syntax::{
1211

1312
use crate::{
1413
assist_ctx::{Assist, AssistCtx},
14+
utils::TryEnum,
1515
AssistId,
1616
};
1717

@@ -45,20 +45,10 @@ pub(crate) fn replace_let_with_if_let(ctx: AssistCtx) -> Option<Assist> {
4545
let init = let_stmt.initializer()?;
4646
let original_pat = let_stmt.pat()?;
4747
let ty = ctx.sema.type_of_expr(&init)?;
48-
let enum_ = match ty.as_adt() {
49-
Some(Adt::Enum(it)) => it,
50-
_ => return None,
51-
};
52-
let happy_case =
53-
[("Result", "Ok"), ("Option", "Some")].iter().find_map(|(known_type, happy_case)| {
54-
if &enum_.name(ctx.db).to_string() == known_type {
55-
return Some(happy_case);
56-
}
57-
None
58-
});
48+
let happy_variant = TryEnum::from_ty(ctx.sema, &ty).map(|it| it.happy_case());
5949

6050
ctx.add_assist(AssistId("replace_let_with_if_let"), "Replace with if-let", |edit| {
61-
let with_placeholder: ast::Pat = match happy_case {
51+
let with_placeholder: ast::Pat = match happy_variant {
6252
None => make::placeholder_pat().into(),
6353
Some(var_name) => make::tuple_struct_pat(
6454
make::path_unqualified(make::path_segment(make::name_ref(var_name))),

crates/ra_assists/src/handlers/replace_unwrap_with_match.rs

Lines changed: 18 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
use std::iter;
22

33
use ra_syntax::{
4-
ast::{self, make},
4+
ast::{self, edit::IndentLevel, make},
55
AstNode,
66
};
77

8-
use crate::{Assist, AssistCtx, AssistId};
9-
use ast::edit::IndentLevel;
8+
use crate::{utils::TryEnum, Assist, AssistCtx, AssistId};
109

1110
// Assist: replace_unwrap_with_match
1211
//
@@ -38,42 +37,27 @@ pub(crate) fn replace_unwrap_with_match(ctx: AssistCtx) -> Option<Assist> {
3837
}
3938
let caller = method_call.expr()?;
4039
let ty = ctx.sema.type_of_expr(&caller)?;
40+
let happy_variant = TryEnum::from_ty(ctx.sema, &ty)?.happy_case();
4141

42-
let type_name = ty.as_adt()?.name(ctx.sema.db).to_string();
42+
ctx.add_assist(AssistId("replace_unwrap_with_match"), "Replace unwrap with match", |edit| {
43+
let ok_path = make::path_unqualified(make::path_segment(make::name_ref(happy_variant)));
44+
let it = make::bind_pat(make::name("a")).into();
45+
let ok_tuple = make::tuple_struct_pat(ok_path, iter::once(it)).into();
4346

44-
for (unwrap_type, variant_name) in [("Result", "Ok"), ("Option", "Some")].iter() {
45-
if &type_name == unwrap_type {
46-
return ctx.add_assist(
47-
AssistId("replace_unwrap_with_match"),
48-
"Replace unwrap with match",
49-
|edit| {
50-
let ok_path =
51-
make::path_unqualified(make::path_segment(make::name_ref(variant_name)));
52-
let it = make::bind_pat(make::name("a")).into();
53-
let ok_tuple = make::tuple_struct_pat(ok_path, iter::once(it)).into();
47+
let bind_path = make::path_unqualified(make::path_segment(make::name_ref("a")));
48+
let ok_arm = make::match_arm(iter::once(ok_tuple), make::expr_path(bind_path));
5449

55-
let bind_path = make::path_unqualified(make::path_segment(make::name_ref("a")));
56-
let ok_arm = make::match_arm(iter::once(ok_tuple), make::expr_path(bind_path));
50+
let unreachable_call = make::unreachable_macro_call().into();
51+
let err_arm = make::match_arm(iter::once(make::placeholder_pat().into()), unreachable_call);
5752

58-
let unreachable_call = make::unreachable_macro_call().into();
59-
let err_arm = make::match_arm(
60-
iter::once(make::placeholder_pat().into()),
61-
unreachable_call,
62-
);
53+
let match_arm_list = make::match_arm_list(vec![ok_arm, err_arm]);
54+
let match_expr = make::expr_match(caller.clone(), match_arm_list);
55+
let match_expr = IndentLevel::from_node(method_call.syntax()).increase_indent(match_expr);
6356

64-
let match_arm_list = make::match_arm_list(vec![ok_arm, err_arm]);
65-
let match_expr = make::expr_match(caller.clone(), match_arm_list);
66-
let match_expr =
67-
IndentLevel::from_node(method_call.syntax()).increase_indent(match_expr);
68-
69-
edit.target(method_call.syntax().text_range());
70-
edit.set_cursor(caller.syntax().text_range().start());
71-
edit.replace_ast::<ast::Expr>(method_call.into(), match_expr);
72-
},
73-
);
74-
}
75-
}
76-
None
57+
edit.target(method_call.syntax().text_range());
58+
edit.set_cursor(caller.syntax().text_range().start());
59+
edit.replace_ast::<ast::Expr>(method_call.into(), match_expr);
60+
})
7761
}
7862

7963
#[cfg(test)]

crates/ra_assists/src/utils.rs

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
//! Assorted functions shared by several assists.
22
pub(crate) mod insert_use;
33

4-
use hir::Semantics;
4+
use std::iter;
5+
6+
use hir::{Adt, Semantics, Type};
57
use ra_ide_db::RootDatabase;
68
use ra_syntax::{
79
ast::{self, make, NameOwner},
@@ -99,3 +101,51 @@ fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> {
99101
_ => None,
100102
}
101103
}
104+
105+
#[derive(Clone, Copy)]
106+
pub(crate) enum TryEnum {
107+
Result,
108+
Option,
109+
}
110+
111+
impl TryEnum {
112+
const ALL: [TryEnum; 2] = [TryEnum::Option, TryEnum::Result];
113+
114+
pub(crate) fn from_ty(sema: &Semantics<RootDatabase>, ty: &Type) -> Option<TryEnum> {
115+
let enum_ = match ty.as_adt() {
116+
Some(Adt::Enum(it)) => it,
117+
_ => return None,
118+
};
119+
TryEnum::ALL.iter().find_map(|&var| {
120+
if &enum_.name(sema.db).to_string() == var.type_name() {
121+
return Some(var);
122+
}
123+
None
124+
})
125+
}
126+
127+
pub(crate) fn happy_case(self) -> &'static str {
128+
match self {
129+
TryEnum::Result => "Ok",
130+
TryEnum::Option => "Some",
131+
}
132+
}
133+
134+
pub(crate) fn sad_pattern(self) -> ast::Pat {
135+
match self {
136+
TryEnum::Result => make::tuple_struct_pat(
137+
make::path_unqualified(make::path_segment(make::name_ref("Err"))),
138+
iter::once(make::placeholder_pat().into()),
139+
)
140+
.into(),
141+
TryEnum::Option => make::bind_pat(make::name("None")).into(),
142+
}
143+
}
144+
145+
fn type_name(self) -> &'static str {
146+
match self {
147+
TryEnum::Result => "Result",
148+
TryEnum::Option => "Option",
149+
}
150+
}
151+
}

0 commit comments

Comments
 (0)