rust-analyzer/crates/ra_ide_api/src/completion/complete_postfix.rs

78 lines
2.5 KiB
Rust
Raw Normal View History

2019-01-21 05:19:51 +00:00
use crate::{
completion::{
completion_item::{
Completions,
Builder,
CompletionKind,
},
completion_context::CompletionContext,
},
CompletionItem
};
use ra_syntax::{
ast::AstNode,
TextRange
};
use ra_text_edit::TextEditBuilder;
fn postfix_snippet(ctx: &CompletionContext, label: &str, detail: &str, snippet: &str) -> Builder {
2019-01-21 05:19:51 +00:00
let replace_range = ctx.source_range();
2019-02-08 11:49:43 +00:00
let receiver_range = ctx.dot_receiver.expect("no receiver available").syntax().range();
2019-01-21 05:19:51 +00:00
let delete_range = TextRange::from_to(receiver_range.start(), replace_range.start());
let mut builder = TextEditBuilder::default();
builder.delete(delete_range);
CompletionItem::new(CompletionKind::Postfix, replace_range, label)
2019-02-18 09:07:47 +00:00
.insert_snippet(snippet)
.detail(detail)
2019-01-21 05:19:51 +00:00
.text_edit(builder.finish())
}
pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
if let Some(dot_receiver) = ctx.dot_receiver {
let receiver_text = dot_receiver.syntax().text().to_string();
postfix_snippet(ctx, "not", "!expr", &format!("!{}", receiver_text)).add_to(acc);
postfix_snippet(ctx, "ref", "&expr", &format!("&{}", receiver_text)).add_to(acc);
postfix_snippet(ctx, "refm", "&mut expr", &format!("&mut {}", receiver_text)).add_to(acc);
postfix_snippet(ctx, "if", "if expr {}", &format!("if {} {{$0}}", receiver_text))
.add_to(acc);
2019-01-21 05:19:51 +00:00
postfix_snippet(
ctx,
"match",
"match expr {}",
2019-01-21 05:19:51 +00:00
&format!("match {} {{\n${{1:_}} => {{$0\\}},\n}}", receiver_text),
)
.add_to(acc);
postfix_snippet(
ctx,
"while",
"while expr {}",
&format!("while {} {{\n$0\n}}", receiver_text),
)
.add_to(acc);
postfix_snippet(ctx, "dbg", "dbg!(expr)", &format!("dbg!({})", receiver_text)).add_to(acc);
2019-01-21 05:19:51 +00:00
}
}
#[cfg(test)]
mod tests {
use crate::completion::completion_item::CompletionKind;
use crate::completion::completion_item::check_completion;
2019-01-21 21:33:30 +00:00
fn check_snippet_completion(test_name: &str, code: &str) {
check_completion(test_name, code, CompletionKind::Postfix);
2019-01-21 05:19:51 +00:00
}
#[test]
2019-02-03 13:12:57 +00:00
fn postfix_completion_works_for_trivial_path_expression() {
2019-01-21 05:19:51 +00:00
check_snippet_completion(
2019-02-03 13:12:57 +00:00
"postfix_completion_works_for_trivial_path_expression",
2019-01-21 05:19:51 +00:00
r#"
fn main() {
let bar = "a";
bar.<|>
}
"#,
);
}
}