1 //! `completions` crate provides utilities for generating completions of user input.
5 mod completion_context;
8 mod generated_lint_completions;
12 mod complete_attribute;
16 mod complete_fn_param;
19 mod complete_qualified_path;
20 mod complete_unqualified_path;
22 mod complete_macro_in_item_position;
23 mod complete_trait_impl;
26 use ide_db::base_db::FilePosition;
27 use ide_db::RootDatabase;
30 completion_context::CompletionContext,
31 completion_item::{CompletionKind, Completions},
35 completion_config::CompletionConfig,
36 completion_item::{CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat},
39 //FIXME: split the following feature into fine-grained features.
41 // Feature: Magic Completions
43 // In addition to usual reference completion, rust-analyzer provides some ✨magic✨
44 // completions as well:
46 // Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
47 // is placed at the appropriate position. Even though `if` is easy to type, you
48 // still want to complete it, to get ` { }` for free! `return` is inserted with a
49 // space or `;` depending on the return type of the function.
51 // When completing a function call, `()` are automatically inserted. If a function
52 // takes arguments, the cursor is positioned inside the parenthesis.
54 // There are postfix completions, which can be triggered by typing something like
55 // `foo().if`. The word after `.` determines postfix completion. Possible variants are:
57 // - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
58 // - `expr.match` -> `match expr {}`
59 // - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
60 // - `expr.ref` -> `&expr`
61 // - `expr.refm` -> `&mut expr`
62 // - `expr.not` -> `!expr`
63 // - `expr.dbg` -> `dbg!(expr)`
64 // - `expr.dbgr` -> `dbg!(&expr)`
65 // - `expr.call` -> `(expr)`
67 // There also snippet completions:
70 // - `pd` -> `eprintln!(" = {:?}", );`
71 // - `ppd` -> `eprintln!(" = {:#?}", );`
74 // - `tfn` -> `#[test] fn feature(){}`
86 /// Main entry point for completion. We run completion as a two-phase process.
88 /// First, we look at the position and collect a so-called `CompletionContext.
89 /// This is a somewhat messy process, because, during completion, syntax tree is
90 /// incomplete and can look really weird.
92 /// Once the context is collected, we run a series of completion routines which
93 /// look at the context and produce completion items. One subtlety about this
94 /// phase is that completion engine should not filter by the substring which is
95 /// already present, it should give all possible variants for the identifier at
96 /// the caret. In other words, for
105 /// `foo` *should* be present among the completion variants. Filtering by
106 /// identifier prefix/fuzzy match should be done higher in the stack, together
107 /// with ordering of completions (currently this is done by the client).
110 config: &CompletionConfig,
111 position: FilePosition,
112 ) -> Option<Completions> {
113 let ctx = CompletionContext::new(db, position, config)?;
115 if ctx.no_completion_required() {
116 // No work required here.
120 let mut acc = Completions::default();
121 complete_attribute::complete_attribute(&mut acc, &ctx);
122 complete_fn_param::complete_fn_param(&mut acc, &ctx);
123 complete_keyword::complete_expr_keyword(&mut acc, &ctx);
124 complete_keyword::complete_use_tree_keyword(&mut acc, &ctx);
125 complete_snippet::complete_expr_snippet(&mut acc, &ctx);
126 complete_snippet::complete_item_snippet(&mut acc, &ctx);
127 complete_qualified_path::complete_qualified_path(&mut acc, &ctx);
128 complete_unqualified_path::complete_unqualified_path(&mut acc, &ctx);
129 complete_dot::complete_dot(&mut acc, &ctx);
130 complete_record::complete_record(&mut acc, &ctx);
131 complete_pattern::complete_pattern(&mut acc, &ctx);
132 complete_postfix::complete_postfix(&mut acc, &ctx);
133 complete_macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
134 complete_trait_impl::complete_trait_impl(&mut acc, &ctx);
135 complete_mod::complete_mod(&mut acc, &ctx);
142 use crate::completion_config::CompletionConfig;
143 use crate::test_utils;
145 struct DetailAndDocumentation<'a> {
147 documentation: &'a str,
150 fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) {
151 let (db, position) = test_utils::position(ra_fixture);
152 let config = CompletionConfig::default();
153 let completions: Vec<_> = crate::completions(&db, &config, position).unwrap().into();
154 for item in completions {
155 if item.detail() == Some(expected.detail) {
156 let opt = item.documentation();
157 let doc = opt.as_ref().map(|it| it.as_str());
158 assert_eq!(doc, Some(expected.documentation));
162 panic!("completion detail not found: {}", expected.detail)
165 fn check_no_completion(ra_fixture: &str) {
166 let (db, position) = test_utils::position(ra_fixture);
167 let config = CompletionConfig::default();
169 let completions: Option<Vec<String>> = crate::completions(&db, &config, position)
170 .and_then(|completions| {
171 let completions: Vec<_> = completions.into();
172 if completions.is_empty() {
179 completions.into_iter().map(|completion| format!("{:?}", completion)).collect()
182 // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic.
183 assert_eq!(completions, None, "Completions were generated, but weren't expected");
187 fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() {
188 check_detail_and_documentation(
195 #[doc = "Do the foo"]
208 DetailAndDocumentation { detail: "fn foo(&self)", documentation: "Do the foo" },
213 fn test_completion_detail_from_macro_generated_struct_fn_doc_comment() {
214 check_detail_and_documentation(
234 DetailAndDocumentation { detail: "fn foo(&self)", documentation: " Do the foo" },
239 fn test_no_completions_required() {
240 // There must be no hint for 'in' keyword.
248 // After 'in' keyword hints may be spawned.
249 check_detail_and_documentation(
252 fn foo() -> &'static str { "foo" }
258 DetailAndDocumentation {
259 detail: "fn foo() -> &'static str",
260 documentation: "Do the foo",