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)
309 use expect_test::{expect, Expect};
312 test_utils::{check_edit, completion_list},
316 fn check(ra_fixture: &str, expect: Expect) {
317 let actual = completion_list(ra_fixture, CompletionKind::Postfix);
318 expect.assert_eq(&actual)
322 fn postfix_completion_works_for_trivial_path_expression() {
332 sn while while expr {}
336 sn match match expr {}
337 sn box Box::new(expr)
343 sn call function(expr)
351 fn postfix_completion_works_for_function_calln() {
354 fn foo(elt: bool) -> bool {
365 sn while while expr {}
369 sn match match expr {}
370 sn box Box::new(expr)
376 sn call function(expr)
382 fn postfix_type_filtering() {
393 sn match match expr {}
394 sn box Box::new(expr)
400 sn call function(expr)
408 fn let_middle_block() {
418 sn while while expr {}
422 sn match match expr {}
423 sn box Box::new(expr)
429 sn call function(expr)
441 enum Option<T> { Some(T), None }
444 let bar = Option::Some(true);
449 enum Option<T> { Some(T), None }
452 let bar = Option::Some(true);
453 if let Some($1) = bar {
466 enum Result<T, E> { Ok(T), Err(E) }
469 let bar = Result::Ok(true);
474 enum Result<T, E> { Ok(T), Err(E) }
477 let bar = Result::Ok(true);
488 fn postfix_completion_works_for_ambiguous_float_literal() {
489 check_edit("refm", r#"fn main() { 42.$0 }"#, r#"fn main() { &mut 42 }"#)
493 fn works_in_simple_macro() {
497 macro_rules! m { ($e:expr) => { $e } }
504 macro_rules! m { ($e:expr) => { $e } }
514 fn postfix_completion_for_references() {
515 check_edit("dbg", r#"fn main() { &&42.$0 }"#, r#"fn main() { dbg!(&&42) }"#);
516 check_edit("refm", r#"fn main() { &&42.$0 }"#, r#"fn main() { &&&mut 42 }"#);
520 enum Option<T> { Some(T), None }
523 let bar = &Option::Some(true);
528 enum Option<T> { Some(T), None }
531 let bar = &Option::Some(true);
532 if let Some($1) = bar {
541 fn postfix_completion_for_format_like_strings() {
544 r#"fn main() { "{some_var:?}".$0 }"#,
545 r#"fn main() { format!("{:?}", some_var) }"#,
549 r#"fn main() { "Panic with {a}".$0 }"#,
550 r#"fn main() { panic!("Panic with {}", a) }"#,
554 r#"fn main() { "{ 2+2 } { SomeStruct { val: 1, other: 32 } :?}".$0 }"#,
555 r#"fn main() { println!("{} {:?}", 2+2, SomeStruct { val: 1, other: 32 }) }"#,
559 r#"fn main() { "{2+2}".$0 }"#,
560 r#"fn main() { log::error!("{}", 2+2) }"#,
564 r#"fn main() { "{2+2}".$0 }"#,
565 r#"fn main() { log::trace!("{}", 2+2) }"#,
569 r#"fn main() { "{2+2}".$0 }"#,
570 r#"fn main() { log::debug!("{}", 2+2) }"#,
572 check_edit("logi", r#"fn main() { "{2+2}".$0 }"#, r#"fn main() { log::info!("{}", 2+2) }"#);
573 check_edit("logw", r#"fn main() { "{2+2}".$0 }"#, r#"fn main() { log::warn!("{}", 2+2) }"#);
576 r#"fn main() { "{2+2}".$0 }"#,
577 r#"fn main() { log::error!("{}", 2+2) }"#,