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

     1  // Copyright 2026 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 the analysis of a single package.
     8  
     9  import (
    10  	"encoding/gob"
    11  	"encoding/json"
    12  	"fmt"
    13  	"go/analysis"
    14  	"go/ast"
    15  	"go/parser"
    16  	"go/token"
    17  	"go/types"
    18  	"go/types/exportdata"
    19  	"internal/analysis/gotestchecker/protocol"
    20  	"log"
    21  	"maps"
    22  	"net/url"
    23  	"os"
    24  	"reflect"
    25  	"runtime"
    26  	"runtime/debug"
    27  	"slices"
    28  	"strings"
    29  	"sync"
    30  	"sync/atomic"
    31  )
    32  
    33  // run analyzes the package described by the named request file (see
    34  // [protocol.AnalyzeRequest]).
    35  //
    36  // A failure of an analyzer on this package (an error or a panic) does
    37  // not cause run to fail: it is recorded in the analyzer's pass file,
    38  // and reported, once, by the go command. The passes that cannot run
    39  // because of it (or because of type errors in the package) are marked
    40  // as skipped. Only problems with the tool's inputs cause run to fail.
    41  func run(configFile string, vars []Var) error {
    42  	data, err := os.ReadFile(configFile)
    43  	if err != nil {
    44  		return err
    45  	}
    46  	areq := new(protocol.AnalyzeRequest)
    47  	if err := json.Unmarshal(data, areq); err != nil {
    48  		return fmt.Errorf("cannot decode JSON config file %s: %v", configFile, err)
    49  	}
    50  	prof, err := startProfiler(areq)
    51  	if err != nil {
    52  		return err
    53  	}
    54  	if err := analyze(areq, vars, prof); err != nil {
    55  		prof.finish() // ignore error
    56  		return err
    57  	}
    58  	return prof.finish()
    59  }
    60  
    61  // analyze analyzes the package described by areq (see [run]),
    62  // recording its costs in prof, if non-nil.
    63  func analyze(areq *protocol.AnalyzeRequest, vars []Var, prof *profiler) error {
    64  	g := newGraph(vars)
    65  	prof.setAnalyzers(g.analyzers)
    66  	analyzer := func(i int) (*analysis.Analyzer, error) {
    67  		if !(0 <= i && i < len(g.analyzers)) {
    68  			return nil, fmt.Errorf("invalid analyzer index %d", i)
    69  		}
    70  		return g.analyzers[i], nil
    71  	}
    72  
    73  	// Identify the analyzers whose results are required.
    74  	var outputs []*analysis.Analyzer
    75  	for _, i := range slices.Sorted(maps.Keys(areq.Outputs)) {
    76  		a, err := analyzer(i)
    77  		if err != nil {
    78  			return err
    79  		}
    80  		outputs = append(outputs, a)
    81  	}
    82  	report := make(map[*analysis.Analyzer]bool)
    83  	for _, i := range areq.Report {
    84  		a, err := analyzer(i)
    85  		if err != nil {
    86  			return err
    87  		}
    88  		report[a] = true
    89  	}
    90  
    91  	// If there is nothing to do, avoid type checking.
    92  	if len(outputs) == 0 && areq.TypeExport == "" {
    93  		return nil
    94  	}
    95  
    96  	// Parse and type-check. Type errors are written to
    97  	// AnalyzeRequest.TypeErrors, for the go command to report once, and
    98  	// cause every analyzer to be skipped.
    99  	var typeErrs []string
   100  	fset := token.NewFileSet()
   101  	var files []*ast.File
   102  	if err := prof.doErr(phaseParse, -1, func() error {
   103  		for _, name := range areq.GoFiles {
   104  			// Analyzers must use go/types, not the
   105  			// syntactic object resolution of go/parser.
   106  			f, err := parser.ParseFile(fset, name, nil, parser.ParseComments|parser.SkipObjectResolution)
   107  			if err != nil {
   108  				if f == nil {
   109  					return err // can't read file
   110  				}
   111  				typeErrs = append(typeErrs, err.Error())
   112  			}
   113  			files = append(files, f)
   114  		}
   115  		return nil
   116  	}); err != nil {
   117  		return err
   118  	}
   119  	imports := make(map[string]*types.Package)
   120  	importer := importerFunc(func(importPath string) (*types.Package, error) {
   121  		path, ok := areq.ImportMap[importPath] // resolve vendoring, etc
   122  		if !ok {
   123  			return nil, fmt.Errorf("can't resolve import %q", importPath)
   124  		}
   125  		if path == "unsafe" {
   126  			return types.Unsafe, nil
   127  		}
   128  		if pkg, ok := imports[path]; ok && pkg.Complete() {
   129  			return pkg, nil
   130  		}
   131  		file, ok := areq.TypeImports[path]
   132  		if !ok {
   133  			return nil, fmt.Errorf("no types file for %q", path)
   134  		}
   135  		// TODO(adonovan): opt: parallelize reads for all imports before type checking.
   136  		data, err := os.ReadFile(file)
   137  		if err != nil {
   138  			return nil, err
   139  		}
   140  		return exportdata.Decode(fset, path, data, exportdata.PackagesFromMap(imports), exportdata.DecodeOptions{})
   141  	})
   142  	tc := &types.Config{
   143  		Importer:  importer,
   144  		Sizes:     types.SizesFor("gc", areq.GOARCH),
   145  		GoVersion: areq.GoVersion,
   146  		Error: func(err error) {
   147  			typeErrs = append(typeErrs, err.Error())
   148  		},
   149  	}
   150  	info := &types.Info{
   151  		Types:        make(map[ast.Expr]types.TypeAndValue),
   152  		Defs:         make(map[*ast.Ident]types.Object),
   153  		Uses:         make(map[*ast.Ident]types.Object),
   154  		Implicits:    make(map[ast.Node]types.Object),
   155  		Instances:    make(map[*ast.Ident]types.Instance),
   156  		Scopes:       make(map[ast.Node]*types.Scope),
   157  		Selections:   make(map[*ast.SelectorExpr]*types.Selection),
   158  		FileVersions: make(map[*ast.File]string),
   159  	}
   160  	var pkg *types.Package
   161  	prof.do(phaseTypecheck, -1, func() {
   162  		pkg, _ = tc.Check(areq.ImportPath, fset, files, info) // errors are in typeErrs
   163  	})
   164  
   165  	const maxTypeErrors = 10
   166  	if len(typeErrs) > maxTypeErrors {
   167  		typeErrs = append(typeErrs[:maxTypeErrors], "too many errors")
   168  	}
   169  
   170  	// Export types (even if there were type errors, so that the
   171  	// analysis of importers can proceed; their analyzers that
   172  	// depend on facts from this package will fail), and the type
   173  	// errors, if any.
   174  	if areq.TypeErrors != "" {
   175  		data, err := json.Marshal(typeErrs)
   176  		if err != nil {
   177  			log.Fatal(err) // can't happen
   178  		}
   179  		if err := os.WriteFile(areq.TypeErrors, data, 0666); err != nil {
   180  			return err
   181  		}
   182  	}
   183  	if areq.TypeExport != "" {
   184  		if err := prof.doErr(phaseExport, -1, func() error {
   185  			data, err := exportdata.Encode(fset, pkg, exportdata.EncodeOptions{})
   186  			if err != nil {
   187  				return fmt.Errorf("type export failed: %v", err)
   188  			}
   189  			return os.WriteFile(areq.TypeExport, data, 0666)
   190  		}); err != nil {
   191  			return err
   192  		}
   193  	}
   194  	if len(outputs) == 0 {
   195  		return nil
   196  	}
   197  
   198  	// Compute the Requires closure of the outputs.
   199  	requires := make(map[*analysis.Analyzer]bool)
   200  	var visit func(a *analysis.Analyzer)
   201  	visit = func(a *analysis.Analyzer) {
   202  		if !requires[a] {
   203  			requires[a] = true
   204  			for _, req := range a.Requires {
   205  				visit(req)
   206  			}
   207  		}
   208  	}
   209  	for _, a := range outputs {
   210  		visit(a)
   211  	}
   212  
   213  	// Decode a separate fact set for each analyzer in the Requires closure,
   214  	// from that analyzer's pass files for each direct import.
   215  	// (Analyzers that use no facts get an empty set.)
   216  	// If the analyzer failed or was skipped on a direct import, it
   217  	// is skipped here.
   218  	var (
   219  		getPackage = func(path string) *types.Package { return imports[path] }
   220  		decoder    = newFactDecoder(pkg, getPackage)
   221  		sets       = make(map[*analysis.Analyzer]*factSet)
   222  		depSkipped = make(map[*analysis.Analyzer]bool)
   223  	)
   224  	// (Each analyzer is charged for decoding its facts.)
   225  	for _, a := range g.analyzers {
   226  		if !requires[a] {
   227  			continue
   228  		}
   229  		if err := prof.doErr(phaseFacts, g.index[a], func() error {
   230  			files := areq.Facts[g.index[a]] // (only for analyzers that use facts)
   231  			// Read each pass file once. A pass file with a
   232  			// failure, or of a skipped pass, has no facts.
   233  			//
   234  			// TODO(adonovan): opt: parallelize reads of pass files.
   235  			passes := make(map[string]*protocol.Pass)
   236  			for path, file := range files {
   237  				pf, err := protocol.ReadPass(file)
   238  				if err != nil {
   239  					return err
   240  				}
   241  				passes[path] = pf
   242  				prof.factPassFile(g.index[a], len(pf.Facts) == 0 && pf.Failure == nil && !pf.Skipped)
   243  				if pf.Failure != nil || pf.Skipped {
   244  					depSkipped[a] = true
   245  				}
   246  			}
   247  			if depSkipped[a] {
   248  				return nil
   249  			}
   250  			for _, f := range a.FactTypes {
   251  				registerFactType(f)
   252  			}
   253  			set, decoded, discarded, err := decoder.Decode(func(pkgPath string) ([]byte, error) {
   254  				var data []byte // nil for e.g. unsafe
   255  				if pf := passes[pkgPath]; pf != nil {
   256  					data = pf.Facts
   257  				}
   258  				prof.factsIn(g.index[a], len(data))
   259  				return data, nil
   260  			})
   261  			if err != nil {
   262  				return err
   263  			}
   264  			prof.factsDecoded(g.index[a], decoded, discarded)
   265  			sets[a] = set
   266  			return nil
   267  		}); err != nil {
   268  			return err
   269  		}
   270  	}
   271  
   272  	// Execute the DAG of analyzers in the Requires closure, in parallel:
   273  	// each analyzer runs as soon as its prerequisites are done.
   274  	type action struct {
   275  		a           *analysis.Analyzer
   276  		preds       []*action    // actions of the analyzers that require this one
   277  		pending     atomic.Int32 // number of prerequisites not yet done
   278  		result      any
   279  		failure     *protocol.Failure // failure of this pass
   280  		skipped     bool              // pass did not run (see protocol.Pass.Skipped)
   281  		diagnostics []analysis.Diagnostic
   282  	}
   283  	var (
   284  		mu      sync.Mutex // guards action.diagnostics
   285  		actions = make(map[*analysis.Analyzer]*action)
   286  	)
   287  	for _, a := range g.analyzers {
   288  		if requires[a] {
   289  			act := &action{a: a}
   290  			act.pending.Store(int32(len(a.Requires)))
   291  			for _, req := range a.Requires {
   292  				reqact := actions[req] // (prerequisites come first)
   293  				reqact.preds = append(reqact.preds, act)
   294  			}
   295  			actions[a] = act
   296  		}
   297  	}
   298  	exec := func(act *action) {
   299  		a := act.a
   300  		// The analyzer is skipped if a prerequisite failed or was
   301  		// skipped, if it failed or was skipped on a dependency, or
   302  		// if the package has type errors.
   303  		inputs := make(map[*analysis.Analyzer]any)
   304  		for _, req := range a.Requires {
   305  			reqact := actions[req]
   306  			if reqact.failure != nil || reqact.skipped {
   307  				act.skipped = true
   308  			}
   309  			inputs[req] = reqact.result
   310  		}
   311  		if act.skipped || depSkipped[a] || len(typeErrs) > 0 {
   312  			act.skipped = true
   313  			return
   314  		}
   315  
   316  		factFilter := make(map[reflect.Type]bool)
   317  		for _, f := range a.FactTypes {
   318  			factFilter[reflect.TypeOf(f)] = true
   319  		}
   320  		set := sets[a]
   321  		pass := &analysis.Pass{
   322  			Analyzer:     a,
   323  			Fset:         fset,
   324  			Files:        files,
   325  			OtherFiles:   areq.NonGoFiles,
   326  			IgnoredFiles: areq.IgnoredFiles,
   327  			Pkg:          pkg,
   328  			TypesInfo:    info,
   329  			TypesSizes:   tc.Sizes,
   330  			ResultOf:     inputs,
   331  			Report: func(d analysis.Diagnostic) {
   332  				mu.Lock()
   333  				act.diagnostics = append(act.diagnostics, d)
   334  				mu.Unlock()
   335  			},
   336  			// TODO(adonovan): make Export*Fact panic (and thus fail
   337  			// the pass) if the fact's type is not among a.FactTypes,
   338  			// or if called after Run returns, as x/tools' checker does
   339  			// for the latter. Today an undeclared fact type is
   340  			// encoded but cannot be decoded, causing the analysis of
   341  			// importers to fail.
   342  			ImportObjectFact:  set.ImportObjectFact,
   343  			ExportObjectFact:  set.ExportObjectFact,
   344  			AllObjectFacts:    func() []analysis.ObjectFact { return set.AllObjectFacts(factFilter) },
   345  			ImportPackageFact: set.ImportPackageFact,
   346  			ExportPackageFact: set.ExportPackageFact,
   347  			AllPackageFacts:   func() []analysis.PackageFact { return set.AllPackageFacts(factFilter) },
   348  			Module:            analysisModule(areq.Module),
   349  		}
   350  		pass.ReadFile = checkedReadFile(pass)
   351  		var (
   352  			result any
   353  			err    error
   354  		)
   355  		prof.do(phaseRun, g.index[a], func() {
   356  			defer func() {
   357  				if r := recover(); r != nil {
   358  					err = fmt.Errorf("panic: %v\n%s", r, trimStack(debug.Stack(), runPass))
   359  				}
   360  			}()
   361  			result, err = runPass(a, pass)
   362  		})
   363  		if err != nil {
   364  			act.failure = &protocol.Failure{Package: areq.ID, Analyzer: a.Name, Message: err.Error()}
   365  		} else {
   366  			act.result = result
   367  		}
   368  	}
   369  	// Start with the leaves; when an action is done, start each
   370  	// action that requires it whose prerequisites are all done.
   371  	var wg sync.WaitGroup
   372  	var enqueue func(act *action)
   373  	enqueue = func(act *action) {
   374  		wg.Go(func() {
   375  			exec(act)
   376  			for _, pred := range act.preds {
   377  				if pred.pending.Add(-1) == 0 {
   378  					enqueue(pred)
   379  				}
   380  			}
   381  		})
   382  	}
   383  	// (Test the static condition, not pending, which the
   384  	// enqueued actions may already be decrementing.)
   385  	for _, act := range actions {
   386  		if len(act.a.Requires) == 0 {
   387  			enqueue(act)
   388  		}
   389  	}
   390  	wg.Wait()
   391  
   392  	// Write a pass file for each required analyzer.
   393  	for _, a := range outputs {
   394  		act := actions[a]
   395  		pf := &protocol.Pass{
   396  			Failure: act.failure,
   397  			Skipped: act.skipped,
   398  		}
   399  		if pf.Failure == nil && !pf.Skipped && len(a.FactTypes) > 0 {
   400  			var (
   401  				data      []byte
   402  				own, deps int
   403  				err       error
   404  			)
   405  			prof.do(phaseFacts, g.index[a], func() {
   406  				// Recover from panics encoding users' Facts.
   407  				defer func() {
   408  					if r := recover(); r != nil {
   409  						err = fmt.Errorf("encoding facts: panic: %v\n%s", r, trimStack(debug.Stack(), encodeFacts))
   410  					}
   411  				}()
   412  				data, own, deps = encodeFacts(sets[a])
   413  			})
   414  			prof.factsOut(g.index[a], own, deps, len(data))
   415  			if err != nil {
   416  				// A fact that cannot be encoded is the analyzer's fault.
   417  				pf.Failure = &protocol.Failure{Package: areq.ID, Analyzer: a.Name, Message: err.Error()}
   418  			} else {
   419  				pf.Facts = data
   420  			}
   421  		}
   422  		if report[a] {
   423  			for _, d := range act.diagnostics {
   424  				diag := &protocol.Diagnostic{
   425  					Posn:     fset.Position(d.Pos).String(),
   426  					Category: d.Category,
   427  					Message:  d.Message,
   428  					URL:      resolveURL(a, d),
   429  				}
   430  				if d.End.IsValid() {
   431  					diag.End = fset.Position(d.End).String()
   432  				}
   433  				pf.Diagnostics = append(pf.Diagnostics, diag)
   434  			}
   435  		}
   436  		if err := prof.doErr(phaseWrite, -1, func() error {
   437  			return protocol.WritePass(areq.Outputs[g.index[a]], pf)
   438  		}); err != nil {
   439  			return err
   440  		}
   441  	}
   442  	return nil
   443  }
   444  
   445  // trimStack trims the output of [debug.Stack], called during a panic
   446  // recovered beneath the call of the recoverer function (runPass or
   447  // encodeFacts), to the frames between the call of panic and the call of
   448  // that function, which are those of the analyzer (or of its fact
   449  // types). The recoverer is a function value, not a name, so that it
   450  // cannot fail to exist.
   451  func trimStack(stack []byte, recoverer any) string {
   452  	name := runtime.FuncForPC(reflect.ValueOf(recoverer).Pointer()).Name()
   453  	lines := strings.Split(strings.TrimSpace(string(stack)), "\n")
   454  	start, end := 0, len(lines)
   455  	for i, line := range lines {
   456  		if strings.HasPrefix(line, "panic(") && start == 0 {
   457  			start = i + 2 // skip the panic frame and its file:line
   458  		} else if strings.HasPrefix(line, name+"(") {
   459  			end = i
   460  			break
   461  		}
   462  	}
   463  	if start > end {
   464  		start = 0
   465  	}
   466  	return strings.Join(lines[start:end], "\n")
   467  }
   468  
   469  // registerFactType registers the concrete type of a fact with gob,
   470  // under a name that includes the full package path of its type, so
   471  // that fact types of the same name in different packages do not
   472  // conflict. (For a pointer type, which every fact type is,
   473  // gob.Register would use only the package name: see the NOTE in its
   474  // implementation.)
   475  func registerFactType(f analysis.Fact) {
   476  	t := reflect.TypeOf(f)
   477  	name := t.String()
   478  	if t.Kind() == reflect.Pointer && t.Elem().Name() != "" {
   479  		name = "*" + t.Elem().PkgPath() + "." + t.Elem().Name()
   480  	}
   481  	registeredMu.Lock()
   482  	defer registeredMu.Unlock()
   483  	if !registered[t] {
   484  		registered[t] = true
   485  		gob.RegisterName(name, f)
   486  	}
   487  }
   488  
   489  var (
   490  	registeredMu sync.Mutex
   491  	registered   = make(map[reflect.Type]bool)
   492  )
   493  
   494  func init() {
   495  	// Keep analysisModule in sync with the Module types.
   496  	if reflect.TypeFor[protocol.Module]().NumField() != reflect.TypeFor[analysis.Module]().NumField() {
   497  		panic("protocol.Module and analysis.Module have different fields")
   498  	}
   499  }
   500  
   501  // analysisModule converts a protocol.Module to an analysis.Module.
   502  func analysisModule(m *protocol.Module) *analysis.Module {
   503  	if m == nil {
   504  		return nil
   505  	}
   506  	am := &analysis.Module{
   507  		Path:      m.Path,
   508  		Version:   m.Version,
   509  		Replace:   analysisModule(m.Replace),
   510  		Time:      m.Time,
   511  		Main:      m.Main,
   512  		Indirect:  m.Indirect,
   513  		Dir:       m.Dir,
   514  		GoMod:     m.GoMod,
   515  		GoVersion: m.GoVersion,
   516  	}
   517  	// cmd/go supplies the go.mod version ("1.22.0"); the
   518  	// documented form, as supplied by unitchecker, is "go1.22.0".
   519  	if am.GoVersion != "" && !strings.HasPrefix(am.GoVersion, "go") {
   520  		am.GoVersion = "go" + am.GoVersion
   521  	}
   522  	if m.Error != nil {
   523  		am.Error = &analysis.ModuleError{Err: m.Error.Err}
   524  	}
   525  	return am
   526  }
   527  
   528  type importerFunc func(path string) (*types.Package, error)
   529  
   530  func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }
   531  
   532  // checkedReadFile returns a Pass.ReadFile function that enforces the
   533  // access policy documented at [analysis.Pass.ReadFile].
   534  func checkedReadFile(pass *analysis.Pass) func(string) ([]byte, error) {
   535  	return func(filename string) ([]byte, error) {
   536  		ok := slices.Contains(pass.OtherFiles, filename) ||
   537  			slices.Contains(pass.IgnoredFiles, filename) ||
   538  			slices.ContainsFunc(pass.Files, func(f *ast.File) bool {
   539  				return pass.Fset.File(f.FileStart).Name() == filename
   540  			})
   541  		if !ok {
   542  			return nil, fmt.Errorf("Pass.ReadFile: %s is not among OtherFiles, IgnoredFiles, or names of Files", filename)
   543  		}
   544  		return os.ReadFile(filename)
   545  	}
   546  }
   547  
   548  // resolveURL returns the URL of a diagnostic, resolved against the
   549  // URL of its analyzer, as documented at [analysis.Diagnostic]. An empty
   550  // URL with a category means "#category". (It follows unitchecker; an
   551  // unparsable URL is returned unchanged.)
   552  func resolveURL(a *analysis.Analyzer, d analysis.Diagnostic) string {
   553  	if d.URL == "" && d.Category == "" && a.URL == "" {
   554  		return ""
   555  	}
   556  	raw := d.URL
   557  	if raw == "" && d.Category != "" {
   558  		raw = "#" + d.Category
   559  	}
   560  	u, err := url.Parse(raw)
   561  	if err != nil {
   562  		return d.URL
   563  	}
   564  	base, err := url.Parse(a.URL)
   565  	if err != nil {
   566  		return d.URL
   567  	}
   568  	return base.ResolveReference(u).String()
   569  }
   570  
   571  // runPass runs analyzer a on the pass. It is the frame at which
   572  // [trimStack] trims the stacks of panics in analyzers.
   573  //
   574  //go:noinline
   575  func runPass(a *analysis.Analyzer, pass *analysis.Pass) (any, error) {
   576  	return a.Run(pass)
   577  }
   578  
   579  // encodeFacts encodes a set of facts. It is the frame at which
   580  // [trimStack] trims the stacks of panics in fact types.
   581  //
   582  //go:noinline
   583  func encodeFacts(set *factSet) (data []byte, own, deps int) {
   584  	return set.Encode()
   585  }
   586  

View as plain text