Source file src/cmd/go/internal/load/analysis.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 load
     6  
     7  // This file supports analysis in go test: the configuration of the
     8  // analyzers that apply to each root package (one for which go test
     9  // reports diagnostics, as opposed to a dependency) as references to
    10  // analyzer and suite variables, and the synthesis of the analysis
    11  // tool that contains them. Planning and running the analysis is in
    12  // cmd/go/internal/work/analysis.go.
    13  //
    14  // Resolution of the configuration has two stages. The static stage,
    15  // here, determines which variables the tool links, from references
    16  // to them, before the tool exists. The dynamic stage (see
    17  // work.Builder.planAnalysis) uses the tool's metadata to expand
    18  // suites into their members and select the analyzers that apply to
    19  // each package.
    20  //
    21  // The configuration of go test's analysis is currently fixed: the
    22  // vet suite (internal/analysis/suite/vet), or the members of it
    23  // selected by the -vet flag.
    24  
    25  import (
    26  	"bytes"
    27  	"context"
    28  	"fmt"
    29  	"iter"
    30  	"maps"
    31  	"slices"
    32  	"strconv"
    33  	"strings"
    34  
    35  	"cmd/go/internal/build"
    36  	"cmd/go/internal/modload"
    37  )
    38  
    39  // AnalysisToolDriver is the import path of the driver package linked
    40  // into the synthesized analysis tool.
    41  const AnalysisToolDriver = "internal/analysis/gotestchecker"
    42  
    43  // analysisVetPackage is the package whose Suite variable holds the
    44  // vet suite, from which go test's analyzers are selected.
    45  const analysisVetPackage = "internal/analysis/suite/vet"
    46  
    47  // An AnalysisVar identifies an exported analyzer or suite variable.
    48  type AnalysisVar struct {
    49  	PkgPath string
    50  	Name    string
    51  }
    52  
    53  func (v AnalysisVar) String() string { return v.PkgPath + "." + v.Name }
    54  
    55  // An AnalysisRef is a reference to an analyzer variable (pkg.Var) or
    56  // to members of a suite variable (pkg.Var[*] or pkg.Var[A,B]), or (if
    57  // Negative) a negation of analyzers of a given Name.
    58  type AnalysisRef struct {
    59  	Negative bool        // a negation (disable)
    60  	Var      AnalysisVar // the referenced variable
    61  	Members  []string    // nil for an analyzer (pkg.Var); ["*"] or names for a suite (pkg.Var[...])
    62  	Name     string      // for a negation by name: the Analyzer.Name (Var and Members are empty)
    63  }
    64  
    65  // Ref returns the reference as written, e.g. "pkgpath.Var[A,B]",
    66  // or the quoted analyzer name of a negation by name.
    67  func (a *AnalysisRef) Ref() string {
    68  	if a.ByName() {
    69  		return strconv.Quote(a.Name)
    70  	}
    71  	ref := a.Var.String()
    72  	if a.Members != nil {
    73  		ref += "[" + strings.Join(a.Members, ",") + "]"
    74  	}
    75  	return ref
    76  }
    77  
    78  // ByName reports whether the reference is a negation that names
    79  // analyzers by Analyzer.Name rather than by reference. Such a negation
    80  // is applied only in the dynamic stage, to every analyzer of that name;
    81  // it is not linked into the tool.
    82  func (a *AnalysisRef) ByName() bool { return a.Name != "" }
    83  
    84  // IsSuite reports whether the reference is to a suite (pkg.Var[...]).
    85  func (a *AnalysisRef) IsSuite() bool { return a.Members != nil }
    86  
    87  // AllMembers reports whether the reference selects all members of a
    88  // suite (pkg.Var[*]).
    89  func (a *AnalysisRef) AllMembers() bool {
    90  	return len(a.Members) == 1 && a.Members[0] == "*"
    91  }
    92  
    93  // Errorf returns an error about the reference.
    94  func (a *AnalysisRef) Errorf(format string, args ...any) error {
    95  	return fmt.Errorf("%s: %s", a.Ref(), fmt.Sprintf(format, args...))
    96  }
    97  
    98  // CompareAnalysisRefs orders references deterministically.
    99  func CompareAnalysisRefs(x, y *AnalysisRef) int {
   100  	return strings.Compare(x.Ref(), y.Ref())
   101  }
   102  
   103  // An AnalysisConfig records the references that apply to a root
   104  // package.
   105  type AnalysisConfig struct {
   106  	// Positive holds the references that enable analyzers for the
   107  	// package, in order of decreasing specificity.
   108  	Positive []*AnalysisRef
   109  
   110  	// Negative holds the negations that apply to the package,
   111  	// which are applied once the analyzers are known.
   112  	Negative []*AnalysisRef
   113  }
   114  
   115  // VetAnalysisConfig returns go test's built-in analysis configuration:
   116  // the members of the vet suite with the specified names, or all of
   117  // them if names is nil.
   118  func VetAnalysisConfig(names []string) *AnalysisConfig {
   119  	var members []string
   120  	if names == nil {
   121  		members = []string{"*"}
   122  	}
   123  	for _, name := range names {
   124  		// cmd/vet accepts some legacy names (see analysisflags).
   125  		if legacy, ok := vetLegacyNames[name]; ok {
   126  			name = legacy
   127  		}
   128  		if !slices.Contains(members, name) {
   129  			members = append(members, name)
   130  		}
   131  	}
   132  	return &AnalysisConfig{
   133  		Positive: []*AnalysisRef{{
   134  			Var:     AnalysisVar{analysisVetPackage, "Suite"},
   135  			Members: members,
   136  		}},
   137  	}
   138  }
   139  
   140  // vetLegacyNames maps the legacy names of vet analyzers, which the
   141  // -vet flag of go test accepts for compatibility with cmd/vet, to
   142  // their names.
   143  var vetLegacyNames = map[string]string{
   144  	"bool":       "bools",
   145  	"buildtags":  "buildtag",
   146  	"methods":    "stdmethods",
   147  	"rangeloops": "loopclosure",
   148  }
   149  
   150  // AnalysisToolPackage returns a synthesized main package for an
   151  // analysis tool and the source of its sole file. The tool contains
   152  // the variables referenced by the specified references (those that
   153  // enable analyzers for some root package).
   154  //
   155  // The package of each reference must load. A reference whose package
   156  // does not load is reported, and dropped. (Whether the package
   157  // declares the variable is discovered only if the tool fails to
   158  // compile.)
   159  //
   160  // It also returns errors about the offending references.
   161  //
   162  // The package's imports are loaded without regard to the rule for
   163  // internal packages, like the generated testmain: the tool must
   164  // import analyzers from internal packages, and the driver itself is
   165  // an internal package of the standard library.
   166  func AnalysisToolPackage(ld *modload.Loader, ctx context.Context, opts PackageOpts, refs []*AnalysisRef) (pmain *Package, src []byte, errs []error) {
   167  	pmain = &Package{
   168  		PackagePublic: PackagePublic{
   169  			Name:       "main",
   170  			GoFiles:    []string{"analysistool.go"},
   171  			ImportPath: "analysistool",
   172  		},
   173  		Internal: PackageInternal{
   174  			Build:     &build.Package{Name: "main"},
   175  			OmitDebug: true,
   176  		},
   177  	}
   178  	pmain.Internal.ExeName = "analysistool"
   179  	setToolFlags(ld, pmain)
   180  
   181  	var stk ImportStack
   182  	stk.Push(ImportInfo{Pkg: "analysistool"})
   183  	defer stk.Pop()
   184  
   185  	// Load the driver and the packages of the references.
   186  	// (For now, all are standard packages.)
   187  	pkgs := make(map[string]*Package)
   188  	load := func(paths []string) {
   189  		for _, path := range paths {
   190  			if _, ok := pkgs[path]; !ok {
   191  				pkgs[path], _ = loadImport(ld, ctx, opts, nil, path, "", nil, &stk, nil, 0)
   192  			}
   193  		}
   194  	}
   195  	refPkgs := []string{AnalysisToolDriver}
   196  	for _, a := range refs {
   197  		if !slices.Contains(refPkgs, a.Var.PkgPath) {
   198  			refPkgs = append(refPkgs, a.Var.PkgPath)
   199  		}
   200  	}
   201  	load(refPkgs)
   202  
   203  	// checkRef checks that the package of the reference loaded
   204  	// without error and is importable. It does not check that the
   205  	// package declares the variable, which would require parsing
   206  	// the whole package: a missing variable makes the analysis tool
   207  	// fail to compile. Nor does it check the variable's type, which
   208  	// is checked by the analysis tool.
   209  	checkRef := func(a *AnalysisRef) error {
   210  		p := pkgs[a.Var.PkgPath]
   211  		if p == nil {
   212  			return fmt.Errorf("cannot find package %s", a.Var.PkgPath)
   213  		}
   214  		if p.Error != nil {
   215  			return fmt.Errorf("cannot load package %s: %v", a.Var.PkgPath, p.Error)
   216  		}
   217  		if p.Name == "main" {
   218  			return fmt.Errorf("package %s is a program, not an importable package", a.Var.PkgPath)
   219  		}
   220  		return nil
   221  	}
   222  
   223  	// Check the references, and link the variables of the valid
   224  	// ones. (checkRef depends only on the package, so all
   225  	// references to one variable succeed or fail together.)
   226  	linked := make(map[AnalysisVar]bool)
   227  	deps := []string{AnalysisToolDriver} // imports of the main package
   228  	depSet := map[string]bool{AnalysisToolDriver: true}
   229  	for _, a := range refs {
   230  		if err := checkRef(a); err != nil {
   231  			errs = append(errs, a.Errorf("%v", err))
   232  			continue
   233  		}
   234  		linked[a.Var] = true
   235  		if !depSet[a.Var.PkgPath] {
   236  			depSet[a.Var.PkgPath] = true
   237  			deps = append(deps, a.Var.PkgPath)
   238  		}
   239  	}
   240  
   241  	// Add the imports needed by the linker.
   242  	ldDeps, err := LinkerDeps(ld, pmain)
   243  	if err != nil && pmain.Error == nil {
   244  		pmain.Error = &PackageError{Err: err}
   245  	}
   246  	deps = append(deps, ldDeps...)
   247  	for _, dep := range deps {
   248  		p1 := pkgs[dep]
   249  		if p1 == nil {
   250  			var err *PackageError
   251  			p1, err = loadImport(ld, ctx, opts, nil, dep, "", nil, &stk, nil, 0)
   252  			if err != nil && pmain.Error == nil {
   253  				pmain.Error = err
   254  				pmain.Incomplete = true
   255  			}
   256  			pkgs[dep] = p1
   257  		}
   258  		if p1.Error != nil && pmain.Error == nil {
   259  			pmain.Error = p1.Error
   260  			pmain.Incomplete = true
   261  		}
   262  		if !slices.Contains(pmain.Imports, dep) {
   263  			pmain.Imports = append(pmain.Imports, dep)
   264  			pmain.Internal.Imports = append(pmain.Internal.Imports, p1)
   265  		}
   266  	}
   267  
   268  	return pmain, AnalysisToolSource(maps.Keys(linked)), errs
   269  }
   270  
   271  // AnalysisToolSource returns the source of the main package of an
   272  // analysis tool that links the specified variables.
   273  func AnalysisToolSource(vars iter.Seq[AnalysisVar]) []byte {
   274  	var imports, entries bytes.Buffer
   275  	pkgname := make(map[string]string) // pkgpath -> import name
   276  	// The variables are in order of qualified name (see
   277  	// gotestchecker.Main).
   278  	byName := func(x, y AnalysisVar) int {
   279  		return strings.Compare(x.String(), y.String())
   280  	}
   281  	for _, v := range slices.SortedFunc(vars, byName) {
   282  		name, ok := pkgname[v.PkgPath]
   283  		if !ok {
   284  			name = fmt.Sprintf("a%d", len(pkgname))
   285  			pkgname[v.PkgPath] = name
   286  			fmt.Fprintf(&imports, "\t%s %q\n", name, v.PkgPath)
   287  		}
   288  		fmt.Fprintf(&entries, "\t\t{%q, %s.%s},\n", v.String(), name, v.Name)
   289  	}
   290  	return fmt.Appendf(nil, `// Code generated by go test. DO NOT EDIT.
   291  
   292  package main
   293  
   294  import (
   295  	%q
   296  %s)
   297  
   298  func main() {
   299  	gotestchecker.Main({
   300  %s	})
   301  }
   302  `, AnalysisToolDriver, imports.Bytes(), entries.Bytes())
   303  }
   304  

View as plain text