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 07:10:40 -05:00
use std::iter::once;
use ide_db::ty_filter::TryEnum;
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};
2020-03-27 06:12:17 -05:00
// Assist: replace_let_with_if_let
//
// Replaces `let` with an `if let`.
2020-03-27 06:12:17 -05:00
//
// ```
// # enum Option<T> { Some(T), None }
//
// fn main(action: Action) {
2021-01-06 14:15:48 -06:00
// $0let x = compute();
2020-03-27 06:12:17 -05: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 }
// ```
2022-07-20 08:02:08 -05:00
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 06:12:17 -05:00
let init = let_stmt.initializer()?;
let original_pat = let_stmt.pat()?;
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),
"Replace let with if let",
2020-06-28 17:36:05 -05:00
target,
|edit| {
let ty = ctx.sema.type_of_expr(&init);
2021-08-03 10:24:43 -05:00
let happy_variant = ty
.and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty.adjusted()))
2021-08-03 10:24:43 -05:00
.map(|it| it.happy_case());
2021-05-10 07:25:56 -05: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 17:36:05 -05:00
};
2021-05-10 07:25:56 -05:00
2020-06-28 17:36:05 -05:00
let block =
2021-05-10 07:25:56 -05: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 17:36:05 -05:00
let stmt = make::expr_stmt(if_);
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() {
2021-01-06 14:15:48 -06:00
$0let x = E::X(92);
2020-03-27 06:12:17 -05:00
}
",
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
}
}
",
)
}
}