Skip to content

Commit

Permalink
add let and letm postfix to turn expressions into variables
Browse files Browse the repository at this point in the history
Signed-off-by: Benjamin Coenen <5719034+bnjjj@users.noreply.github.com>
  • Loading branch information
bnjjj committed Nov 28, 2020
1 parent 775c691 commit 474ebd6
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 11 deletions.
65 changes: 54 additions & 11 deletions crates/completion/src/completions/postfix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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()) {
Expand Down Expand Up @@ -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(
Expand Down
2 changes: 2 additions & 0 deletions crates/completion/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)`
Expand Down

0 comments on commit 474ebd6

Please sign in to comment.