Debian Codegraph @

go/analysis/checker/checker.go

raw symbols SCIP
1 // Copyright 2024 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 checker provides an analysis driver based on the
6 // [golang.org/x/tools/go/packages] representation of a set of
7 // packages and all their dependencies, as produced by
8 // [packages.Load].
9 //
10 // It is the core of multichecker (the multi-analyzer driver),
11 // singlechecker (the single-analyzer driver often used to provide a
12 // convenient command alongside each analyzer), and analysistest, the
13 // test driver.
14 //
15 // By contrast, the 'go vet' command is based on unitchecker, an
16 // analysis driver that uses separate analysis--analogous to separate
17 // compilation--with file-based intermediate results. Like separate
18 // compilation, it is more scalable, especially for incremental
19 // analysis of large code bases. Commands based on multichecker and
20 // singlechecker are capable of detecting when they are being invoked
21 // by "go vet -vettool=exe" and instead dispatching to unitchecker.
22 //
23 // Programs built using this package will, in general, not be usable
24 // in that way. This package is intended only for use in applications
25 // that invoke the analysis driver as a subroutine, and need to insert
26 // additional steps before or after the analysis.
27 //
28 // See the Example of how to build a complete analysis driver program.
29 package checker
30
31 import (
32 "bytes"
33 "encoding/gob"
34 "fmt"
35 "go/types"
36 "io"
37 "iter"
38 "log"
39 "os"
40 "reflect"
41 "sort"
42 "strings"
43 "sync"
44 "time"
45
46 "golang.org/x/tools/go/analysis"
47 "golang.org/x/tools/go/analysis/internal"
48 "golang.org/x/tools/go/packages"
49 "golang.org/x/tools/internal/analysis/driverutil"
50 )
51
52 // Options specifies options that control the analysis driver.
53 type Options struct {
54 // These options correspond to existing flags exposed by multichecker:
55 Sequential bool // disable parallelism
56 SanityCheck bool // check fact encoding is ok and deterministic
57 FactLog io.Writer // if non-nil, log each exported fact to it
58
59 // TODO(adonovan): expose ReadFile so that an Overlay specified
60 // in the [packages.Config] can be communicated via
61 // Pass.ReadFile to each Analyzer.
62 readFile driverutil.ReadFileFunc
63 }
64
65 // Graph holds the results of a round of analysis, including the graph
66 // of requested actions (analyzers applied to packages) plus any
67 // dependent actions that it was necessary to compute.
68 type Graph struct {
69 // Roots contains the roots of the action graph.
70 // Each node (a, p) in the action graph represents the
71 // application of one analyzer a to one package p.
72 // (A node thus corresponds to one analysis.Pass instance.)
73 // Roots holds one action per element of the product
74 // of the analyzers × packages arguments to Analyze,
75 // in unspecified order.
76 //
77 // Each element of Action.Deps represents an edge in the
78 // action graph: a dependency from one action to another.
79 // An edge of the form (a, p) -> (a, p2) indicates that the
80 // analysis of package p requires information ("facts") from
81 // the same analyzer applied to one of p's dependencies, p2.
82 // An edge of the form (a, p) -> (a2, p) indicates that the
83 // analysis of package p requires information ("results")
84 // from a different analyzer a2 applied to the same package.
85 // These two kind of edges are called "vertical" and "horizontal",
86 // respectively.
87 Roots []*Action
88 }
89
90 // All returns an iterator over the action graph in depth-first postorder.
91 //
92 // Example:
93 //
94 // for act := range graph.All() {
95 // ...
96 // }
97 func (g *Graph) All() iter.Seq[*Action] {
98 return func(yield func(*Action) bool) {
99 forEach(g.Roots, func(act *Action) error {
100 if !yield(act) {
101 return io.EOF // any error will do
102 }
103 return nil
104 }) // ignore error
105 }
106 }
107
108 // An Action represents one unit of analysis work by the driver: the
109 // application of one analysis to one package. It provides the inputs
110 // to and records the outputs of a single analysis.Pass.
111 //
112 // Actions form a DAG, both within a package (as different analyzers
113 // are applied, either in sequence or parallel), and across packages
114 // (as dependencies are analyzed).
115 type Action struct {
116 Analyzer *analysis.Analyzer
117 Package *packages.Package
118 IsRoot bool // whether this is a root node of the graph
119 Deps []*Action
120 Result any // computed result of Analyzer.run, if any (and if IsRoot)
121 Err error // error result of Analyzer.run
122 Diagnostics []analysis.Diagnostic
123 Duration time.Duration // execution time of this step
124
125 opts *Options
126 once sync.Once
127 pass *analysis.Pass
128 objectFacts map[objectFactKey]analysis.Fact
129 packageFacts map[packageFactKey]analysis.Fact
130 }
131
132 func (act *Action) String() string {
133 return fmt.Sprintf("%s@%s", act.Analyzer, act.Package)
134 }
135
136 // Analyze runs the specified analyzers on the initial packages.
137 //
138 // The initial packages and all dependencies must have been loaded
139 // using the [packages.LoadAllSyntax] flag, Analyze may need to run
140 // some analyzer (those that consume and produce facts) on
141 // dependencies too.
142 //
143 // On success, it returns a Graph of actions whose Roots hold one
144 // item per (a, p) in the cross-product of analyzers and pkgs.
145 //
146 // If opts is nil, it is equivalent to new(Options).
147 func Analyze(analyzers []*analysis.Analyzer, pkgs []*packages.Package, opts *Options) (*Graph, error) {
148 if opts == nil {
149 opts = new(Options)
150 }
151
152 if err := analysis.Validate(analyzers); err != nil {
153 return nil, err
154 }
155
156 // Construct the action graph.
157 //
158 // Each graph node (action) is one unit of analysis.
159 // Edges express package-to-package (vertical) dependencies,
160 // and analysis-to-analysis (horizontal) dependencies.
161 type key struct {
162 a *analysis.Analyzer
163 pkg *packages.Package
164 }
165 actions := make(map[key]*Action)
166
167 var mkAction func(a *analysis.Analyzer, pkg *packages.Package) *Action
168 mkAction = func(a *analysis.Analyzer, pkg *packages.Package) *Action {
169 k := key{a, pkg}
170 act, ok := actions[k]
171 if !ok {
172 act = &Action{Analyzer: a, Package: pkg, opts: opts}
173
174 // Add a dependency on each required analyzers.
175 for _, req := range a.Requires {
176 act.Deps = append(act.Deps, mkAction(req, pkg))
177 }
178
179 // An analysis that consumes/produces facts
180 // must run on the package's dependencies too.
181 if len(a.FactTypes) > 0 {
182 paths := make([]string, 0, len(pkg.Imports))
183 for path := range pkg.Imports {
184 paths = append(paths, path)
185 }
186 sort.Strings(paths) // for determinism
187 for _, path := range paths {
188 dep := mkAction(a, pkg.Imports[path])
189 act.Deps = append(act.Deps, dep)
190 }
191 }
192
193 actions[k] = act
194 }
195 return act
196 }
197
198 // Build nodes for initial packages.
199 var roots []*Action
200 for _, a := range analyzers {
201 for _, pkg := range pkgs {
202 root := mkAction(a, pkg)
203 root.IsRoot = true
204 roots = append(roots, root)
205 }
206 }
207
208 // Execute the graph in parallel.
209 execAll(roots)
210
211 // Ensure that only root Results are visible to caller.
212 // (The others are considered temporary intermediaries.)
213 // TODO(adonovan): opt: clear them earlier, so we can
214 // release large data structures like SSA sooner.
215 for _, act := range actions {
216 if !act.IsRoot {
217 act.Result = nil
218 }
219 }
220
221 return &Graph{Roots: roots}, nil
222 }
223
224 func init() {
225 // Allow analysistest to access Action.pass,
226 // for the legacy analysistest.Result data type,
227 // and for internal/checker.ApplyFixes to access pass.ReadFile.
228 internal.ActionPass = func(x any) *analysis.Pass { return x.(*Action).pass }
229 }
230
231 type objectFactKey struct {
232 obj types.Object
233 typ reflect.Type
234 }
235
236 type packageFactKey struct {
237 pkg *types.Package
238 typ reflect.Type
239 }
240
241 func execAll(actions []*Action) {
242 var wg sync.WaitGroup
243 for _, act := range actions {
244 wg.Add(1)
245 work := func(act *Action) {
246 act.exec()
247 wg.Done()
248 }
249 if act.opts.Sequential {
250 work(act)
251 } else {
252 go work(act)
253 }
254 }
255 wg.Wait()
256 }
257
258 func (act *Action) exec() { act.once.Do(act.execOnce) }
259
260 func (act *Action) execOnce() {
261 // Analyze dependencies.
262 execAll(act.Deps)
263
264 // Record time spent in this node but not its dependencies.
265 // In parallel mode, due to GC/scheduler contention, the
266 // time is 5x higher than in sequential mode, even with a
267 // semaphore limiting the number of threads here.
268 // So use -debug=tp.
269 t0 := time.Now()
270 defer func() { act.Duration = time.Since(t0) }()
271
272 // Report an error if any dependency failed.
273 var failed []string
274 for _, dep := range act.Deps {
275 if dep.Err != nil {
276 failed = append(failed, dep.String())
277 }
278 }
279 if failed != nil {
280 sort.Strings(failed)
281 act.Err = fmt.Errorf("failed prerequisites: %s", strings.Join(failed, ", "))
282 return
283 }
284
285 // Plumb the output values of the dependencies
286 // into the inputs of this action. Also facts.
287 inputs := make(map[*analysis.Analyzer]any)
288 act.objectFacts = make(map[objectFactKey]analysis.Fact)
289 act.packageFacts = make(map[packageFactKey]analysis.Fact)
290 for _, dep := range act.Deps {
291 if dep.Package == act.Package {
292 // Same package, different analysis (horizontal edge):
293 // in-memory outputs of prerequisite analyzers
294 // become inputs to this analysis pass.
295 inputs[dep.Analyzer] = dep.Result
296 } else if dep.Analyzer == act.Analyzer { // (always true)
297 // Same analysis, different package (vertical edge):
298 // serialized facts produced by prerequisite analysis
299 // become available to this analysis pass.
300 inheritFacts(act, dep)
301 }
302 }
303
304 // Quick (nonexhaustive) check that the correct go/packages mode bits were used.
305 // (If there were errors, all bets are off.)
306 if pkg := act.Package; pkg.Errors == nil {
307 if pkg.Name == "" || pkg.PkgPath == "" || pkg.Types == nil || pkg.Fset == nil || pkg.TypesSizes == nil {
308 panic("packages must be loaded with packages.LoadSyntax mode")
309 }
310 }
311
312 module := &analysis.Module{} // possibly empty (non nil) in go/analysis drivers.
313 if mod := act.Package.Module; mod != nil {
314 module = analysisModuleFromPackagesModule(mod)
315 }
316
317 // Run the analysis.
318 pass := &analysis.Pass{
319 Analyzer: act.Analyzer,
320 Fset: act.Package.Fset,
321 Files: act.Package.Syntax,
322 OtherFiles: act.Package.OtherFiles,
323 IgnoredFiles: act.Package.IgnoredFiles,
324 Pkg: act.Package.Types,
325 TypesInfo: act.Package.TypesInfo,
326 TypesSizes: act.Package.TypesSizes,
327 TypeErrors: act.Package.TypeErrors,
328 Module: module,
329
330 ResultOf: inputs,
331 Report: func(d analysis.Diagnostic) {
332 // Assert that SuggestedFixes are well formed.
333 if err := driverutil.ValidateFixes(act.Package.Fset, act.Analyzer, d.SuggestedFixes); err != nil {
334 panic(err)
335 }
336 act.Diagnostics = append(act.Diagnostics, d)
337 },
338 ImportObjectFact: act.ObjectFact,
339 ExportObjectFact: act.exportObjectFact,
340 ImportPackageFact: act.PackageFact,
341 ExportPackageFact: act.exportPackageFact,
342 AllObjectFacts: act.AllObjectFacts,
343 AllPackageFacts: act.AllPackageFacts,
344 }
345 readFile := os.ReadFile
346 if act.opts.readFile != nil {
347 readFile = act.opts.readFile
348 }
349 pass.ReadFile = driverutil.CheckedReadFile(pass, readFile)
350 act.pass = pass
351
352 act.Result, act.Err = func() (any, error) {
353 if act.Package.IllTyped && !pass.Analyzer.RunDespiteErrors {
354 return nil, fmt.Errorf("analysis skipped due to errors in package")
355 }
356
357 result, err := pass.Analyzer.Run(pass)
358 if err != nil {
359 return nil, err
360 }
361
362 // correct result type?
363 if got, want := reflect.TypeOf(result), pass.Analyzer.ResultType; got != want {
364 return nil, fmt.Errorf(
365 "internal error: on package %s, analyzer %s returned a result of type %v, but declared ResultType %v",
366 pass.Pkg.Path(), pass.Analyzer, got, want)
367 }
368
369 // resolve diagnostic URLs
370 for i := range act.Diagnostics {
371 url, err := driverutil.ResolveURL(act.Analyzer, act.Diagnostics[i])
372 if err != nil {
373 return nil, err
374 }
375 act.Diagnostics[i].URL = url
376 }
377 return result, nil
378 }()
379
380 // Help detect (disallowed) calls after Run.
381 pass.ExportObjectFact = nil
382 pass.ExportPackageFact = nil
383 }
384
385 // inheritFacts populates act.facts with
386 // those it obtains from its dependency, dep.
387 func inheritFacts(act, dep *Action) {
388 for key, fact := range dep.objectFacts {
389 // Filter out facts related to objects
390 // that are irrelevant downstream
391 // (equivalently: not in the compiler export data).
392 if !exportedFrom(key.obj, dep.Package.Types) {
393 if false {
394 log.Printf("%v: discarding %T fact from %s for %s: %s", act, fact, dep, key.obj, fact)
395 }
396 continue
397 }
398
399 // Optionally serialize/deserialize fact
400 // to verify that it works across address spaces.
401 if act.opts.SanityCheck {
402 encodedFact, err := codeFact(fact)
403 if err != nil {
404 log.Panicf("internal error: encoding of %T fact failed in %v", fact, act)
405 }
406 fact = encodedFact
407 }
408
409 if false {
410 log.Printf("%v: inherited %T fact for %s: %s", act, fact, key.obj, fact)
411 }
412 act.objectFacts[key] = fact
413 }
414
415 for key, fact := range dep.packageFacts {
416 // TODO: filter out facts that belong to
417 // packages not mentioned in the export data
418 // to prevent side channels.
419 //
420 // The Pass.All{Object,Package}Facts accessors expose too much:
421 // all facts, of all types, for all dependencies in the action
422 // graph. Not only does the representation grow quadratically,
423 // but it violates the separate compilation paradigm, allowing
424 // analysis implementations to communicate with indirect
425 // dependencies that are not mentioned in the export data.
426 //
427 // It's not clear how to fix this short of a rather expensive
428 // filtering step after each action that enumerates all the
429 // objects that would appear in export data, and deletes
430 // facts associated with objects not in this set.
431
432 // Optionally serialize/deserialize fact
433 // to verify that it works across address spaces
434 // and is deterministic.
435 if act.opts.SanityCheck {
436 encodedFact, err := codeFact(fact)
437 if err != nil {
438 log.Panicf("internal error: encoding of %T fact failed in %v", fact, act)
439 }
440 fact = encodedFact
441 }
442
443 if false {
444 log.Printf("%v: inherited %T fact for %s: %s", act, fact, key.pkg.Path(), fact)
445 }
446 act.packageFacts[key] = fact
447 }
448 }
449
450 // codeFact encodes then decodes a fact,
451 // just to exercise that logic.
452 func codeFact(fact analysis.Fact) (analysis.Fact, error) {
453 // We encode facts one at a time.
454 // A real modular driver would emit all facts
455 // into one encoder to improve gob efficiency.
456 var buf bytes.Buffer
457 if err := gob.NewEncoder(&buf).Encode(fact); err != nil {
458 return nil, err
459 }
460
461 // Encode it twice and assert that we get the same bits.
462 // This helps detect nondeterministic Gob encoding (e.g. of maps).
463 var buf2 bytes.Buffer
464 if err := gob.NewEncoder(&buf2).Encode(fact); err != nil {
465 return nil, err
466 }
467 if !bytes.Equal(buf.Bytes(), buf2.Bytes()) {
468 return nil, fmt.Errorf("encoding of %T fact is nondeterministic", fact)
469 }
470
471 new := reflect.New(reflect.TypeOf(fact).Elem()).Interface().(analysis.Fact)
472 if err := gob.NewDecoder(&buf).Decode(new); err != nil {
473 return nil, err
474 }
475 return new, nil
476 }
477
478 // exportedFrom reports whether obj may be visible to a package that imports pkg.
479 // This includes not just the exported members of pkg, but also unexported
480 // constants, types, fields, and methods, perhaps belonging to other packages,
481 // that find there way into the API.
482 // This is an overapproximation of the more accurate approach used by
483 // gc export data, which walks the type graph, but it's much simpler.
484 //
485 // TODO(adonovan): do more accurate filtering by walking the type graph.
486 func exportedFrom(obj types.Object, pkg *types.Package) bool {
487 switch obj := obj.(type) {
488 case *types.Func:
489 return obj.Exported() && obj.Pkg() == pkg ||
490 obj.Signature().Recv() != nil
491 case *types.Var:
492 if obj.IsField() {
493 return true
494 }
495 // we can't filter more aggressively than this because we need
496 // to consider function parameters exported, but have no way
497 // of telling apart function parameters from local variables.
498 return obj.Pkg() == pkg
499 case *types.TypeName, *types.Const:
500 return true
501 }
502 return false // Nil, Builtin, Label, or PkgName
503 }
504
505 // ObjectFact retrieves a fact associated with obj,
506 // and returns true if one was found.
507 // Given a value ptr of type *T, where *T satisfies Fact,
508 // ObjectFact copies the value to *ptr.
509 //
510 // See documentation at ImportObjectFact field of [analysis.Pass].
511 func (act *Action) ObjectFact(obj types.Object, ptr analysis.Fact) bool {
512 if obj == nil {
513 panic("nil object")
514 }
515 key := objectFactKey{obj, factType(ptr)}
516 if v, ok := act.objectFacts[key]; ok {
517 reflect.ValueOf(ptr).Elem().Set(reflect.ValueOf(v).Elem())
518 return true
519 }
520 return false
521 }
522
523 // exportObjectFact implements Pass.ExportObjectFact.
524 func (act *Action) exportObjectFact(obj types.Object, fact analysis.Fact) {
525 if act.pass.ExportObjectFact == nil {
526 log.Panicf("%s: Pass.ExportObjectFact(%s, %T) called after Run", act, obj, fact)
527 }
528
529 if obj.Pkg() != act.Package.Types {
530 log.Panicf("internal error: in analysis %s of package %s: Fact.Set(%s, %T): can't set facts on objects belonging another package",
531 act.Analyzer, act.Package, obj, fact)
532 }
533
534 key := objectFactKey{obj, factType(fact)}
535 act.objectFacts[key] = fact // clobber any existing entry
536 if log := act.opts.FactLog; log != nil {
537 objstr := types.ObjectString(obj, (*types.Package).Name)
538 fmt.Fprintf(log, "%s: object %s has fact %s\n",
539 act.Package.Fset.Position(obj.Pos()), objstr, fact)
540 }
541 }
542
543 // AllObjectFacts returns a new slice containing all object facts of
544 // the analysis's FactTypes in unspecified order.
545 //
546 // See documentation at AllObjectFacts field of [analysis.Pass].
547 func (act *Action) AllObjectFacts() []analysis.ObjectFact {
548 facts := make([]analysis.ObjectFact, 0, len(act.objectFacts))
549 for k, fact := range act.objectFacts {
550 facts = append(facts, analysis.ObjectFact{Object: k.obj, Fact: fact})
551 }
552 return facts
553 }
554
555 // PackageFact retrieves a fact associated with package pkg,
556 // which must be this package or one of its dependencies.
557 //
558 // See documentation at ImportObjectFact field of [analysis.Pass].
559 func (act *Action) PackageFact(pkg *types.Package, ptr analysis.Fact) bool {
560 if pkg == nil {
561 panic("nil package")
562 }
563 key := packageFactKey{pkg, factType(ptr)}
564 if v, ok := act.packageFacts[key]; ok {
565 reflect.ValueOf(ptr).Elem().Set(reflect.ValueOf(v).Elem())
566 return true
567 }
568 return false
569 }
570
571 // exportPackageFact implements Pass.ExportPackageFact.
572 func (act *Action) exportPackageFact(fact analysis.Fact) {
573 if act.pass.ExportPackageFact == nil {
574 log.Panicf("%s: Pass.ExportPackageFact(%T) called after Run", act, fact)
575 }
576
577 key := packageFactKey{act.pass.Pkg, factType(fact)}
578 act.packageFacts[key] = fact // clobber any existing entry
579 if log := act.opts.FactLog; log != nil {
580 fmt.Fprintf(log, "%s: package %s has fact %s\n",
581 act.Package.Fset.Position(act.pass.Files[0].Pos()), act.pass.Pkg.Path(), fact)
582 }
583 }
584
585 func factType(fact analysis.Fact) reflect.Type {
586 t := reflect.TypeOf(fact)
587 if t.Kind() != reflect.Pointer {
588 log.Fatalf("invalid Fact type: got %T, want pointer", fact)
589 }
590 return t
591 }
592
593 // AllPackageFacts returns a new slice containing all package
594 // facts of the analysis's FactTypes in unspecified order.
595 //
596 // See documentation at AllPackageFacts field of [analysis.Pass].
597 func (act *Action) AllPackageFacts() []analysis.PackageFact {
598 facts := make([]analysis.PackageFact, 0, len(act.packageFacts))
599 for k, fact := range act.packageFacts {
600 facts = append(facts, analysis.PackageFact{Package: k.pkg, Fact: fact})
601 }
602 return facts
603 }
604
605 // forEach is a utility function for traversing the action graph. It
606 // applies function f to each action in the graph reachable from
607 // roots, in depth-first postorder. If any call to f returns an error,
608 // the traversal is aborted and ForEach returns the error.
609 func forEach(roots []*Action, f func(*Action) error) error {
610 seen := make(map[*Action]bool)
611 var visitAll func(actions []*Action) error
612 visitAll = func(actions []*Action) error {
613 for _, act := range actions {
614 if !seen[act] {
615 seen[act] = true
616 if err := visitAll(act.Deps); err != nil {
617 return err
618 }
619 if err := f(act); err != nil {
620 return err
621 }
622 }
623 }
624 return nil
625 }
626 return visitAll(roots)
627 }
628
629 func analysisModuleFromPackagesModule(mod *packages.Module) *analysis.Module {
630 if mod == nil {
631 return nil
632 }
633
634 var modErr *analysis.ModuleError
635 if mod.Error != nil {
636 modErr = &analysis.ModuleError{
637 Err: mod.Error.Err,
638 }
639 }
640
641 return &analysis.Module{
642 Path: mod.Path,
643 Version: mod.Version,
644 Replace: analysisModuleFromPackagesModule(mod.Replace),
645 Time: mod.Time,
646 Main: mod.Main,
647 Indirect: mod.Indirect,
648 Dir: mod.Dir,
649 GoMod: mod.GoMod,
650 GoVersion: mod.GoVersion,
651 Error: modErr,
652 }
653 }