code_completion_tests.rs

  1use crate::code_context_menus::CompletionsMenu;
  2use fuzzy::{StringMatch, StringMatchCandidate};
  3use gpui::TestAppContext;
  4use language::CodeLabel;
  5use lsp::{CompletionItem, CompletionItemKind, LanguageServerId};
  6use project::{Completion, CompletionSource};
  7use settings::SnippetSortOrder;
  8use std::sync::Arc;
  9use std::sync::atomic::AtomicBool;
 10use text::Anchor;
 11
 12#[gpui::test]
 13async fn test_sort_kind(cx: &mut TestAppContext) {
 14    let completions = vec![
 15        CompletionBuilder::function("floorf128", None, "80000000"),
 16        CompletionBuilder::constant("foo_bar_baz", None, "80000000"),
 17        CompletionBuilder::variable("foo_bar_qux", None, "80000000"),
 18    ];
 19    let matches =
 20        filter_and_sort_matches("foo", &completions, SnippetSortOrder::default(), cx).await;
 21
 22    // variable takes precedence over constant
 23    // constant take precedence over function
 24    assert_eq!(
 25        matches
 26            .iter()
 27            .map(|m| m.string.as_str())
 28            .collect::<Vec<_>>(),
 29        vec!["foo_bar_qux", "foo_bar_baz", "floorf128"]
 30    );
 31
 32    // fuzzy score should match for first two items as query is common prefix
 33    assert_eq!(matches[0].score, matches[1].score);
 34}
 35
 36#[gpui::test]
 37async fn test_fuzzy_score(cx: &mut TestAppContext) {
 38    // first character sensitive over sort_text and sort_kind
 39    {
 40        let completions = vec![
 41            CompletionBuilder::variable("element_type", None, "7ffffffe"),
 42            CompletionBuilder::constant("ElementType", None, "7fffffff"),
 43        ];
 44        let matches =
 45            filter_and_sort_matches("Elem", &completions, SnippetSortOrder::default(), cx).await;
 46        assert_eq!(
 47            matches
 48                .iter()
 49                .map(|m| m.string.as_str())
 50                .collect::<Vec<_>>(),
 51            vec!["ElementType", "element_type"]
 52        );
 53        assert!(matches[0].score > matches[1].score);
 54    }
 55
 56    // fuzzy takes over sort_text and sort_kind
 57    {
 58        let completions = vec![
 59            CompletionBuilder::function("onAbort?", None, "12"),
 60            CompletionBuilder::function("onAuxClick?", None, "12"),
 61            CompletionBuilder::variable("onPlay?", None, "12"),
 62            CompletionBuilder::variable("onLoad?", None, "12"),
 63            CompletionBuilder::variable("onDrag?", None, "12"),
 64            CompletionBuilder::function("onPause?", None, "10"),
 65            CompletionBuilder::function("onPaste?", None, "10"),
 66            CompletionBuilder::function("onAnimationEnd?", None, "12"),
 67            CompletionBuilder::function("onAbortCapture?", None, "12"),
 68            CompletionBuilder::constant("onChange?", None, "12"),
 69            CompletionBuilder::constant("onWaiting?", None, "12"),
 70            CompletionBuilder::function("onCanPlay?", None, "12"),
 71        ];
 72        let matches =
 73            filter_and_sort_matches("ona", &completions, SnippetSortOrder::default(), cx).await;
 74        for i in 0..4 {
 75            assert!(matches[i].string.to_lowercase().starts_with("ona"));
 76        }
 77    }
 78
 79    // plain fuzzy prefix match
 80    {
 81        let completions = vec![
 82            CompletionBuilder::function("set_text", None, "7fffffff"),
 83            CompletionBuilder::function("set_placeholder_text", None, "7fffffff"),
 84            CompletionBuilder::function("set_text_style_refinement", None, "7fffffff"),
 85            CompletionBuilder::function("set_context_menu_options", None, "7fffffff"),
 86            CompletionBuilder::function("select_to_next_word_end", None, "7fffffff"),
 87            CompletionBuilder::function("select_to_next_subword_end", None, "7fffffff"),
 88            CompletionBuilder::function("set_custom_context_menu", None, "7fffffff"),
 89            CompletionBuilder::function("select_to_end_of_excerpt", None, "7fffffff"),
 90            CompletionBuilder::function("select_to_start_of_excerpt", None, "7fffffff"),
 91            CompletionBuilder::function("select_to_start_of_next_excerpt", None, "7fffffff"),
 92            CompletionBuilder::function("select_to_end_of_previous_excerpt", None, "7fffffff"),
 93        ];
 94        let matches =
 95            filter_and_sort_matches("set_text", &completions, SnippetSortOrder::Top, cx).await;
 96        assert_eq!(matches[0].string, "set_text");
 97        assert_eq!(matches[1].string, "set_text_style_refinement");
 98        assert_eq!(matches[2].string, "set_placeholder_text");
 99    }
100
101    // fuzzy filter text over label, sort_text and sort_kind
102    {
103        // Case 1: "awa"
104        let completions = vec![
105            CompletionBuilder::method("await", Some("await"), "7fffffff"),
106            CompletionBuilder::method("await.ne", Some("ne"), "80000010"),
107            CompletionBuilder::method("await.eq", Some("eq"), "80000010"),
108            CompletionBuilder::method("await.or", Some("or"), "7ffffff8"),
109            CompletionBuilder::method("await.zip", Some("zip"), "80000006"),
110            CompletionBuilder::method("await.xor", Some("xor"), "7ffffff8"),
111            CompletionBuilder::method("await.and", Some("and"), "80000006"),
112            CompletionBuilder::method("await.map", Some("map"), "80000006"),
113        ];
114
115        test_for_each_prefix("await", &completions, cx, |matches| {
116            // for each prefix, first item should always be one with lower sort_text
117            assert_eq!(matches[0].string, "await");
118        })
119        .await;
120    }
121}
122
123#[gpui::test]
124async fn test_sort_text(cx: &mut TestAppContext) {
125    // sort text takes precedance over sort_kind, when fuzzy is same
126    {
127        let completions = vec![
128            CompletionBuilder::variable("unreachable", None, "80000000"),
129            CompletionBuilder::function("unreachable!(…)", None, "7fffffff"),
130            CompletionBuilder::function("unchecked_rem", None, "80000010"),
131            CompletionBuilder::function("unreachable_unchecked", None, "80000020"),
132        ];
133
134        test_for_each_prefix("unreachabl", &completions, cx, |matches| {
135            // for each prefix, first item should always be one with lower sort_text
136            assert_eq!(matches[0].string, "unreachable!(…)");
137            assert_eq!(matches[1].string, "unreachable");
138
139            // fuzzy score should match for first two items as query is common prefix
140            assert_eq!(matches[0].score, matches[1].score);
141        })
142        .await;
143
144        let matches =
145            filter_and_sort_matches("unreachable", &completions, SnippetSortOrder::Top, cx).await;
146        // exact match comes first
147        assert_eq!(matches[0].string, "unreachable");
148        assert_eq!(matches[1].string, "unreachable!(…)");
149
150        // fuzzy score should match for first two items as query is common prefix
151        assert_eq!(matches[0].score, matches[1].score);
152    }
153}
154
155#[gpui::test]
156async fn test_sort_snippet(cx: &mut TestAppContext) {
157    let completions = vec![
158        CompletionBuilder::constant("println", None, "7fffffff"),
159        CompletionBuilder::snippet("println!(…)", None, "80000000"),
160    ];
161    let matches = filter_and_sort_matches("prin", &completions, SnippetSortOrder::Top, cx).await;
162
163    // snippet take precedence over sort_text and sort_kind
164    assert_eq!(matches[0].string, "println!(…)");
165}
166
167#[gpui::test]
168async fn test_sort_exact(cx: &mut TestAppContext) {
169    // sort_text takes over if no exact match
170    let completions = vec![
171        CompletionBuilder::function("into", None, "80000004"),
172        CompletionBuilder::function("try_into", None, "80000004"),
173        CompletionBuilder::snippet("println", None, "80000004"),
174        CompletionBuilder::function("clone_into", None, "80000004"),
175        CompletionBuilder::function("into_searcher", None, "80000000"),
176        CompletionBuilder::snippet("eprintln", None, "80000004"),
177    ];
178    let matches =
179        filter_and_sort_matches("int", &completions, SnippetSortOrder::default(), cx).await;
180    assert_eq!(matches[0].string, "into_searcher");
181
182    // exact match takes over sort_text
183    let completions = vec![
184        CompletionBuilder::function("into", None, "80000004"),
185        CompletionBuilder::function("try_into", None, "80000004"),
186        CompletionBuilder::function("clone_into", None, "80000004"),
187        CompletionBuilder::function("into_searcher", None, "80000000"),
188        CompletionBuilder::function("split_terminator", None, "7fffffff"),
189        CompletionBuilder::function("rsplit_terminator", None, "7fffffff"),
190    ];
191    let matches =
192        filter_and_sort_matches("into", &completions, SnippetSortOrder::default(), cx).await;
193    assert_eq!(matches[0].string, "into");
194}
195
196#[gpui::test]
197async fn test_sort_positions(cx: &mut TestAppContext) {
198    // positions take precedence over fuzzy score and sort_text
199    let completions = vec![
200        CompletionBuilder::function("rounded-full", None, "15788"),
201        CompletionBuilder::variable("rounded-t-full", None, "15846"),
202        CompletionBuilder::variable("rounded-b-full", None, "15731"),
203        CompletionBuilder::function("rounded-tr-full", None, "15866"),
204    ];
205
206    let matches = filter_and_sort_matches(
207        "rounded-full",
208        &completions,
209        SnippetSortOrder::default(),
210        cx,
211    )
212    .await;
213    assert_eq!(matches[0].string, "rounded-full");
214
215    let matches =
216        filter_and_sort_matches("roundedfull", &completions, SnippetSortOrder::default(), cx).await;
217    assert_eq!(matches[0].string, "rounded-full");
218}
219
220#[gpui::test]
221async fn test_fuzzy_over_sort_positions(cx: &mut TestAppContext) {
222    let completions = vec![
223        CompletionBuilder::variable("lsp_document_colors", None, "7fffffff"), // 0.29 fuzzy score
224        CompletionBuilder::function(
225            "language_servers_running_disk_based_diagnostics",
226            None,
227            "7fffffff",
228        ), // 0.168 fuzzy score
229        CompletionBuilder::function("code_lens", None, "7fffffff"),           // 3.2 fuzzy score
230        CompletionBuilder::variable("lsp_code_lens", None, "7fffffff"),       // 3.2 fuzzy score
231        CompletionBuilder::function("fetch_code_lens", None, "7fffffff"),     // 3.2 fuzzy score
232    ];
233
234    let matches =
235        filter_and_sort_matches("lens", &completions, SnippetSortOrder::default(), cx).await;
236
237    assert_eq!(matches[0].string, "code_lens");
238    assert_eq!(matches[1].string, "lsp_code_lens");
239    assert_eq!(matches[2].string, "fetch_code_lens");
240}
241
242#[gpui::test]
243async fn test_semver_label_sort_by_latest_version(cx: &mut TestAppContext) {
244    let mut versions = [
245        "10.4.112",
246        "10.4.22",
247        "10.4.2",
248        "10.4.20",
249        "10.4.21",
250        "10.4.12",
251        // Pre-release versions
252        "10.4.22-alpha",
253        "10.4.22-beta.1",
254        "10.4.22-rc.1",
255        // Build metadata versions
256        "10.4.21+build.123",
257        "10.4.20+20210327",
258    ];
259    versions.sort_by(|a, b| {
260        match (
261            semver::Version::parse(a).ok(),
262            semver::Version::parse(b).ok(),
263        ) {
264            (Some(a_ver), Some(b_ver)) => b_ver.cmp(&a_ver),
265            _ => std::cmp::Ordering::Equal,
266        }
267    });
268    let completions: Vec<_> = versions
269        .iter()
270        .enumerate()
271        .map(|(i, version)| {
272            // This sort text would come from the LSP
273            let sort_text = format!("{:08}", i);
274            CompletionBuilder::new(version, None, &sort_text, None)
275        })
276        .collect();
277
278    // Case 1: User types just the major and minor version
279    let matches =
280        filter_and_sort_matches("10.4.", &completions, SnippetSortOrder::default(), cx).await;
281    // Versions are ordered by recency (latest first)
282    let expected_versions = [
283        "10.4.112",
284        "10.4.22",
285        "10.4.22-rc.1",
286        "10.4.22-beta.1",
287        "10.4.22-alpha",
288        "10.4.21+build.123",
289        "10.4.21",
290        "10.4.20+20210327",
291        "10.4.20",
292        "10.4.12",
293        "10.4.2",
294    ];
295    for (match_item, expected) in matches.iter().zip(expected_versions.iter()) {
296        assert_eq!(match_item.string.as_ref() as &str, *expected);
297    }
298
299    // Case 2: User types the major, minor, and patch version
300    let matches =
301        filter_and_sort_matches("10.4.2", &completions, SnippetSortOrder::default(), cx).await;
302    let expected_versions = [
303        // Exact match comes first
304        "10.4.2",
305        // Ordered by recency with exact major, minor, and patch versions
306        "10.4.22",
307        "10.4.22-rc.1",
308        "10.4.22-beta.1",
309        "10.4.22-alpha",
310        "10.4.21+build.123",
311        "10.4.21",
312        "10.4.20+20210327",
313        "10.4.20",
314        // Versions with non-exact patch versions are ordered by fuzzy score
315        // Higher fuzzy score than 112 patch version since "2" appears before "1"
316        // in "12", making it rank higher than "112"
317        "10.4.12",
318        "10.4.112",
319    ];
320    for (match_item, expected) in matches.iter().zip(expected_versions.iter()) {
321        assert_eq!(match_item.string.as_ref() as &str, *expected);
322    }
323}
324
325async fn test_for_each_prefix<F>(
326    target: &str,
327    completions: &Vec<Completion>,
328    cx: &mut TestAppContext,
329    mut test_fn: F,
330) where
331    F: FnMut(Vec<StringMatch>),
332{
333    for i in 1..=target.len() {
334        let prefix = &target[..i];
335        let matches =
336            filter_and_sort_matches(prefix, completions, SnippetSortOrder::default(), cx).await;
337        test_fn(matches);
338    }
339}
340
341struct CompletionBuilder;
342
343impl CompletionBuilder {
344    fn constant(label: &str, filter_text: Option<&str>, sort_text: &str) -> Completion {
345        Self::new(
346            label,
347            filter_text,
348            sort_text,
349            Some(CompletionItemKind::CONSTANT),
350        )
351    }
352
353    fn function(label: &str, filter_text: Option<&str>, sort_text: &str) -> Completion {
354        Self::new(
355            label,
356            filter_text,
357            sort_text,
358            Some(CompletionItemKind::FUNCTION),
359        )
360    }
361
362    fn method(label: &str, filter_text: Option<&str>, sort_text: &str) -> Completion {
363        Self::new(
364            label,
365            filter_text,
366            sort_text,
367            Some(CompletionItemKind::METHOD),
368        )
369    }
370
371    fn variable(label: &str, filter_text: Option<&str>, sort_text: &str) -> Completion {
372        Self::new(
373            label,
374            filter_text,
375            sort_text,
376            Some(CompletionItemKind::VARIABLE),
377        )
378    }
379
380    fn snippet(label: &str, filter_text: Option<&str>, sort_text: &str) -> Completion {
381        Self::new(
382            label,
383            filter_text,
384            sort_text,
385            Some(CompletionItemKind::SNIPPET),
386        )
387    }
388
389    fn new(
390        label: &str,
391        filter_text: Option<&str>,
392        sort_text: &str,
393        kind: Option<CompletionItemKind>,
394    ) -> Completion {
395        Completion {
396            replace_range: Anchor::MIN..Anchor::MAX,
397            new_text: label.to_string(),
398            label: CodeLabel::plain(label.to_string(), filter_text),
399            documentation: None,
400            source: CompletionSource::Lsp {
401                insert_range: None,
402                server_id: LanguageServerId(0),
403                lsp_completion: Box::new(CompletionItem {
404                    label: label.to_string(),
405                    kind: kind,
406                    sort_text: Some(sort_text.to_string()),
407                    filter_text: filter_text.map(|text| text.to_string()),
408                    ..Default::default()
409                }),
410                lsp_defaults: None,
411                resolved: false,
412            },
413            icon_path: None,
414            insert_text_mode: None,
415            confirm: None,
416            match_start: None,
417            snippet_deduplication_key: None,
418        }
419    }
420}
421
422async fn filter_and_sort_matches(
423    query: &str,
424    completions: &Vec<Completion>,
425    snippet_sort_order: SnippetSortOrder,
426    cx: &mut TestAppContext,
427) -> Vec<StringMatch> {
428    let candidates: Arc<[StringMatchCandidate]> = completions
429        .iter()
430        .enumerate()
431        .map(|(id, completion)| StringMatchCandidate::new(id, completion.label.filter_text()))
432        .collect();
433    let cancel_flag = Arc::new(AtomicBool::new(false));
434    let background_executor = cx.executor();
435    let matches = fuzzy::match_strings(
436        &candidates,
437        query,
438        query.chars().any(|c| c.is_uppercase()),
439        false,
440        100,
441        &cancel_flag,
442        background_executor,
443    )
444    .await;
445    CompletionsMenu::sort_string_matches(matches, Some(query), snippet_sort_order, completions)
446}