add let and letm postfix to turn expressions into variables

Signed-off-by: Benjamin Coenen <5719034+bnjjj@users.noreply.github.com>
This commit is contained in:
Benjamin Coenen 2020-11-28 17:38:16 +01:00
parent 775c69183c
commit 474ebd60d1
2 changed files with 56 additions and 11 deletions

View file

@ -5,6 +5,7 @@ mod format_like;
use ide_db::ty_filter::TryEnum; use ide_db::ty_filter::TryEnum;
use syntax::{ use syntax::{
ast::{self, AstNode, AstToken}, ast::{self, AstNode, AstToken},
SyntaxKind::BLOCK_EXPR,
TextRange, TextSize, TextRange, TextSize,
}; };
use text_edit::TextEdit; use text_edit::TextEdit;
@ -220,17 +221,29 @@ pub(crate) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
) )
.add_to(acc); .add_to(acc);
postfix_snippet(ctx, cap, &dot_receiver, "let", "let", &format!("let $0 = {};", receiver_text)) let parent_node = dot_receiver.syntax().parent().and_then(|p| p.parent());
.add_to(acc); if let Some(parent) = parent_node {
postfix_snippet( if parent.kind() == BLOCK_EXPR {
ctx, postfix_snippet(
cap, ctx,
&dot_receiver, cap,
"letm", &dot_receiver,
"let mut", "let",
&format!("let mut $0 = {};", receiver_text), "let",
) &format!("let $0 = {};", receiver_text),
.add_to(acc); )
.add_to(acc);
postfix_snippet(
ctx,
cap,
&dot_receiver,
"letm",
"let mut",
&format!("let mut $0 = {};", receiver_text),
)
.add_to(acc);
}
}
if let ast::Expr::Literal(literal) = dot_receiver.clone() { if let ast::Expr::Literal(literal) = dot_receiver.clone() {
if let Some(literal_text) = ast::String::cast(literal.token()) { if let Some(literal_text) = ast::String::cast(literal.token()) {
@ -321,6 +334,36 @@ fn main() {
); );
} }
#[test]
fn postfix_completion_works_for_function_calln() {
check(
r#"
fn foo(elt: bool) -> bool {
!elt
}
fn main() {
let bar = true;
foo(bar.<|>)
}
"#,
expect![[r#"
sn box Box::new(expr)
sn call function(expr)
sn dbg dbg!(expr)
sn dbgr dbg!(&expr)
sn if if expr {}
sn match match expr {}
sn not !expr
sn ok Ok(expr)
sn ref &expr
sn refm &mut expr
sn some Some(expr)
sn while while expr {}
"#]],
);
}
#[test] #[test]
fn postfix_type_filtering() { fn postfix_type_filtering() {
check( check(

View file

@ -44,6 +44,8 @@ pub use crate::{
// - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result` // - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
// - `expr.ref` -> `&expr` // - `expr.ref` -> `&expr`
// - `expr.refm` -> `&mut expr` // - `expr.refm` -> `&mut expr`
// - `expr.let` -> `let <|> = expr;`
// - `expr.letm` -> `let mut <|> = expr;`
// - `expr.not` -> `!expr` // - `expr.not` -> `!expr`
// - `expr.dbg` -> `dbg!(expr)` // - `expr.dbg` -> `dbg!(expr)`
// - `expr.dbgr` -> `dbg!(&expr)` // - `expr.dbgr` -> `dbg!(&expr)`