Debian Codegraph @

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

raw symbols SCIP
1 // Copyright 2020 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 "os"
10 "path"
11 "path/filepath"
12 "reflect"
13 "regexp"
14 "strings"
15 "testing"
16
17 "github.com/google/go-cmp/cmp"
18 "golang.org/x/tools/gopls/internal/protocol"
19 "golang.org/x/tools/gopls/internal/test/compare"
20 . "golang.org/x/tools/gopls/internal/test/integration"
21 )
22
23 const internalDefinition = `
24 -- go.mod --
25 module mod.com
26
27 go 1.12
28 -- main.go --
29 package main
30
31 import "fmt"
32
33 func main() {
34 fmt.Println(message)
35 }
36 -- const.go --
37 package main
38
39 const message = "Hello World."
40 `
41
42 func TestGoToInternalDefinition(t *testing.T) {
43 Run(t, internalDefinition, func(t *testing.T, env *Env) {
44 env.OpenFile("main.go")
45 loc := env.FirstDefinition(env.RegexpSearch("main.go", "message"))
46 name := env.Sandbox.Workdir.URIToPath(loc.URI)
47 if want := "const.go"; name != want {
48 t.Errorf("Definition: got file %q, want %q", name, want)
49 }
50 if want := env.RegexpSearch("const.go", "message"); loc != want {
51 t.Errorf("Definition: got location %v, want %v", loc, want)
52 }
53 })
54 }
55
56 const linknameDefinition = `
57 -- go.mod --
58 module mod.com
59
60 -- upper/upper.go --
61 package upper
62
63 import (
64 _ "unsafe"
65
66 _ "mod.com/middle"
67 )
68
69 //go:linkname foo mod.com/lower.bar
70 func foo() string
71
72 -- middle/middle.go --
73 package middle
74
75 import (
76 _ "mod.com/lower"
77 )
78
79 -- lower/lower.s --
80
81 -- lower/lower.go --
82 package lower
83
84 func bar() string {
85 return "bar as foo"
86 }`
87
88 func TestGoToLinknameDefinition(t *testing.T) {
89 Run(t, linknameDefinition, func(t *testing.T, env *Env) {
90 env.OpenFile("upper/upper.go")
91
92 // Jump from directives 2nd arg.
93 start := env.RegexpSearch("upper/upper.go", `lower.bar`)
94 loc := env.FirstDefinition(start)
95 name := env.Sandbox.Workdir.URIToPath(loc.URI)
96 if want := "lower/lower.go"; name != want {
97 t.Errorf("Definition: got file %q, want %q", name, want)
98 }
99 if want := env.RegexpSearch("lower/lower.go", `bar`); loc != want {
100 t.Errorf("Definition: got position %v, want %v", loc, want)
101 }
102 })
103 }
104
105 const linknameDefinitionReverse = `
106 -- go.mod --
107 module mod.com
108
109 -- upper/upper.s --
110
111 -- upper/upper.go --
112 package upper
113
114 import (
115 _ "mod.com/middle"
116 )
117
118 func foo() string
119
120 -- middle/middle.go --
121 package middle
122
123 import (
124 _ "mod.com/lower"
125 )
126
127 -- lower/lower.go --
128 package lower
129
130 import _ "unsafe"
131
132 //go:linkname bar mod.com/upper.foo
133 func bar() string {
134 return "bar as foo"
135 }`
136
137 func TestGoToLinknameDefinitionInReverseDep(t *testing.T) {
138 Run(t, linknameDefinitionReverse, func(t *testing.T, env *Env) {
139 env.OpenFile("lower/lower.go")
140
141 // Jump from directives 2nd arg.
142 start := env.RegexpSearch("lower/lower.go", `upper.foo`)
143 loc := env.FirstDefinition(start)
144 name := env.Sandbox.Workdir.URIToPath(loc.URI)
145 if want := "upper/upper.go"; name != want {
146 t.Errorf("Definition: got file %q, want %q", name, want)
147 }
148 if want := env.RegexpSearch("upper/upper.go", `foo`); loc != want {
149 t.Errorf("Definition: got position %v, want %v", loc, want)
150 }
151 })
152 }
153
154 // The linkname directive connects two packages not related in the import graph.
155 const linknameDefinitionDisconnected = `
156 -- go.mod --
157 module mod.com
158
159 -- a/a.go --
160 package a
161
162 import (
163 _ "unsafe"
164 )
165
166 //go:linkname foo mod.com/b.bar
167 func foo() string
168
169 -- b/b.go --
170 package b
171
172 func bar() string {
173 return "bar as foo"
174 }`
175
176 func TestGoToLinknameDefinitionDisconnected(t *testing.T) {
177 Run(t, linknameDefinitionDisconnected, func(t *testing.T, env *Env) {
178 env.OpenFile("a/a.go")
179
180 // Jump from directives 2nd arg.
181 start := env.RegexpSearch("a/a.go", `b.bar`)
182 loc := env.FirstDefinition(start)
183 name := env.Sandbox.Workdir.URIToPath(loc.URI)
184 if want := "b/b.go"; name != want {
185 t.Errorf("Definition: got file %q, want %q", name, want)
186 }
187 if want := env.RegexpSearch("b/b.go", `bar`); loc != want {
188 t.Errorf("Definition: got position %v, want %v", loc, want)
189 }
190 })
191 }
192
193 const stdlibDefinition = `
194 -- go.mod --
195 module mod.com
196
197 go 1.12
198 -- main.go --
199 package main
200
201 import "fmt"
202
203 func main() {
204 fmt.Printf()
205 }`
206
207 func TestGoToStdlibDefinition_Issue37045(t *testing.T) {
208 Run(t, stdlibDefinition, func(t *testing.T, env *Env) {
209 env.OpenFile("main.go")
210 loc := env.FirstDefinition(env.RegexpSearch("main.go", `fmt.(Printf)`))
211 name := env.Sandbox.Workdir.URIToPath(loc.URI)
212 if got, want := path.Base(name), "print.go"; got != want {
213 t.Errorf("Definition: got file %q, want %q", name, want)
214 }
215 env.OpenFile(name)
216
217 // Test that we can jump to definition from outside our workspace.
218 // See golang.org/issues/37045.
219 newLoc := env.FirstDefinition(loc)
220 newName := env.Sandbox.Workdir.URIToPath(newLoc.URI)
221 if newName != name {
222 t.Errorf("Definition is not idempotent: got %q, want %q", newName, name)
223 }
224 if newLoc != loc {
225 t.Errorf("Definition is not idempotent: got %v, want %v", newLoc, loc)
226 }
227 })
228 }
229
230 // This test depends on the internal symbol fmt.newPrinter.
231 // It may need updating as the fmt package evolves.
232 func TestUnexportedStdlib_Issue40809(t *testing.T) {
233 Run(t, stdlibDefinition, func(t *testing.T, env *Env) {
234 env.OpenFile("main.go")
235 loc := env.FirstDefinition(env.RegexpSearch("main.go", `fmt.(Printf)`))
236 name := env.Sandbox.Workdir.URIToPath(loc.URI)
237 env.OpenFile(name)
238
239 loc = env.RegexpSearch(name, `:=\s*(newPrinter)\(.*\)`)
240
241 // Check that we can find references on a reference
242 refs := env.References(loc)
243 if len(refs) < 5 {
244 t.Errorf("expected 5+ references to newPrinter, found: %#v", refs)
245 }
246
247 loc = env.FirstDefinition(loc)
248 content, _ := env.Hover(loc)
249 if !strings.Contains(content.Value, "newPrinter") {
250 t.Fatal("definition of newPrinter went to the incorrect place")
251 }
252 // And on the definition too.
253 refs = env.References(loc)
254 if len(refs) < 5 {
255 t.Errorf("expected 5+ references to newPrinter, found: %#v", refs)
256 }
257 })
258 }
259
260 // Test the hover on an error's Error function.
261 // This can't be done via the marker tests because Error is a builtin.
262 func TestHoverOnError(t *testing.T) {
263 const mod = `
264 -- go.mod --
265 module mod.com
266
267 go 1.12
268 -- main.go --
269 package main
270
271 func main() {
272 var err error
273 err.Error()
274 }`
275 Run(t, mod, func(t *testing.T, env *Env) {
276 env.OpenFile("main.go")
277 content, _ := env.Hover(env.RegexpSearch("main.go", "Error"))
278 if content == nil {
279 t.Fatalf("nil hover content for Error")
280 }
281 want := "```go\nfunc (error).Error() string\n```"
282 if content.Value != want {
283 t.Fatalf("hover failed:\n%s", compare.Text(want, content.Value))
284 }
285 })
286 }
287
288 func TestImportShortcut(t *testing.T) {
289 const mod = `
290 -- go.mod --
291 module mod.com
292
293 go 1.12
294 -- main.go --
295 package main
296
297 import "fmt"
298
299 func main() {}
300 `
301 for _, tt := range []struct {
302 wantLinks int
303 importShortcut string
304 }{
305 {1, "Link"},
306 {0, "Definition"},
307 {1, "Both"},
308 } {
309 t.Run(tt.importShortcut, func(t *testing.T) {
310 WithOptions(
311 Settings{"importShortcut": tt.importShortcut},
312 ).Run(t, mod, func(t *testing.T, env *Env) {
313 env.OpenFile("main.go")
314 loc := env.FirstDefinition(env.RegexpSearch("main.go", `"fmt"`))
315 if loc == (protocol.Location{}) {
316 t.Fatalf("expected definition, got none")
317 }
318 links := env.DocumentLink("main.go")
319 if len(links) != tt.wantLinks {
320 t.Fatalf("expected %v links, got %v", tt.wantLinks, len(links))
321 }
322 })
323 })
324 }
325 }
326
327 // Test for golang/go#47825.
328 func TestImportTestVariant(t *testing.T) {
329 const mod = `
330 -- go.mod --
331 module mod.com
332
333 go 1.12
334 -- client/test/role.go --
335 package test
336
337 import _ "mod.com/client"
338
339 type RoleSetup struct{}
340 -- client/client_role_test.go --
341 package client_test
342
343 import (
344 "testing"
345 _ "mod.com/client"
346 ctest "mod.com/client/test"
347 )
348
349 func TestClient(t *testing.T) {
350 _ = ctest.RoleSetup{}
351 }
352 -- client/client_test.go --
353 package client
354
355 import "testing"
356
357 func TestClient(t *testing.T) {}
358 -- client.go --
359 package client
360 `
361 Run(t, mod, func(t *testing.T, env *Env) {
362 env.OpenFile("client/client_role_test.go")
363 env.FirstDefinition(env.RegexpSearch("client/client_role_test.go", "RoleSetup"))
364 })
365 }
366
367 // This test exercises a crashing pattern from golang/go#49223.
368 func TestGoToCrashingDefinition_Issue49223(t *testing.T) {
369 Run(t, "", func(t *testing.T, env *Env) {
370 params := &protocol.DefinitionParams{}
371 params.TextDocument.URI = protocol.DocumentURI("fugitive%3A///Users/user/src/mm/ems/.git//0/pkg/domain/treasury/provider.go")
372 params.Position.Character = 18
373 params.Position.Line = 0
374 env.Editor.Server.Definition(env.Ctx, params) // ignore error
375 })
376 }
377
378 // TestVendoringInvalidatesMetadata ensures that gopls uses the
379 // correct metadata even after an external 'go mod vendor' command
380 // causes packages to move; see issue #55995.
381 // See also TestImplementationsInVendor, which tests the same fix.
382 func TestVendoringInvalidatesMetadata(t *testing.T) {
383 t.Skip("golang/go#56169: file watching does not capture vendor dirs")
384
385 const proxy = `
386 -- other.com/[email protected]/go.mod --
387 module other.com/b
388 go 1.14
389
390 -- other.com/[email protected]/b.go --
391 package b
392 const K = 0
393 `
394 const src = `
395 -- go.mod --
396 module example.com/a
397 go 1.14
398 require other.com/b v1.0.0
399
400 -- a.go --
401 package a
402 import "other.com/b"
403 const _ = b.K
404
405 `
406 WithOptions(
407 WriteGoSum("."),
408 ProxyFiles(proxy),
409 Modes(Default), // fails in 'experimental' mode
410 ).Run(t, src, func(t *testing.T, env *Env) {
411 // Enable to debug go.sum mismatch, which may appear as
412 // "module lookup disabled by GOPROXY=off", confusingly.
413 if false {
414 env.DumpGoSum(".")
415 }
416
417 env.OpenFile("a.go")
418 refLoc := env.RegexpSearch("a.go", "K") // find "b.K" reference
419
420 // Initially, b.K is defined in the module cache.
421 gotLoc := env.FirstDefinition(refLoc)
422 gotFile := env.Sandbox.Workdir.URIToPath(gotLoc.URI)
423 wantCache := filepath.ToSlash(env.Sandbox.GOPATH()) + "/pkg/mod/other.com/[email protected]/b.go"
424 if gotFile != wantCache {
425 t.Errorf("Definition, before: got file %q, want %q", gotFile, wantCache)
426 }
427
428 // Run 'go mod vendor' outside the editor.
429 env.RunGoCommand("mod", "vendor")
430
431 // Synchronize changes to watched files.
432 env.Await(env.DoneWithChangeWatchedFiles())
433
434 // Now, b.K is defined in the vendor tree.
435 gotLoc = env.FirstDefinition(refLoc)
436 wantVendor := "vendor/other.com/b/b.go"
437 if gotFile != wantVendor {
438 t.Errorf("Definition, after go mod vendor: got file %q, want %q", gotFile, wantVendor)
439 }
440
441 // Delete the vendor tree.
442 if err := os.RemoveAll(env.Sandbox.Workdir.AbsPath("vendor")); err != nil {
443 t.Fatal(err)
444 }
445 // Notify the server of the deletion.
446 if err := env.Sandbox.Workdir.CheckForFileChanges(env.Ctx); err != nil {
447 t.Fatal(err)
448 }
449
450 // Synchronize again.
451 env.Await(env.DoneWithChangeWatchedFiles())
452
453 // b.K is once again defined in the module cache.
454 gotLoc = env.FirstDefinition(gotLoc)
455 gotFile = env.Sandbox.Workdir.URIToPath(gotLoc.URI)
456 if gotFile != wantCache {
457 t.Errorf("Definition, after rm -rf vendor: got file %q, want %q", gotFile, wantCache)
458 }
459 })
460 }
461
462 const embedDefinition = `
463 -- go.mod --
464 module mod.com
465
466 -- main.go --
467 package main
468
469 import (
470 "embed"
471 )
472
473 //go:embed *.txt
474 var foo embed.FS
475
476 func main() {}
477
478 -- skip.sql --
479 SKIP
480
481 -- foo.txt --
482 FOO
483
484 -- skip.bat --
485 SKIP
486 `
487
488 func TestEmbedDefinition(t *testing.T) {
489 Run(t, embedDefinition, func(t *testing.T, env *Env) {
490 env.OpenFile("main.go")
491
492 start := env.RegexpSearch("main.go", `\*.txt`)
493 loc := env.FirstDefinition(start)
494
495 name := env.Sandbox.Workdir.URIToPath(loc.URI)
496 if want := "foo.txt"; name != want {
497 t.Errorf("Definition: got file %q, want %q", name, want)
498 }
499 })
500 }
501
502 func TestDefinitionOfErrorErrorMethod(t *testing.T) {
503 const src = `Regression test for a panic in definition of error.Error (of course).
504 golang/go#64086
505
506 -- go.mod --
507 module mod.com
508 go 1.18
509
510 -- a.go --
511 package a
512
513 func _(err error) {
514 _ = err.Error()
515 }
516
517 `
518 Run(t, src, func(t *testing.T, env *Env) {
519 env.OpenFile("a.go")
520
521 start := env.RegexpSearch("a.go", `Error`)
522 loc := env.FirstDefinition(start)
523
524 if !strings.HasSuffix(string(loc.URI), "builtin.go") {
525 t.Errorf("Definition(err.Error) = %#v, want builtin.go", loc)
526 }
527 })
528 }
529
530 func TestAssemblyDefinition(t *testing.T) {
531 // This test cannot be expressed as a marker test because
532 // the expect package ignores markers (@loc) within a .s file.
533 const src = `
534 -- go.mod --
535 module mod.com
536
537 -- foo_darwin_arm64.s --
538
539 // assembly implementation
540 TEXT ·foo(SB),NOSPLIT,$0
541 RET
542
543 -- a.go --
544 //go:build darwin && arm64
545
546 package a
547
548 // Go declaration
549 func foo(int) int
550
551 var _ = foo(123) // call
552 `
553 Run(t, src, func(t *testing.T, env *Env) {
554 env.OpenFile("a.go")
555
556 locString := func(loc protocol.Location) string {
557 return fmt.Sprintf("%s:%s", loc.URI.Base(), loc.Range)
558 }
559
560 // Definition at the call"foo(123)" takes us to the Go declaration.
561 callLoc := env.RegexpSearch("a.go", regexp.QuoteMeta("foo(123)"))
562 declLoc := env.FirstDefinition(callLoc)
563 if got, want := locString(declLoc), "a.go:5:5-5:8"; got != want {
564 t.Errorf("Definition(call): got %s, want %s", got, want)
565 }
566
567 // Definition a second time takes us to the assembly implementation.
568 implLoc := env.FirstDefinition(declLoc)
569 if got, want := locString(implLoc), "foo_darwin_arm64.s:2:6-2:9"; got != want {
570 t.Errorf("Definition(go decl): got %s, want %s", got, want)
571 }
572 })
573 }
574
575 func TestPackageKeyInvalidationAfterSave(t *testing.T) {
576 // This test is a little subtle, but catches a bug that slipped through
577 // testing of https://go.dev/cl/614165, which moved active packages to the
578 // packageHandle.
579 //
580 // The bug was that after a format-and-save operation, the save marks the
581 // package as dirty but doesn't change its identity. In other words, this is
582 // the sequence of change:
583 //
584 // S_0 --format--> S_1 --save--> S_2
585 //
586 // A package is computed on S_0, invalidated in S_1 and immediately
587 // invalidated again in S_2. Due to an invalidation bug, the validity of the
588 // package from S_0 was checked by comparing the identical keys of S_1 and
589 // S_2, and so the stale package from S_0 was marked as valid.
590 const src = `
591 -- go.mod --
592 module mod.com
593
594 -- a.go --
595 package a
596
597 func Foo() {
598 }
599 `
600 Run(t, src, func(t *testing.T, env *Env) {
601 env.OpenFile("a.go")
602
603 fooLoc := env.RegexpSearch("a.go", "()Foo")
604 loc0 := env.FirstDefinition(fooLoc)
605
606 // Insert a space that will be removed by formatting.
607 env.EditBuffer("a.go", protocol.TextEdit{
608 Range: fooLoc.Range,
609 NewText: " ",
610 })
611 env.SaveBuffer("a.go") // reformats the file before save
612 env.AfterChange()
613 loc1 := env.FirstDefinition(env.RegexpSearch("a.go", "Foo"))
614 if diff := cmp.Diff(loc0, loc1); diff != "" {
615 t.Errorf("mismatching locations (-want +got):\n%s", diff)
616 }
617 })
618 }
619
620 func TestCommentDefinition_Issue69616(t *testing.T) {
621 // This test exercises a few edge cases discovered by telemetry in
622 // golang/go#69616, namely situations where a parsed Go file might
623 // not have an associated scope in the package types.Info.
624 //
625 // The files below set up two types of edge cases:
626 // - a 'compiled' Go file that isn't actually type-checked, because it has
627 // the wrong package name
628 // - a non-compiled Go file (unsafe.go).
629 const src = `
630 -- go.mod --
631 module mod.com
632
633 go 1.21
634 -- cmd/main.go --
635 package main
636
637 import "unsafe"
638
639 var _ = unsafe.Offsetof
640
641 func Foo() {}
642 -- cmd/x.go --
643 package x
644
645 // Bar is like [Foo]
646 func Bar() {}
647 `
648
649 Run(t, src, func(t *testing.T, env *Env) {
650 // First, check that we don't produce a crash or bug when
651 // finding definitions in a 'compiled' go file that isn't actually type
652 // checked.
653 env.OpenFile("cmd/x.go")
654 _, _ = env.Editor.Definitions(env.Ctx, env.RegexpSearch("cmd/x.go", "()Foo"))
655
656 // Next, go to the unsafe package, and find the doc link to [Sizeof].
657 // It will also fail to resolve, because unsafe.go isn't compiled, but
658 // again should not panic or result in a bug.
659 env.OpenFile("cmd/main.go")
660 loc := env.FirstDefinition(env.RegexpSearch("cmd/main.go", `unsafe\.(Offsetof)`))
661 unsafePath := loc.URI.Path()
662 env.OpenFile(unsafePath)
663 _, _ = env.Editor.Definitions(env.Ctx,
664 env.RegexpSearch(unsafePath, `\[()Sizeof\]`))
665 })
666 }
667 func TestUndefinedLabel_Issue76625(t *testing.T) {
668 const src = `
669 -- go.mod --
670 module mod.com
671
672 go 1.22
673 -- a.go --
674 package a
675
676 func UndefinedLabel() {
677 for i := range 10 {
678 if i > 2 {
679 goto undefinedLabel
680 }
681 }
682 }
683 `
684 Run(t, src, func(t *testing.T, env *Env) {
685 env.OpenFile("a.go")
686 expectedErr := "undefined label"
687 gotoUndefined := env.RegexpSearch("a.go", `goto`)
688 _, err := env.Editor.Definitions(env.Ctx, gotoUndefined)
689 if err == nil {
690 t.Fatalf("request succeeded unexpectedly, want error %s", err)
691 }
692 if !strings.Contains(err.Error(), expectedErr) {
693 t.Fatalf("received unexpected error message %s, want %s", err, expectedErr)
694 }
695 })
696
697 }
698
699 func TestDefinition_embedSeparator(t *testing.T) {
700 // This test checks that Definition on a //go:embed glob pattern reports
701 // the location of the (first) matching file. It is a regression test for
702 // a path-separator bug on Windows (https://go.dev/issue/77131).
703 //
704 // It can't be expressed as a marker test because it would require
705 // a @def marker within a //go:embed directive.
706 const src = `
707 -- go.mod --
708 module example.com
709 go 1.22
710
711 -- a/subdir/embed.txt --
712 hello
713
714 -- a/a.go --
715 package a
716
717 import _ "embed"
718
719 //go:embed subdir/embed.txt
720 var _ string
721 `
722 Run(t, src, func(t *testing.T, env *Env) {
723 env.OpenFile("a/a.go")
724 loc := env.FirstDefinition(env.RegexpSearch("a/a.go", "subdir"))
725 got := fileLocations(env, []protocol.Location{loc})
726 want := []string{"a/subdir/embed.txt:1"}
727 if !reflect.DeepEqual(got, want) {
728 t.Errorf("Definition at 'subdir' returned %v, want %v", got, want)
729 }
730 })
731 }