Source file src/internal/analysis/gotestchecker/facts.go

     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 gotestchecker
     6  
     7  // This file defines [factSet], a serializable set of [analysis.Fact].
     8  // It was adapted from [golang.org/x/tools/internal/facts] for this
     9  // driver, in which each analyzer has its own fact set.
    10  //
    11  // It provides a partial implementation of the Fact-related parts of the
    12  // analysis.Pass interface for use in analysis drivers such as "go vet"
    13  // and other build systems.
    14  //
    15  // The serial format is unspecified and may change, so the same version
    16  // of this package must be used for reading and writing serialized facts.
    17  //
    18  // The handling of facts in the analysis system parallels the handling
    19  // of type information in the compiler: during compilation of package P,
    20  // the compiler emits an export data file that describes the type of
    21  // every object (named thing) defined in package P, plus every object
    22  // indirectly reachable from one of those objects. Thus the downstream
    23  // compiler of package Q need only load one export data file per direct
    24  // import of Q, and it will learn everything about the API of package P
    25  // and everything it needs to know about the API of P's dependencies.
    26  //
    27  // Similarly, analysis of package P emits a fact set containing facts
    28  // about all objects exported from P, plus additional facts about only
    29  // those objects of P's dependencies that are reachable from the API of
    30  // package P; the downstream analysis of Q need only load one fact set
    31  // per direct import of Q.
    32  //
    33  // The notion of "exportedness" that matters here is that of the
    34  // compiler. According to the language spec, a method pkg.T.f is
    35  // unexported simply because its name starts with lowercase. But the
    36  // compiler must nonetheless export f so that downstream compilations can
    37  // accurately ascertain whether pkg.T implements an interface pkg.I
    38  // defined as interface{f()}. Exported thus means "described in export
    39  // data".
    40  
    41  import (
    42  	"bytes"
    43  	"encoding/gob"
    44  	"fmt"
    45  	"go/analysis"
    46  	"go/types"
    47  	"io"
    48  	"log"
    49  	"reflect"
    50  	"sort"
    51  	"sync"
    52  
    53  	"golang.org/x/tools/go/types/objectpath"
    54  )
    55  
    56  const debugFacts = false
    57  
    58  // A factSet is a set of [analysis.Fact].
    59  //
    60  // Decode creates a factSet of facts by reading from the imports of a given
    61  // package, and Encode writes out the set. Between these operation,
    62  // the Import and Export methods will query and update the set.
    63  //
    64  // All of factSet's methods except String are safe to call concurrently.
    65  type factSet struct {
    66  	pkg *types.Package
    67  	mu  sync.Mutex
    68  	m   map[factKey]analysis.Fact
    69  }
    70  
    71  type factKey struct {
    72  	pkg *types.Package
    73  	obj types.Object // (object facts only)
    74  	t   reflect.Type
    75  }
    76  
    77  // ImportObjectFact implements analysis.Pass.ImportObjectFact.
    78  func (s *factSet) ImportObjectFact(obj types.Object, ptr analysis.Fact) bool {
    79  	if obj == nil {
    80  		panic("nil object")
    81  	}
    82  	key := factKey{pkg: obj.Pkg(), obj: obj, t: reflect.TypeOf(ptr)}
    83  	s.mu.Lock()
    84  	defer s.mu.Unlock()
    85  	if v, ok := s.m[key]; ok {
    86  		reflect.ValueOf(ptr).Elem().Set(reflect.ValueOf(v).Elem())
    87  		return true
    88  	}
    89  	return false
    90  }
    91  
    92  // ExportObjectFact implements analysis.Pass.ExportObjectFact.
    93  func (s *factSet) ExportObjectFact(obj types.Object, fact analysis.Fact) {
    94  	if obj.Pkg() != s.pkg {
    95  		log.Panicf("in package %s: ExportObjectFact(%s, %T): can't set fact on object belonging another package",
    96  			s.pkg, obj, fact)
    97  	}
    98  	key := factKey{pkg: obj.Pkg(), obj: obj, t: reflect.TypeOf(fact)}
    99  	s.mu.Lock()
   100  	s.m[key] = fact // clobber any existing entry
   101  	s.mu.Unlock()
   102  }
   103  
   104  func (s *factSet) AllObjectFacts(filter map[reflect.Type]bool) []analysis.ObjectFact {
   105  	var facts []analysis.ObjectFact
   106  	s.mu.Lock()
   107  	for k, v := range s.m {
   108  		if k.obj != nil && filter[k.t] {
   109  			facts = append(facts, analysis.ObjectFact{Object: k.obj, Fact: v})
   110  		}
   111  	}
   112  	s.mu.Unlock()
   113  	return facts
   114  }
   115  
   116  // ImportPackageFact implements analysis.Pass.ImportPackageFact.
   117  func (s *factSet) ImportPackageFact(pkg *types.Package, ptr analysis.Fact) bool {
   118  	if pkg == nil {
   119  		panic("nil package")
   120  	}
   121  	key := factKey{pkg: pkg, t: reflect.TypeOf(ptr)}
   122  	s.mu.Lock()
   123  	defer s.mu.Unlock()
   124  	if v, ok := s.m[key]; ok {
   125  		reflect.ValueOf(ptr).Elem().Set(reflect.ValueOf(v).Elem())
   126  		return true
   127  	}
   128  	return false
   129  }
   130  
   131  // ExportPackageFact implements analysis.Pass.ExportPackageFact.
   132  func (s *factSet) ExportPackageFact(fact analysis.Fact) {
   133  	key := factKey{pkg: s.pkg, t: reflect.TypeOf(fact)}
   134  	s.mu.Lock()
   135  	s.m[key] = fact // clobber any existing entry
   136  	s.mu.Unlock()
   137  }
   138  
   139  func (s *factSet) AllPackageFacts(filter map[reflect.Type]bool) []analysis.PackageFact {
   140  	var facts []analysis.PackageFact
   141  	s.mu.Lock()
   142  	for k, v := range s.m {
   143  		if k.obj == nil && filter[k.t] {
   144  			facts = append(facts, analysis.PackageFact{Package: k.pkg, Fact: v})
   145  		}
   146  	}
   147  	s.mu.Unlock()
   148  	return facts
   149  }
   150  
   151  // gobFact is the Gob declaration of a serialized fact.
   152  type gobFact struct {
   153  	PkgPath string          // path of package
   154  	Object  objectpath.Path // optional path of object relative to package itself
   155  	Fact    analysis.Fact   // type and value of user-defined Fact
   156  }
   157  
   158  // A factDecoder decodes the facts from the direct imports of the package
   159  // provided to newFactDecoder. A single decoder may be used to decode
   160  // multiple fact sets (e.g. each for a different set of fact types)
   161  // for the same package. Each call to Decode returns an independent
   162  // fact set.
   163  type factDecoder struct {
   164  	pkg        *types.Package
   165  	getPackage getPackageFunc
   166  }
   167  
   168  // newFactDecoder returns a fact decoder for the specified package.
   169  //
   170  // It calls the getPackage function for the package path string of
   171  // each dependency (perhaps indirect) that it encounters in the
   172  // encoding. If the function returns nil, the fact is discarded.
   173  //
   174  // Typically getPackage consults the package map of the importer used
   175  // to type-check pkg. Any package not in that map cannot be the owner
   176  // of an object or package that an analyzer could query, so facts
   177  // about it are of no use and may safely be discarded.
   178  func newFactDecoder(pkg *types.Package, getPackage getPackageFunc) *factDecoder {
   179  	return &factDecoder{
   180  		pkg:        pkg,
   181  		getPackage: getPackage,
   182  	}
   183  }
   184  
   185  // A getPackageFunc function returns the package denoted by a package path.
   186  type getPackageFunc = func(pkgPath string) *types.Package
   187  
   188  // Decode decodes all the facts relevant to the analysis of package
   189  // pkgPath. The read function reads serialized fact data from an external
   190  // source for one of pkg's direct imports, identified by package path.
   191  // The empty file is a valid encoding of an empty fact set.
   192  //
   193  // It is the caller's responsibility to call gob.Register on all
   194  // necessary fact types.
   195  //
   196  // Concurrent calls to Decode are safe, so long as the
   197  // [getPackageFunc] (if any) is also concurrency-safe.
   198  //
   199  // It also returns the number of facts decoded, and the number of those
   200  // discarded because they relate to a package or object not present
   201  // in this translation unit.
   202  func (d *factDecoder) Decode(read func(pkgPath string) ([]byte, error)) (_ *factSet, decoded, discarded int, _ error) {
   203  	// Read facts from imported packages.
   204  	// Facts may describe indirectly imported packages, or their objects.
   205  	m := make(map[factKey]analysis.Fact) // one big bucket
   206  	for _, imp := range d.pkg.Imports() {
   207  		logf := func(format string, args ...any) {
   208  			if debugFacts {
   209  				prefix := fmt.Sprintf("in %s, importing %s: ",
   210  					d.pkg.Path(), imp.Path())
   211  				log.Print(prefix, fmt.Sprintf(format, args...))
   212  			}
   213  		}
   214  
   215  		// Read the gob-encoded facts.
   216  		data, err := read(imp.Path())
   217  		if err != nil {
   218  			return nil, 0, 0, fmt.Errorf("in %s, can't import facts for package %q: %v",
   219  				d.pkg.Path(), imp.Path(), err)
   220  		}
   221  		if len(data) == 0 {
   222  			continue // no facts
   223  		}
   224  		var gobFacts []gobFact
   225  		if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&gobFacts); err != nil {
   226  			return nil, 0, 0, fmt.Errorf("decoding facts for %q: %v", imp.Path(), err)
   227  		}
   228  		logf("decoded %d facts: %v", len(gobFacts), gobFacts)
   229  		decoded += len(gobFacts)
   230  
   231  		// Parse each one into a key and a Fact.
   232  		for _, f := range gobFacts {
   233  			factPkg := d.getPackage(f.PkgPath) // possibly an indirect dependency
   234  			if factPkg == nil {
   235  				// Fact relates to a dependency that was
   236  				// unused in this translation unit. Skip.
   237  				logf("no package %q; discarding %v", f.PkgPath, f.Fact)
   238  				discarded++
   239  				continue
   240  			}
   241  			key := factKey{pkg: factPkg, t: reflect.TypeOf(f.Fact)}
   242  			if f.Object != "" {
   243  				// object fact
   244  				obj, err := objectpath.Object(factPkg, f.Object)
   245  				if err != nil {
   246  					// (most likely due to unexported object)
   247  					// TODO(adonovan): audit for other possibilities.
   248  					logf("no object for path: %v; discarding %s", err, f.Fact)
   249  					discarded++
   250  					continue
   251  				}
   252  				key.obj = obj
   253  				logf("read %T fact %s for %v", f.Fact, f.Fact, key.obj)
   254  			} else {
   255  				// package fact
   256  				logf("read %T fact %s for %v", f.Fact, f.Fact, factPkg)
   257  			}
   258  			m[key] = f.Fact
   259  		}
   260  	}
   261  
   262  	return &factSet{pkg: d.pkg, m: m}, decoded, discarded, nil
   263  }
   264  
   265  // Encode encodes a set of facts to a memory buffer. It also returns
   266  // the number of facts encoded about the package itself (own) and
   267  // re-exported about objects of its dependencies (deps).
   268  //
   269  // It may fail if one of the Facts could not be gob-encoded, but this is
   270  // a sign of a bug in an Analyzer.
   271  func (s *factSet) Encode() (data []byte, own, deps int) {
   272  	encoder := new(objectpath.Encoder)
   273  
   274  	// TODO(adonovan): opt: use a more efficient encoding
   275  	// that avoids repeating PkgPath for each fact.
   276  
   277  	// Gather all facts, including those from imported packages.
   278  	var gobFacts []gobFact
   279  
   280  	s.mu.Lock()
   281  	for k, fact := range s.m {
   282  		if debugFacts {
   283  			log.Printf("%v => %s\n", k, fact)
   284  		}
   285  
   286  		// Don't export facts that we imported from another
   287  		// package, unless they represent fields or methods,
   288  		// or package-level types.
   289  		// (Facts about packages, and other package-level
   290  		// objects, are only obtained from direct imports so
   291  		// they needn't be reexported.)
   292  		//
   293  		// This is analogous to the pruning done by "deep"
   294  		// export data for types, but not as precise because
   295  		// we aren't careful about which structs or methods
   296  		// we rexport: it should be only those referenced
   297  		// from the API of s.pkg.
   298  		// TODO(adonovan): opt: be more precise. e.g.
   299  		// intersect with the set of objects reachable
   300  		// from the API of s.pkg.
   301  		// TODO(adonovan): opt: implement "shallow" facts.
   302  		if k.pkg != s.pkg {
   303  			if k.obj == nil {
   304  				continue // imported package fact
   305  			}
   306  			if _, isType := k.obj.(*types.TypeName); !isType &&
   307  				k.obj.Parent() == k.obj.Pkg().Scope() {
   308  				continue // imported fact about package-level non-type object
   309  			}
   310  		}
   311  
   312  		var object objectpath.Path
   313  		if k.obj != nil {
   314  			path, err := encoder.For(k.obj)
   315  			if err != nil {
   316  				if debugFacts {
   317  					log.Printf("discarding fact %s about %s\n", fact, k.obj)
   318  				}
   319  				continue // object not accessible from package API; discard fact
   320  			}
   321  			object = path
   322  		}
   323  		gobFacts = append(gobFacts, gobFact{
   324  			PkgPath: k.pkg.Path(),
   325  			Object:  object,
   326  			Fact:    fact,
   327  		})
   328  		if k.pkg == s.pkg {
   329  			own++
   330  		} else {
   331  			deps++
   332  		}
   333  	}
   334  	s.mu.Unlock()
   335  
   336  	// Sort facts by (package, object, type) for determinism.
   337  	sort.Slice(gobFacts, func(i, j int) bool {
   338  		x, y := gobFacts[i], gobFacts[j]
   339  		if x.PkgPath != y.PkgPath {
   340  			return x.PkgPath < y.PkgPath
   341  		}
   342  		if x.Object != y.Object {
   343  			return x.Object < y.Object
   344  		}
   345  		tx := reflect.TypeOf(x.Fact)
   346  		ty := reflect.TypeOf(y.Fact)
   347  		if tx != ty {
   348  			return tx.String() < ty.String()
   349  		}
   350  		return false // equal
   351  	})
   352  
   353  	var buf bytes.Buffer
   354  	if len(gobFacts) > 0 {
   355  		if err := gob.NewEncoder(&buf).Encode(gobFacts); err != nil {
   356  			// Fact encoding should never fail. Identify the culprit.
   357  			for _, gf := range gobFacts {
   358  				if err := gob.NewEncoder(io.Discard).Encode(gf); err != nil {
   359  					fact := gf.Fact
   360  					pkgpath := reflect.TypeOf(fact).Elem().PkgPath()
   361  					log.Panicf("internal error: gob encoding of analysis fact %s failed: %v; please report a bug against fact %T in package %q",
   362  						fact, err, fact, pkgpath)
   363  				}
   364  			}
   365  		}
   366  	}
   367  
   368  	if debugFacts {
   369  		log.Printf("package %q: encode %d facts, %d bytes\n",
   370  			s.pkg.Path(), len(gobFacts), buf.Len())
   371  	}
   372  
   373  	return buf.Bytes(), own, deps
   374  }
   375  
   376  // String is provided only for debugging, and must not be called
   377  // concurrent with any Import/Export method.
   378  func (s *factSet) String() string {
   379  	var buf bytes.Buffer
   380  	buf.WriteString("{")
   381  	for k, f := range s.m {
   382  		if buf.Len() > 1 {
   383  			buf.WriteString(", ")
   384  		}
   385  		if k.obj != nil {
   386  			buf.WriteString(k.obj.String())
   387  		} else {
   388  			buf.WriteString(k.pkg.Path())
   389  		}
   390  		fmt.Fprintf(&buf, ": %v", f)
   391  	}
   392  	buf.WriteString("}")
   393  	return buf.String()
   394  }
   395  

View as plain text