Debian Codegraph @

gopls/internal/test/integration/misc/references_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/filepath"
11 "reflect"
12 "sort"
13 "strings"
14 "testing"
15
16 "github.com/google/go-cmp/cmp"
17 "golang.org/x/tools/gopls/internal/protocol"
18 "golang.org/x/tools/gopls/internal/test/integration"
19 . "golang.org/x/tools/gopls/internal/test/integration"
20 )
21
22 func TestStdlibReferences(t *testing.T) {
23 const files = `
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.Print()
35 }
36 `
37
38 Run(t, files, func(t *testing.T, env *Env) {
39 env.OpenFile("main.go")
40 loc := env.FirstDefinition(env.RegexpSearch("main.go", `fmt.(Print)`))
41 env.OpenFile(env.Sandbox.Workdir.URIToPath(loc.URI))
42 refs, err := env.Editor.References(env.Ctx, loc)
43 if err != nil {
44 t.Fatal(err)
45 }
46 if len(refs) != 2 {
47 // TODO(adonovan): make this assertion less maintainer-hostile.
48 t.Fatalf("got %v reference(s), want 2", len(refs))
49 }
50 // The first reference is guaranteed to be the definition.
51 if got, want := refs[1].URI, env.Sandbox.Workdir.URI("main.go"); got != want {
52 t.Errorf("found reference in %v, wanted %v", got, want)
53 }
54 })
55 }
56
57 // This is a regression test for golang/go#48400 (a panic).
58 func TestReferencesOnErrorMethod(t *testing.T) {
59 // Ideally this would actually return the correct answer,
60 // instead of merely failing gracefully.
61 const files = `
62 -- go.mod --
63 module mod.com
64
65 go 1.12
66 -- main.go --
67 package main
68
69 type t interface {
70 error
71 }
72
73 type s struct{}
74
75 func (*s) Error() string {
76 return ""
77 }
78
79 func _() {
80 var s s
81 _ = s.Error()
82 }
83 `
84 Run(t, files, func(t *testing.T, env *Env) {
85 env.OpenFile("main.go")
86 loc := env.FirstDefinition(env.RegexpSearch("main.go", `Error`))
87 refs, err := env.Editor.References(env.Ctx, loc)
88 if err != nil {
89 t.Fatalf("references on (*s).Error failed: %v", err)
90 }
91 // TODO(adonovan): this test is crying out for marker support in integration tests.
92 var buf strings.Builder
93 for _, ref := range refs {
94 fmt.Fprintf(&buf, "%s %s\n", env.Sandbox.Workdir.URIToPath(ref.URI), ref.Range)
95 }
96 got := buf.String()
97 want := "main.go 8:10-8:15\n" + // (*s).Error decl
98 "main.go 14:7-14:12\n" // s.Error() call
99 if diff := cmp.Diff(want, got); diff != "" {
100 t.Errorf("unexpected references on (*s).Error (-want +got):\n%s", diff)
101 }
102 })
103 }
104
105 func TestDefsRefsBuiltins(t *testing.T) {
106 // TODO(adonovan): add unsafe.{SliceData,String,StringData} in later go versions.
107 const files = `
108 -- go.mod --
109 module example.com
110 go 1.16
111
112 -- a.go --
113 package a
114
115 import "unsafe"
116
117 const _ = iota
118 var _ error
119 var _ int
120 var _ = append()
121 var _ = unsafe.Pointer(nil)
122 var _ = unsafe.Add(nil, nil)
123 var _ = unsafe.Sizeof(0)
124 var _ = unsafe.Alignof(0)
125 var _ = unsafe.Slice(nil, 0)
126 `
127
128 Run(t, files, func(t *testing.T, env *Env) {
129 env.OpenFile("a.go")
130 for name := range strings.FieldsSeq(
131 "iota error int nil append iota Pointer Sizeof Alignof Add Slice") {
132 loc := env.RegexpSearch("a.go", `\b`+name+`\b`)
133
134 // definition -> {builtin,unsafe}.go
135 def := env.FirstDefinition(loc)
136 if (!strings.HasSuffix(string(def.URI), "builtin.go") &&
137 !strings.HasSuffix(string(def.URI), "unsafe.go")) ||
138 def.Range.Start.Line == 0 {
139 t.Errorf("definition(%q) = %v, want {builtin,unsafe}.go",
140 name, def)
141 }
142
143 // "references to (builtin "Foo"|unsafe.Foo) are not supported"
144 _, err := env.Editor.References(env.Ctx, loc)
145 gotErr := fmt.Sprint(err)
146 if !strings.Contains(gotErr, "references to") ||
147 !strings.Contains(gotErr, "not supported") ||
148 !strings.Contains(gotErr, name) {
149 t.Errorf("references(%q) error: got %q, want %q",
150 name, gotErr, "references to ... are not supported")
151 }
152 }
153 })
154 }
155
156 func TestPackageReferences(t *testing.T) {
157 tests := []struct {
158 packageName string
159 wantRefCount int
160 wantFiles []string
161 }{
162 {
163 "lib1",
164 3,
165 []string{
166 "main.go",
167 "lib1/a.go",
168 "lib1/b.go",
169 },
170 },
171 {
172 "lib2",
173 2,
174 []string{
175 "main.go",
176 "lib2/a.go",
177 },
178 },
179 }
180
181 const files = `
182 -- go.mod --
183 module mod.com
184
185 go 1.18
186 -- lib1/a.go --
187 package lib1
188
189 const A = 1
190
191 -- lib1/b.go --
192 package lib1
193
194 const B = 1
195
196 -- lib2/a.go --
197 package lib2
198
199 const C = 1
200
201 -- main.go --
202 package main
203
204 import (
205 "mod.com/lib1"
206 "mod.com/lib2"
207 )
208
209 func main() {
210 println("Hello")
211 }
212 `
213 Run(t, files, func(t *testing.T, env *Env) {
214 for _, test := range tests {
215 file := fmt.Sprintf("%s/a.go", test.packageName)
216 env.OpenFile(file)
217 loc := env.RegexpSearch(file, test.packageName)
218 refs := env.References(loc)
219 if len(refs) != test.wantRefCount {
220 // TODO(adonovan): make this assertion less maintainer-hostile.
221 t.Fatalf("got %v reference(s), want %d", len(refs), test.wantRefCount)
222 }
223 var refURIs []string
224 for _, ref := range refs {
225 refURIs = append(refURIs, string(ref.URI))
226 }
227 for _, base := range test.wantFiles {
228 hasBase := false
229 for _, ref := range refURIs {
230 if strings.HasSuffix(ref, base) {
231 hasBase = true
232 break
233 }
234 }
235 if !hasBase {
236 t.Fatalf("got [%v], want reference ends with \"%v\"", strings.Join(refURIs, ","), base)
237 }
238 }
239 }
240 })
241 }
242
243 // Test for golang/go#43144.
244 //
245 // Verify that we search for references and implementations in intermediate
246 // test variants.
247 func TestReferencesInTestVariants(t *testing.T) {
248 const files = `
249 -- go.mod --
250 module foo.mod
251
252 go 1.12
253 -- foo/foo.go --
254 package foo
255
256 import "foo.mod/bar"
257
258 const Foo = 42
259
260 type T int
261 type InterfaceM interface{ M() }
262 type InterfaceF interface{ F() }
263
264 func _() {
265 _ = bar.Blah
266 }
267
268 -- foo/foo_test.go --
269 package foo
270
271 type Fer struct{}
272 func (Fer) F() {}
273
274 -- bar/bar.go --
275 package bar
276
277 var Blah = 123
278
279 -- bar/bar_test.go --
280 package bar
281
282 type Mer struct{}
283 func (Mer) M() {}
284
285 func TestBar() {
286 _ = Blah
287 }
288 -- bar/bar_x_test.go --
289 package bar_test
290
291 import (
292 "foo.mod/bar"
293 "foo.mod/foo"
294 )
295
296 type Mer struct{}
297 func (Mer) M() {}
298
299 func _() {
300 _ = bar.Blah
301 _ = foo.Foo
302 }
303 `
304
305 Run(t, files, func(t *testing.T, env *Env) {
306 env.OpenFile("foo/foo.go")
307
308 refTests := []struct {
309 re string
310 wantRefs []string
311 }{
312 // Blah is referenced:
313 // - inside the foo.mod/bar (ordinary) package
314 // - inside the foo.mod/bar [foo.mod/bar.test] test variant package
315 // - from the foo.mod/bar_test [foo.mod/bar.test] x_test package
316 // - from the foo.mod/foo package
317 {"Blah", []string{"bar/bar.go:3", "bar/bar_test.go:7", "bar/bar_x_test.go:12", "foo/foo.go:12"}},
318
319 // Foo is referenced in bar_x_test.go via the intermediate test variant
320 // foo.mod/foo [foo.mod/bar.test].
321 {"Foo", []string{"bar/bar_x_test.go:13", "foo/foo.go:5"}},
322 }
323
324 for _, test := range refTests {
325 loc := env.RegexpSearch("foo/foo.go", test.re)
326 refs := env.References(loc)
327
328 got := fileLocations(env, refs)
329 if diff := cmp.Diff(test.wantRefs, got); diff != "" {
330 t.Errorf("References(%q) returned unexpected diff (-want +got):\n%s", test.re, diff)
331 }
332 }
333
334 implTests := []struct {
335 re string
336 wantImpls []string
337 }{
338 // InterfaceM is implemented both in foo.mod/bar [foo.mod/bar.test] (which
339 // doesn't import foo), and in foo.mod/bar_test [foo.mod/bar.test], which
340 // imports the test variant of foo.
341 {"InterfaceM", []string{"bar/bar_test.go:3", "bar/bar_x_test.go:8"}},
342
343 // A search within the ordinary package to should find implementations
344 // (Fer) within the augmented test package.
345 {"InterfaceF", []string{"foo/foo_test.go:3"}},
346 }
347
348 for _, test := range implTests {
349 loc := env.RegexpSearch("foo/foo.go", test.re)
350 impls := env.Implementations(loc)
351
352 got := fileLocations(env, impls)
353 if diff := cmp.Diff(test.wantImpls, got); diff != "" {
354 t.Errorf("Implementations(%q) returned unexpected diff (-want +got):\n%s", test.re, diff)
355 }
356 }
357 })
358 }
359
360 // This is a regression test for Issue #56169, in which interface
361 // implementations in vendored modules were not found. The actual fix
362 // was the same as for #55995; see TestVendoringInvalidatesMetadata.
363 func TestImplementationsInVendor(t *testing.T) {
364 const proxy = `
365 -- other.com/[email protected]/go.mod --
366 module other.com/b
367 go 1.14
368
369 -- other.com/[email protected]/b.go --
370 package b
371 type B int
372 func (B) F() {}
373 `
374 const src = `
375 -- go.mod --
376 module example.com/a
377 go 1.14
378 require other.com/b v1.0.0
379
380 -- a.go --
381 package a
382 import "other.com/b"
383 type I interface { F() }
384 var _ b.B
385
386 `
387 WithOptions(
388 WriteGoSum("."),
389 ProxyFiles(proxy),
390 Modes(Default), // fails in 'experimental' mode
391 ).Run(t, src, func(t *testing.T, env *Env) {
392 // Enable to debug go.sum mismatch, which may appear as
393 // "module lookup disabled by GOPROXY=off", confusingly.
394 if false {
395 env.DumpGoSum(".")
396 }
397
398 checkVendor := func(locs []protocol.Location, wantVendor bool) {
399 if len(locs) != 1 {
400 t.Errorf("got %d locations, want 1", len(locs))
401 } else if strings.Contains(string(locs[0].URI), "/vendor/") != wantVendor {
402 t.Errorf("got location %s, wantVendor=%t", locs[0], wantVendor)
403 }
404 }
405
406 env.OpenFile("a.go")
407 refLoc := env.RegexpSearch("a.go", "I") // find "I" reference
408
409 // Initially, a.I has one implementation b.B in
410 // the module cache, not the vendor tree.
411 checkVendor(env.Implementations(refLoc), false)
412
413 // Run 'go mod vendor' outside the editor.
414 env.RunGoCommand("mod", "vendor")
415
416 // Synchronize changes to watched files.
417 env.Await(env.DoneWithChangeWatchedFiles())
418
419 // Now, b.B is found in the vendor tree.
420 checkVendor(env.Implementations(refLoc), true)
421
422 // Delete the vendor tree.
423 if err := os.RemoveAll(env.Sandbox.Workdir.AbsPath("vendor")); err != nil {
424 t.Fatal(err)
425 }
426 // Notify the server of the deletion.
427 if err := env.Sandbox.Workdir.CheckForFileChanges(env.Ctx); err != nil {
428 t.Fatal(err)
429 }
430
431 // Synchronize again.
432 env.Await(env.DoneWithChangeWatchedFiles())
433
434 // b.B is once again defined in the module cache.
435 checkVendor(env.Implementations(refLoc), false)
436 })
437 }
438
439 // This test can't be expressed as a marker test because the marker
440 // test framework opens all files (which is a bit of a hack), creating
441 // a <command-line-arguments> package for packages that otherwise
442 // wouldn't be found from the go.work file.
443 func TestReferencesFromWorkspacePackages59674(t *testing.T) {
444 const src = `
445 -- a/go.mod --
446 module example.com/a
447 go 1.12
448
449 -- b/go.mod --
450 module example.com/b
451 go 1.12
452
453 -- c/go.mod --
454 module example.com/c
455 go 1.12
456
457 -- lib/go.mod --
458 module example.com/lib
459 go 1.12
460
461 -- go.work --
462 use ./a
463 use ./b
464 // don't use ./c
465 use ./lib
466
467 -- a/a.go --
468 package a
469
470 import "example.com/lib"
471
472 var _ = lib.F // query here
473
474 -- b/b.go --
475 package b
476
477 import "example.com/lib"
478
479 var _ = lib.F // also found by references
480
481 -- c/c.go --
482 package c
483
484 import "example.com/lib"
485
486 var _ = lib.F // this reference should not be reported
487
488 -- lib/lib.go --
489 package lib
490
491 func F() {} // declaration
492 `
493 Run(t, src, func(t *testing.T, env *Env) {
494 env.OpenFile("a/a.go")
495 refLoc := env.RegexpSearch("a/a.go", "F")
496 got := fileLocations(env, env.References(refLoc))
497 want := []string{"a/a.go:5", "b/b.go:5", "lib/lib.go:3"}
498 if diff := cmp.Diff(want, got); diff != "" {
499 t.Errorf("incorrect References (-want +got):\n%s", diff)
500 }
501 })
502 }
503
504 // Test an 'implementation' query on a type that implements 'error'.
505 // (Unfortunately builtin locations cannot be expressed using @loc
506 // in the marker test framework.)
507 func TestImplementationsOfError(t *testing.T) {
508 const src = `
509 -- go.mod --
510 module example.com
511 go 1.12
512
513 -- a.go --
514 package a
515
516 type Error2 interface {
517 Error() string
518 }
519
520 type MyError int
521 func (MyError) Error() string { return "" }
522
523 type MyErrorPtr int
524 func (*MyErrorPtr) Error() string { return "" }
525 `
526 Run(t, src, func(t *testing.T, env *Env) {
527 env.OpenFile("a.go")
528
529 for _, test := range []struct {
530 re string
531 want []string
532 }{
533 // error type
534 {"Error2", []string{"a.go:10", "a.go:7", "std:builtin/builtin.go"}},
535 {"MyError", []string{"a.go:3", "std:builtin/builtin.go"}},
536 {"MyErrorPtr", []string{"a.go:3", "std:builtin/builtin.go"}},
537 // error.Error method
538 {"(Error).. string", []string{"a.go:11", "a.go:8", "std:builtin/builtin.go"}},
539 {"MyError. (Error)", []string{"a.go:4", "std:builtin/builtin.go"}},
540 {"MyErrorPtr. (Error)", []string{"a.go:4", "std:builtin/builtin.go"}},
541 } {
542 matchLoc := env.RegexpSearch("a.go", test.re)
543 impls := env.Implementations(matchLoc)
544 got := fileLocations(env, impls)
545 if !reflect.DeepEqual(got, test.want) {
546 t.Errorf("Implementations(%q) = %q, want %q",
547 test.re, got, test.want)
548 }
549 }
550 })
551 }
552
553 // fileLocations returns a new sorted array of the
554 // relative file name and line number of each location.
555 // Duplicates are not removed.
556 // Standard library filenames are abstracted for robustness.
557 func fileLocations(env *integration.Env, locs []protocol.Location) []string {
558 got := make([]string, 0, len(locs))
559 for _, loc := range locs {
560 path := env.Sandbox.Workdir.URIToPath(loc.URI) // (slashified)
561 if i := strings.LastIndex(path, "/src/"); i >= 0 && filepath.IsAbs(path) {
562 // Absolute path with "src" segment: assume it's in GOROOT.
563 // Strip directory and don't add line/column since they are fragile.
564 path = "std:" + path[i+len("/src/"):]
565 } else {
566 path = fmt.Sprintf("%s:%d", path, loc.Range.Start.Line+1)
567 }
568 got = append(got, path)
569 }
570 sort.Strings(got)
571 return got
572 }