Debian Codegraph @

internal/facts/facts_test.go

raw symbols SCIP
1 // Copyright 2018 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 facts_test
6
7 import (
8 "encoding/gob"
9 "fmt"
10 "go/ast"
11 "go/parser"
12 "go/token"
13 "go/types"
14 "os"
15 "reflect"
16 "strings"
17 "testing"
18
19 "golang.org/x/tools/go/analysis/analysistest"
20 "golang.org/x/tools/go/packages"
21
22 "golang.org/x/tools/internal/facts"
23 "golang.org/x/tools/internal/testenv"
24 "golang.org/x/tools/internal/typesinternal"
25 )
26
27 type myFact struct {
28 S string
29 }
30
31 func (f *myFact) String() string { return fmt.Sprintf("myFact(%s)", f.S) }
32 func (f *myFact) AFact() {}
33
34 func init() {
35 gob.Register(new(myFact))
36 }
37
38 func TestEncodeDecode(t *testing.T) {
39 tests := []struct {
40 name string
41 files map[string]string
42 plookups []pkgLookups // see testEncodeDecode for details
43 }{
44 {
45 name: "loading-order",
46 // c -> b -> a, a2
47 // c does not directly depend on a, but it indirectly uses a.T.
48 //
49 // Package a2 is never loaded directly so it is incomplete.
50 //
51 // We use only types in this example because we rely on
52 // types.Eval to resolve the lookup expressions, and it only
53 // works for types. This is a definite gap in the typechecker API.
54 files: map[string]string{
55 "a/a.go": `package a; type A int; type T int`,
56 "a2/a.go": `package a2; type A2 int; type Unneeded int`,
57 "b/b.go": `package b; import ("a"; "a2"); type B chan a2.A2; type F func() a.T`,
58 "c/c.go": `package c; import "b"; type C []b.B`,
59 },
60 // In the following table, we analyze packages (a, b, c) in order,
61 // look up various objects accessible within each package,
62 // and see if they have a fact. The "analysis" exports a fact
63 // for every object at package level.
64 //
65 // Note: Loop iterations are not independent test cases;
66 // order matters, as we populate factmap.
67 plookups: []pkgLookups{
68 {"a", []lookup{
69 {"A", "myFact(a.A)"},
70 }},
71 {"b", []lookup{
72 {"a.A", "myFact(a.A)"},
73 {"a.T", "myFact(a.T)"},
74 {"B", "myFact(b.B)"},
75 {"F", "myFact(b.F)"},
76 {"F(nil)()", "myFact(a.T)"}, // (result type of b.F)
77 }},
78 {"c", []lookup{
79 {"b.B", "myFact(b.B)"},
80 {"b.F", "myFact(b.F)"},
81 {"b.F(nil)()", "myFact(a.T)"},
82 {"C", "myFact(c.C)"},
83 {"C{}[0]", "myFact(b.B)"},
84 {"<-(C{}[0])", "no fact"}, // object but no fact (we never "analyze" a2)
85 }},
86 },
87 },
88 {
89 name: "underlying",
90 // c->b->a
91 // c does not import a directly or use any of its types, but it does use
92 // the types within a indirectly. c.q has the type a.a so package a should
93 // be included by importMap.
94 files: map[string]string{
95 "a/a.go": `package a; type a int; type T *a`,
96 "b/b.go": `package b; import "a"; type B a.T`,
97 "c/c.go": `package c; import "b"; type C b.B; var q = *C(nil)`,
98 },
99 plookups: []pkgLookups{
100 {"a", []lookup{
101 {"a", "myFact(a.a)"},
102 {"T", "myFact(a.T)"},
103 }},
104 {"b", []lookup{
105 {"B", "myFact(b.B)"},
106 {"B(nil)", "myFact(b.B)"},
107 {"*(B(nil))", "myFact(a.a)"},
108 }},
109 {"c", []lookup{
110 {"C", "myFact(c.C)"},
111 {"C(nil)", "myFact(c.C)"},
112 {"*C(nil)", "myFact(a.a)"},
113 {"q", "myFact(a.a)"},
114 }},
115 },
116 },
117 {
118 name: "methods",
119 // c->b->a
120 // c does not import a directly or use any of its types, but it does use
121 // the types within a indirectly via a method.
122 files: map[string]string{
123 "a/a.go": `package a; type T int`,
124 "b/b.go": `package b; import "a"; type B struct{}; func (_ B) M() a.T { return 0 }`,
125 "c/c.go": `package c; import "b"; var C b.B`,
126 },
127 plookups: []pkgLookups{
128 {"a", []lookup{
129 {"T", "myFact(a.T)"},
130 }},
131 {"b", []lookup{
132 {"B{}", "myFact(b.B)"},
133 {"B{}.M()", "myFact(a.T)"},
134 }},
135 {"c", []lookup{
136 {"C", "myFact(b.B)"},
137 {"C.M()", "myFact(a.T)"},
138 }},
139 },
140 },
141 {
142 name: "globals",
143 files: map[string]string{
144 "a/a.go": `package a;
145 type T1 int
146 type T2 int
147 type T3 int
148 type T4 int
149 type T5 int
150 type K int; type V string
151 `,
152 "b/b.go": `package b
153 import "a"
154 var (
155 G1 []a.T1
156 G2 [7]a.T2
157 G3 chan a.T3
158 G4 *a.T4
159 G5 struct{ F a.T5 }
160 G6 map[a.K]a.V
161 )
162 `,
163 "c/c.go": `package c; import "b";
164 var (
165 v1 = b.G1
166 v2 = b.G2
167 v3 = b.G3
168 v4 = b.G4
169 v5 = b.G5
170 v6 = b.G6
171 )
172 `,
173 },
174 plookups: []pkgLookups{
175 {"a", []lookup{}},
176 {"b", []lookup{}},
177 {"c", []lookup{
178 {"v1[0]", "myFact(a.T1)"},
179 {"v2[0]", "myFact(a.T2)"},
180 {"<-v3", "myFact(a.T3)"},
181 {"*v4", "myFact(a.T4)"},
182 {"v5.F", "myFact(a.T5)"},
183 {"v6[0]", "myFact(a.V)"},
184 }},
185 },
186 },
187 {
188 name: "typeparams",
189 files: map[string]string{
190 "a/a.go": `package a
191 type T1 int
192 type T2 int
193 type T3 interface{Foo()}
194 type T4 int
195 type T5 int
196 type T6 interface{Foo()}
197 `,
198 "b/b.go": `package b
199 import "a"
200 type N1[T a.T1|int8] func() T
201 type N2[T any] struct{ F T }
202 type N3[T a.T3] func() T
203 type N4[T a.T4|int8] func() T
204 type N5[T interface{Bar() a.T5} ] func() T
205
206 type t5 struct{}; func (t5) Bar() a.T5 { return 0 }
207
208 var G1 N1[a.T1]
209 var G2 func() N2[a.T2]
210 var G3 N3[a.T3]
211 var G4 N4[a.T4]
212 var G5 N5[t5]
213
214 func F6[T a.T6]() T { var x T; return x }
215 `,
216 "c/c.go": `package c; import "b";
217 var (
218 v1 = b.G1
219 v2 = b.G2
220 v3 = b.G3
221 v4 = b.G4
222 v5 = b.G5
223 v6 = b.F6[t6]
224 )
225
226 type t6 struct{}; func (t6) Foo() {}
227 `,
228 },
229 plookups: []pkgLookups{
230 {"a", []lookup{}},
231 {"b", []lookup{}},
232 {"c", []lookup{
233 {"v1", "myFact(b.N1)"},
234 {"v1()", "myFact(a.T1)"},
235 {"v2()", "myFact(b.N2)"},
236 {"v2().F", "myFact(a.T2)"},
237 {"v3", "myFact(b.N3)"},
238 {"v4", "myFact(b.N4)"},
239 {"v4()", "myFact(a.T4)"},
240 {"v5", "myFact(b.N5)"},
241 {"v5()", "myFact(b.t5)"},
242 {"v6()", "myFact(c.t6)"},
243 }},
244 },
245 },
246 }
247 for _, test := range tests {
248 t.Run(test.name, func(t *testing.T) {
249 t.Parallel()
250 testEncodeDecode(t, test.files, test.plookups)
251 })
252 }
253 }
254
255 func TestEncodeDecodeAliases(t *testing.T) {
256 testenv.NeedsGo1Point(t, 24)
257
258 files := map[string]string{
259 "a/a.go": `package a
260 type A = int
261 `,
262 "b/b.go": `package b
263 import "a"
264 type B = a.A
265 `,
266 "c/c.go": `package c
267 import "b";
268 type N1[T int|~string] = struct{}
269
270 var V1 = N1[b.B]{}
271 `,
272 }
273 plookups := []pkgLookups{
274 {"a", []lookup{}},
275 {"b", []lookup{}},
276 // fake objexpr for RHS of V1's type arg (see customFind hack)
277 {"c", []lookup{{"c.V1->c.N1->b.B->a.A", "myFact(a.A)"}}},
278 }
279 testEncodeDecode(t, files, plookups)
280 }
281
282 type lookup struct {
283 objexpr string // expression whose type is a named type
284 want string // printed form of fact associated with that type (or "no fact")
285 }
286
287 type pkgLookups struct {
288 path string
289 lookups []lookup
290 }
291
292 // testEncodeDecode tests fact encoding and decoding and simulates how package facts
293 // are passed during analysis. It operates on a group of Go file contents. Then
294 // for each <package, []lookup> in tests it does the following:
295 // 1. loads and type checks the package,
296 // 2. calls (*facts.Decoder).Decode to load the facts exported by its imports,
297 // 3. exports a myFact Fact for all of package level objects,
298 // 4. For each lookup for the current package:
299 // 4.a) lookup the types.Object for a Go source expression in the current package
300 // (or confirms one is not expected want=="no object"),
301 // 4.b) finds a Fact for the object (or confirms one is not expected want=="no fact"),
302 // 4.c) compares the content of the Fact to want.
303 // 5. encodes the Facts of the package.
304 //
305 // Note: tests are not independent test cases; order matters (as does a package being
306 // skipped). It changes what Facts can be imported.
307 //
308 // Failures are reported on t.
309 func testEncodeDecode(t *testing.T, files map[string]string, tests []pkgLookups) {
310 dir, cleanup, err := analysistest.WriteFiles(files)
311 if err != nil {
312 t.Fatal(err)
313 }
314 defer cleanup()
315
316 // factmap represents the passing of encoded facts from one
317 // package to another. In practice one would use the file system.
318 factmap := make(map[string][]byte)
319 read := func(pkgPath string) ([]byte, error) { return factmap[pkgPath], nil }
320
321 // Analyze packages in order, look up various objects accessible within
322 // each package, and see if they have a fact. The "analysis" exports a
323 // fact for every object at package level.
324 //
325 // Note: Loop iterations are not independent test cases;
326 // order matters, as we populate factmap.
327 for _, test := range tests {
328 // load package
329 pkg, err := load(t, dir, test.path)
330 if err != nil {
331 t.Fatal(err)
332 }
333
334 // decode
335 facts, err := facts.NewDecoder(pkg).Decode(read)
336 if err != nil {
337 t.Fatalf("Decode failed: %v", err)
338 }
339 t.Logf("decode %s facts = %v", pkg.Path(), facts) // show all facts
340
341 // export
342 // (one fact for each package-level object)
343 for _, name := range pkg.Scope().Names() {
344 obj := pkg.Scope().Lookup(name)
345 fact := &myFact{obj.Pkg().Name() + "." + obj.Name()}
346 facts.ExportObjectFact(obj, fact)
347 }
348 t.Logf("exported %s facts = %v", pkg.Path(), facts) // show all facts
349
350 // import
351 // (after export, because an analyzer may import its own facts)
352 for _, lookup := range test.lookups {
353 fact := new(myFact)
354 var got string
355 if obj := find(pkg, lookup.objexpr); obj == nil {
356 got = "no object"
357 } else if facts.ImportObjectFact(obj, fact) {
358 got = fact.String()
359 } else {
360 got = "no fact"
361 }
362 if got != lookup.want {
363 t.Errorf("in %s, ImportObjectFact(%s, %T) = %s, want %s",
364 pkg.Path(), lookup.objexpr, fact, got, lookup.want)
365 }
366 }
367
368 // encode
369 factmap[pkg.Path()] = facts.Encode()
370 }
371 }
372
373 // customFind allows for overriding how an object is looked up
374 // by find. This is necessary for objects that are accessible through
375 // the API but are not the type of any expression we can pass to types.CheckExpr.
376 var customFind = map[string]func(p *types.Package) types.Object{
377 "c.V1->c.N1->b.B->a.A": func(p *types.Package) types.Object {
378 cV1 := p.Scope().Lookup("V1")
379 cN1 := cV1.Type().(*types.Alias)
380 aT1 := cN1.TypeArgs().At(0).(*types.Alias)
381 zZ1 := aT1.Rhs().(*types.Alias)
382 return zZ1.Obj()
383 },
384 }
385
386 func find(p *types.Package, expr string) types.Object {
387 // types.Eval only allows us to compute a TypeName object for an expression.
388 // TODO(adonovan): support other expressions that denote an object:
389 // - an identifier (or qualified ident) for a func, const, or var
390 // - new(T).f for a field or method
391 // I've added CheckExpr in https://go-review.googlesource.com/c/go/+/144677.
392 // If that becomes available, use it.
393 if f := customFind[expr]; f != nil {
394 return f(p)
395 }
396 // Choose an arbitrary position within the (single-file) package
397 // so that we are within the scope of its import declarations.
398 somepos := p.Scope().Lookup(p.Scope().Names()[0]).Pos()
399 tv, err := types.Eval(token.NewFileSet(), p, somepos, expr)
400 if err != nil {
401 return nil
402 }
403 if n, ok := tv.Type.(typesinternal.NamedOrAlias); ok {
404 return n.Obj()
405 }
406 return nil
407 }
408
409 func load(t *testing.T, dir string, path string) (*types.Package, error) {
410 cfg := &packages.Config{
411 Mode: packages.LoadSyntax,
412 Dir: dir,
413 Env: append(os.Environ(), "GOPATH="+dir, "GO111MODULE=off", "GOPROXY=off"),
414 }
415 testenv.NeedsGoPackagesEnv(t, cfg.Env)
416 pkgs, err := packages.Load(cfg, path)
417 if err != nil {
418 return nil, err
419 }
420 if packages.PrintErrors(pkgs) > 0 {
421 return nil, fmt.Errorf("packages had errors")
422 }
423 if len(pkgs) == 0 {
424 return nil, fmt.Errorf("no package matched %s", path)
425 }
426 return pkgs[0].Types, nil
427 }
428
429 type otherFact struct {
430 S string
431 }
432
433 func (f *otherFact) String() string { return fmt.Sprintf("otherFact(%s)", f.S) }
434 func (f *otherFact) AFact() {}
435
436 func TestFactFilter(t *testing.T) {
437 files := map[string]string{
438 "a/a.go": `package a; type A int`,
439 }
440 dir, cleanup, err := analysistest.WriteFiles(files)
441 if err != nil {
442 t.Fatal(err)
443 }
444 defer cleanup()
445
446 pkg, err := load(t, dir, "a")
447 if err != nil {
448 t.Fatal(err)
449 }
450
451 obj := pkg.Scope().Lookup("A")
452 s, err := facts.NewDecoder(pkg).Decode(func(pkgPath string) ([]byte, error) { return nil, nil })
453 if err != nil {
454 t.Fatal(err)
455 }
456 s.ExportObjectFact(obj, &myFact{"good object fact"})
457 s.ExportPackageFact(&myFact{"good package fact"})
458 s.ExportObjectFact(obj, &otherFact{"bad object fact"})
459 s.ExportPackageFact(&otherFact{"bad package fact"})
460
461 filter := map[reflect.Type]bool{
462 reflect.TypeFor[*myFact](): true,
463 }
464
465 pkgFacts := s.AllPackageFacts(filter)
466 wantPkgFacts := `[{package a ("a") myFact(good package fact)}]`
467 if got := fmt.Sprintf("%v", pkgFacts); got != wantPkgFacts {
468 t.Errorf("AllPackageFacts: got %v, want %v", got, wantPkgFacts)
469 }
470
471 objFacts := s.AllObjectFacts(filter)
472 wantObjFacts := "[{type a.A int myFact(good object fact)}]"
473 if got := fmt.Sprintf("%v", objFacts); got != wantObjFacts {
474 t.Errorf("AllObjectFacts: got %v, want %v", got, wantObjFacts)
475 }
476 }
477
478 // TestMalformed checks that facts can be encoded and decoded *despite*
479 // types.Config.Check returning an error. Importing facts is expected to
480 // happen when Analyzers have RunDespiteErrors set to true. So this
481 // needs to robust, e.g. no infinite loops.
482 func TestMalformed(t *testing.T) {
483 var findPkg func(*types.Package, string) *types.Package
484 findPkg = func(p *types.Package, name string) *types.Package {
485 if p.Name() == name {
486 return p
487 }
488 for _, o := range p.Imports() {
489 if f := findPkg(o, name); f != nil {
490 return f
491 }
492 }
493 return nil
494 }
495
496 type pkgTest struct {
497 content string
498 err string // if non-empty, expected substring of err.Error() from conf.Check().
499 wants map[string]string // package path to expected name
500 }
501 tests := []struct {
502 name string
503 pkgs []pkgTest
504 }{
505 {
506 name: "initialization-cycle",
507 pkgs: []pkgTest{
508 // Notation: myFact(a.[N]) means: package a has members {N}.
509 {
510 content: `package a; type N[T any] struct { F *N[N[T]] }`,
511 err: "instantiation cycle:",
512 wants: map[string]string{"a": "myFact(a.[N])", "b": "no package", "c": "no package"},
513 },
514 {
515 content: `package b; import "a"; type B a.N[int]`,
516 wants: map[string]string{"a": "myFact(a.[N])", "b": "myFact(b.[B])", "c": "no package"},
517 },
518 {
519 content: `package c; import "b"; var C b.B`,
520 wants: map[string]string{"a": "no fact", "b": "myFact(b.[B])", "c": "myFact(c.[C])"},
521 // package fact myFact(a.[N]) not reexported
522 },
523 },
524 },
525 }
526
527 for i := range tests {
528 test := tests[i]
529 t.Run(test.name, func(t *testing.T) {
530 t.Parallel()
531
532 // setup for test wide variables.
533 packages := make(map[string]*types.Package)
534 conf := types.Config{
535 Importer: closure(packages),
536 Error: func(err error) {}, // do not stop on first type checking error
537 }
538 fset := token.NewFileSet()
539 factmap := make(map[string][]byte)
540 read := func(pkgPath string) ([]byte, error) { return factmap[pkgPath], nil }
541
542 // Processes the pkgs in order. For package, export a package fact,
543 // and use this fact to verify which package facts are reachable via Decode.
544 // We allow for packages to have type checking errors.
545 for i, pkgTest := range test.pkgs {
546 // parse
547 f, err := parser.ParseFile(fset, fmt.Sprintf("%d.go", i), pkgTest.content, 0)
548 if err != nil {
549 t.Fatal(err)
550 }
551
552 // typecheck
553 pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
554 var got string
555 if err != nil {
556 got = err.Error()
557 }
558 if !strings.Contains(got, pkgTest.err) {
559 t.Fatalf("%s: type checking error %q did not match pattern %q", pkg.Path(), err.Error(), pkgTest.err)
560 }
561 packages[pkg.Path()] = pkg
562
563 // decode facts
564 facts, err := facts.NewDecoder(pkg).Decode(read)
565 if err != nil {
566 t.Fatalf("Decode failed: %v", err)
567 }
568
569 // export facts
570 fact := &myFact{fmt.Sprintf("%s.%s", pkg.Name(), pkg.Scope().Names())}
571 facts.ExportPackageFact(fact)
572
573 // import facts
574 for other, want := range pkgTest.wants {
575 fact := new(myFact)
576 var got string
577 if found := findPkg(pkg, other); found == nil {
578 got = "no package"
579 } else if facts.ImportPackageFact(found, fact) {
580 got = fact.String()
581 } else {
582 got = "no fact"
583 }
584 if got != want {
585 t.Errorf("in %s, ImportPackageFact(%s, %T) = %s, want %s",
586 pkg.Path(), other, fact, got, want)
587 }
588 }
589
590 // encode facts
591 factmap[pkg.Path()] = facts.Encode()
592 }
593 })
594 }
595 }
596
597 type closure map[string]*types.Package
598
599 func (c closure) Import(path string) (*types.Package, error) { return c[path], nil }