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 syntax::{
ast::{self, AstNode, AstToken},
SyntaxKind::BLOCK_EXPR,
TextRange, TextSize,
};
use text_edit::TextEdit;
@ -220,17 +221,29 @@ pub(crate) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
)
.add_to(acc);
postfix_snippet(ctx, cap, &dot_receiver, "let", "let", &format!("let $0 = {};", receiver_text))
.add_to(acc);
postfix_snippet(
ctx,
cap,
&dot_receiver,
"letm",
"let mut",
&format!("let mut $0 = {};", receiver_text),
)
.add_to(acc);
let parent_node = dot_receiver.syntax().parent().and_then(|p| p.parent());
if let Some(parent) = parent_node {
if parent.kind() == BLOCK_EXPR {
postfix_snippet(
ctx,
cap,
&dot_receiver,
"let",
"let",
&format!("let $0 = {};", receiver_text),
)
.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 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]
fn postfix_type_filtering() {
check(

View file

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