rust/crates/assists/src/handlers/replace_let_with_if_let.rs

102 lines
2.5 KiB
Rust
Raw Normal View History

2020-03-27 13:10:40 +01:00
use std::iter::once;
2020-08-12 18:26:51 +02:00
use syntax::{
2020-03-27 13:10:40 +01:00
ast::{
self,
edit::{AstNodeEdit, IndentLevel},
make,
},
2020-03-27 12:12:17 +01:00
AstNode, T,
};
use crate::{AssistContext, AssistId, AssistKind, Assists};
use ide_db::ty_filter::TryEnum;
2020-03-27 12:12:17 +01:00
// Assist: replace_let_with_if_let
//
2020-03-27 13:10:40 +01:00
// Replaces `let` with an `if-let`.
2020-03-27 12:12:17 +01:00
//
// ```
// # enum Option<T> { Some(T), None }
//
// fn main(action: Action) {
// <|>let x = compute();
// }
//
// fn compute() -> Option<i32> { None }
// ```
// ->
// ```
// # enum Option<T> { Some(T), None }
//
// fn main(action: Action) {
// if let Some(x) = compute() {
// }
// }
//
// fn compute() -> Option<i32> { None }
// ```
pub(crate) fn replace_let_with_if_let(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
let let_kw = ctx.find_token_syntax_at_offset(T![let])?;
2020-03-27 12:12:17 +01:00
let let_stmt = let_kw.ancestors().find_map(ast::LetStmt::cast)?;
let init = let_stmt.initializer()?;
let original_pat = let_stmt.pat()?;
let ty = ctx.sema.type_of_expr(&init)?;
let happy_variant = TryEnum::from_ty(&ctx.sema, &ty).map(|it| it.happy_case());
2020-03-27 12:12:17 +01:00
let target = let_kw.text_range();
2020-06-28 18:36:05 -04:00
acc.add(
2020-07-02 17:48:35 -04:00
AssistId("replace_let_with_if_let", AssistKind::RefactorRewrite),
2020-06-28 18:36:05 -04:00
"Replace with if-let",
target,
|edit| {
let with_placeholder: ast::Pat = match happy_variant {
2020-08-05 19:29:24 +02:00
None => make::wildcard_pat().into(),
2020-06-28 18:36:05 -04:00
Some(var_name) => make::tuple_struct_pat(
make::path_unqualified(make::path_segment(make::name_ref(var_name))),
2020-08-05 19:29:24 +02:00
once(make::wildcard_pat().into()),
2020-06-28 18:36:05 -04:00
)
.into(),
};
let block =
make::block_expr(None, None).indent(IndentLevel::from_node(let_stmt.syntax()));
let if_ = make::expr_if(make::condition(init, Some(with_placeholder)), block);
let stmt = make::expr_stmt(if_);
2020-03-27 12:12:17 +01:00
2020-07-31 20:07:21 +02:00
let placeholder = stmt.syntax().descendants().find_map(ast::WildcardPat::cast).unwrap();
2020-06-28 18:36:05 -04:00
let stmt = stmt.replace_descendant(placeholder.into(), original_pat);
2020-03-27 12:12:17 +01:00
2020-06-28 18:36:05 -04:00
edit.replace_ast(ast::Stmt::from(let_stmt), ast::Stmt::from(stmt));
},
)
2020-03-27 12:12:17 +01:00
}
#[cfg(test)]
mod tests {
2020-05-06 10:16:55 +02:00
use crate::tests::check_assist;
2020-03-27 12:12:17 +01:00
use super::*;
#[test]
fn replace_let_unknown_enum() {
check_assist(
replace_let_with_if_let,
r"
enum E<T> { X(T), Y(T) }
fn main() {
<|>let x = E::X(92);
}
",
r"
enum E<T> { X(T), Y(T) }
fn main() {
2020-05-20 23:50:29 +02:00
if let x = E::X(92) {
2020-03-27 12:12:17 +01:00
}
}
",
)
}
}