1 //! `completions` crate provides utilities for generating completions of user input.
7 mod generated_lint_completions;
14 use ide_db::base_db::FilePosition;
15 use ide_db::RootDatabase;
17 use crate::{completions::Completions, context::CompletionContext, item::CompletionKind};
20 config::CompletionConfig,
21 item::{CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat},
24 //FIXME: split the following feature into fine-grained features.
26 // Feature: Magic Completions
28 // In addition to usual reference completion, rust-analyzer provides some ✨magic✨
29 // completions as well:
31 // Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
32 // is placed at the appropriate position. Even though `if` is easy to type, you
33 // still want to complete it, to get ` { }` for free! `return` is inserted with a
34 // space or `;` depending on the return type of the function.
36 // When completing a function call, `()` are automatically inserted. If a function
37 // takes arguments, the cursor is positioned inside the parenthesis.
39 // There are postfix completions, which can be triggered by typing something like
40 // `foo().if`. The word after `.` determines postfix completion. Possible variants are:
42 // - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
43 // - `expr.match` -> `match expr {}`
44 // - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
45 // - `expr.ref` -> `&expr`
46 // - `expr.refm` -> `&mut expr`
47 // - `expr.let` -> `let <|> = expr;`
48 // - `expr.letm` -> `let mut <|> = expr;`
49 // - `expr.not` -> `!expr`
50 // - `expr.dbg` -> `dbg!(expr)`
51 // - `expr.dbgr` -> `dbg!(&expr)`
52 // - `expr.call` -> `(expr)`
54 // There also snippet completions:
57 // - `pd` -> `eprintln!(" = {:?}", );`
58 // - `ppd` -> `eprintln!(" = {:#?}", );`
61 // - `tfn` -> `#[test] fn feature(){}`
73 /// Main entry point for completion. We run completion as a two-phase process.
75 /// First, we look at the position and collect a so-called `CompletionContext.
76 /// This is a somewhat messy process, because, during completion, syntax tree is
77 /// incomplete and can look really weird.
79 /// Once the context is collected, we run a series of completion routines which
80 /// look at the context and produce completion items. One subtlety about this
81 /// phase is that completion engine should not filter by the substring which is
82 /// already present, it should give all possible variants for the identifier at
83 /// the caret. In other words, for
92 /// `foo` *should* be present among the completion variants. Filtering by
93 /// identifier prefix/fuzzy match should be done higher in the stack, together
94 /// with ordering of completions (currently this is done by the client).
97 config: &CompletionConfig,
98 position: FilePosition,
99 ) -> Option<Completions> {
100 let ctx = CompletionContext::new(db, position, config)?;
102 if ctx.no_completion_required() {
103 // No work required here.
107 let mut acc = Completions::default();
108 completions::attribute::complete_attribute(&mut acc, &ctx);
109 completions::fn_param::complete_fn_param(&mut acc, &ctx);
110 completions::keyword::complete_expr_keyword(&mut acc, &ctx);
111 completions::keyword::complete_use_tree_keyword(&mut acc, &ctx);
112 completions::snippet::complete_expr_snippet(&mut acc, &ctx);
113 completions::snippet::complete_item_snippet(&mut acc, &ctx);
114 completions::qualified_path::complete_qualified_path(&mut acc, &ctx);
115 completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx);
116 completions::dot::complete_dot(&mut acc, &ctx);
117 completions::record::complete_record(&mut acc, &ctx);
118 completions::pattern::complete_pattern(&mut acc, &ctx);
119 completions::postfix::complete_postfix(&mut acc, &ctx);
120 completions::macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
121 completions::trait_impl::complete_trait_impl(&mut acc, &ctx);
122 completions::mod_::complete_mod(&mut acc, &ctx);
129 use crate::config::CompletionConfig;
130 use crate::test_utils;
132 struct DetailAndDocumentation<'a> {
134 documentation: &'a str,
137 fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) {
138 let (db, position) = test_utils::position(ra_fixture);
139 let config = CompletionConfig::default();
140 let completions: Vec<_> = crate::completions(&db, &config, position).unwrap().into();
141 for item in completions {
142 if item.detail() == Some(expected.detail) {
143 let opt = item.documentation();
144 let doc = opt.as_ref().map(|it| it.as_str());
145 assert_eq!(doc, Some(expected.documentation));
149 panic!("completion detail not found: {}", expected.detail)
152 fn check_no_completion(ra_fixture: &str) {
153 let (db, position) = test_utils::position(ra_fixture);
154 let config = CompletionConfig::default();
156 let completions: Option<Vec<String>> = crate::completions(&db, &config, position)
157 .and_then(|completions| {
158 let completions: Vec<_> = completions.into();
159 if completions.is_empty() {
166 completions.into_iter().map(|completion| format!("{:?}", completion)).collect()
169 // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic.
170 assert_eq!(completions, None, "Completions were generated, but weren't expected");
174 fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() {
175 check_detail_and_documentation(
182 #[doc = "Do the foo"]
195 DetailAndDocumentation { detail: "fn foo(&self)", documentation: "Do the foo" },
200 fn test_completion_detail_from_macro_generated_struct_fn_doc_comment() {
201 check_detail_and_documentation(
221 DetailAndDocumentation { detail: "fn foo(&self)", documentation: " Do the foo" },
226 fn test_no_completions_required() {
227 // There must be no hint for 'in' keyword.
235 // After 'in' keyword hints may be spawned.
236 check_detail_and_documentation(
239 fn foo() -> &'static str { "foo" }
245 DetailAndDocumentation {
246 detail: "fn foo() -> &'static str",
247 documentation: "Do the foo",