go.rs

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