Skip to content

Commit 382d10e

Browse files
bors[bot]matklad
andauthored
Merge #4811
4811: Unwrap block works with match arms r=matklad a=matklad bors r+ 🤖 Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
2 parents 4cacedd + 53cc2c1 commit 382d10e

File tree

1 file changed

+40
-4
lines changed

1 file changed

+40
-4
lines changed

crates/ra_assists/src/handlers/unwrap_block.rs

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
use ra_fmt::unwrap_trivial_block;
2-
use ra_syntax::{ast, AstNode, TextRange, T};
2+
use ra_syntax::{
3+
ast::{
4+
self,
5+
edit::{AstNodeEdit, IndentLevel},
6+
},
7+
AstNode, TextRange, T,
8+
};
39

410
use crate::{AssistContext, AssistId, Assists};
511

@@ -21,15 +27,21 @@ use crate::{AssistContext, AssistId, Assists};
2127
// }
2228
// ```
2329
pub(crate) fn unwrap_block(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
24-
let l_curly_token = ctx.find_token_at_offset(T!['{'])?;
25-
let block = ast::BlockExpr::cast(l_curly_token.parent())?;
26-
let parent = block.syntax().parent()?;
2730
let assist_id = AssistId("unwrap_block");
2831
let assist_label = "Unwrap block";
32+
33+
let l_curly_token = ctx.find_token_at_offset(T!['{'])?;
34+
let mut block = ast::BlockExpr::cast(l_curly_token.parent())?;
35+
let mut parent = block.syntax().parent()?;
36+
if ast::MatchArm::can_cast(parent.kind()) {
37+
parent = parent.ancestors().find(|it| ast::MatchExpr::can_cast(it.kind()))?
38+
}
39+
2940
let parent = ast::Expr::cast(parent)?;
3041

3142
match parent.clone() {
3243
ast::Expr::ForExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::LoopExpr(_) => (),
44+
ast::Expr::MatchExpr(_) => block = block.dedent(IndentLevel(1)),
3345
ast::Expr::IfExpr(if_expr) => {
3446
let then_branch = if_expr.then_branch()?;
3547
if then_branch == block {
@@ -459,6 +471,30 @@ mod tests {
459471
);
460472
}
461473

474+
#[test]
475+
fn unwrap_match_arm() {
476+
check_assist(
477+
unwrap_block,
478+
r#"
479+
fn main() {
480+
match rel_path {
481+
Ok(rel_path) => {<|>
482+
let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
483+
Some((*id, rel_path))
484+
}
485+
Err(_) => None,
486+
}
487+
}
488+
"#,
489+
r#"
490+
fn main() {
491+
let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
492+
Some((*id, rel_path))
493+
}
494+
"#,
495+
);
496+
}
497+
462498
#[test]
463499
fn simple_if_in_while_bad_cursor_position() {
464500
check_assist_not_applicable(

0 commit comments

Comments
 (0)