Cleanup early return assist

This commit is contained in:
Aleksey Kladov 2020-02-07 11:51:16 +01:00
parent aa1234e02b
commit 36ee9ecb67
2 changed files with 29 additions and 11 deletions

View file

@ -10,6 +10,7 @@ use ra_syntax::{
use crate::{
assist_ctx::{Assist, AssistCtx},
assists::invert_if::invert_boolean_expression,
AssistId,
};
@ -99,9 +100,13 @@ pub(crate) fn convert_to_guarded_return(ctx: AssistCtx) -> Option<Assist> {
let new_block = match if_let_pat {
None => {
// If.
let early_expression = &(early_expression.syntax().to_string() + ";");
let new_expr = if_indent_level
.increase_indent(make::if_expression(cond_expr, early_expression));
let new_expr = {
let then_branch =
make::block_expr(once(make::expr_stmt(early_expression).into()), None);
let cond = invert_boolean_expression(cond_expr);
let e = make::expr_if(cond, then_branch);
if_indent_level.increase_indent(e)
};
replace(new_expr.syntax(), &then_block, &parent_block, &if_expr)
}
Some((path, bound_ident)) => {

View file

@ -33,6 +33,21 @@ pub fn record_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordF
}
}
pub fn block_expr(
stmts: impl IntoIterator<Item = ast::Stmt>,
tail_expr: Option<ast::Expr>,
) -> ast::BlockExpr {
let mut text = "{\n".to_string();
for stmt in stmts.into_iter() {
text += &format!(" {}\n", stmt.syntax());
}
if let Some(tail_expr) = tail_expr {
text += &format!(" {}\n", tail_expr.syntax())
}
text += "}";
ast_from_text(&format!("fn f() {}", text))
}
pub fn block_from_expr(e: ast::Expr) -> ast::Block {
return from_text(&format!("{{ {} }}", e.syntax()));
@ -62,6 +77,9 @@ pub fn expr_return() -> ast::Expr {
pub fn expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr {
expr_from_text(&format!("match {} {}", expr.syntax(), match_arm_list.syntax()))
}
pub fn expr_if(condition: ast::Expr, then_branch: ast::BlockExpr) -> ast::Expr {
expr_from_text(&format!("if {} {}", condition.syntax(), then_branch.syntax()))
}
pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr {
let token = token(op);
expr_from_text(&format!("{}{}", token, expr.syntax()))
@ -162,14 +180,6 @@ pub fn where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::Whe
}
}
pub fn if_expression(condition: ast::Expr, statement: &str) -> ast::IfExpr {
ast_from_text(&format!(
"fn f() {{ if !{} {{\n {}\n}}\n}}",
condition.syntax().text(),
statement
))
}
pub fn let_stmt(pattern: ast::Pat, initializer: Option<ast::Expr>) -> ast::LetStmt {
let text = match initializer {
Some(it) => format!("let {} = {};", pattern.syntax(), it.syntax()),
@ -177,6 +187,9 @@ pub fn let_stmt(pattern: ast::Pat, initializer: Option<ast::Expr>) -> ast::LetSt
};
ast_from_text(&format!("fn f() {{ {} }}", text))
}
pub fn expr_stmt(expr: ast::Expr) -> ast::ExprStmt {
ast_from_text(&format!("fn f() {{ {}; }}", expr.syntax()))
}
pub fn token(kind: SyntaxKind) -> SyntaxToken {
tokens::SOURCE_FILE