1 //! Postfix completions, like `Ok(10).ifl$0` => `if let Ok() = Ok(10) { $0 }`.
5 use hir::{Documentation, HasAttrs};
6 use ide_db::{imports::insert_use::ImportScope, ty_filter::TryEnum, SnippetCap};
8 ast::{self, AstNode, AstToken},
9 SyntaxKind::{EXPR_STMT, STMT_LIST},
12 use text_edit::TextEdit;
15 completions::postfix::format_like::add_format_like_completions,
16 context::{CompletionContext, DotAccess, DotAccessKind},
17 item::{Builder, CompletionRelevancePostfixMatch},
18 CompletionItem, CompletionItemKind, CompletionRelevance, Completions, SnippetScope,
21 pub(crate) fn complete_postfix(
22 acc: &mut Completions,
23 ctx: &CompletionContext<'_>,
24 dot_access: &DotAccess,
26 if !ctx.config.enable_postfix_completions {
30 let (dot_receiver, receiver_ty, receiver_is_ambiguous_float_literal) = match dot_access {
31 DotAccess { receiver_ty: Some(ty), receiver: Some(it), kind, .. } => (
35 DotAccessKind::Field { receiver_is_ambiguous_float_literal } => {
36 receiver_is_ambiguous_float_literal
38 DotAccessKind::Method { .. } => false,
44 let receiver_text = get_receiver_text(dot_receiver, receiver_is_ambiguous_float_literal);
46 let cap = match ctx.config.snippet_cap {
51 let postfix_snippet = match build_postfix_snippet_builder(ctx, cap, dot_receiver) {
56 if let Some(drop_trait) = ctx.famous_defs().core_ops_Drop() {
57 if receiver_ty.impls_trait(ctx.db, drop_trait, &[]) {
58 if let &[hir::AssocItem::Function(drop_fn)] = &*drop_trait.items(ctx.db) {
59 cov_mark::hit!(postfix_drop_completion);
60 // FIXME: check that `drop` is in scope, use fully qualified path if it isn't/if shadowed
61 let mut item = postfix_snippet(
64 &format!("drop($0{})", receiver_text),
66 item.set_documentation(drop_fn.docs(ctx.db));
72 if !ctx.config.snippets.is_empty() {
73 add_custom_postfix_completions(acc, ctx, &postfix_snippet, &receiver_text);
76 let try_enum = TryEnum::from_ty(&ctx.sema, &receiver_ty.strip_references());
77 if let Some(try_enum) = &try_enum {
83 &format!("if let Ok($1) = {} {{\n $0\n}}", receiver_text),
90 &format!("while let Ok($1) = {} {{\n $0\n}}", receiver_text),
98 &format!("if let Some($1) = {} {{\n $0\n}}", receiver_text),
105 &format!("while let Some($1) = {} {{\n $0\n}}", receiver_text),
110 } else if receiver_ty.is_bool() || receiver_ty.is_unknown() {
111 postfix_snippet("if", "if expr {}", &format!("if {} {{\n $0\n}}", receiver_text))
116 &format!("while {} {{\n $0\n}}", receiver_text),
119 postfix_snippet("not", "!expr", &format!("!{}", receiver_text)).add_to(acc);
120 } else if let Some(trait_) = ctx.famous_defs().core_iter_IntoIterator() {
121 if receiver_ty.impls_trait(ctx.db, trait_, &[]) {
124 "for ele in expr {}",
125 &format!("for ele in {} {{\n $0\n}}", receiver_text),
131 postfix_snippet("ref", "&expr", &format!("&{}", receiver_text)).add_to(acc);
132 postfix_snippet("refm", "&mut expr", &format!("&mut {}", receiver_text)).add_to(acc);
134 // The rest of the postfix completions create an expression that moves an argument,
135 // so it's better to consider references now to avoid breaking the compilation
136 let dot_receiver = include_references(dot_receiver);
137 let receiver_text = get_receiver_text(&dot_receiver, receiver_is_ambiguous_float_literal);
138 let postfix_snippet = match build_postfix_snippet_builder(ctx, cap, &dot_receiver) {
144 Some(try_enum) => match try_enum {
149 &format!("match {} {{\n Ok(${{1:_}}) => {{$2}},\n Err(${{3:_}}) => {{$0}},\n}}", receiver_text),
158 "match {} {{\n Some(${{1:_}}) => {{$2}},\n None => {{$0}},\n}}",
169 &format!("match {} {{\n ${{1:_}} => {{$0}},\n}}", receiver_text),
175 postfix_snippet("box", "Box::new(expr)", &format!("Box::new({})", receiver_text)).add_to(acc);
176 postfix_snippet("dbg", "dbg!(expr)", &format!("dbg!({})", receiver_text)).add_to(acc); // fixme
177 postfix_snippet("dbgr", "dbg!(&expr)", &format!("dbg!(&{})", receiver_text)).add_to(acc);
178 postfix_snippet("call", "function(expr)", &format!("${{1}}({})", receiver_text)).add_to(acc);
180 if let Some(parent) = dot_receiver.syntax().parent().and_then(|p| p.parent()) {
181 if matches!(parent.kind(), STMT_LIST | EXPR_STMT) {
182 postfix_snippet("let", "let", &format!("let $0 = {};", receiver_text)).add_to(acc);
183 postfix_snippet("letm", "let mut", &format!("let mut $0 = {};", receiver_text))
188 if let ast::Expr::Literal(literal) = dot_receiver.clone() {
189 if let Some(literal_text) = ast::String::cast(literal.token()) {
190 add_format_like_completions(acc, ctx, &dot_receiver, cap, &literal_text);
195 fn get_receiver_text(receiver: &ast::Expr, receiver_is_ambiguous_float_literal: bool) -> String {
196 let text = if receiver_is_ambiguous_float_literal {
197 let text = receiver.syntax().text();
198 let without_dot = ..text.len() - TextSize::of('.');
199 text.slice(without_dot).to_string()
204 // The receiver texts should be interpreted as-is, as they are expected to be
205 // normal Rust expressions. We escape '\' and '$' so they don't get treated as
206 // snippet-specific constructs.
208 // Note that we don't need to escape the other characters that can be escaped,
209 // because they wouldn't be treated as snippet-specific constructs without '$'.
210 text.replace('\\', "\\\\").replace('$', "\\$")
213 fn include_references(initial_element: &ast::Expr) -> ast::Expr {
214 let mut resulting_element = initial_element.clone();
215 while let Some(parent_ref_element) =
216 resulting_element.syntax().parent().and_then(ast::RefExpr::cast)
218 resulting_element = ast::Expr::from(parent_ref_element);
223 fn build_postfix_snippet_builder<'ctx>(
224 ctx: &'ctx CompletionContext<'_>,
226 receiver: &'ctx ast::Expr,
227 ) -> Option<impl Fn(&str, &str, &str) -> Builder + 'ctx> {
228 let receiver_syntax = receiver.syntax();
229 let receiver_range = ctx.sema.original_range_opt(receiver_syntax)?.range;
230 if ctx.source_range().end() < receiver_range.start() {
231 // This shouldn't happen, yet it does. I assume this might be due to an incorrect token mapping.
234 let delete_range = TextRange::new(receiver_range.start(), ctx.source_range().end());
236 // Wrapping impl Fn in an option ruins lifetime inference for the parameters in a way that
237 // can't be annotated for the closure, hence fix it by constructing it without the Option first
239 ctx: &'ctx CompletionContext<'_>,
241 delete_range: TextRange,
242 ) -> impl Fn(&str, &str, &str) -> Builder + 'ctx {
243 move |label, detail, snippet| {
244 let edit = TextEdit::replace(delete_range, snippet.to_string());
246 CompletionItem::new(CompletionItemKind::Snippet, ctx.source_range(), label);
247 item.detail(detail).snippet_edit(cap, edit);
248 let postfix_match = if ctx.original_token.text() == label {
249 cov_mark::hit!(postfix_exact_match_is_high_priority);
250 Some(CompletionRelevancePostfixMatch::Exact)
252 cov_mark::hit!(postfix_inexact_match_is_low_priority);
253 Some(CompletionRelevancePostfixMatch::NonExact)
255 let relevance = CompletionRelevance { postfix_match, ..Default::default() };
256 item.set_relevance(relevance);
260 Some(build(ctx, cap, delete_range))
263 fn add_custom_postfix_completions(
264 acc: &mut Completions,
265 ctx: &CompletionContext<'_>,
266 postfix_snippet: impl Fn(&str, &str, &str) -> Builder,
269 if ImportScope::find_insert_use_container(&ctx.token.parent()?, &ctx.sema).is_none() {
272 ctx.config.postfix_snippets().filter(|(_, snip)| snip.scope == SnippetScope::Expr).for_each(
273 |(trigger, snippet)| {
274 let imports = match snippet.imports(ctx) {
275 Some(imports) => imports,
278 let body = snippet.postfix_snippet(receiver_text);
280 postfix_snippet(trigger, snippet.description.as_deref().unwrap_or_default(), &body);
281 builder.documentation(Documentation::new(format!("```rust\n{}\n```", body)));
282 for import in imports.into_iter() {
283 builder.add_import(import);
293 use expect_test::{expect, Expect};
296 tests::{check_edit, check_edit_with_config, completion_list, TEST_CONFIG},
297 CompletionConfig, Snippet,
300 fn check(ra_fixture: &str, expect: Expect) {
301 let actual = completion_list(ra_fixture);
302 expect.assert_eq(&actual)
306 fn postfix_completion_works_for_trivial_path_expression() {
315 sn box Box::new(expr)
316 sn call function(expr)
322 sn match match expr {}
326 sn while while expr {}
332 fn postfix_completion_works_for_function_calln() {
335 fn foo(elt: bool) -> bool {
345 sn box Box::new(expr)
346 sn call function(expr)
350 sn match match expr {}
354 sn while while expr {}
360 fn postfix_type_filtering() {
369 sn box Box::new(expr)
370 sn call function(expr)
375 sn match match expr {}
383 fn let_middle_block() {
392 sn box Box::new(expr)
393 sn call function(expr)
399 sn match match expr {}
403 sn while while expr {}
415 let bar = Some(true);
421 let bar = Some(true);
422 if let Some($1) = bar {
454 fn postfix_completion_works_for_ambiguous_float_literal() {
455 check_edit("refm", r#"fn main() { 42.$0 }"#, r#"fn main() { &mut 42 }"#)
459 fn works_in_simple_macro() {
463 macro_rules! m { ($e:expr) => { $e } }
470 macro_rules! m { ($e:expr) => { $e } }
480 fn postfix_completion_for_references() {
481 check_edit("dbg", r#"fn main() { &&42.$0 }"#, r#"fn main() { dbg!(&&42) }"#);
482 check_edit("refm", r#"fn main() { &&42.$0 }"#, r#"fn main() { &&&mut 42 }"#);
488 let bar = &Some(true);
494 let bar = &Some(true);
495 if let Some($1) = bar {
504 fn custom_postfix_completion() {
505 let config = CompletionConfig {
506 snippets: vec![Snippet::new(
509 &["ControlFlow::Break(${receiver})".into()],
511 &["core::ops::ControlFlow".into()],
512 crate::SnippetScope::Expr,
518 check_edit_with_config(
526 use core::ops::ControlFlow;
528 fn main() { ControlFlow::Break(42) }
532 // The receiver texts should be escaped, see comments in `get_receiver_text()`
535 // Note that the last argument is what *lsp clients would see* rather than
536 // what users would see. Unescaping happens thereafter.
537 check_edit_with_config(
542 fn main() { '\\'.$0 }
545 use core::ops::ControlFlow;
547 fn main() { ControlFlow::Break('\\\\') }
551 check_edit_with_config(
558 true => "${1:placeholder}",
564 use core::ops::ControlFlow;
567 ControlFlow::Break(match true {
568 true => "\${1:placeholder}",
577 fn postfix_completion_for_format_like_strings() {
580 r#"fn main() { "{some_var:?}".$0 }"#,
581 r#"fn main() { format!("{:?}", some_var) }"#,
585 r#"fn main() { "Panic with {a}".$0 }"#,
586 r#"fn main() { panic!("Panic with {}", a) }"#,
590 r#"fn main() { "{ 2+2 } { SomeStruct { val: 1, other: 32 } :?}".$0 }"#,
591 r#"fn main() { println!("{} {:?}", 2+2, SomeStruct { val: 1, other: 32 }) }"#,
595 r#"fn main() { "{2+2}".$0 }"#,
596 r#"fn main() { log::error!("{}", 2+2) }"#,
600 r#"fn main() { "{2+2}".$0 }"#,
601 r#"fn main() { log::trace!("{}", 2+2) }"#,
605 r#"fn main() { "{2+2}".$0 }"#,
606 r#"fn main() { log::debug!("{}", 2+2) }"#,
608 check_edit("logi", r#"fn main() { "{2+2}".$0 }"#, r#"fn main() { log::info!("{}", 2+2) }"#);
609 check_edit("logw", r#"fn main() { "{2+2}".$0 }"#, r#"fn main() { log::warn!("{}", 2+2) }"#);
612 r#"fn main() { "{2+2}".$0 }"#,
613 r#"fn main() { log::error!("{}", 2+2) }"#,