Debian Codegraph @

gopls/internal/test/integration/misc/hover_test.go

raw symbols SCIP
1 // Copyright 2021 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package misc
6
7 import (
8 "fmt"
9 "regexp"
10 "strings"
11 "testing"
12
13 "github.com/google/go-cmp/cmp"
14 "golang.org/x/tools/gopls/internal/protocol"
15 . "golang.org/x/tools/gopls/internal/test/integration"
16 "golang.org/x/tools/gopls/internal/test/integration/fake"
17 )
18
19 func TestHoverUnexported(t *testing.T) {
20 const proxy = `
21 -- golang.org/x/[email protected]/go.mod --
22 module golang.org/x/structs
23
24 go 1.21
25
26 -- golang.org/x/[email protected]/types.go --
27 package structs
28
29 type Mixed struct {
30 // Exported comment
31 Exported int
32 unexported string
33 }
34
35 func printMixed(m Mixed) {
36 println(m)
37 }
38 `
39 const mod = `
40 -- go.mod --
41 module mod.com
42
43 go 1.21
44
45 require golang.org/x/structs v1.0.0
46 -- main.go --
47 package main
48
49 import "golang.org/x/structs"
50
51 func main() {
52 var m structs.Mixed
53 _ = m.Exported
54 }
55 `
56
57 // TODO: use a nested workspace folder here.
58 WithOptions(
59 ProxyFiles(proxy),
60 WriteGoSum("."),
61 ).Run(t, mod, func(t *testing.T, env *Env) {
62 env.OpenFile("main.go")
63 mixedLoc := env.RegexpSearch("main.go", "Mixed")
64 got, _ := env.Hover(mixedLoc)
65 if !strings.Contains(got.Value, "unexported") {
66 t.Errorf("Workspace hover: missing expected field 'unexported'. Got:\n%q", got.Value)
67 }
68
69 cacheLoc := env.FirstDefinition(mixedLoc)
70 cacheFile := env.Sandbox.Workdir.URIToPath(cacheLoc.URI)
71 env.OpenFile(cacheFile)
72 argLoc := env.RegexpSearch(cacheFile, "printMixed.*(Mixed)")
73 got, _ = env.Hover(argLoc)
74 if !strings.Contains(got.Value, "unexported") {
75 t.Errorf("Non-workspace hover: missing expected field 'unexported'. Got:\n%q", got.Value)
76 }
77
78 exportedFieldLoc := env.RegexpSearch("main.go", "Exported")
79 got, _ = env.Hover(exportedFieldLoc)
80 if !strings.Contains(got.Value, "comment") {
81 t.Errorf("Workspace hover: missing comment for field 'Exported'. Got:\n%q", got.Value)
82 }
83 })
84 }
85
86 func TestHoverIntLiteral(t *testing.T) {
87 const source = `
88 -- main.go --
89 package main
90
91 var (
92 bigBin = 0b1001001
93 )
94
95 var hex = 0xe34e
96
97 func main() {
98 }
99 `
100 Run(t, source, func(t *testing.T, env *Env) {
101 env.OpenFile("main.go")
102 hexExpected := "58190"
103 got, _ := env.Hover(env.RegexpSearch("main.go", "0xe"))
104 if got != nil && !strings.Contains(got.Value, hexExpected) {
105 t.Errorf("Hover: missing expected field '%s'. Got:\n%q", hexExpected, got.Value)
106 }
107
108 binExpected := "73"
109 got, _ = env.Hover(env.RegexpSearch("main.go", "0b1"))
110 if got != nil && !strings.Contains(got.Value, binExpected) {
111 t.Errorf("Hover: missing expected field '%s'. Got:\n%q", binExpected, got.Value)
112 }
113 })
114 }
115
116 // Tests that hovering does not trigger the panic in golang/go#48249.
117 func TestPanicInHoverBrokenCode(t *testing.T) {
118 // Note: this test can not be expressed as a marker test, as it must use
119 // content without a trailing newline.
120 const source = `
121 -- main.go --
122 package main
123
124 type Example struct`
125 Run(t, source, func(t *testing.T, env *Env) {
126 env.OpenFile("main.go")
127 env.Editor.Hover(env.Ctx, env.RegexpSearch("main.go", "Example"))
128 })
129 }
130
131 func TestHoverRune_48492(t *testing.T) {
132 const files = `
133 -- go.mod --
134 module mod.com
135
136 go 1.18
137 -- main.go --
138 package main
139 `
140 Run(t, files, func(t *testing.T, env *Env) {
141 env.OpenFile("main.go")
142 env.EditBuffer("main.go", fake.NewEdit(0, 0, 1, 0, "package main\nfunc main() {\nconst x = `\nfoo\n`\n}"))
143 env.Editor.Hover(env.Ctx, env.RegexpSearch("main.go", "foo"))
144 })
145 }
146
147 func TestHoverImport(t *testing.T) {
148 const packageDoc1 = "Package lib1 hover documentation"
149 const packageDoc2 = "Package lib2 hover documentation"
150 tests := []struct {
151 hoverPackage string
152 want string
153 wantError bool
154 }{
155 {
156 "mod.com/lib1",
157 packageDoc1,
158 false,
159 },
160 {
161 "mod.com/lib2",
162 packageDoc2,
163 false,
164 },
165 {
166 "mod.com/lib3",
167 "",
168 false,
169 },
170 {
171 "mod.com/lib4",
172 "",
173 true,
174 },
175 }
176 source := fmt.Sprintf(`
177 -- go.mod --
178 module mod.com
179
180 go 1.12
181 -- lib1/a.go --
182 // %s
183 package lib1
184
185 const C = 1
186
187 -- lib1/b.go --
188 package lib1
189
190 const D = 1
191
192 -- lib2/a.go --
193 // %s
194 package lib2
195
196 const E = 1
197
198 -- lib3/a.go --
199 package lib3
200
201 const F = 1
202
203 -- main.go --
204 package main
205
206 import (
207 "mod.com/lib1"
208 "mod.com/lib2"
209 "mod.com/lib3"
210 "mod.com/lib4"
211 )
212
213 func main() {
214 println("Hello")
215 }
216 `, packageDoc1, packageDoc2)
217 Run(t, source, func(t *testing.T, env *Env) {
218 env.OpenFile("main.go")
219 for _, test := range tests {
220 got, _, err := env.Editor.Hover(env.Ctx, env.RegexpSearch("main.go", test.hoverPackage))
221 if test.wantError {
222 if err == nil {
223 t.Errorf("Hover(%q) succeeded unexpectedly", test.hoverPackage)
224 }
225 } else if !strings.Contains(got.Value, test.want) {
226 t.Errorf("Hover(%q): got:\n%q\nwant:\n%q", test.hoverPackage, got.Value, test.want)
227 }
228 }
229 })
230 }
231
232 func TestHoverPackageIdent(t *testing.T) {
233 const packageDoc1 = "Package lib1 hover documentation"
234 const packageDoc2 = "Package lib2 hover documentation"
235 tests := []struct {
236 hoverIdent string
237 want string
238 wantError bool
239 }{
240 {
241 "lib1",
242 packageDoc1,
243 false,
244 },
245 {
246 "lib2",
247 packageDoc2,
248 false,
249 },
250 {
251 "lib3",
252 "",
253 false,
254 },
255 {
256 "lib4",
257 "",
258 true,
259 },
260 }
261 source := fmt.Sprintf(`
262 -- go.mod --
263 module mod.com
264
265 go 1.12
266 -- lib1/a.go --
267 // %s
268 package lib1
269
270 const C = 1
271
272 -- lib1/b.go --
273 package lib1
274
275 const D = 1
276
277 -- lib2/a.go --
278 // %s
279 package lib2
280
281 const E = 1
282
283 -- lib3/a.go --
284 package lib3
285
286 const F = 1
287
288 -- main.go --
289 package main
290
291 import (
292 "mod.com/lib1"
293 "mod.com/lib2"
294 "mod.com/lib3"
295 "mod.com/lib4"
296 )
297
298 func main() {
299 println(lib1.C)
300 println(lib2.E)
301 println(lib3.F)
302 println(lib4.Z)
303 }
304 `, packageDoc1, packageDoc2)
305 Run(t, source, func(t *testing.T, env *Env) {
306 env.OpenFile("main.go")
307 for _, test := range tests {
308 got, _, err := env.Editor.Hover(env.Ctx, env.RegexpSearch("main.go", "("+test.hoverIdent+")\\."))
309 if test.wantError {
310 if err == nil {
311 t.Errorf("Hover(%q) succeeded unexpectedly", test.hoverIdent)
312 }
313 } else if !strings.Contains(got.Value, test.want) {
314 t.Errorf("Hover(%q): got:\n%q\nwant:\n%q", test.hoverIdent, got.Value, test.want)
315 }
316 }
317 })
318 }
319
320 // for x/tools/gopls: unhandled named anchor on the hover #57048
321 func TestHoverTags(t *testing.T) {
322 const source = `
323 -- go.mod --
324 module mod.com
325
326 go 1.19
327
328 -- lib/a.go --
329
330 // variety of execution modes.
331 //
332 // # Test package setup
333 //
334 // The regression test package uses a couple of uncommon patterns to reduce
335 package lib
336
337 -- a.go --
338 package main
339 import "mod.com/lib"
340
341 const A = 1
342
343 }
344 `
345 Run(t, source, func(t *testing.T, env *Env) {
346 t.Run("tags", func(t *testing.T) {
347 env.OpenFile("a.go")
348 z := env.RegexpSearch("a.go", "lib")
349 t.Logf("%#v", z)
350 got, _ := env.Hover(env.RegexpSearch("a.go", "lib"))
351 if strings.Contains(got.Value, "{#hdr-") {
352 t.Errorf("Hover: got {#hdr- tag:\n%q", got)
353 }
354 })
355 })
356 }
357
358 // This is a regression test for Go issue #57625.
359 func TestHoverModMissingModuleStmt(t *testing.T) {
360 const source = `
361 -- go.mod --
362 go 1.16
363 `
364 Run(t, source, func(t *testing.T, env *Env) {
365 env.OpenFile("go.mod")
366 env.Hover(env.RegexpSearch("go.mod", "go")) // no panic
367 })
368 }
369
370 func TestHoverCompletionMarkdown(t *testing.T) {
371 const source = `
372 -- go.mod --
373 module mod.com
374 go 1.19
375 -- main.go --
376 package main
377 // Just says [hello].
378 //
379 // [hello]: https://en.wikipedia.org/wiki/Hello
380 func Hello() string {
381 Hello() //Here
382 return "hello"
383 }
384 `
385 Run(t, source, func(t *testing.T, env *Env) {
386 // Hover, Completion, and SignatureHelp should all produce markdown
387 // check that the markdown for SignatureHelp and Completion are
388 // the same, and contained in that for Hover (up to trailing \n)
389 env.OpenFile("main.go")
390 loc := env.RegexpSearch("main.go", "func ()Hello")
391 hover, _ := env.Hover(loc)
392 hoverContent := hover.Value
393
394 loc = env.RegexpSearch("main.go", `Hello()\(\) \/\/Here`) // Hello_() //Here
395 completions := env.Completion(loc)
396 signatures := env.SignatureHelp(loc)
397
398 if len(completions.Items) != 1 {
399 t.Errorf("got %d completions, expected 1", len(completions.Items))
400 }
401 if len(signatures.Signatures) != 1 {
402 t.Errorf("got %d signatures, expected 1", len(signatures.Signatures))
403 }
404 item := completions.Items[0].Documentation.Value
405 var itemContent string
406 if x, ok := item.(protocol.MarkupContent); !ok || x.Kind != protocol.Markdown {
407 t.Fatalf("%#v is not markdown", item)
408 } else {
409 itemContent = strings.Trim(x.Value, "\n")
410 }
411 sig := signatures.Signatures[0].Documentation.Value
412 var sigContent string
413 if x, ok := sig.(protocol.MarkupContent); !ok || x.Kind != protocol.Markdown {
414 t.Fatalf("%#v is not markdown", item)
415 } else {
416 sigContent = x.Value
417 }
418 if itemContent != sigContent {
419 t.Errorf("item:%q not sig:%q", itemContent, sigContent)
420 }
421 if !strings.Contains(hoverContent, itemContent) {
422 t.Errorf("hover:%q does not contain sig;%q", hoverContent, sigContent)
423 }
424 })
425 }
426
427 // Test that the generated markdown contains links for Go references.
428 // https://github.com/golang/go/issues/58352
429 func TestHoverLinks(t *testing.T) {
430 const input = `
431 -- go.mod --
432 go 1.19
433 module mod.com
434 -- main.go --
435 package main
436 // [fmt]
437 var A int
438 // [fmt.Println]
439 var B int
440 // [golang.org/x/tools/go/packages.Package.String]
441 var C int
442 `
443 var tests = []struct {
444 pat string
445 ans string
446 }{
447 {"A", "fmt"},
448 {"B", "fmt#Println"},
449 {"C", "golang.org/x/tools/go/packages#Package.String"},
450 }
451 for _, test := range tests {
452 Run(t, input, func(t *testing.T, env *Env) {
453 env.OpenFile("main.go")
454 loc := env.RegexpSearch("main.go", test.pat)
455 hover, _ := env.Hover(loc)
456 hoverContent := hover.Value
457 want := fmt.Sprintf("%s/%s", "https://pkg.go.dev", test.ans)
458 if !strings.Contains(hoverContent, want) {
459 t.Errorf("hover:%q does not contain link %q", hoverContent, want)
460 }
461 })
462 }
463 }
464
465 const linknameHover = `
466 -- go.mod --
467 module mod.com
468
469 -- upper/upper.go --
470 package upper
471
472 import (
473 _ "unsafe"
474 _ "mod.com/lower"
475 )
476
477 //go:linkname foo mod.com/lower.bar
478 func foo() string
479
480 -- lower/lower.go --
481 package lower
482
483 // bar does foo.
484 func bar() string {
485 return "foo by bar"
486 }`
487
488 func TestHoverLinknameDirective(t *testing.T) {
489 Run(t, linknameHover, func(t *testing.T, env *Env) {
490 // Jump from directives 2nd arg.
491 env.OpenFile("upper/upper.go")
492 from := env.RegexpSearch("upper/upper.go", `lower.bar`)
493
494 hover, _ := env.Hover(from)
495 content := hover.Value
496
497 expect := "bar does foo"
498 if !strings.Contains(content, expect) {
499 t.Errorf("hover: %q does not contain: %q", content, expect)
500 }
501 })
502 }
503
504 func TestHoverGoWork_Issue60821(t *testing.T) {
505 const files = `
506 -- go.work --
507 go 1.19
508
509 use (
510 moda
511 modb
512 )
513 -- moda/go.mod --
514
515 `
516 Run(t, files, func(t *testing.T, env *Env) {
517 env.OpenFile("go.work")
518 // Neither of the requests below should crash gopls.
519 _, _, _ = env.Editor.Hover(env.Ctx, env.RegexpSearch("go.work", "moda"))
520 _, _, _ = env.Editor.Hover(env.Ctx, env.RegexpSearch("go.work", "modb"))
521 })
522 }
523
524 const embedHover = `
525 -- go.mod --
526 module mod.com
527 go 1.19
528 -- main.go --
529 package main
530
531 import "embed"
532
533 //go:embed *.txt
534 var foo embed.FS
535
536 func main() {
537 }
538 -- foo.txt --
539 FOO
540 -- bar.txt --
541 BAR
542 -- baz.txt --
543 BAZ
544 -- other.sql --
545 SKIPPED
546 -- dir.txt/skip.txt --
547 SKIPPED
548 `
549
550 func TestHoverEmbedDirective(t *testing.T) {
551 Run(t, embedHover, func(t *testing.T, env *Env) {
552 env.OpenFile("main.go")
553 from := env.RegexpSearch("main.go", `\*.txt`)
554
555 got, _ := env.Hover(from)
556 if got == nil {
557 t.Fatalf("hover over //go:embed arg not found")
558 }
559 content := got.Value
560
561 wants := []string{"foo.txt", "bar.txt", "baz.txt"}
562 for _, want := range wants {
563 if !strings.Contains(content, want) {
564 t.Errorf("hover: %q does not contain: %q", content, want)
565 }
566 }
567
568 // A directory should never be matched, even if it happens to have a matching name.
569 // Content in subdirectories should not match on only one asterisk.
570 skips := []string{"other.sql", "dir.txt", "skip.txt"}
571 for _, skip := range skips {
572 if strings.Contains(content, skip) {
573 t.Errorf("hover: %q should not contain: %q", content, skip)
574 }
575 }
576 })
577 }
578
579 func TestHoverBrokenImport_Issue60592(t *testing.T) {
580 const files = `
581 -- go.mod --
582 module testdata
583 go 1.18
584
585 -- p.go --
586 package main
587
588 import foo "a"
589
590 func _() {
591 foo.Print()
592 }
593
594 `
595 Run(t, files, func(t *testing.T, env *Env) {
596 env.OpenFile("p.go")
597 // This request should not crash gopls.
598 _, _, _ = env.Editor.Hover(env.Ctx, env.RegexpSearch("p.go", "foo[.]"))
599 })
600 }
601
602 func TestHoverInternalLinks(t *testing.T) {
603 const src = `
604 -- main.go --
605 package main
606
607 import "errors"
608
609 func main() {
610 errors.New("oops")
611 }
612 `
613 for _, test := range []struct {
614 linksInHover any // JSON configuration value
615 wantRE string // pattern to match the Hover Markdown output
616 }{
617 {
618 true, // default: use options.LinkTarget domain
619 regexp.QuoteMeta("[`errors.New` on pkg.go.dev](https://pkg.go.dev/errors#New)"),
620 },
621 {
622 "gopls", // use gopls' internal viewer
623 "\\[`errors.New` in gopls doc viewer\\]\\(http://127.0.0.1:[0-9]+/gopls/[^/]+/pkg/errors\\?view=[0-9]+#New\\)",
624 },
625 } {
626 WithOptions(
627 Settings{"linksInHover": test.linksInHover},
628 ).Run(t, src, func(t *testing.T, env *Env) {
629 env.OpenFile("main.go")
630 got, _ := env.Hover(env.RegexpSearch("main.go", "New"))
631 if m, err := regexp.MatchString(test.wantRE, got.Value); err != nil {
632 t.Fatalf("bad regexp in test: %v", err)
633 } else if !m {
634 t.Fatalf("hover output does not match %q; got:\n\n%s", test.wantRE, got.Value)
635 }
636 })
637 }
638 }
639
640 func TestHoverInternalLinksIssue68116(t *testing.T) {
641 // Links for the internal viewer should not include a module version suffix:
642 // the package path and the view are an unambiguous key; see #68116.
643
644 const proxy = `
645 -- [email protected]/go.mod --
646 module example.com
647
648 go 1.12
649
650 -- [email protected]/a/a.go --
651 package a
652
653 // F is a function.
654 func F()
655 `
656
657 const mod = `
658 -- go.mod --
659 module main
660
661 go 1.12
662
663 require example.com v1.2.3
664
665 -- main.go --
666 package main
667
668 import "example.com/a"
669
670 func main() {
671 a.F()
672 }
673 `
674 WithOptions(
675 ProxyFiles(proxy),
676 Settings{"linksInHover": "gopls"},
677 WriteGoSum("."),
678 ).Run(t, mod, func(t *testing.T, env *Env) {
679 env.OpenFile("main.go")
680 got, _ := env.Hover(env.RegexpSearch("main.go", "F"))
681 const wantRE = "\\[`a.F` in gopls doc viewer\\]\\(http://127.0.0.1:[0-9]+/gopls/[^/]+/pkg/example.com/a\\?view=[0-9]+#F\\)" // no version
682 if m, err := regexp.MatchString(wantRE, got.Value); err != nil {
683 t.Fatalf("bad regexp in test: %v", err)
684 } else if !m {
685 t.Fatalf("hover output does not match %q; got:\n\n%s", wantRE, got.Value)
686 }
687 })
688 }
689
690 func TestHoverBuiltinFile(t *testing.T) {
691 // This test verifies that hovering in the builtin file provides the same
692 // hover content as hovering over a use of a builtin.
693
694 const src = `
695 -- p.go --
696 package p
697
698 func _() {
699 const (
700 _ = iota
701 _ = true
702 )
703 var (
704 _ any
705 err error = e{} // avoid nil deref warning
706 )
707 _ = err.Error
708 println("Hello")
709 _ = min(1, 2)
710 }
711
712 // e implements Error, for use above.
713 type e struct{}
714 func (e) Error() string
715 `
716
717 // Test hovering over various builtins with different kinds of declarations.
718 tests := []string{
719 "iota",
720 "true",
721 "any",
722 "error",
723 "Error",
724 "println",
725 "min",
726 }
727
728 Run(t, src, func(t *testing.T, env *Env) {
729 env.OpenFile("p.go")
730 env.AfterChange(NoDiagnostics()) // avoid accidental compiler errors
731
732 for _, builtin := range tests {
733 useLocation := env.RegexpSearch("p.go", builtin)
734 calleeHover, _ := env.Hover(useLocation)
735 declLocation := env.FirstDefinition(useLocation)
736 env.OpenFile(env.Sandbox.Workdir.URIToPath(declLocation.URI))
737 declHover, _ := env.Hover(declLocation)
738 if diff := cmp.Diff(calleeHover, declHover); diff != "" {
739 t.Errorf("Hover mismatch (-callee hover +decl hover):\n%s", diff)
740 }
741 }
742 })
743 }
744
745 func TestHoverStdlibWithAvailableVersion(t *testing.T) {
746 const src = `
747 -- stdlib.go --
748 package stdlib
749
750 import "fmt"
751 import "context"
752 import "crypto"
753 import "regexp"
754 import "go/doc/comment"
755
756 type testRegexp = *regexp.Regexp
757
758 func _() {
759 var ctx context.Context
760 ctx = context.Background()
761 if ctx.Err(); e == context.Canceled {
762 fmt.Println("Canceled")
763 fmt.Printf("%v", crypto.SHA512_224)
764 }
765 _ := fmt.Appendf(make([]byte, 100), "world, %d", 23)
766
767 var re = regexp.MustCompile("\n{2,}")
768 copy := re.Copy()
769 var testRE testRegexp
770 testRE.Longest()
771
772 var pr comment.Printer
773 pr.HeadingID = func(*comment.Heading) string { return "" }
774 }
775 `
776
777 testcases := []struct {
778 symbolRE string // regexp matching symbol to hover over
779 shouldContain bool
780 targetString string
781 }{
782 {"Println", false, "go1.0"}, // package-level func
783 {"Appendf", true, "go1.19"}, // package-level func
784 {"Background", true, "go1.7"}, // package-level func
785 {"Canceled", true, "go1.7"}, // package-level var
786 {"Context", true, "go1.7"}, // package-level type
787 {"SHA512_224", true, "go1.5"}, // package-level const
788 {"Copy", true, "go1.6"}, // method
789 {"Longest", true, "go1.1"}, // method with alias receiver
790 {"HeadingID", true, "go1.19"}, // field
791 }
792
793 Run(t, src, func(t *testing.T, env *Env) {
794 env.OpenFile("stdlib.go")
795 for _, tc := range testcases {
796 content, _ := env.Hover(env.RegexpSearch("stdlib.go", tc.symbolRE))
797 if tc.shouldContain && !strings.Contains(content.Value, tc.targetString) {
798 t.Errorf("Hover(%q) should contain string %s", tc.symbolRE, tc.targetString)
799 }
800 if !tc.shouldContain && strings.Contains(content.Value, tc.targetString) {
801 t.Errorf("Hover(%q) should not contain string %s", tc.symbolRE, tc.targetString)
802 }
803 }
804 })
805 }