1 //! `completions` crate provides utilities for generating completions of user input.
7 mod generated_lint_completions;
15 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, CompletionResolveCapability},
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 <|> = expr;`
51 // - `expr.letm` -> `let mut <|> = 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 experimental completions, enabled with the `rust-analyzer.completion.disableFuzzyAutoimports` setting.
77 // This flag enables or disables:
79 // - Auto import: additional completion options with automatic `use` import and options from all project importable items, matched for the input
81 // Experimental completions might cause issues with performance and completion list look.
83 /// Main entry point for completion. We run completion as a two-phase process.
85 /// First, we look at the position and collect a so-called `CompletionContext.
86 /// This is a somewhat messy process, because, during completion, syntax tree is
87 /// incomplete and can look really weird.
89 /// Once the context is collected, we run a series of completion routines which
90 /// look at the context and produce completion items. One subtlety about this
91 /// phase is that completion engine should not filter by the substring which is
92 /// already present, it should give all possible variants for the identifier at
93 /// the caret. In other words, for
102 /// `foo` *should* be present among the completion variants. Filtering by
103 /// identifier prefix/fuzzy match should be done higher in the stack, together
104 /// with ordering of completions (currently this is done by the client).
107 config: &CompletionConfig,
108 position: FilePosition,
109 ) -> Option<Completions> {
110 let ctx = CompletionContext::new(db, position, config)?;
112 if ctx.no_completion_required() {
113 // No work required here.
117 let mut acc = Completions::default();
118 completions::attribute::complete_attribute(&mut acc, &ctx);
119 completions::fn_param::complete_fn_param(&mut acc, &ctx);
120 completions::keyword::complete_expr_keyword(&mut acc, &ctx);
121 completions::keyword::complete_use_tree_keyword(&mut acc, &ctx);
122 completions::snippet::complete_expr_snippet(&mut acc, &ctx);
123 completions::snippet::complete_item_snippet(&mut acc, &ctx);
124 completions::qualified_path::complete_qualified_path(&mut acc, &ctx);
125 completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx);
126 completions::dot::complete_dot(&mut acc, &ctx);
127 completions::record::complete_record(&mut acc, &ctx);
128 completions::pattern::complete_pattern(&mut acc, &ctx);
129 completions::postfix::complete_postfix(&mut acc, &ctx);
130 completions::macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
131 completions::trait_impl::complete_trait_impl(&mut acc, &ctx);
132 completions::mod_::complete_mod(&mut acc, &ctx);
137 /// Resolves additional completion data at the position given.
138 pub fn resolve_completion_edits(
140 config: &CompletionConfig,
141 position: FilePosition,
142 full_import_path: &str,
144 ) -> Option<Vec<TextEdit>> {
145 let ctx = CompletionContext::new(db, position, config)?;
146 let anchor = ctx.name_ref_syntax.as_ref()?;
147 let import_scope = ImportScope::find_insert_use_container(anchor.syntax(), &ctx.sema)?;
149 let current_module = ctx.sema.scope(anchor.syntax()).module()?;
150 let current_crate = current_module.krate();
152 let import_path = imports_locator::find_exact_imports(&ctx.sema, current_crate, imported_name)
153 .filter_map(|candidate| {
154 let item: hir::ItemInNs = candidate.either(Into::into, Into::into);
155 current_module.find_use_path(db, item)
157 .find(|mod_path| mod_path.to_string() == full_import_path)?;
159 ImportEdit { import_path, import_scope, merge_behaviour: config.merge }
161 .map(|edit| vec![edit])
166 use crate::config::CompletionConfig;
167 use crate::test_utils;
169 struct DetailAndDocumentation<'a> {
171 documentation: &'a str,
174 fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) {
175 let (db, position) = test_utils::position(ra_fixture);
176 let config = CompletionConfig::default();
177 let completions: Vec<_> = crate::completions(&db, &config, position).unwrap().into();
178 for item in completions {
179 if item.detail() == Some(expected.detail) {
180 let opt = item.documentation();
181 let doc = opt.as_ref().map(|it| it.as_str());
182 assert_eq!(doc, Some(expected.documentation));
186 panic!("completion detail not found: {}", expected.detail)
189 fn check_no_completion(ra_fixture: &str) {
190 let (db, position) = test_utils::position(ra_fixture);
191 let config = CompletionConfig::default();
193 let completions: Option<Vec<String>> = crate::completions(&db, &config, position)
194 .and_then(|completions| {
195 let completions: Vec<_> = completions.into();
196 if completions.is_empty() {
203 completions.into_iter().map(|completion| format!("{:?}", completion)).collect()
206 // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic.
207 assert_eq!(completions, None, "Completions were generated, but weren't expected");
211 fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() {
212 check_detail_and_documentation(
219 #[doc = "Do the foo"]
232 DetailAndDocumentation { detail: "fn foo(&self)", documentation: "Do the foo" },
237 fn test_completion_detail_from_macro_generated_struct_fn_doc_comment() {
238 check_detail_and_documentation(
258 DetailAndDocumentation { detail: "fn foo(&self)", documentation: " Do the foo" },
263 fn test_no_completions_required() {
264 // There must be no hint for 'in' keyword.
272 // After 'in' keyword hints may be spawned.
273 check_detail_and_documentation(
276 fn foo() -> &'static str { "foo" }
282 DetailAndDocumentation {
283 detail: "fn foo() -> &'static str",
284 documentation: "Do the foo",