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

102 lines
2.5 KiB
Rust
Raw Normal View History

2020-03-27 07:10:40 -05:00
use std::iter::once;
2020-08-12 11:26:51 -05:00
use syntax::{
2020-03-27 07:10:40 -05:00
ast::{
self,
edit::{AstNodeEdit, IndentLevel},
make,
},
2020-03-27 06:12:17 -05:00
AstNode, T,
};
use crate::{AssistContext, AssistId, AssistKind, Assists};
use ide_db::ty_filter::TryEnum;
2020-03-27 06:12:17 -05:00
// Assist: replace_let_with_if_let
//
2020-03-27 07:10:40 -05:00
// Replaces `let` with an `if-let`.
2020-03-27 06:12:17 -05: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<()> {
2020-03-27 06:12:17 -05:00
let let_kw = ctx.find_token_at_offset(T![let])?;
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 06:12:17 -05:00
let target = let_kw.text_range();
2020-06-28 17:36:05 -05:00
acc.add(
2020-07-02 16:48:35 -05:00
AssistId("replace_let_with_if_let", AssistKind::RefactorRewrite),
2020-06-28 17:36:05 -05:00
"Replace with if-let",
target,
|edit| {
let with_placeholder: ast::Pat = match happy_variant {
2020-08-05 12:29:24 -05:00
None => make::wildcard_pat().into(),
2020-06-28 17:36:05 -05:00
Some(var_name) => make::tuple_struct_pat(
make::path_unqualified(make::path_segment(make::name_ref(var_name))),
2020-08-05 12:29:24 -05:00
once(make::wildcard_pat().into()),
2020-06-28 17:36:05 -05: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 06:12:17 -05:00
2020-07-31 13:07:21 -05:00
let placeholder = stmt.syntax().descendants().find_map(ast::WildcardPat::cast).unwrap();
2020-06-28 17:36:05 -05:00
let stmt = stmt.replace_descendant(placeholder.into(), original_pat);
2020-03-27 06:12:17 -05:00
2020-06-28 17:36:05 -05:00
edit.replace_ast(ast::Stmt::from(let_stmt), ast::Stmt::from(stmt));
},
)
2020-03-27 06:12:17 -05:00
}
#[cfg(test)]
mod tests {
2020-05-06 03:16:55 -05:00
use crate::tests::check_assist;
2020-03-27 06:12:17 -05: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 16:50:29 -05:00
if let x = E::X(92) {
2020-03-27 06:12:17 -05:00
}
}
",
)
}
}