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
242async fn test_for_each_prefix<F>(
243 target: &str,
244 completions: &Vec<Completion>,
245 cx: &mut TestAppContext,
246 mut test_fn: F,
247) where
248 F: FnMut(Vec<StringMatch>),
249{
250 for i in 1..=target.len() {
251 let prefix = &target[..i];
252 let matches =
253 filter_and_sort_matches(prefix, completions, SnippetSortOrder::default(), cx).await;
254 test_fn(matches);
255 }
256}
257
258struct CompletionBuilder;
259
260impl CompletionBuilder {
261 fn constant(label: &str, filter_text: Option<&str>, sort_text: &str) -> Completion {
262 Self::new(label, filter_text, sort_text, CompletionItemKind::CONSTANT)
263 }
264
265 fn function(label: &str, filter_text: Option<&str>, sort_text: &str) -> Completion {
266 Self::new(label, filter_text, sort_text, CompletionItemKind::FUNCTION)
267 }
268
269 fn method(label: &str, filter_text: Option<&str>, sort_text: &str) -> Completion {
270 Self::new(label, filter_text, sort_text, CompletionItemKind::METHOD)
271 }
272
273 fn variable(label: &str, filter_text: Option<&str>, sort_text: &str) -> Completion {
274 Self::new(label, filter_text, sort_text, CompletionItemKind::VARIABLE)
275 }
276
277 fn snippet(label: &str, filter_text: Option<&str>, sort_text: &str) -> Completion {
278 Self::new(label, filter_text, sort_text, CompletionItemKind::SNIPPET)
279 }
280
281 fn new(
282 label: &str,
283 filter_text: Option<&str>,
284 sort_text: &str,
285 kind: CompletionItemKind,
286 ) -> Completion {
287 Completion {
288 replace_range: Anchor::MIN..Anchor::MAX,
289 new_text: label.to_string(),
290 label: CodeLabel::plain(label.to_string(), filter_text),
291 documentation: None,
292 source: CompletionSource::Lsp {
293 insert_range: None,
294 server_id: LanguageServerId(0),
295 lsp_completion: Box::new(CompletionItem {
296 label: label.to_string(),
297 kind: Some(kind),
298 sort_text: Some(sort_text.to_string()),
299 filter_text: filter_text.map(|text| text.to_string()),
300 ..Default::default()
301 }),
302 lsp_defaults: None,
303 resolved: false,
304 },
305 icon_path: None,
306 insert_text_mode: None,
307 confirm: None,
308 }
309 }
310}
311
312async fn filter_and_sort_matches(
313 query: &str,
314 completions: &Vec<Completion>,
315 snippet_sort_order: SnippetSortOrder,
316 cx: &mut TestAppContext,
317) -> Vec<StringMatch> {
318 let candidates: Arc<[StringMatchCandidate]> = completions
319 .iter()
320 .enumerate()
321 .map(|(id, completion)| StringMatchCandidate::new(id, completion.label.filter_text()))
322 .collect();
323 let cancel_flag = Arc::new(AtomicBool::new(false));
324 let background_executor = cx.executor();
325 let matches = fuzzy::match_strings(
326 &candidates,
327 query,
328 query.chars().any(|c| c.is_uppercase()),
329 false,
330 100,
331 &cancel_flag,
332 background_executor,
333 )
334 .await;
335 CompletionsMenu::sort_string_matches(matches, Some(query), snippet_sort_order, completions)
336}