1 //! Postfix completions, like `Ok(10).ifl$0` => `if let Ok() = Ok(10) { $0 }`.
5 use hir::Documentation;
7 helpers::{insert_use::ImportScope, FamousDefs, SnippetCap},
11 ast::{self, AstNode, AstToken},
12 SyntaxKind::{EXPR_STMT, STMT_LIST},
15 use text_edit::TextEdit;
18 completions::postfix::format_like::add_format_like_completions, context::CompletionContext,
19 item::Builder, patterns::ImmediateLocation, CompletionItem, CompletionItemKind,
20 CompletionRelevance, Completions, SnippetScope,
23 pub(crate) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
24 if !ctx.config.enable_postfix_completions {
28 let (dot_receiver, receiver_is_ambiguous_float_literal) = match &ctx.completion_location {
29 Some(ImmediateLocation::MethodCall { receiver: Some(it), .. }) => (it, false),
30 Some(ImmediateLocation::FieldAccess {
32 receiver_is_ambiguous_float_literal,
33 }) => (it, *receiver_is_ambiguous_float_literal),
37 let receiver_text = get_receiver_text(dot_receiver, receiver_is_ambiguous_float_literal);
39 let receiver_ty = match ctx.sema.type_of_expr(dot_receiver) {
40 Some(it) => it.original,
44 // Suggest .await syntax for types that implement Future trait
45 if receiver_ty.impls_future(ctx.db) {
47 CompletionItem::new(CompletionItemKind::Keyword, ctx.source_range(), "await");
48 item.detail("expr.await");
52 let cap = match ctx.config.snippet_cap {
57 let postfix_snippet = match build_postfix_snippet_builder(ctx, cap, &dot_receiver) {
62 if !ctx.config.snippets.is_empty() {
63 add_custom_postfix_completions(acc, ctx, &postfix_snippet, &receiver_text);
66 let try_enum = TryEnum::from_ty(&ctx.sema, &receiver_ty.strip_references());
67 if let Some(try_enum) = &try_enum {
73 &format!("if let Ok($1) = {} {{\n $0\n}}", receiver_text),
80 &format!("while let Ok($1) = {} {{\n $0\n}}", receiver_text),
88 &format!("if let Some($1) = {} {{\n $0\n}}", receiver_text),
95 &format!("while let Some($1) = {} {{\n $0\n}}", receiver_text),
100 } else if receiver_ty.is_bool() || receiver_ty.is_unknown() {
101 postfix_snippet("if", "if expr {}", &format!("if {} {{\n $0\n}}", receiver_text))
106 &format!("while {} {{\n $0\n}}", receiver_text),
109 postfix_snippet("not", "!expr", &format!("!{}", receiver_text)).add_to(acc);
110 } else if let Some(trait_) = FamousDefs(&ctx.sema, ctx.krate).core_iter_IntoIterator() {
111 if receiver_ty.impls_trait(ctx.db, trait_, &[]) {
114 "for ele in expr {}",
115 &format!("for ele in {} {{\n $0\n}}", receiver_text),
121 postfix_snippet("ref", "&expr", &format!("&{}", receiver_text)).add_to(acc);
122 postfix_snippet("refm", "&mut expr", &format!("&mut {}", receiver_text)).add_to(acc);
124 // The rest of the postfix completions create an expression that moves an argument,
125 // so it's better to consider references now to avoid breaking the compilation
126 let dot_receiver = include_references(dot_receiver);
127 let receiver_text = get_receiver_text(&dot_receiver, receiver_is_ambiguous_float_literal);
128 let postfix_snippet = match build_postfix_snippet_builder(ctx, cap, &dot_receiver) {
134 Some(try_enum) => match try_enum {
139 &format!("match {} {{\n Ok(${{1:_}}) => {{$2}},\n Err(${{3:_}}) => {{$0}},\n}}", receiver_text),
148 "match {} {{\n Some(${{1:_}}) => {{$2}},\n None => {{$0}},\n}}",
159 &format!("match {} {{\n ${{1:_}} => {{$0}},\n}}", receiver_text),
165 postfix_snippet("box", "Box::new(expr)", &format!("Box::new({})", receiver_text)).add_to(acc);
166 postfix_snippet("dbg", "dbg!(expr)", &format!("dbg!({})", receiver_text)).add_to(acc);
167 postfix_snippet("dbgr", "dbg!(&expr)", &format!("dbg!(&{})", receiver_text)).add_to(acc);
168 postfix_snippet("call", "function(expr)", &format!("${{1}}({})", receiver_text)).add_to(acc);
170 if let Some(parent) = dot_receiver.syntax().parent().and_then(|p| p.parent()) {
171 if matches!(parent.kind(), STMT_LIST | EXPR_STMT) {
172 postfix_snippet("let", "let", &format!("let $0 = {};", receiver_text)).add_to(acc);
173 postfix_snippet("letm", "let mut", &format!("let mut $0 = {};", receiver_text))
178 if let ast::Expr::Literal(literal) = dot_receiver.clone() {
179 if let Some(literal_text) = ast::String::cast(literal.token()) {
180 add_format_like_completions(acc, ctx, &dot_receiver, cap, &literal_text);
185 fn get_receiver_text(receiver: &ast::Expr, receiver_is_ambiguous_float_literal: bool) -> String {
186 if receiver_is_ambiguous_float_literal {
187 let text = receiver.syntax().text();
188 let without_dot = ..text.len() - TextSize::of('.');
189 text.slice(without_dot).to_string()
195 fn include_references(initial_element: &ast::Expr) -> ast::Expr {
196 let mut resulting_element = initial_element.clone();
197 while let Some(parent_ref_element) =
198 resulting_element.syntax().parent().and_then(ast::RefExpr::cast)
200 resulting_element = ast::Expr::from(parent_ref_element);
205 fn build_postfix_snippet_builder<'ctx>(
206 ctx: &'ctx CompletionContext,
208 receiver: &'ctx ast::Expr,
209 ) -> Option<impl Fn(&str, &str, &str) -> Builder + 'ctx> {
210 let receiver_syntax = receiver.syntax();
211 let receiver_range = ctx.sema.original_range_opt(receiver_syntax)?.range;
212 let delete_range = TextRange::new(receiver_range.start(), ctx.source_range().end());
214 // Wrapping impl Fn in an option ruins lifetime inference for the parameters in a way that
215 // can't be annotated for the closure, hence fix it by constructing it without the Option first
217 ctx: &'ctx CompletionContext,
219 delete_range: TextRange,
220 ) -> impl Fn(&str, &str, &str) -> Builder + 'ctx {
221 move |label, detail, snippet| {
222 let edit = TextEdit::replace(delete_range, snippet.to_string());
224 CompletionItem::new(CompletionItemKind::Snippet, ctx.source_range(), label);
225 item.detail(detail).snippet_edit(cap, edit);
226 if ctx.original_token.text() == label {
228 CompletionRelevance { exact_postfix_snippet_match: true, ..Default::default() };
229 item.set_relevance(relevance);
235 Some(build(ctx, cap, delete_range))
238 fn add_custom_postfix_completions(
239 acc: &mut Completions,
240 ctx: &CompletionContext,
241 postfix_snippet: impl Fn(&str, &str, &str) -> Builder,
244 let import_scope = ImportScope::find_insert_use_container(&ctx.token.parent()?, &ctx.sema)?;
245 ctx.config.postfix_snippets().filter(|(_, snip)| snip.scope == SnippetScope::Expr).for_each(
246 |(trigger, snippet)| {
247 let imports = match snippet.imports(ctx, &import_scope) {
248 Some(imports) => imports,
251 let body = snippet.postfix_snippet(&receiver_text);
253 postfix_snippet(trigger, snippet.description.as_deref().unwrap_or_default(), &body);
254 builder.documentation(Documentation::new(format!("```rust\n{}\n```", body)));
255 for import in imports.into_iter() {
256 builder.add_import(import);
266 use expect_test::{expect, Expect};
269 tests::{check_edit, check_edit_with_config, completion_list, TEST_CONFIG},
270 CompletionConfig, Snippet,
273 fn check(ra_fixture: &str, expect: Expect) {
274 let actual = completion_list(ra_fixture);
275 expect.assert_eq(&actual)
279 fn postfix_completion_works_for_trivial_path_expression() {
289 sn while while expr {}
293 sn match match expr {}
294 sn box Box::new(expr)
300 sn call function(expr)
308 fn postfix_completion_works_for_function_calln() {
311 fn foo(elt: bool) -> bool {
322 sn while while expr {}
326 sn match match expr {}
327 sn box Box::new(expr)
333 sn call function(expr)
339 fn postfix_type_filtering() {
350 sn match match expr {}
351 sn box Box::new(expr)
357 sn call function(expr)
365 fn let_middle_block() {
375 sn while while expr {}
379 sn match match expr {}
380 sn box Box::new(expr)
386 sn call function(expr)
400 let bar = Some(true);
406 let bar = Some(true);
407 if let Some($1) = bar {
439 fn postfix_completion_works_for_ambiguous_float_literal() {
440 check_edit("refm", r#"fn main() { 42.$0 }"#, r#"fn main() { &mut 42 }"#)
444 fn works_in_simple_macro() {
448 macro_rules! m { ($e:expr) => { $e } }
455 macro_rules! m { ($e:expr) => { $e } }
465 fn postfix_completion_for_references() {
466 check_edit("dbg", r#"fn main() { &&42.$0 }"#, r#"fn main() { dbg!(&&42) }"#);
467 check_edit("refm", r#"fn main() { &&42.$0 }"#, r#"fn main() { &&&mut 42 }"#);
473 let bar = &Some(true);
479 let bar = &Some(true);
480 if let Some($1) = bar {
489 fn custom_postfix_completion() {
490 check_edit_with_config(
492 snippets: vec![Snippet::new(
495 &["ControlFlow::Break(${receiver})".into()],
497 &["core::ops::ControlFlow".into()],
498 crate::SnippetScope::Expr,
509 use core::ops::ControlFlow;
511 fn main() { ControlFlow::Break(42) }
517 fn postfix_completion_for_format_like_strings() {
520 r#"fn main() { "{some_var:?}".$0 }"#,
521 r#"fn main() { format!("{:?}", some_var) }"#,
525 r#"fn main() { "Panic with {a}".$0 }"#,
526 r#"fn main() { panic!("Panic with {}", a) }"#,
530 r#"fn main() { "{ 2+2 } { SomeStruct { val: 1, other: 32 } :?}".$0 }"#,
531 r#"fn main() { println!("{} {:?}", 2+2, SomeStruct { val: 1, other: 32 }) }"#,
535 r#"fn main() { "{2+2}".$0 }"#,
536 r#"fn main() { log::error!("{}", 2+2) }"#,
540 r#"fn main() { "{2+2}".$0 }"#,
541 r#"fn main() { log::trace!("{}", 2+2) }"#,
545 r#"fn main() { "{2+2}".$0 }"#,
546 r#"fn main() { log::debug!("{}", 2+2) }"#,
548 check_edit("logi", r#"fn main() { "{2+2}".$0 }"#, r#"fn main() { log::info!("{}", 2+2) }"#);
549 check_edit("logw", r#"fn main() { "{2+2}".$0 }"#, r#"fn main() { log::warn!("{}", 2+2) }"#);
552 r#"fn main() { "{2+2}".$0 }"#,
553 r#"fn main() { log::error!("{}", 2+2) }"#,