aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/utils.rs
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2020-04-29 10:57:06 +0100
committerAleksey Kladov <[email protected]>2020-04-29 10:59:11 +0100
commit7c3c289dab46d1dbe9196549c81307f291e631f7 (patch)
tree9f9249e03c3ecf09bff04bc1fa80c00280ff6be6 /crates/ra_assists/src/utils.rs
parent73bef854ab854ab1a289944966444453e6f4aadf (diff)
Use specific pattern when translating if-let-else to match
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.
Diffstat (limited to 'crates/ra_assists/src/utils.rs')
-rw-r--r--crates/ra_assists/src/utils.rs57
1 files changed, 47 insertions, 10 deletions
diff --git a/crates/ra_assists/src/utils.rs b/crates/ra_assists/src/utils.rs
index 316c8b20f..61f8bd1dc 100644
--- a/crates/ra_assists/src/utils.rs
+++ b/crates/ra_assists/src/utils.rs
@@ -1,6 +1,8 @@
1//! Assorted functions shared by several assists. 1//! Assorted functions shared by several assists.
2pub(crate) mod insert_use; 2pub(crate) mod insert_use;
3 3
4use std::iter;
5
4use hir::{Adt, Semantics, Type}; 6use hir::{Adt, Semantics, Type};
5use ra_ide_db::RootDatabase; 7use ra_ide_db::RootDatabase;
6use ra_syntax::{ 8use ra_syntax::{
@@ -100,15 +102,50 @@ fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> {
100 } 102 }
101} 103}
102 104
103pub(crate) fn happy_try_variant(sema: &Semantics<RootDatabase>, ty: &Type) -> Option<&'static str> { 105#[derive(Clone, Copy)]
104 let enum_ = match ty.as_adt() { 106pub(crate) enum TryEnum {
105 Some(Adt::Enum(it)) => it, 107 Result,
106 _ => return None, 108 Option,
107 }; 109}
108 [("Result", "Ok"), ("Option", "Some")].iter().find_map(|(known_type, happy_case)| { 110
109 if &enum_.name(sema.db).to_string() == known_type { 111impl TryEnum {
110 return Some(*happy_case); 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",
111 } 131 }
112 None 132 }
113 }) 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 }
114} 151}