1 //! See `CompletionItem` structure.
5 use hir::{Documentation, Mutability};
8 import_assets::LocatedImport,
9 insert_use::{self, ImportScope, InsertUseConfig},
10 mod_path_to_ast, SnippetCap,
14 use smallvec::SmallVec;
15 use stdx::{impl_from, never};
16 use syntax::{algo, SmolStr, TextRange};
17 use text_edit::TextEdit;
19 /// `CompletionItem` describes a single completion variant in the editor pop-up.
20 /// It is basically a POD with various properties. To construct a
21 /// `CompletionItem`, use `new` method and the `Builder` struct.
23 pub struct CompletionItem {
24 /// Label in the completion pop up which identifies completion.
26 /// Range of identifier that is being completed.
28 /// It should be used primarily for UI, but we also use this to convert
29 /// generic TextEdit into LSP's completion edit (see conv.rs).
31 /// `source_range` must contain the completion offset. `insert_text` should
32 /// start with what `source_range` points to, or VSCode will filter out the
33 /// completion silently.
34 source_range: TextRange,
35 /// What happens when user selects this item.
37 /// Typically, replaces `source_range` with new identifier.
41 /// What item (struct, function, etc) are we completing.
42 kind: CompletionItemKind,
44 /// Lookup is used to check if completion item indeed can complete current
47 /// That is, in `foo.bar$0` lookup of `abracadabra` will be accepted (it
48 /// contains `bar` sub sequence), and `quux` will rejected.
49 lookup: Option<SmolStr>,
51 /// Additional info to show in the UI pop up.
52 detail: Option<String>,
53 documentation: Option<Documentation>,
55 /// Whether this item is marked as deprecated
58 /// If completing a function call, ask the editor to show parameter popup
60 trigger_call_info: bool,
62 /// We use this to sort completion. Relevance records facts like "do the
63 /// types align precisely?". We can't sort by relevances directly, they are
64 /// only partially ordered.
66 /// Note that Relevance ignores fuzzy match score. We compute Relevance for
67 /// all possible items, and then separately build an ordered completion list
68 /// based on relevance and fuzzy matching with the already typed identifier.
69 relevance: CompletionRelevance,
71 /// Indicates that a reference or mutable reference to this variable is a
73 ref_match: Option<Mutability>,
75 /// The import data to add to completion's edits.
76 import_to_add: SmallVec<[ImportEdit; 1]>,
79 // We use custom debug for CompletionItem to make snapshot tests more readable.
80 impl fmt::Debug for CompletionItem {
81 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
82 let mut s = f.debug_struct("CompletionItem");
83 s.field("label", &self.label()).field("source_range", &self.source_range());
84 if self.text_edit().len() == 1 {
85 let atom = &self.text_edit().iter().next().unwrap();
86 s.field("delete", &atom.delete);
87 s.field("insert", &atom.insert);
89 s.field("text_edit", &self.text_edit);
91 s.field("kind", &self.kind());
92 if self.lookup() != self.label() {
93 s.field("lookup", &self.lookup());
95 if let Some(detail) = self.detail() {
96 s.field("detail", &detail);
98 if let Some(documentation) = self.documentation() {
99 s.field("documentation", &documentation);
102 s.field("deprecated", &true);
105 if self.relevance != CompletionRelevance::default() {
106 s.field("relevance", &self.relevance);
109 if let Some(mutability) = &self.ref_match {
110 s.field("ref_match", &format!("&{}", mutability.as_keyword_for_ref()));
112 if self.trigger_call_info {
113 s.field("trigger_call_info", &true);
119 #[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
120 pub struct CompletionRelevance {
121 /// This is set in cases like these:
124 /// fn f(spam: String) {}
127 /// f($0) // name of local matches the name of param
130 pub exact_name_match: bool,
131 /// See CompletionRelevanceTypeMatch doc comments for cases where this is set.
132 pub type_match: Option<CompletionRelevanceTypeMatch>,
133 /// This is set in cases like these:
138 /// $0 // `a` and `b` are local
142 /// This is set in cases like these:
148 /// Basically, we want to guarantee that postfix snippets always takes
149 /// precedence over everything else.
150 pub exact_postfix_snippet_match: bool,
153 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
154 pub enum CompletionRelevanceTypeMatch {
155 /// This is set in cases like these:
158 /// enum Option<T> { Some(T), None }
159 /// fn f(a: Option<u32>) {}
161 /// f(Option::N$0) // type `Option<T>` could unify with `Option<u32>`
165 /// This is set in cases like these:
168 /// fn f(spam: String) {}
170 /// let foo = String::new();
171 /// f($0) // type of local matches the type of param
177 impl CompletionRelevance {
178 /// Provides a relevance score. Higher values are more relevant.
180 /// The absolute value of the relevance score is not meaningful, for
181 /// example a value of 0 doesn't mean "not relevant", rather
182 /// it means "least relevant". The score value should only be used
183 /// for relative ordering.
185 /// See is_relevant if you need to make some judgement about score
186 /// in an absolute sense.
187 pub fn score(&self) -> u32 {
190 if self.exact_name_match {
193 score += match self.type_match {
194 Some(CompletionRelevanceTypeMatch::Exact) => 4,
195 Some(CompletionRelevanceTypeMatch::CouldUnify) => 3,
201 if self.exact_postfix_snippet_match {
207 /// Returns true when the score for this threshold is above
208 /// some threshold such that we think it is especially likely
210 pub fn is_relevant(&self) -> bool {
215 /// The type of the completion item.
216 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
217 pub enum CompletionItemKind {
218 SymbolKind(SymbolKind),
228 impl_from!(SymbolKind for CompletionItemKind);
230 impl CompletionItemKind {
232 pub(crate) fn tag(&self) -> &'static str {
234 CompletionItemKind::SymbolKind(kind) => match kind {
235 SymbolKind::Const => "ct",
236 SymbolKind::ConstParam => "cp",
237 SymbolKind::Enum => "en",
238 SymbolKind::Field => "fd",
239 SymbolKind::Function => "fn",
240 SymbolKind::Impl => "im",
241 SymbolKind::Label => "lb",
242 SymbolKind::LifetimeParam => "lt",
243 SymbolKind::Local => "lc",
244 SymbolKind::Macro => "ma",
245 SymbolKind::Module => "md",
246 SymbolKind::SelfParam => "sp",
247 SymbolKind::Static => "sc",
248 SymbolKind::Struct => "st",
249 SymbolKind::Trait => "tt",
250 SymbolKind::TypeAlias => "ta",
251 SymbolKind::TypeParam => "tp",
252 SymbolKind::Union => "un",
253 SymbolKind::ValueParam => "vp",
254 SymbolKind::Variant => "ev",
256 CompletionItemKind::Attribute => "at",
257 CompletionItemKind::Binding => "bn",
258 CompletionItemKind::BuiltinType => "bt",
259 CompletionItemKind::Keyword => "kw",
260 CompletionItemKind::Method => "me",
261 CompletionItemKind::Snippet => "sn",
262 CompletionItemKind::UnresolvedReference => "??",
267 impl CompletionItem {
269 kind: impl Into<CompletionItemKind>,
270 source_range: TextRange,
271 label: impl Into<SmolStr>,
273 let label = label.into();
286 trigger_call_info: None,
287 relevance: CompletionRelevance::default(),
289 imports_to_add: Default::default(),
293 /// What user sees in pop-up in the UI.
294 pub fn label(&self) -> &str {
297 pub fn source_range(&self) -> TextRange {
301 pub fn text_edit(&self) -> &TextEdit {
304 /// Whether `text_edit` is a snippet (contains `$0` markers).
305 pub fn is_snippet(&self) -> bool {
309 /// Short one-line additional information, like a type
310 pub fn detail(&self) -> Option<&str> {
311 self.detail.as_deref()
314 pub fn documentation(&self) -> Option<Documentation> {
315 self.documentation.clone()
317 /// What string is used for filtering.
318 pub fn lookup(&self) -> &str {
319 self.lookup.as_deref().unwrap_or(&self.label)
322 pub fn kind(&self) -> CompletionItemKind {
326 pub fn deprecated(&self) -> bool {
330 pub fn relevance(&self) -> CompletionRelevance {
334 pub fn trigger_call_info(&self) -> bool {
335 self.trigger_call_info
338 pub fn ref_match(&self) -> Option<(Mutability, CompletionRelevance)> {
339 // Relevance of the ref match should be the same as the original
340 // match, but with exact type match set because self.ref_match
341 // is only set if there is an exact type match.
342 let mut relevance = self.relevance;
343 relevance.type_match = Some(CompletionRelevanceTypeMatch::Exact);
345 self.ref_match.map(|mutability| (mutability, relevance))
348 pub fn imports_to_add(&self) -> &[ImportEdit] {
353 /// An extra import to add after the completion is applied.
354 #[derive(Debug, Clone)]
355 pub struct ImportEdit {
356 pub import: LocatedImport,
357 pub scope: ImportScope,
361 /// Attempts to insert the import to the given scope, producing a text edit.
362 /// May return no edit in edge cases, such as scope already containing the import.
363 pub fn to_text_edit(&self, cfg: InsertUseConfig) -> Option<TextEdit> {
364 let _p = profile::span("ImportEdit::to_text_edit");
366 let new_ast = self.scope.clone_for_update();
367 insert_use::insert_use(&new_ast, mod_path_to_ast(&self.import.import_path), &cfg);
368 let mut import_insert = TextEdit::builder();
369 algo::diff(self.scope.as_syntax_node(), new_ast.as_syntax_node())
370 .into_text_edit(&mut import_insert);
372 Some(import_insert.finish())
376 /// A helper to make `CompletionItem`s.
379 pub(crate) struct Builder {
380 source_range: TextRange,
381 imports_to_add: SmallVec<[ImportEdit; 1]>,
382 trait_name: Option<SmolStr>,
384 insert_text: Option<String>,
386 detail: Option<String>,
387 documentation: Option<Documentation>,
388 lookup: Option<SmolStr>,
389 kind: CompletionItemKind,
390 text_edit: Option<TextEdit>,
392 trigger_call_info: Option<bool>,
393 relevance: CompletionRelevance,
394 ref_match: Option<Mutability>,
398 pub(crate) fn build(self) -> CompletionItem {
399 let _p = profile::span("item::Builder::build");
401 let mut label = self.label;
402 let mut lookup = self.lookup;
403 let insert_text = self.insert_text.unwrap_or_else(|| label.to_string());
405 if let [import_edit] = &*self.imports_to_add {
406 // snippets can have multiple imports, but normal completions only have up to one
407 if let Some(original_path) = import_edit.import.original_path.as_ref() {
408 lookup = lookup.or_else(|| Some(label.clone()));
409 label = SmolStr::from(format!("{} (use {})", label, original_path));
411 } else if let Some(trait_name) = self.trait_name {
412 label = SmolStr::from(format!("{} (as {})", label, trait_name));
415 let text_edit = match self.text_edit {
417 None => TextEdit::replace(self.source_range, insert_text),
421 source_range: self.source_range,
424 is_snippet: self.is_snippet,
426 documentation: self.documentation,
429 deprecated: self.deprecated,
430 trigger_call_info: self.trigger_call_info.unwrap_or(false),
431 relevance: self.relevance,
432 ref_match: self.ref_match,
433 import_to_add: self.imports_to_add,
436 pub(crate) fn lookup_by(&mut self, lookup: impl Into<SmolStr>) -> &mut Builder {
437 self.lookup = Some(lookup.into());
440 pub(crate) fn label(&mut self, label: impl Into<SmolStr>) -> &mut Builder {
441 self.label = label.into();
444 pub(crate) fn trait_name(&mut self, trait_name: SmolStr) -> &mut Builder {
445 self.trait_name = Some(trait_name);
448 pub(crate) fn insert_text(&mut self, insert_text: impl Into<String>) -> &mut Builder {
449 self.insert_text = Some(insert_text.into());
452 pub(crate) fn insert_snippet(
455 snippet: impl Into<String>,
458 self.is_snippet = true;
459 self.insert_text(snippet)
461 pub(crate) fn text_edit(&mut self, edit: TextEdit) -> &mut Builder {
462 self.text_edit = Some(edit);
465 pub(crate) fn snippet_edit(&mut self, _cap: SnippetCap, edit: TextEdit) -> &mut Builder {
466 self.is_snippet = true;
469 pub(crate) fn detail(&mut self, detail: impl Into<String>) -> &mut Builder {
470 self.set_detail(Some(detail))
472 pub(crate) fn set_detail(&mut self, detail: Option<impl Into<String>>) -> &mut Builder {
473 self.detail = detail.map(Into::into);
474 if let Some(detail) = &self.detail {
475 if never!(detail.contains('\n'), "multiline detail:\n{}", detail) {
476 self.detail = Some(detail.splitn(2, '\n').next().unwrap().to_string());
482 pub(crate) fn documentation(&mut self, docs: Documentation) -> &mut Builder {
483 self.set_documentation(Some(docs))
485 pub(crate) fn set_documentation(&mut self, docs: Option<Documentation>) -> &mut Builder {
486 self.documentation = docs.map(Into::into);
489 pub(crate) fn set_deprecated(&mut self, deprecated: bool) -> &mut Builder {
490 self.deprecated = deprecated;
493 pub(crate) fn set_relevance(&mut self, relevance: CompletionRelevance) -> &mut Builder {
494 self.relevance = relevance;
497 pub(crate) fn trigger_call_info(&mut self) -> &mut Builder {
498 self.trigger_call_info = Some(true);
501 pub(crate) fn add_import(&mut self, import_to_add: ImportEdit) -> &mut Builder {
502 self.imports_to_add.push(import_to_add);
505 pub(crate) fn ref_match(&mut self, mutability: Mutability) -> &mut Builder {
506 self.ref_match = Some(mutability);
513 use itertools::Itertools;
514 use test_utils::assert_eq_text;
516 use super::{CompletionRelevance, CompletionRelevanceTypeMatch};
518 /// Check that these are CompletionRelevance are sorted in ascending order
519 /// by their relevance score.
521 /// We want to avoid making assertions about the absolute score of any
522 /// item, but we do want to assert whether each is >, <, or == to the
525 /// If provided vec![vec![a], vec![b, c], vec![d]], then this will assert:
526 /// a.score < b.score == c.score < d.score
527 fn check_relevance_score_ordered(expected_relevance_order: Vec<Vec<CompletionRelevance>>) {
528 let expected = format!("{:#?}", &expected_relevance_order);
530 let actual_relevance_order = expected_relevance_order
533 .map(|r| (r.score(), r))
534 .sorted_by_key(|(score, _r)| *score)
536 (u32::MIN, vec![vec![]]),
537 |(mut currently_collecting_score, mut out), (score, r)| {
538 if currently_collecting_score == score {
539 out.last_mut().unwrap().push(r);
541 currently_collecting_score = score;
544 (currently_collecting_score, out)
549 let actual = format!("{:#?}", &actual_relevance_order);
551 assert_eq_text!(&expected, &actual);
555 fn relevance_score() {
556 // This test asserts that the relevance score for these items is ascending, and
557 // that any items in the same vec have the same score.
558 let expected_relevance_order = vec![
559 vec![CompletionRelevance::default()],
561 CompletionRelevance { exact_name_match: true, ..CompletionRelevance::default() },
562 CompletionRelevance { is_local: true, ..CompletionRelevance::default() },
564 vec![CompletionRelevance {
565 exact_name_match: true,
567 ..CompletionRelevance::default()
569 vec![CompletionRelevance {
570 type_match: Some(CompletionRelevanceTypeMatch::CouldUnify),
571 ..CompletionRelevance::default()
573 vec![CompletionRelevance {
574 type_match: Some(CompletionRelevanceTypeMatch::Exact),
575 ..CompletionRelevance::default()
577 vec![CompletionRelevance {
578 exact_name_match: true,
579 type_match: Some(CompletionRelevanceTypeMatch::Exact),
580 ..CompletionRelevance::default()
582 vec![CompletionRelevance {
583 exact_name_match: true,
584 type_match: Some(CompletionRelevanceTypeMatch::Exact),
586 ..CompletionRelevance::default()
588 vec![CompletionRelevance {
589 exact_name_match: false,
592 exact_postfix_snippet_match: true,
596 check_relevance_score_ordered(expected_relevance_order);