go.rs

  1use anyhow::{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::{InitializeParams, 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        atomic::{AtomicBool, Ordering::SeqCst},
 23        Arc, LazyLock,
 24    },
 25};
 26use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
 27use util::{fs::remove_matching, maybe, ResultExt};
 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(|cx| async move {
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                return Err(anyhow!("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
171            return Err(anyhow!("failed to install gopls with `go install`. Is `go` installed and in the PATH? Check logs for more information."));
172        }
173
174        let installed_binary_path = gobin_dir.join(BINARY);
175        let version_output = util::command::new_smol_command(&installed_binary_path)
176            .arg("version")
177            .output()
178            .await
179            .context("failed to run installed gopls binary")?;
180        let gopls_version = parse_version_output(&version_output)?;
181        let binary_path = container_dir.join(format!("gopls_{gopls_version}_go_{go_version}"));
182        fs::rename(&installed_binary_path, &binary_path).await?;
183
184        Ok(LanguageServerBinary {
185            path: binary_path.to_path_buf(),
186            arguments: server_binary_arguments(),
187            env: None,
188        })
189    }
190
191    async fn cached_server_binary(
192        &self,
193        container_dir: PathBuf,
194        _: &dyn LspAdapterDelegate,
195    ) -> Option<LanguageServerBinary> {
196        get_cached_server_binary(container_dir).await
197    }
198
199    async fn initialization_options(
200        self: Arc<Self>,
201        _: &dyn Fs,
202        _: &Arc<dyn LspAdapterDelegate>,
203    ) -> Result<Option<serde_json::Value>> {
204        Ok(Some(json!({
205            "usePlaceholders": true,
206            "hints": {
207                "assignVariableTypes": true,
208                "compositeLiteralFields": true,
209                "compositeLiteralTypes": true,
210                "constantValues": true,
211                "functionTypeParameters": true,
212                "parameterNames": true,
213                "rangeVariableTypes": true
214            }
215        })))
216    }
217
218    async fn label_for_completion(
219        &self,
220        completion: &lsp::CompletionItem,
221        language: &Arc<Language>,
222    ) -> Option<CodeLabel> {
223        let label = &completion.label;
224
225        // Gopls returns nested fields and methods as completions.
226        // To syntax highlight these, combine their final component
227        // with their detail.
228        let name_offset = label.rfind('.').unwrap_or(0);
229
230        match completion.kind.zip(completion.detail.as_ref()) {
231            Some((lsp::CompletionItemKind::MODULE, detail)) => {
232                let text = format!("{label} {detail}");
233                let source = Rope::from(format!("import {text}").as_str());
234                let runs = language.highlight_text(&source, 7..7 + text.len());
235                return Some(CodeLabel {
236                    text,
237                    runs,
238                    filter_range: 0..label.len(),
239                });
240            }
241            Some((
242                lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE,
243                detail,
244            )) => {
245                let text = format!("{label} {detail}");
246                let source =
247                    Rope::from(format!("var {} {}", &text[name_offset..], detail).as_str());
248                let runs = adjust_runs(
249                    name_offset,
250                    language.highlight_text(&source, 4..4 + text.len()),
251                );
252                return Some(CodeLabel {
253                    text,
254                    runs,
255                    filter_range: 0..label.len(),
256                });
257            }
258            Some((lsp::CompletionItemKind::STRUCT, _)) => {
259                let text = format!("{label} struct {{}}");
260                let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
261                let runs = adjust_runs(
262                    name_offset,
263                    language.highlight_text(&source, 5..5 + text.len()),
264                );
265                return Some(CodeLabel {
266                    text,
267                    runs,
268                    filter_range: 0..label.len(),
269                });
270            }
271            Some((lsp::CompletionItemKind::INTERFACE, _)) => {
272                let text = format!("{label} interface {{}}");
273                let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
274                let runs = adjust_runs(
275                    name_offset,
276                    language.highlight_text(&source, 5..5 + text.len()),
277                );
278                return Some(CodeLabel {
279                    text,
280                    runs,
281                    filter_range: 0..label.len(),
282                });
283            }
284            Some((lsp::CompletionItemKind::FIELD, detail)) => {
285                let text = format!("{label} {detail}");
286                let source =
287                    Rope::from(format!("type T struct {{ {} }}", &text[name_offset..]).as_str());
288                let runs = adjust_runs(
289                    name_offset,
290                    language.highlight_text(&source, 16..16 + text.len()),
291                );
292                return Some(CodeLabel {
293                    text,
294                    runs,
295                    filter_range: 0..label.len(),
296                });
297            }
298            Some((lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD, detail)) => {
299                if let Some(signature) = detail.strip_prefix("func") {
300                    let text = format!("{label}{signature}");
301                    let source = Rope::from(format!("func {} {{}}", &text[name_offset..]).as_str());
302                    let runs = adjust_runs(
303                        name_offset,
304                        language.highlight_text(&source, 5..5 + text.len()),
305                    );
306                    return Some(CodeLabel {
307                        filter_range: 0..label.len(),
308                        text,
309                        runs,
310                    });
311                }
312            }
313            _ => {}
314        }
315        None
316    }
317
318    async fn label_for_symbol(
319        &self,
320        name: &str,
321        kind: lsp::SymbolKind,
322        language: &Arc<Language>,
323    ) -> Option<CodeLabel> {
324        let (text, filter_range, display_range) = match kind {
325            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
326                let text = format!("func {} () {{}}", name);
327                let filter_range = 5..5 + name.len();
328                let display_range = 0..filter_range.end;
329                (text, filter_range, display_range)
330            }
331            lsp::SymbolKind::STRUCT => {
332                let text = format!("type {} struct {{}}", name);
333                let filter_range = 5..5 + name.len();
334                let display_range = 0..text.len();
335                (text, filter_range, display_range)
336            }
337            lsp::SymbolKind::INTERFACE => {
338                let text = format!("type {} interface {{}}", name);
339                let filter_range = 5..5 + name.len();
340                let display_range = 0..text.len();
341                (text, filter_range, display_range)
342            }
343            lsp::SymbolKind::CLASS => {
344                let text = format!("type {} T", name);
345                let filter_range = 5..5 + name.len();
346                let display_range = 0..filter_range.end;
347                (text, filter_range, display_range)
348            }
349            lsp::SymbolKind::CONSTANT => {
350                let text = format!("const {} = nil", name);
351                let filter_range = 6..6 + name.len();
352                let display_range = 0..filter_range.end;
353                (text, filter_range, display_range)
354            }
355            lsp::SymbolKind::VARIABLE => {
356                let text = format!("var {} = nil", name);
357                let filter_range = 4..4 + name.len();
358                let display_range = 0..filter_range.end;
359                (text, filter_range, display_range)
360            }
361            lsp::SymbolKind::MODULE => {
362                let text = format!("package {}", name);
363                let filter_range = 8..8 + name.len();
364                let display_range = 0..filter_range.end;
365                (text, filter_range, display_range)
366            }
367            _ => return None,
368        };
369
370        Some(CodeLabel {
371            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
372            text: text[display_range].to_string(),
373            filter_range,
374        })
375    }
376    fn prepare_initialize_params(
377        &self,
378        mut original: InitializeParams,
379    ) -> Result<InitializeParams> {
380        #[allow(deprecated)]
381        let _ = original.root_uri.take();
382        Ok(original)
383    }
384}
385
386fn parse_version_output(output: &Output) -> Result<&str> {
387    let version_stdout =
388        str::from_utf8(&output.stdout).context("version command produced invalid utf8 output")?;
389
390    let version = VERSION_REGEX
391        .find(version_stdout)
392        .with_context(|| format!("failed to parse version output '{version_stdout}'"))?
393        .as_str();
394
395    Ok(version)
396}
397
398async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
399    maybe!(async {
400        let mut last_binary_path = None;
401        let mut entries = fs::read_dir(&container_dir).await?;
402        while let Some(entry) = entries.next().await {
403            let entry = entry?;
404            if entry.file_type().await?.is_file()
405                && entry
406                    .file_name()
407                    .to_str()
408                    .map_or(false, |name| name.starts_with("gopls_"))
409            {
410                last_binary_path = Some(entry.path());
411            }
412        }
413
414        if let Some(path) = last_binary_path {
415            Ok(LanguageServerBinary {
416                path,
417                arguments: server_binary_arguments(),
418                env: None,
419            })
420        } else {
421            Err(anyhow!("no cached binary"))
422        }
423    })
424    .await
425    .log_err()
426}
427
428fn adjust_runs(
429    delta: usize,
430    mut runs: Vec<(Range<usize>, HighlightId)>,
431) -> Vec<(Range<usize>, HighlightId)> {
432    for (range, _) in &mut runs {
433        range.start += delta;
434        range.end += delta;
435    }
436    runs
437}
438
439pub(crate) struct GoContextProvider;
440
441const GO_PACKAGE_TASK_VARIABLE: VariableName = VariableName::Custom(Cow::Borrowed("GO_PACKAGE"));
442const GO_MODULE_ROOT_TASK_VARIABLE: VariableName =
443    VariableName::Custom(Cow::Borrowed("GO_MODULE_ROOT"));
444const GO_SUBTEST_NAME_TASK_VARIABLE: VariableName =
445    VariableName::Custom(Cow::Borrowed("GO_SUBTEST_NAME"));
446
447impl ContextProvider for GoContextProvider {
448    fn build_context(
449        &self,
450        variables: &TaskVariables,
451        location: &Location,
452        _: Option<HashMap<String, String>>,
453        _: Arc<dyn LanguageToolchainStore>,
454        cx: &mut gpui::App,
455    ) -> Task<Result<TaskVariables>> {
456        let local_abs_path = location
457            .buffer
458            .read(cx)
459            .file()
460            .and_then(|file| Some(file.as_local()?.abs_path(cx)));
461
462        let go_package_variable = local_abs_path
463            .as_deref()
464            .and_then(|local_abs_path| local_abs_path.parent())
465            .map(|buffer_dir| {
466                // Prefer the relative form `./my-nested-package/is-here` over
467                // absolute path, because it's more readable in the modal, but
468                // the absolute path also works.
469                let package_name = variables
470                    .get(&VariableName::WorktreeRoot)
471                    .and_then(|worktree_abs_path| buffer_dir.strip_prefix(worktree_abs_path).ok())
472                    .map(|relative_pkg_dir| {
473                        if relative_pkg_dir.as_os_str().is_empty() {
474                            ".".into()
475                        } else {
476                            format!("./{}", relative_pkg_dir.to_string_lossy())
477                        }
478                    })
479                    .unwrap_or_else(|| format!("{}", buffer_dir.to_string_lossy()));
480
481                (GO_PACKAGE_TASK_VARIABLE.clone(), package_name.to_string())
482            });
483
484        let go_module_root_variable = local_abs_path
485            .as_deref()
486            .and_then(|local_abs_path| local_abs_path.parent())
487            .map(|buffer_dir| {
488                // Walk dirtree up until getting the first go.mod file
489                let module_dir = buffer_dir
490                    .ancestors()
491                    .find(|dir| dir.join("go.mod").is_file())
492                    .map(|dir| dir.to_string_lossy().to_string())
493                    .unwrap_or_else(|| ".".to_string());
494
495                (GO_MODULE_ROOT_TASK_VARIABLE.clone(), module_dir)
496            });
497
498        let _subtest_name = variables.get(&VariableName::Custom(Cow::Borrowed("_subtest_name")));
499
500        let go_subtest_variable = extract_subtest_name(_subtest_name.unwrap_or(""))
501            .map(|subtest_name| (GO_SUBTEST_NAME_TASK_VARIABLE.clone(), subtest_name));
502
503        Task::ready(Ok(TaskVariables::from_iter(
504            [
505                go_package_variable,
506                go_subtest_variable,
507                go_module_root_variable,
508            ]
509            .into_iter()
510            .flatten(),
511        )))
512    }
513
514    fn associated_tasks(
515        &self,
516        _: Option<Arc<dyn language::File>>,
517        _: &App,
518    ) -> Option<TaskTemplates> {
519        let package_cwd = if GO_PACKAGE_TASK_VARIABLE.template_value() == "." {
520            None
521        } else {
522            Some("$ZED_DIRNAME".to_string())
523        };
524        let module_cwd = Some(GO_MODULE_ROOT_TASK_VARIABLE.template_value());
525
526        Some(TaskTemplates(vec![
527            TaskTemplate {
528                label: format!(
529                    "go test {} -run {}",
530                    GO_PACKAGE_TASK_VARIABLE.template_value(),
531                    VariableName::Symbol.template_value(),
532                ),
533                command: "go".into(),
534                args: vec![
535                    "test".into(),
536                    "-run".into(),
537                    format!("^{}\\$", VariableName::Symbol.template_value(),),
538                ],
539                tags: vec!["go-test".to_owned()],
540                cwd: package_cwd.clone(),
541                ..TaskTemplate::default()
542            },
543            TaskTemplate {
544                label: format!("go test {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
545                command: "go".into(),
546                args: vec!["test".into()],
547                cwd: package_cwd.clone(),
548                ..TaskTemplate::default()
549            },
550            TaskTemplate {
551                label: "go test ./...".into(),
552                command: "go".into(),
553                args: vec!["test".into(), "./...".into()],
554                cwd: module_cwd.clone(),
555                ..TaskTemplate::default()
556            },
557            TaskTemplate {
558                label: format!(
559                    "go test {} -v -run {}/{}",
560                    GO_PACKAGE_TASK_VARIABLE.template_value(),
561                    VariableName::Symbol.template_value(),
562                    GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
563                ),
564                command: "go".into(),
565                args: vec![
566                    "test".into(),
567                    "-v".into(),
568                    "-run".into(),
569                    format!(
570                        "^{}\\$/^{}\\$",
571                        VariableName::Symbol.template_value(),
572                        GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
573                    ),
574                ],
575                cwd: package_cwd.clone(),
576                tags: vec!["go-subtest".to_owned()],
577                ..TaskTemplate::default()
578            },
579            TaskTemplate {
580                label: format!(
581                    "go test {} -bench {}",
582                    GO_PACKAGE_TASK_VARIABLE.template_value(),
583                    VariableName::Symbol.template_value()
584                ),
585                command: "go".into(),
586                args: vec![
587                    "test".into(),
588                    "-benchmem".into(),
589                    "-run=^$".into(),
590                    "-bench".into(),
591                    format!("^{}\\$", VariableName::Symbol.template_value()),
592                ],
593                cwd: package_cwd.clone(),
594                tags: vec!["go-benchmark".to_owned()],
595                ..TaskTemplate::default()
596            },
597            TaskTemplate {
598                label: format!(
599                    "go test {} -fuzz=Fuzz -run {}",
600                    GO_PACKAGE_TASK_VARIABLE.template_value(),
601                    VariableName::Symbol.template_value(),
602                ),
603                command: "go".into(),
604                args: vec![
605                    "test".into(),
606                    "-fuzz=Fuzz".into(),
607                    "-run".into(),
608                    format!("^{}\\$", VariableName::Symbol.template_value(),),
609                ],
610                tags: vec!["go-fuzz".to_owned()],
611                cwd: package_cwd.clone(),
612                ..TaskTemplate::default()
613            },
614            TaskTemplate {
615                label: format!("go run {}", GO_PACKAGE_TASK_VARIABLE.template_value(),),
616                command: "go".into(),
617                args: vec!["run".into(), ".".into()],
618                cwd: package_cwd.clone(),
619                tags: vec!["go-main".to_owned()],
620                ..TaskTemplate::default()
621            },
622            TaskTemplate {
623                label: format!("go generate {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
624                command: "go".into(),
625                args: vec!["generate".into()],
626                cwd: package_cwd.clone(),
627                tags: vec!["go-generate".to_owned()],
628                ..TaskTemplate::default()
629            },
630            TaskTemplate {
631                label: "go generate ./...".into(),
632                command: "go".into(),
633                args: vec!["generate".into(), "./...".into()],
634                cwd: module_cwd.clone(),
635                ..TaskTemplate::default()
636            },
637        ]))
638    }
639}
640
641fn extract_subtest_name(input: &str) -> Option<String> {
642    let replaced_spaces = input.trim_matches('"').replace(' ', "_");
643
644    Some(
645        GO_ESCAPE_SUBTEST_NAME_REGEX
646            .replace_all(&replaced_spaces, |caps: &regex::Captures| {
647                format!("\\{}", &caps[0])
648            })
649            .to_string(),
650    )
651}
652
653#[cfg(test)]
654mod tests {
655    use super::*;
656    use crate::language;
657    use gpui::Hsla;
658    use theme::SyntaxTheme;
659
660    #[gpui::test]
661    async fn test_go_label_for_completion() {
662        let adapter = Arc::new(GoLspAdapter);
663        let language = language("go", tree_sitter_go::LANGUAGE.into());
664
665        let theme = SyntaxTheme::new_test([
666            ("type", Hsla::default()),
667            ("keyword", Hsla::default()),
668            ("function", Hsla::default()),
669            ("number", Hsla::default()),
670            ("property", Hsla::default()),
671        ]);
672        language.set_theme(&theme);
673
674        let grammar = language.grammar().unwrap();
675        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
676        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
677        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
678        let highlight_number = grammar.highlight_id_for_name("number").unwrap();
679
680        assert_eq!(
681            adapter
682                .label_for_completion(
683                    &lsp::CompletionItem {
684                        kind: Some(lsp::CompletionItemKind::FUNCTION),
685                        label: "Hello".to_string(),
686                        detail: Some("func(a B) c.D".to_string()),
687                        ..Default::default()
688                    },
689                    &language
690                )
691                .await,
692            Some(CodeLabel {
693                text: "Hello(a B) c.D".to_string(),
694                filter_range: 0..5,
695                runs: vec![
696                    (0..5, highlight_function),
697                    (8..9, highlight_type),
698                    (13..14, highlight_type),
699                ],
700            })
701        );
702
703        // Nested methods
704        assert_eq!(
705            adapter
706                .label_for_completion(
707                    &lsp::CompletionItem {
708                        kind: Some(lsp::CompletionItemKind::METHOD),
709                        label: "one.two.Three".to_string(),
710                        detail: Some("func() [3]interface{}".to_string()),
711                        ..Default::default()
712                    },
713                    &language
714                )
715                .await,
716            Some(CodeLabel {
717                text: "one.two.Three() [3]interface{}".to_string(),
718                filter_range: 0..13,
719                runs: vec![
720                    (8..13, highlight_function),
721                    (17..18, highlight_number),
722                    (19..28, highlight_keyword),
723                ],
724            })
725        );
726
727        // Nested fields
728        assert_eq!(
729            adapter
730                .label_for_completion(
731                    &lsp::CompletionItem {
732                        kind: Some(lsp::CompletionItemKind::FIELD),
733                        label: "two.Three".to_string(),
734                        detail: Some("a.Bcd".to_string()),
735                        ..Default::default()
736                    },
737                    &language
738                )
739                .await,
740            Some(CodeLabel {
741                text: "two.Three a.Bcd".to_string(),
742                filter_range: 0..9,
743                runs: vec![(12..15, highlight_type)],
744            })
745        );
746    }
747}