Use correct indent when replacing with match

This commit is contained in:
Aleksey Kladov 2020-06-09 12:38:47 +02:00
parent 53cc2c16e7
commit 8cad7d1a2b
3 changed files with 45 additions and 7 deletions

View file

@ -154,7 +154,7 @@ pub(crate) fn convert_to_guarded_return(acc: &mut Assists, ctx: &AssistContext)
parent_block: &ast::BlockExpr,
if_expr: &ast::IfExpr,
) -> SyntaxNode {
let then_block_items = then_block.dedent(IndentLevel::from(1));
let then_block_items = then_block.dedent(IndentLevel(1));
let end_of_then = then_block_items.syntax().last_child_or_token().unwrap();
let end_of_then =
if end_of_then.prev_sibling_or_token().map(|n| n.kind()) == Some(WHITESPACE) {

View file

@ -51,6 +51,7 @@ pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext)
acc.add(AssistId("replace_if_let_with_match"), "Replace with match", target, move |edit| {
let match_expr = {
let then_arm = {
let then_block = then_block.reset_indent().indent(IndentLevel(1));
let then_expr = unwrap_trivial_block(then_block);
make::match_arm(vec![pat.clone()], then_expr)
};
@ -64,8 +65,8 @@ pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext)
let else_expr = unwrap_trivial_block(else_block);
make::match_arm(vec![pattern], else_expr)
};
make::expr_match(expr, make::match_arm_list(vec![then_arm, else_arm]))
.indent(IndentLevel::from_node(if_expr.syntax()))
let match_expr = make::expr_match(expr, make::match_arm_list(vec![then_arm, else_arm]));
match_expr.indent(IndentLevel::from_node(if_expr.syntax()))
};
edit.replace_ast::<ast::Expr>(if_expr.into(), match_expr);
@ -213,4 +214,36 @@ fn foo(x: Result<i32, ()>) {
"#,
);
}
#[test]
fn nested_indent() {
check_assist(
replace_if_let_with_match,
r#"
fn main() {
if true {
<|>if let Ok(rel_path) = path.strip_prefix(root_path) {
let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
Some((*id, rel_path))
} else {
None
}
}
}
"#,
r#"
fn main() {
if true {
match path.strip_prefix(root_path) {
Ok(rel_path) => {
let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
Some((*id, rel_path))
}
_ => None,
}
}
}
"#,
)
}
}

View file

@ -579,12 +579,17 @@ pub trait AstNodeEdit: AstNode + Clone + Sized {
rewriter.rewrite_ast(self)
}
#[must_use]
fn indent(&self, indent: IndentLevel) -> Self {
Self::cast(indent.increase_indent(self.syntax().clone())).unwrap()
fn indent(&self, level: IndentLevel) -> Self {
Self::cast(level.increase_indent(self.syntax().clone())).unwrap()
}
#[must_use]
fn dedent(&self, indent: IndentLevel) -> Self {
Self::cast(indent.decrease_indent(self.syntax().clone())).unwrap()
fn dedent(&self, level: IndentLevel) -> Self {
Self::cast(level.decrease_indent(self.syntax().clone())).unwrap()
}
#[must_use]
fn reset_indent(&self) -> Self {
let level = IndentLevel::from_node(self.syntax());
self.dedent(level)
}
}