1use anyhow::{Context as _, Result};
2use async_trait::async_trait;
3use collections::HashMap;
4use futures::StreamExt;
5use gpui::{App, AsyncApp, Task};
6use http_client::github::latest_github_release;
7pub use language::*;
8use lsp::{LanguageServerBinary, LanguageServerName};
9use project::Fs;
10use regex::Regex;
11use serde_json::json;
12use smol::fs;
13use std::{
14 any::Any,
15 borrow::Cow,
16 ffi::{OsStr, OsString},
17 ops::Range,
18 path::PathBuf,
19 process::Output,
20 str,
21 sync::{
22 Arc, LazyLock,
23 atomic::{AtomicBool, Ordering::SeqCst},
24 },
25};
26use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
27use util::{ResultExt, fs::remove_matching, maybe};
28
29fn server_binary_arguments() -> Vec<OsString> {
30 vec!["-mode=stdio".into()]
31}
32
33#[derive(Copy, Clone)]
34pub struct GoLspAdapter;
35
36impl GoLspAdapter {
37 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("gopls");
38}
39
40static VERSION_REGEX: LazyLock<Regex> =
41 LazyLock::new(|| Regex::new(r"\d+\.\d+\.\d+").expect("Failed to create VERSION_REGEX"));
42
43static GO_ESCAPE_SUBTEST_NAME_REGEX: LazyLock<Regex> = LazyLock::new(|| {
44 Regex::new(r#"[.*+?^${}()|\[\]\\]"#).expect("Failed to create GO_ESCAPE_SUBTEST_NAME_REGEX")
45});
46
47const BINARY: &str = if cfg!(target_os = "windows") {
48 "gopls.exe"
49} else {
50 "gopls"
51};
52
53#[async_trait(?Send)]
54impl super::LspAdapter for GoLspAdapter {
55 fn name(&self) -> LanguageServerName {
56 Self::SERVER_NAME.clone()
57 }
58
59 async fn fetch_latest_server_version(
60 &self,
61 delegate: &dyn LspAdapterDelegate,
62 ) -> Result<Box<dyn 'static + Send + Any>> {
63 let release =
64 latest_github_release("golang/tools", false, false, delegate.http_client()).await?;
65 let version: Option<String> = release.tag_name.strip_prefix("gopls/v").map(str::to_string);
66 if version.is_none() {
67 log::warn!(
68 "couldn't infer gopls version from GitHub release tag name '{}'",
69 release.tag_name
70 );
71 }
72 Ok(Box::new(version) as Box<_>)
73 }
74
75 async fn check_if_user_installed(
76 &self,
77 delegate: &dyn LspAdapterDelegate,
78 _: Arc<dyn LanguageToolchainStore>,
79 _: &AsyncApp,
80 ) -> Option<LanguageServerBinary> {
81 let path = delegate.which(Self::SERVER_NAME.as_ref()).await?;
82 Some(LanguageServerBinary {
83 path,
84 arguments: server_binary_arguments(),
85 env: None,
86 })
87 }
88
89 fn will_fetch_server(
90 &self,
91 delegate: &Arc<dyn LspAdapterDelegate>,
92 cx: &mut AsyncApp,
93 ) -> Option<Task<Result<()>>> {
94 static DID_SHOW_NOTIFICATION: AtomicBool = AtomicBool::new(false);
95
96 const NOTIFICATION_MESSAGE: &str =
97 "Could not install the Go language server `gopls`, because `go` was not found.";
98
99 let delegate = delegate.clone();
100 Some(cx.spawn(async move |cx| {
101 if delegate.which("go".as_ref()).await.is_none() {
102 if DID_SHOW_NOTIFICATION
103 .compare_exchange(false, true, SeqCst, SeqCst)
104 .is_ok()
105 {
106 cx.update(|cx| {
107 delegate.show_notification(NOTIFICATION_MESSAGE, cx);
108 })?
109 }
110 anyhow::bail!("cannot install gopls");
111 }
112 Ok(())
113 }))
114 }
115
116 async fn fetch_server_binary(
117 &self,
118 version: Box<dyn 'static + Send + Any>,
119 container_dir: PathBuf,
120 delegate: &dyn LspAdapterDelegate,
121 ) -> Result<LanguageServerBinary> {
122 let go = delegate.which("go".as_ref()).await.unwrap_or("go".into());
123 let go_version_output = util::command::new_smol_command(&go)
124 .args(["version"])
125 .output()
126 .await
127 .context("failed to get go version via `go version` command`")?;
128 let go_version = parse_version_output(&go_version_output)?;
129 let version = version.downcast::<Option<String>>().unwrap();
130 let this = *self;
131
132 if let Some(version) = *version {
133 let binary_path = container_dir.join(format!("gopls_{version}_go_{go_version}"));
134 if let Ok(metadata) = fs::metadata(&binary_path).await {
135 if metadata.is_file() {
136 remove_matching(&container_dir, |entry| {
137 entry != binary_path && entry.file_name() != Some(OsStr::new("gobin"))
138 })
139 .await;
140
141 return Ok(LanguageServerBinary {
142 path: binary_path.to_path_buf(),
143 arguments: server_binary_arguments(),
144 env: None,
145 });
146 }
147 }
148 } else if let Some(path) = this
149 .cached_server_binary(container_dir.clone(), delegate)
150 .await
151 {
152 return Ok(path);
153 }
154
155 let gobin_dir = container_dir.join("gobin");
156 fs::create_dir_all(&gobin_dir).await?;
157 let install_output = util::command::new_smol_command(go)
158 .env("GO111MODULE", "on")
159 .env("GOBIN", &gobin_dir)
160 .args(["install", "golang.org/x/tools/gopls@latest"])
161 .output()
162 .await?;
163
164 if !install_output.status.success() {
165 log::error!(
166 "failed to install gopls via `go install`. stdout: {:?}, stderr: {:?}",
167 String::from_utf8_lossy(&install_output.stdout),
168 String::from_utf8_lossy(&install_output.stderr)
169 );
170 anyhow::bail!(
171 "failed to install gopls with `go install`. Is `go` installed and in the PATH? Check logs for more information."
172 );
173 }
174
175 let installed_binary_path = gobin_dir.join(BINARY);
176 let version_output = util::command::new_smol_command(&installed_binary_path)
177 .arg("version")
178 .output()
179 .await
180 .context("failed to run installed gopls binary")?;
181 let gopls_version = parse_version_output(&version_output)?;
182 let binary_path = container_dir.join(format!("gopls_{gopls_version}_go_{go_version}"));
183 fs::rename(&installed_binary_path, &binary_path).await?;
184
185 Ok(LanguageServerBinary {
186 path: binary_path.to_path_buf(),
187 arguments: server_binary_arguments(),
188 env: None,
189 })
190 }
191
192 async fn cached_server_binary(
193 &self,
194 container_dir: PathBuf,
195 _: &dyn LspAdapterDelegate,
196 ) -> Option<LanguageServerBinary> {
197 get_cached_server_binary(container_dir).await
198 }
199
200 async fn initialization_options(
201 self: Arc<Self>,
202 _: &dyn Fs,
203 _: &Arc<dyn LspAdapterDelegate>,
204 ) -> Result<Option<serde_json::Value>> {
205 Ok(Some(json!({
206 "usePlaceholders": true,
207 "hints": {
208 "assignVariableTypes": true,
209 "compositeLiteralFields": true,
210 "compositeLiteralTypes": true,
211 "constantValues": true,
212 "functionTypeParameters": true,
213 "parameterNames": true,
214 "rangeVariableTypes": true
215 }
216 })))
217 }
218
219 async fn label_for_completion(
220 &self,
221 completion: &lsp::CompletionItem,
222 language: &Arc<Language>,
223 ) -> Option<CodeLabel> {
224 let label = &completion.label;
225
226 // Gopls returns nested fields and methods as completions.
227 // To syntax highlight these, combine their final component
228 // with their detail.
229 let name_offset = label.rfind('.').unwrap_or(0);
230
231 match completion.kind.zip(completion.detail.as_ref()) {
232 Some((lsp::CompletionItemKind::MODULE, detail)) => {
233 let text = format!("{label} {detail}");
234 let source = Rope::from(format!("import {text}").as_str());
235 let runs = language.highlight_text(&source, 7..7 + text.len());
236 let filter_range = completion
237 .filter_text
238 .as_deref()
239 .and_then(|filter_text| {
240 text.find(filter_text)
241 .map(|start| start..start + filter_text.len())
242 })
243 .unwrap_or(0..label.len());
244 return Some(CodeLabel {
245 text,
246 runs,
247 filter_range,
248 });
249 }
250 Some((
251 lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE,
252 detail,
253 )) => {
254 let text = format!("{label} {detail}");
255 let source =
256 Rope::from(format!("var {} {}", &text[name_offset..], detail).as_str());
257 let runs = adjust_runs(
258 name_offset,
259 language.highlight_text(&source, 4..4 + text.len()),
260 );
261 let filter_range = completion
262 .filter_text
263 .as_deref()
264 .and_then(|filter_text| {
265 text.find(filter_text)
266 .map(|start| start..start + filter_text.len())
267 })
268 .unwrap_or(0..label.len());
269 return Some(CodeLabel {
270 text,
271 runs,
272 filter_range,
273 });
274 }
275 Some((lsp::CompletionItemKind::STRUCT, _)) => {
276 let text = format!("{label} struct {{}}");
277 let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
278 let runs = adjust_runs(
279 name_offset,
280 language.highlight_text(&source, 5..5 + text.len()),
281 );
282 let filter_range = completion
283 .filter_text
284 .as_deref()
285 .and_then(|filter_text| {
286 text.find(filter_text)
287 .map(|start| start..start + filter_text.len())
288 })
289 .unwrap_or(0..label.len());
290 return Some(CodeLabel {
291 text,
292 runs,
293 filter_range,
294 });
295 }
296 Some((lsp::CompletionItemKind::INTERFACE, _)) => {
297 let text = format!("{label} interface {{}}");
298 let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
299 let runs = adjust_runs(
300 name_offset,
301 language.highlight_text(&source, 5..5 + text.len()),
302 );
303 let filter_range = completion
304 .filter_text
305 .as_deref()
306 .and_then(|filter_text| {
307 text.find(filter_text)
308 .map(|start| start..start + filter_text.len())
309 })
310 .unwrap_or(0..label.len());
311 return Some(CodeLabel {
312 text,
313 runs,
314 filter_range,
315 });
316 }
317 Some((lsp::CompletionItemKind::FIELD, detail)) => {
318 let text = format!("{label} {detail}");
319 let source =
320 Rope::from(format!("type T struct {{ {} }}", &text[name_offset..]).as_str());
321 let runs = adjust_runs(
322 name_offset,
323 language.highlight_text(&source, 16..16 + text.len()),
324 );
325 let filter_range = completion
326 .filter_text
327 .as_deref()
328 .and_then(|filter_text| {
329 text.find(filter_text)
330 .map(|start| start..start + filter_text.len())
331 })
332 .unwrap_or(0..label.len());
333 return Some(CodeLabel {
334 text,
335 runs,
336 filter_range,
337 });
338 }
339 Some((lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD, detail)) => {
340 if let Some(signature) = detail.strip_prefix("func") {
341 let text = format!("{label}{signature}");
342 let source = Rope::from(format!("func {} {{}}", &text[name_offset..]).as_str());
343 let runs = adjust_runs(
344 name_offset,
345 language.highlight_text(&source, 5..5 + text.len()),
346 );
347 let filter_range = completion
348 .filter_text
349 .as_deref()
350 .and_then(|filter_text| {
351 text.find(filter_text)
352 .map(|start| start..start + filter_text.len())
353 })
354 .unwrap_or(0..label.len());
355 return Some(CodeLabel {
356 filter_range,
357 text,
358 runs,
359 });
360 }
361 }
362 _ => {}
363 }
364 None
365 }
366
367 async fn label_for_symbol(
368 &self,
369 name: &str,
370 kind: lsp::SymbolKind,
371 language: &Arc<Language>,
372 ) -> Option<CodeLabel> {
373 let (text, filter_range, display_range) = match kind {
374 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
375 let text = format!("func {} () {{}}", name);
376 let filter_range = 5..5 + name.len();
377 let display_range = 0..filter_range.end;
378 (text, filter_range, display_range)
379 }
380 lsp::SymbolKind::STRUCT => {
381 let text = format!("type {} struct {{}}", name);
382 let filter_range = 5..5 + name.len();
383 let display_range = 0..text.len();
384 (text, filter_range, display_range)
385 }
386 lsp::SymbolKind::INTERFACE => {
387 let text = format!("type {} interface {{}}", name);
388 let filter_range = 5..5 + name.len();
389 let display_range = 0..text.len();
390 (text, filter_range, display_range)
391 }
392 lsp::SymbolKind::CLASS => {
393 let text = format!("type {} T", name);
394 let filter_range = 5..5 + name.len();
395 let display_range = 0..filter_range.end;
396 (text, filter_range, display_range)
397 }
398 lsp::SymbolKind::CONSTANT => {
399 let text = format!("const {} = nil", name);
400 let filter_range = 6..6 + name.len();
401 let display_range = 0..filter_range.end;
402 (text, filter_range, display_range)
403 }
404 lsp::SymbolKind::VARIABLE => {
405 let text = format!("var {} = nil", name);
406 let filter_range = 4..4 + name.len();
407 let display_range = 0..filter_range.end;
408 (text, filter_range, display_range)
409 }
410 lsp::SymbolKind::MODULE => {
411 let text = format!("package {}", name);
412 let filter_range = 8..8 + name.len();
413 let display_range = 0..filter_range.end;
414 (text, filter_range, display_range)
415 }
416 _ => return None,
417 };
418
419 Some(CodeLabel {
420 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
421 text: text[display_range].to_string(),
422 filter_range,
423 })
424 }
425
426 fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
427 static REGEX: LazyLock<Regex> =
428 LazyLock::new(|| Regex::new(r"(?m)\n\s*").expect("Failed to create REGEX"));
429 Some(REGEX.replace_all(message, "\n\n").to_string())
430 }
431}
432
433fn parse_version_output(output: &Output) -> Result<&str> {
434 let version_stdout =
435 str::from_utf8(&output.stdout).context("version command produced invalid utf8 output")?;
436
437 let version = VERSION_REGEX
438 .find(version_stdout)
439 .with_context(|| format!("failed to parse version output '{version_stdout}'"))?
440 .as_str();
441
442 Ok(version)
443}
444
445async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
446 maybe!(async {
447 let mut last_binary_path = None;
448 let mut entries = fs::read_dir(&container_dir).await?;
449 while let Some(entry) = entries.next().await {
450 let entry = entry?;
451 if entry.file_type().await?.is_file()
452 && entry
453 .file_name()
454 .to_str()
455 .map_or(false, |name| name.starts_with("gopls_"))
456 {
457 last_binary_path = Some(entry.path());
458 }
459 }
460
461 let path = last_binary_path.context("no cached binary")?;
462 anyhow::Ok(LanguageServerBinary {
463 path,
464 arguments: server_binary_arguments(),
465 env: None,
466 })
467 })
468 .await
469 .log_err()
470}
471
472fn adjust_runs(
473 delta: usize,
474 mut runs: Vec<(Range<usize>, HighlightId)>,
475) -> Vec<(Range<usize>, HighlightId)> {
476 for (range, _) in &mut runs {
477 range.start += delta;
478 range.end += delta;
479 }
480 runs
481}
482
483pub(crate) struct GoContextProvider;
484
485const GO_PACKAGE_TASK_VARIABLE: VariableName = VariableName::Custom(Cow::Borrowed("GO_PACKAGE"));
486const GO_MODULE_ROOT_TASK_VARIABLE: VariableName =
487 VariableName::Custom(Cow::Borrowed("GO_MODULE_ROOT"));
488const GO_SUBTEST_NAME_TASK_VARIABLE: VariableName =
489 VariableName::Custom(Cow::Borrowed("GO_SUBTEST_NAME"));
490
491impl ContextProvider for GoContextProvider {
492 fn build_context(
493 &self,
494 variables: &TaskVariables,
495 location: ContextLocation<'_>,
496 _: Option<HashMap<String, String>>,
497 _: Arc<dyn LanguageToolchainStore>,
498 cx: &mut gpui::App,
499 ) -> Task<Result<TaskVariables>> {
500 let local_abs_path = location
501 .file_location
502 .buffer
503 .read(cx)
504 .file()
505 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
506
507 let go_package_variable = local_abs_path
508 .as_deref()
509 .and_then(|local_abs_path| local_abs_path.parent())
510 .map(|buffer_dir| {
511 // Prefer the relative form `./my-nested-package/is-here` over
512 // absolute path, because it's more readable in the modal, but
513 // the absolute path also works.
514 let package_name = variables
515 .get(&VariableName::WorktreeRoot)
516 .and_then(|worktree_abs_path| buffer_dir.strip_prefix(worktree_abs_path).ok())
517 .map(|relative_pkg_dir| {
518 if relative_pkg_dir.as_os_str().is_empty() {
519 ".".into()
520 } else {
521 format!("./{}", relative_pkg_dir.to_string_lossy())
522 }
523 })
524 .unwrap_or_else(|| format!("{}", buffer_dir.to_string_lossy()));
525
526 (GO_PACKAGE_TASK_VARIABLE.clone(), package_name.to_string())
527 });
528
529 let go_module_root_variable = local_abs_path
530 .as_deref()
531 .and_then(|local_abs_path| local_abs_path.parent())
532 .map(|buffer_dir| {
533 // Walk dirtree up until getting the first go.mod file
534 let module_dir = buffer_dir
535 .ancestors()
536 .find(|dir| dir.join("go.mod").is_file())
537 .map(|dir| dir.to_string_lossy().to_string())
538 .unwrap_or_else(|| ".".to_string());
539
540 (GO_MODULE_ROOT_TASK_VARIABLE.clone(), module_dir)
541 });
542
543 let _subtest_name = variables.get(&VariableName::Custom(Cow::Borrowed("_subtest_name")));
544
545 let go_subtest_variable = extract_subtest_name(_subtest_name.unwrap_or(""))
546 .map(|subtest_name| (GO_SUBTEST_NAME_TASK_VARIABLE.clone(), subtest_name));
547
548 Task::ready(Ok(TaskVariables::from_iter(
549 [
550 go_package_variable,
551 go_subtest_variable,
552 go_module_root_variable,
553 ]
554 .into_iter()
555 .flatten(),
556 )))
557 }
558
559 fn associated_tasks(
560 &self,
561 _: Arc<dyn Fs>,
562 _: Option<Arc<dyn File>>,
563 _: &App,
564 ) -> Task<Option<TaskTemplates>> {
565 let package_cwd = if GO_PACKAGE_TASK_VARIABLE.template_value() == "." {
566 None
567 } else {
568 Some("$ZED_DIRNAME".to_string())
569 };
570 let module_cwd = Some(GO_MODULE_ROOT_TASK_VARIABLE.template_value());
571
572 Task::ready(Some(TaskTemplates(vec![
573 TaskTemplate {
574 label: format!(
575 "go test {} -run {}",
576 GO_PACKAGE_TASK_VARIABLE.template_value(),
577 VariableName::Symbol.template_value(),
578 ),
579 command: "go".into(),
580 args: vec![
581 "test".into(),
582 "-run".into(),
583 format!("\\^{}\\$", VariableName::Symbol.template_value(),),
584 ],
585 tags: vec!["go-test".to_owned()],
586 cwd: package_cwd.clone(),
587 ..TaskTemplate::default()
588 },
589 TaskTemplate {
590 label: format!("go test {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
591 command: "go".into(),
592 args: vec!["test".into()],
593 cwd: package_cwd.clone(),
594 ..TaskTemplate::default()
595 },
596 TaskTemplate {
597 label: "go test ./...".into(),
598 command: "go".into(),
599 args: vec!["test".into(), "./...".into()],
600 cwd: module_cwd.clone(),
601 ..TaskTemplate::default()
602 },
603 TaskTemplate {
604 label: format!(
605 "go test {} -v -run {}/{}",
606 GO_PACKAGE_TASK_VARIABLE.template_value(),
607 VariableName::Symbol.template_value(),
608 GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
609 ),
610 command: "go".into(),
611 args: vec![
612 "test".into(),
613 "-v".into(),
614 "-run".into(),
615 format!(
616 "\\^{}\\$/\\^{}\\$",
617 VariableName::Symbol.template_value(),
618 GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
619 ),
620 ],
621 cwd: package_cwd.clone(),
622 tags: vec!["go-subtest".to_owned()],
623 ..TaskTemplate::default()
624 },
625 TaskTemplate {
626 label: format!(
627 "go test {} -bench {}",
628 GO_PACKAGE_TASK_VARIABLE.template_value(),
629 VariableName::Symbol.template_value()
630 ),
631 command: "go".into(),
632 args: vec![
633 "test".into(),
634 "-benchmem".into(),
635 "-run='^$'".into(),
636 "-bench".into(),
637 format!("\\^{}\\$", VariableName::Symbol.template_value()),
638 ],
639 cwd: package_cwd.clone(),
640 tags: vec!["go-benchmark".to_owned()],
641 ..TaskTemplate::default()
642 },
643 TaskTemplate {
644 label: format!(
645 "go test {} -fuzz=Fuzz -run {}",
646 GO_PACKAGE_TASK_VARIABLE.template_value(),
647 VariableName::Symbol.template_value(),
648 ),
649 command: "go".into(),
650 args: vec![
651 "test".into(),
652 "-fuzz=Fuzz".into(),
653 "-run".into(),
654 format!("\\^{}\\$", VariableName::Symbol.template_value(),),
655 ],
656 tags: vec!["go-fuzz".to_owned()],
657 cwd: package_cwd.clone(),
658 ..TaskTemplate::default()
659 },
660 TaskTemplate {
661 label: format!("go run {}", GO_PACKAGE_TASK_VARIABLE.template_value(),),
662 command: "go".into(),
663 args: vec!["run".into(), ".".into()],
664 cwd: package_cwd.clone(),
665 tags: vec!["go-main".to_owned()],
666 ..TaskTemplate::default()
667 },
668 TaskTemplate {
669 label: format!("go generate {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
670 command: "go".into(),
671 args: vec!["generate".into()],
672 cwd: package_cwd.clone(),
673 tags: vec!["go-generate".to_owned()],
674 ..TaskTemplate::default()
675 },
676 TaskTemplate {
677 label: "go generate ./...".into(),
678 command: "go".into(),
679 args: vec!["generate".into(), "./...".into()],
680 cwd: module_cwd.clone(),
681 ..TaskTemplate::default()
682 },
683 ])))
684 }
685}
686
687fn extract_subtest_name(input: &str) -> Option<String> {
688 let replaced_spaces = input.trim_matches('"').replace(' ', "_");
689
690 Some(
691 GO_ESCAPE_SUBTEST_NAME_REGEX
692 .replace_all(&replaced_spaces, |caps: ®ex::Captures| {
693 format!("\\{}", &caps[0])
694 })
695 .to_string(),
696 )
697}
698
699#[cfg(test)]
700mod tests {
701 use super::*;
702 use crate::language;
703 use gpui::Hsla;
704 use theme::SyntaxTheme;
705
706 #[gpui::test]
707 async fn test_go_label_for_completion() {
708 let adapter = Arc::new(GoLspAdapter);
709 let language = language("go", tree_sitter_go::LANGUAGE.into());
710
711 let theme = SyntaxTheme::new_test([
712 ("type", Hsla::default()),
713 ("keyword", Hsla::default()),
714 ("function", Hsla::default()),
715 ("number", Hsla::default()),
716 ("property", Hsla::default()),
717 ]);
718 language.set_theme(&theme);
719
720 let grammar = language.grammar().unwrap();
721 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
722 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
723 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
724 let highlight_number = grammar.highlight_id_for_name("number").unwrap();
725
726 assert_eq!(
727 adapter
728 .label_for_completion(
729 &lsp::CompletionItem {
730 kind: Some(lsp::CompletionItemKind::FUNCTION),
731 label: "Hello".to_string(),
732 detail: Some("func(a B) c.D".to_string()),
733 ..Default::default()
734 },
735 &language
736 )
737 .await,
738 Some(CodeLabel {
739 text: "Hello(a B) c.D".to_string(),
740 filter_range: 0..5,
741 runs: vec![
742 (0..5, highlight_function),
743 (8..9, highlight_type),
744 (13..14, highlight_type),
745 ],
746 })
747 );
748
749 // Nested methods
750 assert_eq!(
751 adapter
752 .label_for_completion(
753 &lsp::CompletionItem {
754 kind: Some(lsp::CompletionItemKind::METHOD),
755 label: "one.two.Three".to_string(),
756 detail: Some("func() [3]interface{}".to_string()),
757 ..Default::default()
758 },
759 &language
760 )
761 .await,
762 Some(CodeLabel {
763 text: "one.two.Three() [3]interface{}".to_string(),
764 filter_range: 0..13,
765 runs: vec![
766 (8..13, highlight_function),
767 (17..18, highlight_number),
768 (19..28, highlight_keyword),
769 ],
770 })
771 );
772
773 // Nested fields
774 assert_eq!(
775 adapter
776 .label_for_completion(
777 &lsp::CompletionItem {
778 kind: Some(lsp::CompletionItemKind::FIELD),
779 label: "two.Three".to_string(),
780 detail: Some("a.Bcd".to_string()),
781 ..Default::default()
782 },
783 &language
784 )
785 .await,
786 Some(CodeLabel {
787 text: "two.Three a.Bcd".to_string(),
788 filter_range: 0..9,
789 runs: vec![(12..15, highlight_type)],
790 })
791 );
792 }
793}