1 //! Postfix completions, like `Ok(10).ifl$0` => `if let Ok() = Ok(10) { $0 }`.
5 use ide_db::{helpers::SnippetCap, ty_filter::TryEnum};
7 ast::{self, AstNode, AstToken},
8 SyntaxKind::{BLOCK_EXPR, EXPR_STMT},
11 use text_edit::TextEdit;
14 completions::postfix::format_like::add_format_like_completions,
15 context::CompletionContext,
16 item::{Builder, CompletionKind},
17 CompletionItem, CompletionItemKind, Completions,
20 pub(crate) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
21 if !ctx.config.enable_postfix_completions {
25 let dot_receiver = match &ctx.dot_receiver {
31 get_receiver_text(dot_receiver, ctx.dot_receiver_is_ambiguous_float_literal);
33 let receiver_ty = match ctx.sema.type_of_expr(&dot_receiver) {
39 std::iter::successors(Some(receiver_ty.clone()), |ty| ty.remove_ref()).last().unwrap();
41 let cap = match ctx.config.snippet_cap {
45 let try_enum = TryEnum::from_ty(&ctx.sema, &ref_removed_ty);
46 if let Some(try_enum) = &try_enum {
55 &format!("if let Ok($1) = {} {{\n $0\n}}", receiver_text),
65 &format!("while let Ok($1) = {} {{\n $0\n}}", receiver_text),
76 &format!("if let Some($1) = {} {{\n $0\n}}", receiver_text),
86 &format!("while let Some($1) = {} {{\n $0\n}}", receiver_text),
91 } else if receiver_ty.is_bool() || receiver_ty.is_unknown() {
98 &format!("if {} {{\n $0\n}}", receiver_text),
107 &format!("while {} {{\n $0\n}}", receiver_text),
110 postfix_snippet(ctx, cap, &dot_receiver, "not", "!expr", &format!("!{}", receiver_text))
114 postfix_snippet(ctx, cap, &dot_receiver, "ref", "&expr", &format!("&{}", receiver_text))
122 &format!("&mut {}", receiver_text),
126 // The rest of the postfix completions create an expression that moves an argument,
127 // so it's better to consider references now to avoid breaking the compilation
128 let dot_receiver = include_references(dot_receiver);
130 get_receiver_text(&dot_receiver, ctx.dot_receiver_is_ambiguous_float_literal);
133 Some(try_enum) => match try_enum {
141 &format!("match {} {{\n Ok(${{1:_}}) => {{$2}},\n Err(${{3:_}}) => {{$0}},\n}}", receiver_text),
153 "match {} {{\n Some(${{1:_}}) => {{$2}},\n None => {{$0}},\n}}",
167 &format!("match {} {{\n ${{1:_}} => {{$0}},\n}}", receiver_text),
179 &format!("Box::new({})", receiver_text),
183 postfix_snippet(ctx, cap, &dot_receiver, "ok", "Ok(expr)", &format!("Ok({})", receiver_text))
192 &format!("Err({})", receiver_text),
202 &format!("Some({})", receiver_text),
212 &format!("dbg!({})", receiver_text),
222 &format!("dbg!(&{})", receiver_text),
232 &format!("${{1}}({})", receiver_text),
236 if let Some(parent) = dot_receiver.syntax().parent().and_then(|p| p.parent()) {
237 if matches!(parent.kind(), BLOCK_EXPR | EXPR_STMT) {
244 &format!("let $0 = {};", receiver_text),
253 &format!("let mut $0 = {};", receiver_text),
259 if let ast::Expr::Literal(literal) = dot_receiver.clone() {
260 if let Some(literal_text) = ast::String::cast(literal.token()) {
261 add_format_like_completions(acc, ctx, &dot_receiver, cap, &literal_text);
266 fn get_receiver_text(receiver: &ast::Expr, receiver_is_ambiguous_float_literal: bool) -> String {
267 if receiver_is_ambiguous_float_literal {
268 let text = receiver.syntax().text();
269 let without_dot = ..text.len() - TextSize::of('.');
270 text.slice(without_dot).to_string()
276 fn include_references(initial_element: &ast::Expr) -> ast::Expr {
277 let mut resulting_element = initial_element.clone();
278 while let Some(parent_ref_element) =
279 resulting_element.syntax().parent().and_then(ast::RefExpr::cast)
281 resulting_element = ast::Expr::from(parent_ref_element);
287 ctx: &CompletionContext,
289 receiver: &ast::Expr,
295 let receiver_syntax = receiver.syntax();
296 let receiver_range = ctx.sema.original_range(receiver_syntax).range;
297 let delete_range = TextRange::new(receiver_range.start(), ctx.source_range().end());
298 TextEdit::replace(delete_range, snippet.to_string())
300 CompletionItem::new(CompletionKind::Postfix, ctx.source_range(), label)
302 .kind(CompletionItemKind::Snippet)
303 .snippet_edit(cap, edit)
308 use expect_test::{expect, Expect};
311 test_utils::{check_edit, completion_list},
315 fn check(ra_fixture: &str, expect: Expect) {
316 let actual = completion_list(ra_fixture, CompletionKind::Postfix);
317 expect.assert_eq(&actual)
321 fn postfix_completion_works_for_trivial_path_expression() {
331 sn while while expr {}
335 sn match match expr {}
336 sn box Box::new(expr)
342 sn call function(expr)
350 fn postfix_completion_works_for_function_calln() {
353 fn foo(elt: bool) -> bool {
364 sn while while expr {}
368 sn match match expr {}
369 sn box Box::new(expr)
375 sn call function(expr)
381 fn postfix_type_filtering() {
392 sn match match expr {}
393 sn box Box::new(expr)
399 sn call function(expr)
407 fn let_middle_block() {
417 sn while while expr {}
421 sn match match expr {}
422 sn box Box::new(expr)
428 sn call function(expr)
440 enum Option<T> { Some(T), None }
443 let bar = Option::Some(true);
448 enum Option<T> { Some(T), None }
451 let bar = Option::Some(true);
452 if let Some($1) = bar {
465 enum Result<T, E> { Ok(T), Err(E) }
468 let bar = Result::Ok(true);
473 enum Result<T, E> { Ok(T), Err(E) }
476 let bar = Result::Ok(true);
487 fn postfix_completion_works_for_ambiguous_float_literal() {
488 check_edit("refm", r#"fn main() { 42.$0 }"#, r#"fn main() { &mut 42 }"#)
492 fn works_in_simple_macro() {
496 macro_rules! m { ($e:expr) => { $e } }
503 macro_rules! m { ($e:expr) => { $e } }
513 fn postfix_completion_for_references() {
514 check_edit("dbg", r#"fn main() { &&42.$0 }"#, r#"fn main() { dbg!(&&42) }"#);
515 check_edit("refm", r#"fn main() { &&42.$0 }"#, r#"fn main() { &&&mut 42 }"#);
519 enum Option<T> { Some(T), None }
522 let bar = &Option::Some(true);
527 enum Option<T> { Some(T), None }
530 let bar = &Option::Some(true);
531 if let Some($1) = bar {
540 fn postfix_completion_for_format_like_strings() {
543 r#"fn main() { "{some_var:?}".$0 }"#,
544 r#"fn main() { format!("{:?}", some_var) }"#,
548 r#"fn main() { "Panic with {a}".$0 }"#,
549 r#"fn main() { panic!("Panic with {}", a) }"#,
553 r#"fn main() { "{ 2+2 } { SomeStruct { val: 1, other: 32 } :?}".$0 }"#,
554 r#"fn main() { println!("{} {:?}", 2+2, SomeStruct { val: 1, other: 32 }) }"#,
558 r#"fn main() { "{2+2}".$0 }"#,
559 r#"fn main() { log::error!("{}", 2+2) }"#,
563 r#"fn main() { "{2+2}".$0 }"#,
564 r#"fn main() { log::trace!("{}", 2+2) }"#,
568 r#"fn main() { "{2+2}".$0 }"#,
569 r#"fn main() { log::debug!("{}", 2+2) }"#,
571 check_edit("logi", r#"fn main() { "{2+2}".$0 }"#, r#"fn main() { log::info!("{}", 2+2) }"#);
572 check_edit("logw", r#"fn main() { "{2+2}".$0 }"#, r#"fn main() { log::warn!("{}", 2+2) }"#);
575 r#"fn main() { "{2+2}".$0 }"#,
576 r#"fn main() { log::error!("{}", 2+2) }"#,