1 //! `completions` crate provides utilities for generating completions of user input.
7 mod generated_lint_completions;
14 use completions::flyimport::position_for_import;
16 base_db::FilePosition, helpers::insert_use::ImportScope, imports_locator, RootDatabase,
18 use text_edit::TextEdit;
20 use crate::{completions::Completions, context::CompletionContext, item::CompletionKind};
23 config::CompletionConfig,
24 item::{CompletionItem, CompletionItemKind, CompletionScore, ImportEdit, InsertTextFormat},
27 //FIXME: split the following feature into fine-grained features.
29 // Feature: Magic Completions
31 // In addition to usual reference completion, rust-analyzer provides some ✨magic✨
32 // completions as well:
34 // Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
35 // is placed at the appropriate position. Even though `if` is easy to type, you
36 // still want to complete it, to get ` { }` for free! `return` is inserted with a
37 // space or `;` depending on the return type of the function.
39 // When completing a function call, `()` are automatically inserted. If a function
40 // takes arguments, the cursor is positioned inside the parenthesis.
42 // There are postfix completions, which can be triggered by typing something like
43 // `foo().if`. The word after `.` determines postfix completion. Possible variants are:
45 // - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
46 // - `expr.match` -> `match expr {}`
47 // - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
48 // - `expr.ref` -> `&expr`
49 // - `expr.refm` -> `&mut expr`
50 // - `expr.let` -> `let $0 = expr;`
51 // - `expr.letm` -> `let mut $0 = expr;`
52 // - `expr.not` -> `!expr`
53 // - `expr.dbg` -> `dbg!(expr)`
54 // - `expr.dbgr` -> `dbg!(&expr)`
55 // - `expr.call` -> `(expr)`
57 // There also snippet completions:
60 // - `pd` -> `eprintln!(" = {:?}", );`
61 // - `ppd` -> `eprintln!(" = {:#?}", );`
64 // - `tfn` -> `#[test] fn feature(){}`
76 // And the auto import completions, enabled with the `rust-analyzer.completion.autoimport.enable` setting and the corresponding LSP client capabilities.
77 // Those are the additional completion options with automatic `use` import and options from all project importable items,
78 // fuzzy matched agains the completion imput.
80 /// Main entry point for completion. We run completion as a two-phase process.
82 /// First, we look at the position and collect a so-called `CompletionContext.
83 /// This is a somewhat messy process, because, during completion, syntax tree is
84 /// incomplete and can look really weird.
86 /// Once the context is collected, we run a series of completion routines which
87 /// look at the context and produce completion items. One subtlety about this
88 /// phase is that completion engine should not filter by the substring which is
89 /// already present, it should give all possible variants for the identifier at
90 /// the caret. In other words, for
99 /// `foo` *should* be present among the completion variants. Filtering by
100 /// identifier prefix/fuzzy match should be done higher in the stack, together
101 /// with ordering of completions (currently this is done by the client).
104 config: &CompletionConfig,
105 position: FilePosition,
106 ) -> Option<Completions> {
107 let ctx = CompletionContext::new(db, position, config)?;
109 if ctx.no_completion_required() {
110 // No work required here.
114 let mut acc = Completions::default();
115 completions::attribute::complete_attribute(&mut acc, &ctx);
116 completions::fn_param::complete_fn_param(&mut acc, &ctx);
117 completions::keyword::complete_expr_keyword(&mut acc, &ctx);
118 completions::keyword::complete_use_tree_keyword(&mut acc, &ctx);
119 completions::snippet::complete_expr_snippet(&mut acc, &ctx);
120 completions::snippet::complete_item_snippet(&mut acc, &ctx);
121 completions::qualified_path::complete_qualified_path(&mut acc, &ctx);
122 completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx);
123 completions::dot::complete_dot(&mut acc, &ctx);
124 completions::record::complete_record(&mut acc, &ctx);
125 completions::pattern::complete_pattern(&mut acc, &ctx);
126 completions::postfix::complete_postfix(&mut acc, &ctx);
127 completions::macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
128 completions::trait_impl::complete_trait_impl(&mut acc, &ctx);
129 completions::mod_::complete_mod(&mut acc, &ctx);
130 completions::flyimport::import_on_the_fly(&mut acc, &ctx);
135 /// Resolves additional completion data at the position given.
136 pub fn resolve_completion_edits(
138 config: &CompletionConfig,
139 position: FilePosition,
140 full_import_path: &str,
141 imported_name: String,
142 import_for_trait_assoc_item: bool,
143 ) -> Option<Vec<TextEdit>> {
144 let ctx = CompletionContext::new(db, position, config)?;
145 let position_for_import = position_for_import(&ctx, None)?;
146 let import_scope = ImportScope::find_insert_use_container(position_for_import, &ctx.sema)?;
148 let current_module = ctx.sema.scope(position_for_import).module()?;
149 let current_crate = current_module.krate();
151 let import_path = imports_locator::find_exact_imports(&ctx.sema, current_crate, imported_name)
152 .filter_map(|candidate| {
153 let item: hir::ItemInNs = candidate.either(Into::into, Into::into);
154 current_module.find_use_path(db, item)
156 .find(|mod_path| mod_path.to_string() == full_import_path)?;
158 ImportEdit { import_path, import_scope, import_for_trait_assoc_item }
159 .to_text_edit(config.insert_use.merge)
160 .map(|edit| vec![edit])
165 use crate::test_utils::{self, TEST_CONFIG};
167 struct DetailAndDocumentation<'a> {
169 documentation: &'a str,
172 fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) {
173 let (db, position) = test_utils::position(ra_fixture);
174 let config = TEST_CONFIG;
175 let completions: Vec<_> = crate::completions(&db, &config, position).unwrap().into();
176 for item in completions {
177 if item.detail() == Some(expected.detail) {
178 let opt = item.documentation();
179 let doc = opt.as_ref().map(|it| it.as_str());
180 assert_eq!(doc, Some(expected.documentation));
184 panic!("completion detail not found: {}", expected.detail)
187 fn check_no_completion(ra_fixture: &str) {
188 let (db, position) = test_utils::position(ra_fixture);
189 let config = TEST_CONFIG;
191 let completions: Option<Vec<String>> = crate::completions(&db, &config, position)
192 .and_then(|completions| {
193 let completions: Vec<_> = completions.into();
194 if completions.is_empty() {
201 completions.into_iter().map(|completion| format!("{:?}", completion)).collect()
204 // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic.
205 assert_eq!(completions, None, "Completions were generated, but weren't expected");
209 fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() {
210 check_detail_and_documentation(
217 #[doc = "Do the foo"]
230 DetailAndDocumentation { detail: "-> ()", documentation: "Do the foo" },
235 fn test_completion_detail_from_macro_generated_struct_fn_doc_comment() {
236 check_detail_and_documentation(
256 DetailAndDocumentation { detail: "-> ()", documentation: " Do the foo" },
261 fn test_no_completions_required() {
262 // There must be no hint for 'in' keyword.
270 // After 'in' keyword hints may be spawned.
271 check_detail_and_documentation(
274 fn foo() -> &'static str { "foo" }
280 DetailAndDocumentation { detail: "-> &str", documentation: "Do the foo" },