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

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

101 lines
2.3 KiB
Rust
Raw Normal View History

2020-03-27 13:10:40 +01:00
use std::iter::once;
use ide_db::ty_filter::TryEnum;
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};
2020-03-27 12:12:17 +01:00
// Assist: replace_let_with_if_let
//
// Replaces `let` with an `if let`.
2020-03-27 12:12:17 +01:00
//
// ```
// # enum Option<T> { Some(T), None }
//
// fn main(action: Action) {
2021-01-06 20:15:48 +00:00
// $0let x = compute();
2020-03-27 12:12:17 +01:00
// }
//
// 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])?;
let let_stmt = let_kw.parent().and_then(ast::LetStmt::cast)?;
2020-03-27 12:12:17 +01:00
let init = let_stmt.initializer()?;
let original_pat = let_stmt.pat()?;
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),
"Replace let with if let",
2020-06-28 18:36:05 -04:00
target,
|edit| {
let ty = ctx.sema.type_of_expr(&init);
2021-08-03 17:24:43 +02:00
let happy_variant = ty
.and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty.adjusted()))
2021-08-03 17:24:43 +02:00
.map(|it| it.happy_case());
2021-05-10 15:25:56 +03:00
let pat = match happy_variant {
None => original_pat,
Some(var_name) => {
make::tuple_struct_pat(make::ext::ident_path(var_name), once(original_pat))
.into()
}
2020-06-28 18:36:05 -04:00
};
2021-05-10 15:25:56 +03:00
2020-06-28 18:36:05 -04:00
let block =
2021-05-10 15:25:56 +03:00
make::ext::empty_block_expr().indent(IndentLevel::from_node(let_stmt.syntax()));
let if_ = make::expr_if(make::expr_let(pat, init).into(), block, None);
2020-06-28 18:36:05 -04:00
let stmt = make::expr_stmt(if_);
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() {
2021-01-06 20:15:48 +00:00
$0let x = E::X(92);
2020-03-27 12:12:17 +01:00
}
",
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
}
}
",
)
}
}