Commit 0356517f65 for golang

commit 0356517f6558f2fb50443426ea6764e6b2adbe25
Author: Alan Donovan <adonovan@google.com>
Date:   Wed Nov 25 15:30:12 2026 -0500

    cmd/go: test: configure core vet checks using go.vet files

    This change causes 'go test' (with GOEXPERIMENT=vetfiles) to
    read its configuration of core vet checks dynamically using
    the new go.vet mechanism:

    - fmt, errors, sync/atomic, and log/slog enable
      printf, errorsas, atomic, and slog for their importers;

    - GOROOT/src/go.vet enables the remaining high-confidence
      checks for every package, using the "global" scope,
      which is permitted only in that file;

    - GOROOT/src and GOROOT/src/cmd enable the whole suite, minus
      unsafeptr and unreachable, for the packages of the distribution
      (except vendor), replacing the GOROOT special case.

    For now, a disable declaration must name analyzers by Analyzer.Name
    (as GOROOT/src/go.vet does for unsafeptr); a disable by reference
    (pkg.Var or pkg.Var[A,B]) is an error. A follow-up CL will support it.

    Reading order:
     load (static resolution), work (dynamic), test.

    For #82464

    Change-Id: Ic00f09996ed9894bf8816177f12de637c136ddb4
    Reviewed-on: https://go-review.googlesource.com/c/go/+/856984
    Reviewed-by: Michael Matloob <matloob@google.com>
    LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
    Reviewed-by: Michael Matloob <matloob@golang.org>
    Auto-Submit: Alan Donovan <adonovan@google.com>

diff --git a/src/cmd/go.vet b/src/cmd/go.vet
new file mode 100644
index 0000000000..76f295aca9
--- /dev/null
+++ b/src/cmd/go.vet
@@ -0,0 +1,14 @@
+// This file declares the analyzers that go test runs on the packages
+// beneath this directory (see go.dev/issue/82464).
+
+// The packages of the Go distribution are checked by go test with all
+// the analyzers of the vet suite, except those disabled below.
+enable ./... internal/analysis/suite/vet.Suite[*]
+
+// There is too much unsafe.Pointer code that unsafeptr does not like
+// in low-level packages (go.dev/cl/176439, for go.dev/issue/31916).
+disable ./... "unsafeptr"
+
+// During testing it is common to make changes, such as forced
+// returns, that make code unreachable (go.dev/cl/240550).
+disable ./... "unreachable"
diff --git a/src/cmd/go/internal/load/analysis.go b/src/cmd/go/internal/load/analysis.go
index 42933f51b9..8f0e9e2587 100644
--- a/src/cmd/go/internal/load/analysis.go
+++ b/src/cmd/go/internal/load/analysis.go
@@ -15,12 +15,14 @@ package load
 // here, determines which variables the tool links, from references
 // to them, before the tool exists. The dynamic stage (see
 // work.Builder.planAnalysis) uses the tool's metadata to expand
-// suites into their members and select the analyzers that apply to
-// each package.
+// suites into their members, apply negations, and select the
+// analyzers that apply to each package.
 //
-// The configuration of go test's analysis is currently fixed: the
-// vet suite (internal/analysis/suite/vet), or the members of it
-// selected by the -vet flag.
+// The configuration of go test's analysis comes from its built-in
+// configuration (which the -vet flag can override) and from the
+// declarations of go.vet files (see vetfile.go), which in the standard
+// library select members of the vet suite
+// (internal/analysis/suite/vet).

 import (
 	"bytes"
@@ -29,11 +31,11 @@ import (
 	"iter"
 	"maps"
 	"slices"
-	"strconv"
 	"strings"

 	"cmd/go/internal/build"
 	"cmd/go/internal/modload"
+	"cmd/go/internal/vetfile"
 )

 // AnalysisToolDriver is the import path of the driver package linked
@@ -44,78 +46,64 @@ const AnalysisToolDriver = "internal/analysis/gotestchecker"
 // vet suite, from which go test's analyzers are selected.
 const analysisVetPackage = "internal/analysis/suite/vet"

-// An AnalysisVar identifies an exported analyzer or suite variable.
-type AnalysisVar struct {
-	PkgPath string
-	Name    string
-}
-
-func (v AnalysisVar) String() string { return v.PkgPath + "." + v.Name }
+// A VetRef is a reference to an analyzer variable (pkg.Var) or to
+// members of a suite variable (pkg.Var[*] or pkg.Var[A,B]), or (if
+// !Decl.Enable) a negation of one, or of analyzers of a given Name.
+//
+// A reference is the declaration of a go.vet file, or (for go test's
+// built-in configuration, as with an explicit -vet flag) a synthesized
+// declaration, whose Scope and Pos are zero.
+type VetRef struct {
+	Decl *vetfile.Decl // syntactic declaration in go.vet file (or 'go test -vet' flag)
+	Std  bool          // declaration is in the standard library

-// An AnalysisRef is a reference to an analyzer variable (pkg.Var) or
-// to members of a suite variable (pkg.Var[*] or pkg.Var[A,B]), or (if
-// Negative) a negation of analyzers of a given Name.
-type AnalysisRef struct {
-	Negative bool        // a negation (disable)
-	Var      AnalysisVar // the referenced variable
-	Members  []string    // nil for an analyzer (pkg.Var); ["*"] or names for a suite (pkg.Var[...])
-	Name     string      // for a negation by name: the Analyzer.Name (Var and Members are empty)
+	// Problems records problems with the reference encountered
+	// before analysis (e.g. unresolvable package, nonexistent
+	// suite member). They are reported once and cause nonzero
+	// exit but do not prevent progress of other references.
+	Problems []string
 }

-// Ref returns the reference as written, e.g. "pkgpath.Var[A,B]",
-// or the quoted analyzer name of a negation by name.
-func (a *AnalysisRef) Ref() string {
-	if a.ByName() {
-		return strconv.Quote(a.Name)
-	}
-	ref := a.Var.String()
-	if a.Members != nil {
-		ref += "[" + strings.Join(a.Members, ",") + "]"
-	}
-	return ref
+// InVetSuite reports whether the reference denotes the vet suite,
+// internal/analysis/suite/vet.Suite.
+func (ref *VetRef) InVetSuite() bool {
+	return ref.Decl.Var == vetfile.Var{PkgPath: analysisVetPackage, Name: "Suite"} // (a disable by name has no Var)
 }

 // ByName reports whether the reference is a negation that names
 // analyzers by Analyzer.Name rather than by reference. Such a negation
 // is applied only in the dynamic stage, to every analyzer of that name;
 // it is not linked into the tool.
-func (a *AnalysisRef) ByName() bool { return a.Name != "" }
+func (ref *VetRef) ByName() bool { return ref.Decl.Name != "" }

-// IsSuite reports whether the reference is to a suite (pkg.Var[...]).
-func (a *AnalysisRef) IsSuite() bool { return a.Members != nil }
+// IsSuite reports whether the reference is to a suite (pkg.Var[x,y] or pkg.Var[*]).
+func (ref *VetRef) IsSuite() bool { return ref.Decl.Members != nil }

 // AllMembers reports whether the reference selects all members of a
 // suite (pkg.Var[*]).
-func (a *AnalysisRef) AllMembers() bool {
-	return len(a.Members) == 1 && a.Members[0] == "*"
+func (ref *VetRef) AllMembers() bool {
+	return len(ref.Decl.Members) == 1 && ref.Decl.Members[0] == "*"
 }

-// Errorf returns an error about the reference.
-func (a *AnalysisRef) Errorf(format string, args ...any) error {
-	return fmt.Errorf("%s: %s", a.Ref(), fmt.Sprintf(format, args...))
-}
-
-// CompareAnalysisRefs orders references deterministically.
-func CompareAnalysisRefs(x, y *AnalysisRef) int {
-	return strings.Compare(x.Ref(), y.Ref())
-}
+// HasPos reports whether the reference was declared in a file.
+func (ref *VetRef) HasPos() bool { return ref.Decl.File != nil }

-// An AnalysisConfig records the references that apply to a root
-// package.
-type AnalysisConfig struct {
-	// Positive holds the references that enable analyzers for the
-	// package, in order of decreasing specificity.
-	Positive []*AnalysisRef
-
-	// Negative holds the negations that apply to the package,
-	// which are applied once the analyzers are known.
-	Negative []*AnalysisRef
+// Position returns the position of the reference as "file:line:col",
+// using the file name for display (see readVetFile), or "-vet flag"
+// for a reference of the configuration of an explicit -vet flag.
+func (ref *VetRef) Position() string {
+	if !ref.HasPos() {
+		return "-vet flag"
+	}
+	return ref.Decl.Position()
 }

-// VetAnalysisConfig returns go test's built-in analysis configuration:
-// the members of the vet suite with the specified names, or all of
-// them if names is nil.
-func VetAnalysisConfig(names []string) *AnalysisConfig {
+// VetSuiteRef returns the reference denoted by an explicit -vet
+// flag of go test: the members of the vet suite with the specified
+// names, or all of them if names is nil. (Without the flag, go test's
+// default checks are declared by GOROOT/src/go.vet, and other go.vet
+// files of the standard library.)
+func VetSuiteRef(names []string) *VetRef {
 	var members []string
 	if names == nil {
 		members = []string{"*"}
@@ -129,17 +117,22 @@ func VetAnalysisConfig(names []string) *AnalysisConfig {
 			members = append(members, name)
 		}
 	}
-	return &AnalysisConfig{
-		Positive: []*AnalysisRef{{
-			Var:     AnalysisVar{analysisVetPackage, "Suite"},
+	return &VetRef{
+		// fake "enable global vet.Suite[...]" decl
+		Decl: &vetfile.Decl{
+			Enable:  true,
+			Scope:   "global",
+			Var:     vetfile.Var{PkgPath: analysisVetPackage, Name: "Suite"},
 			Members: members,
-		}},
+		},
 	}
 }

 // vetLegacyNames maps the legacy names of vet analyzers, which the
 // -vet flag of go test accepts for compatibility with cmd/vet, to
 // their names.
+//
+// TODO(adonovan): it may be time to retire these old names.
 var vetLegacyNames = map[string]string{
 	"bool":       "bools",
 	"buildtags":  "buildtag",
@@ -149,22 +142,28 @@ var vetLegacyNames = map[string]string{

 // AnalysisToolPackage returns a synthesized main package for an
 // analysis tool and the source of its sole file. The tool contains
-// the variables referenced by the specified references (those that
-// enable analyzers for some root package).
+// the variables referenced by the specified positive references (those
+// that enable analyzers for some root package), subject to the checks
+// below.
+//
+// The package of each positive reference must load. A reference
+// whose package does not load is reported at each declaration that
+// uses it, and dropped. (Whether the package declares the variable
+// is discovered only if the tool fails to compile.)
 //
-// The package of each reference must load. A reference whose package
-// does not load is reported, and dropped. (Whether the package
-// declares the variable is discovered only if the tool fails to
-// compile.)
+// A negation (for now, always a disable by name; see readVetFile) is
+// not linked, and needs no checks.
 //
-// It also returns errors about the offending references.
+// It records the problems of the offending references (see
+// VetRef.Problems).
 //
 // The package's imports are loaded without regard to the rule for
 // internal packages, like the generated testmain: the tool must
 // import analyzers from internal packages, and the driver itself is
 // an internal package of the standard library.
-func AnalysisToolPackage(ld *modload.Loader, ctx context.Context, opts PackageOpts, refs []*AnalysisRef) (pmain *Package, src []byte, errs []error) {
+func AnalysisToolPackage(ld *modload.Loader, ctx context.Context, opts PackageOpts, refs []*VetRef) (pmain *Package, src []byte) {
 	pmain = &Package{
+		// Avoid de-nesting this literal until bootstrap has go1.27.
 		PackagePublic: PackagePublic{
 			Name:       "main",
 			GoFiles:    []string{"analysistool.go"},
@@ -182,8 +181,10 @@ func AnalysisToolPackage(ld *modload.Loader, ctx context.Context, opts PackageOp
 	stk.Push(ImportInfo{Pkg: "analysistool"})
 	defer stk.Pop()

-	// Load the driver and the packages of the references.
+	// Load the driver and the packages of positive references.
 	// (For now, all are standard packages.)
+	//
+	// TODO(adonovan): relax this restriction (see CL 857003).
 	pkgs := make(map[string]*Package)
 	load := func(paths []string) {
 		for _, path := range paths {
@@ -192,53 +193,56 @@ func AnalysisToolPackage(ld *modload.Loader, ctx context.Context, opts PackageOp
 			}
 		}
 	}
-	refPkgs := []string{AnalysisToolDriver}
-	for _, a := range refs {
-		if !slices.Contains(refPkgs, a.Var.PkgPath) {
-			refPkgs = append(refPkgs, a.Var.PkgPath)
+	var positive []*VetRef
+	for _, ref := range refs {
+		if ref.Decl.Enable {
+			positive = append(positive, ref)
 		}
 	}
-	load(refPkgs)
+	load(append([]string{AnalysisToolDriver}, refPkgPaths(positive)...))

-	// checkRef checks that the package of the reference loaded
-	// without error and is importable. It does not check that the
-	// package declares the variable, which would require parsing
-	// the whole package: a missing variable makes the analysis tool
-	// fail to compile. Nor does it check the variable's type, which
-	// is checked by the analysis tool.
-	checkRef := func(a *AnalysisRef) error {
-		p := pkgs[a.Var.PkgPath]
-		if p == nil {
-			return fmt.Errorf("cannot find package %s", a.Var.PkgPath)
-		}
-		if p.Error != nil {
-			return fmt.Errorf("cannot load package %s: %v", a.Var.PkgPath, p.Error)
-		}
-		if p.Name == "main" {
-			return fmt.Errorf("package %s is a program, not an importable package", a.Var.PkgPath)
+	// checkRef reports whether the package of the reference loaded
+	// without error and is importable, recording a problem if not.
+	// It does not check that the package declares the variable,
+	// which would require parsing the whole package: a missing
+	// variable makes the analysis tool fail to compile. Nor does it
+	// check the variable's type, which is checked by the analysis
+	// tool.
+	checkRef := func(ref *VetRef) bool {
+		path := ref.Decl.Var.PkgPath
+		var msg string
+		switch p := pkgs[path]; {
+		case p == nil:
+			msg = fmt.Sprintf("cannot find package %s", path)
+		case p.Error != nil:
+			msg = fmt.Sprintf("cannot load package %s: %v", path, p.Error)
+		case p.Name == "main":
+			msg = fmt.Sprintf("package %s is a program, not an importable package", path)
+		default:
+			return true
 		}
-		return nil
+		ref.Problems = append(ref.Problems, msg)
+		return false
 	}

-	// Check the references, and link the variables of the valid
-	// ones. (checkRef depends only on the package, so all
+	// Check the positive references, and link the variables of the
+	// valid ones. (checkRef depends only on the package, so all
 	// references to one variable succeed or fail together.)
-	linked := make(map[AnalysisVar]bool)
-	deps := []string{AnalysisToolDriver} // imports of the main package
-	depSet := map[string]bool{AnalysisToolDriver: true}
-	for _, a := range refs {
-		if err := checkRef(a); err != nil {
-			errs = append(errs, a.Errorf("%v", err))
-			continue
-		}
-		linked[a.Var] = true
-		if !depSet[a.Var.PkgPath] {
-			depSet[a.Var.PkgPath] = true
-			deps = append(deps, a.Var.PkgPath)
+	linked := make(map[vetfile.Var]bool) // set of variables to link
+	for _, ref := range positive {
+		if checkRef(ref) {
+			linked[ref.Decl.Var] = true
 		}
 	}

-	// Add the imports needed by the linker.
+	// The main package imports the driver and the packages of the
+	// linked variables, plus the packages needed by the linker.
+	deps := []string{AnalysisToolDriver}
+	for v := range linked {
+		deps = append(deps, v.PkgPath)
+	}
+	slices.Sort(deps[1:])
+	deps = slices.Compact(deps)
 	ldDeps, err := LinkerDeps(ld, pmain)
 	if err != nil && pmain.Error == nil {
 		pmain.Error = &PackageError{Err: err}
@@ -265,17 +269,28 @@ func AnalysisToolPackage(ld *modload.Loader, ctx context.Context, opts PackageOp
 		}
 	}

-	return pmain, AnalysisToolSource(maps.Keys(linked)), errs
+	return pmain, AnalysisToolSource(maps.Keys(linked))
+}
+
+// refPkgPaths returns the sorted package paths of the variables of
+// the specified references, without duplicates.
+func refPkgPaths(refs []*VetRef) []string {
+	var paths []string
+	for _, ref := range refs {
+		paths = append(paths, ref.Decl.Var.PkgPath)
+	}
+	slices.Sort(paths)
+	return slices.Compact(paths)
 }

 // AnalysisToolSource returns the source of the main package of an
 // analysis tool that links the specified variables.
-func AnalysisToolSource(vars iter.Seq[AnalysisVar]) []byte {
-	var imports, entries bytes.Buffer
+func AnalysisToolSource(vars iter.Seq[vetfile.Var]) []byte {
+	var imps, entries bytes.Buffer
 	pkgname := make(map[string]string) // pkgpath -> import name
 	// The variables are in order of qualified name (see
 	// gotestchecker.Main).
-	byName := func(x, y AnalysisVar) int {
+	byName := func(x, y vetfile.Var) int {
 		return strings.Compare(x.String(), y.String())
 	}
 	for _, v := range slices.SortedFunc(vars, byName) {
@@ -283,7 +298,7 @@ func AnalysisToolSource(vars iter.Seq[AnalysisVar]) []byte {
 		if !ok {
 			name = fmt.Sprintf("a%d", len(pkgname))
 			pkgname[v.PkgPath] = name
-			fmt.Fprintf(&imports, "\t%s %q\n", name, v.PkgPath)
+			fmt.Fprintf(&imps, "\t%s %q\n", name, v.PkgPath)
 		}
 		fmt.Fprintf(&entries, "\t\t{%q, %s.%s},\n", v.String(), name, v.Name)
 	}
@@ -299,5 +314,5 @@ func main() {
 	gotestchecker.Main({
 %s	})
 }
-`, AnalysisToolDriver, imports.Bytes(), entries.Bytes())
+`, AnalysisToolDriver, imps.Bytes(), entries.Bytes())
 }
diff --git a/src/cmd/go/internal/load/vetfile.go b/src/cmd/go/internal/load/vetfile.go
new file mode 100644
index 0000000000..7d77897f5b
--- /dev/null
+++ b/src/cmd/go/internal/load/vetfile.go
@@ -0,0 +1,266 @@
+// Copyright 2026 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package load
+
+// This file implements workspace-specified analyzers in go test:
+// directories enable analyzers with directives (enable and disable
+// declarations) in a file named go.vet, whose syntax follows that of
+// go.mod, and go test runs them over the relevant packages (with
+// GOEXPERIMENT=vetfiles; see cfg.Experiment.VetFiles). For now, only
+// the go.vet files of the standard library (GOROOT/src) are read;
+// they declare go test's vet checks.
+//
+// This file implements the static stage of resolution for the
+// declarations: parsing them, and computing which apply to each
+// root package.
+//
+// See go.dev/issue/82464.
+
+import (
+	"errors"
+	"io/fs"
+	"path/filepath"
+	"slices"
+
+	"cmd/go/internal/base"
+	"cmd/go/internal/cfg"
+	"cmd/go/internal/vetfile"
+	"cmd/internal/par"
+
+	"golang.org/x/mod/modfile"
+)
+
+// readVetFile returns the references declared by the
+// declarations of the go.vet file in dir, whose import path is
+// dirPath, and which belongs to the standard library if std (see
+// [vetfile.InStd] and [vetfile.Read]), if any. A missing,
+// unreadable, or invalid file yields no references.
+//
+// The results are cached, so each declaration yields a single
+// VetRef, whose identity matters: references are keys of sets.
+// Likewise, the problems
+// with the file (a failure to read it, other than its absence, or
+// errors in it) are reported once, when it is first read,
+// and cause go test to fail. A file with any error is ignored
+// entirely: none of its declarations take effect.
+//
+// Declarations that are invalid in dir (see [vetfile.Read]),
+// such as a reference to a package that is not visible from dir, are
+// likewise errors. (The cache is keyed by dir alone, so all callers
+// must agree on dirPath and std, which are properties of the tree of
+// the package whose directory or ancestor dir is; see
+// [vetfile.EnclosingDirs].)
+func readVetFile(dir, dirPath string, std bool) []*VetRef {
+	return vetFileCache.Do(dir, func() []*VetRef {
+		if !std {
+			// TODO(adonovan): relax this restriction (see CL 857003).
+			return nil // only the go.vet files of std are read
+		}
+		f, err := vetfile.Read(dir, dirPath, std)
+		if err != nil {
+			if list, ok := errors.AsType[modfile.ErrorList](err); ok {
+				for i := range list {
+					base.Errorf("go: %v", &list[i]) // (modfile.Error has a pointer receiver)
+				}
+			} else if !errors.Is(err, fs.ErrNotExist) {
+				base.Errorf("go: %v", err)
+			}
+			return nil
+		}
+		// For now, a disable declaration must name analyzers
+		// by Analyzer.Name, not by reference.
+		//
+		// TODO(adonovan): support disable by reference.
+		ok := true
+		for _, decl := range f.Decls {
+			if !decl.Enable && decl.Name == "" {
+				base.Errorf("go: %s: %s: disable by reference is not yet supported; disable by analyzer name", decl.Position(), decl)
+				ok = false
+			}
+		}
+		if !ok {
+			return nil
+		}
+		var refs []*VetRef
+		for _, decl := range f.Decls {
+			refs = append(refs, &VetRef{Decl: decl, Std: std})
+		}
+		return refs
+	})
+}
+
+var vetFileCache par.Cache[string, []*VetRef] // see readVetFile; keyed by directory
+
+// dirImportPath returns the import path of the directory of package
+// p. A test variant (P [P.test]) or external test package (P_test) is
+// in the directory of P.
+func dirImportPath(p *Package) string {
+	path := p.ImportPath
+	if p.ForTest != "" && (path == p.ForTest || path == p.ForTest+"_test") {
+		path = p.ForTest
+	}
+	return path
+}
+
+// inStd reports whether package p belongs to the standard library
+// (see [vetfile.InStd]). A test variant or external test package
+// belongs where its package does.
+func inStd(p *Package) bool {
+	return vetfile.InStd(p.Dir, dirImportPath(p))
+}
+
+// inModule reports whether the go.vet declarations of package p may
+// apply: it belongs to a module (perhaps vendored) or GOROOT.
+//
+// It may returns false for non-std packages in GOPATH mode
+// (GO111MODULE=off), for a command-line-arguments package.
+func inModule(p *Package) bool {
+	// (Every package should have a p.Dir; but let's
+	// be defensive before calling readVetFile(p.Dir, path).)
+	return p.Dir != "" && !p.Internal.CmdlineFiles && (p.Goroot || p.Module != nil)
+}
+
+// importersCache memoizes importersRefs.
+var importersCache par.Cache[*Package, []*VetRef]
+
+// importersRefs returns the "importers" references declared by the
+// go.vet files of the (non-reflexive) transitive imports of p,
+// in a deterministic order.
+func importersRefs(p *Package) []*VetRef {
+	// Results are memoized bottom-up, so the total cost is linear
+	// in the size of the import graph. The graph is acyclic (a
+	// package in an import cycle has an error, so go test does not
+	// analyze it), so the recursion never re-enters Do for the same
+	// package, which would deadlock.
+	//
+	// TODO(adonovan): opt: use a bit-vector fixed-point iteration
+	// to compute reachability more scalably.
+	return importersCache.Do(p, func() []*VetRef {
+		var refs []*VetRef
+		seen := make(map[*VetRef]bool)
+		add := func(ref *VetRef) {
+			if !seen[ref] {
+				seen[ref] = true
+				refs = append(refs, ref)
+			}
+		}
+		for _, imp := range p.Internal.Imports {
+			if inModule(imp) {
+				for _, ref := range readVetFile(imp.Dir, imp.ImportPath, inStd(imp)) {
+					if ref.Decl.Scope == "importers" {
+						add(ref)
+					}
+				}
+			}
+			for _, ref := range importersRefs(imp) {
+				add(ref)
+			}
+		}
+		return refs
+	})
+}
+
+// AnalyzersFor returns the references that apply to root package p.
+//
+// A root package is a test variant "P [P.test]", an external test
+// package "P_test", or a package without tests.
+//
+// References with errors are discarded; problems are reported as a
+// side effect as they are discovered (see [readVetFile]).
+//
+// The result contains a mix of positive (enable) and negative
+// (disable) references. Positive references are ordered by decreasing
+// specificity. Order is immaterial for negations since a negation
+// prevails over every positive reference, however specific.
+//
+// Negations (for now, always by name; see [readVetFile]) are applied
+// once the analyzers and their names are known.
+//
+// The "." and "./..." declarations of p's directory and its ancestors
+// (up to the root of its module) apply if p belongs to a module (main
+// or not) or the standard library. The "importers" declarations of
+// p's transitive imports apply if p belongs to a module or the
+// standard library; otherwise only those of the standard library
+// apply.
+//
+// If vetFlag is non-nil, it is the reference of an explicit -vet flag
+// (see [VetSuiteRef]), which overrides the standard library's
+// configuration of the vet checks (see [vetFlagOverrides]), and
+// applies to every root package, least specifically.
+//
+// Not safe for concurrent use.
+func AnalyzersFor(p *Package, vetFlag *VetRef) []*VetRef {
+	// refs, in order of specificity
+	var (
+		ancestors []*VetRef // "." and "./..."
+		importers []*VetRef // "importers" and "global"
+	)
+
+	// Scan ancestor directories for "." and "./..." decls.
+	//
+	// The declarations of GOROOT/src/go.vet and
+	// GOROOT/src/cmd/go.vet apply to the external test packages
+	// of std and cmd (which are not Standard), but not to their
+	// vendored packages.
+	if inModule(p) {
+		var modPath string
+		if p.Module != nil {
+			modPath = p.Module.Path
+		}
+		pkgPath := dirImportPath(p) // remove "_test"
+		std := inStd(p)             // (and so of each enclosing directory)
+		for dir, dirPath := range vetfile.EnclosingDirs(p.Dir, pkgPath, modPath) {
+			for _, ref := range readVetFile(dir, dirPath, std) {
+				// (Only p's own directory has p's import path.)
+				if ref.Decl.Scope == "./..." || ref.Decl.Scope == "." && dirPath == pkgPath {
+					ancestors = append(ancestors, ref)
+				}
+			}
+		}
+	}
+
+	// Gather the "importers" declarations of p's transitive imports.
+	for _, ref := range importersRefs(p) {
+		// An "importers" declaration applies to every
+		// importer, even one from which its analyzer is
+		// not visible (because it is internal to the
+		// declaring package's tree); such an importer can
+		// disable it by name (`disable . "name"`).
+		if inModule(p) || ref.Std {
+			importers = append(importers, ref)
+		}
+	}
+
+	// The "global" declarations of GOROOT/src/go.vet (go test's
+	// default checks) apply to every package, least specifically.
+	for _, a := range readVetFile(filepath.Clean(cfg.GOROOTsrc), "", true) {
+		if a.Decl.Scope == "global" {
+			importers = append(importers, a)
+		}
+	}
+
+	result := slices.Concat(ancestors, importers)
+
+	// The -vet=... flag disables the standard library's
+	// configuration of the vet checks and enables only the
+	// named ones.
+	if vetFlag != nil {
+		result = slices.DeleteFunc(result, vetFlagOverrides)
+		result = append(result, vetFlag)
+	}
+
+	return result
+}
+
+// vetFlagOverrides reports whether an explicit -vet flag of go test
+// overrides the reference: whether it belongs to the standard library's
+// configuration of the vet checks, that is, it is a declaration of the
+// standard library that refers to the vet suite, or that disables
+// analyzers by name (such as unsafeptr in GOROOT/src/go.vet). Other
+// declarations of the standard library, which enable analyzers outside
+// the vet suite, are unaffected by the flag.
+func vetFlagOverrides(ref *VetRef) bool {
+	return ref.Std && (ref.InVetSuite() || ref.ByName())
+}
diff --git a/src/cmd/go/internal/test/analysis.go b/src/cmd/go/internal/test/analysis.go
index f460b7cecd..d9599f1dad 100644
--- a/src/cmd/go/internal/test/analysis.go
+++ b/src/cmd/go/internal/test/analysis.go
@@ -9,7 +9,6 @@ package test

 import (
 	"context"
-	"maps"
 	"os"
 	"path/filepath"
 	"slices"
@@ -23,48 +22,30 @@ import (
 	"cmd/go/internal/work"
 )

-// positiveRefs holds the references that enable analyzers for some
-// root package.
-var positiveRefs = make(map[*load.AnalysisRef]bool)
-
-// vetAnalysisConfig returns go test's analysis configuration for
-// package p, from the -vet flag: the selected members of the vet
-// suite, or all of them for -vet=all.
+// vetFlagRef returns the reference of an explicit -vet flag, or nil in
+// its absence: a single reference to the selected members of the vet
+// suite, or all of them for -vet=all, which applies to every root
+// package (and replaces the declarations of the standard library; see
+// load.AnalyzersFor). Without the flag, go test's default checks are
+// declared by the go.vet files of the standard library,
+// GOROOT/src/go.vet for those that apply to every package ("global"),
+// and those of the packages whose use they check (e.g. printf for
+// "importers" of fmt) for the others.
 //
-// As with cmd/vet, packages in GOROOT are by default checked with
-// nearly all analyzers (see gorootAnalysisConfig).
-func vetAnalysisConfig(p *load.Package) *load.AnalysisConfig {
-	if p.Goroot && !testVet.explicit {
-		return gorootAnalysisConfig()
+// It is computed once, so that all root packages share a single
+// reference.
+var vetFlagRef = sync.OnceValue(func() *load.VetRef {
+	if !testVet.explicit {
+		return nil
 	}
-	return userAnalysisConfig()
-}
-
-var userAnalysisConfig = sync.OnceValue(func() *load.AnalysisConfig {
-	if testVet.explicit && testVet.flags == nil {
-		return load.VetAnalysisConfig(nil) // -vet=all
+	if testVet.flags == nil {
+		return load.VetSuiteRef(nil) // -vet=all
 	}
 	var names []string
 	for _, flag := range testVet.flags {
 		names = append(names, strings.TrimPrefix(flag, "-"))
 	}
-	return load.VetAnalysisConfig(names)
-})
-
-// gorootAnalysisConfig is the default configuration for packages in
-// GOROOT: all vet analyzers except unsafeptr (there is too much
-// unsafe.Pointer code that it does not like in low-level packages)
-// and unreachable (during testing it is common to make changes, such
-// as forced returns, that make code unreachable). See also
-// work.vetFlags.
-var gorootAnalysisConfig = sync.OnceValue(func() *load.AnalysisConfig {
-	config := load.VetAnalysisConfig(nil)
-	// TODO(adonovan): this list is temporary; it will soon move
-	// into a go.vet file in GOROOT/src.
-	for _, name := range []string{"unsafeptr", "unreachable"} {
-		config.Negative = append(config.Negative, &load.AnalysisRef{Negative: true, Name: name})
-	}
-	return config
+	return load.VetSuiteRef(names)
 })

 // addTestAnalysis adds an action to report the analyzers enabled for
@@ -83,11 +64,11 @@ func addTestAnalysis(ld *modload.Loader, b *work.Builder, p *load.Package, runAc
 		// vet checks. (This differs from cmd/vet, which -c ran.)
 		return
 	}
-	config := vetAnalysisConfig(p)
-	for _, a := range config.Positive {
-		positiveRefs[a] = true
+	refs := load.AnalyzersFor(p, vetFlagRef())
+	if !slices.ContainsFunc(refs, func(ref *load.VetRef) bool { return ref.Decl.Enable }) {
+		return // no analyzers enabled
 	}
-	a := b.AnalysisVetAction(ld, p, config)
+	a := b.AnalysisVetAction(ld, p, refs)
 	// Install will clean the build directory; make sure analysis runs first.
 	if installAction != nil {
 		installAction.Deps = append(installAction.Deps, a)
@@ -108,10 +89,7 @@ func buildAnalysisTool(ld *modload.Loader, ctx context.Context, b *work.Builder,
 	if !b.HasAnalysisActions() {
 		return
 	}
-	refs := slices.SortedFunc(maps.Keys(positiveRefs), load.CompareAnalysisRefs)
-	for _, err := range synthesizeAnalysisTool(ld, ctx, b, opts, refs) {
-		base.Errorf("go: %v", err)
-	}
+	synthesizeAnalysisTool(ld, ctx, b, opts, b.AnalysisRefs())
 }

 // analysisUsesCmdVet reports whether go test uses cmd/vet in place of
@@ -134,11 +112,12 @@ var analysisUsesCmdVet = sync.OnceValue(func() bool {
 })

 // synthesizeAnalysisTool synthesizes the main package of the analysis
-// tool, containing the variables referenced by refs, and adds the
-// actions to build it and query its metadata to b. It returns errors
-// loading the packages of the references.
-func synthesizeAnalysisTool(ld *modload.Loader, ctx context.Context, b *work.Builder, opts load.PackageOpts, refs []*load.AnalysisRef) []error {
-	pmain, src, errs := load.AnalysisToolPackage(ld, ctx, opts, refs)
+// tool, containing the variables referenced by the specified
+// references, and adds the actions to build it and query its
+// metadata to b. It records the problems of the references whose
+// packages could not be loaded (see load.VetRef.Problems).
+func synthesizeAnalysisTool(ld *modload.Loader, ctx context.Context, b *work.Builder, opts load.PackageOpts, refs []*load.VetRef) {
+	pmain, src := load.AnalysisToolPackage(ld, ctx, opts, refs)
 	dir := b.CompileAction(work.ModeBuild, work.ModeBuild, pmain).Objdir
 	if err := b.BackgroundShell().Mkdir(dir); err != nil {
 		base.Fatal(err)
@@ -153,5 +132,4 @@ func synthesizeAnalysisTool(ld *modload.Loader, ctx context.Context, b *work.Bui
 	link.Target = dir + "analysistool" + cfg.ExeSuffix
 	link.CacheExecutable = true
 	b.SetAnalysisTool(link)
-	return errs
 }
diff --git a/src/cmd/go/internal/work/analysis.go b/src/cmd/go/internal/work/analysis.go
index 396b94b41f..f8d72d45a5 100644
--- a/src/cmd/go/internal/work/analysis.go
+++ b/src/cmd/go/internal/work/analysis.go
@@ -80,6 +80,7 @@ package work

 import (
 	"bytes"
+	"cmp"
 	"context"
 	"crypto/sha256"
 	"encoding/json"
@@ -131,11 +132,15 @@ func analysisResultOf(a *Action) *analysisResult {

 // analysisState is the per-Builder state of analysis in go test.
 type analysisState struct {
-	actions    []*Action                        // all actions of Mode "analysisvet"
-	roots      []*Action                        // analysisvet actions of root packages, in order of request
-	rootConfig map[*Action]*load.AnalysisConfig // root analysisvet action -> references that apply to its package
-	tool       *Action                          // link action for the tool
-	meta       *Action                          // analysismeta action
+	actions  []*Action                  // all actions of Mode "analysisvet"
+	roots    []*Action                  // analysisvet actions of root packages, in order of request
+	rootRefs map[*Action][]*load.VetRef // root analysisvet action -> references that apply to its package (see [load.AnalyzersFor])
+	tool     *Action                    // link action for the tool
+	meta     *Action                    // analysismeta action
+
+	// refs is the union of rootRefs, in order of first appearance.
+	refs    []*load.VetRef
+	refSeen map[*load.VetRef]bool

 	// toolPath is the executable of the tool. toolID identifies
 	// the executable for caching its metadata ("" if not cacheable).
@@ -149,11 +154,10 @@ type analysisState struct {
 // An analysisPlan holds the metadata of the analysis tool's analyzers
 // (by index) and the plan derived from it.
 type analysisPlan struct {
-	analyzers []analyzerInfo                        // index -> analyzer
-	driverID  cache.ActionID                        // dependency identity of the driver package
-	need      map[*Action][]int                     // analysisvet action -> sorted indexes of needed pass files
-	reported  map[*Action]map[int]*reportedAnalyzer // root analysisvet action -> index -> analyzer whose diagnostics are reported
-	refErrs   map[*Action][]string                  // root analysisvet action -> errors in its references
+	analyzers []analyzerInfo                   // index -> analyzer
+	driverID  cache.ActionID                   // dependency identity of the driver package
+	need      map[*Action][]int                // analysisvet action -> sorted indexes of needed pass files
+	reported  map[*Action]map[int]*load.VetRef // root analysisvet action -> index of analyzer whose diagnostics are reported -> most specific reference that enabled it
 }

 // An analyzerInfo holds the metadata of one of the analysis tool's
@@ -164,18 +168,10 @@ type analyzerInfo struct {
 	id                 cache.ActionID // identity
 }

-// A reportedAnalyzer describes an analyzer whose diagnostics are
-// reported for a root package. (The pass of that analyzer on that
-// package is a reported pass.)
-type reportedAnalyzer struct {
-	name string // "pkg.Var" or "pkg.Var[Name]"
-
-	// TODO(adonovan): more to come
-}
-
 // AnalysisVetAction returns an action that reports the diagnostics of
-// the analyzers enabled for package p by the specified configuration,
-// which must be non-nil. The action depends on the analysis of p,
+// the analyzers enabled for package p by the specified references
+// (see [load.AnalyzersFor]), at least one of which must be positive.
+// The action depends on the analysis of p,
 // which in turn depends on the analysis of each of p's dependencies,
 // which computes the facts needed by p's analyzers.
 // The tool must be supplied later by SetAnalysisTool.
@@ -185,19 +181,28 @@ type reportedAnalyzer struct {
 // package (e.g. a package without test files is itself the root, not
 // a test variant of it), and its diagnostics must not cause the
 // analysis of its importers to fail.
-func (b *Builder) AnalysisVetAction(s *modload.Loader, p *load.Package, config *load.AnalysisConfig) *Action {
-	if config == nil {
-		panic("nil config")
+func (b *Builder) AnalysisVetAction(s *modload.Loader, p *load.Package, refs []*load.VetRef) *Action {
+	if len(refs) == 0 {
+		panic("no references")
 	}
 	a := b.analysisVetAction(s, p)
 	st := &b.analysis
-	if _, ok := st.rootConfig[a]; !ok { // first request to vet p
+	if _, ok := st.rootRefs[a]; !ok { // first request to vet p
 		st.roots = append(st.roots, a)
-		if st.rootConfig == nil {
-			st.rootConfig = make(map[*Action]*load.AnalysisConfig)
+		if st.rootRefs == nil {
+			st.rootRefs = make(map[*Action][]*load.VetRef)
+		}
+	}
+	st.rootRefs[a] = refs // (makes p a root package)
+	for _, ref := range refs {
+		if !st.refSeen[ref] {
+			if st.refSeen == nil {
+				st.refSeen = make(map[*load.VetRef]bool)
+			}
+			st.refSeen[ref] = true
+			st.refs = append(st.refs, ref)
 		}
 	}
-	st.rootConfig[a] = config // (makes p a root package)
 	return &Action{
 		Mode:       "analysisreport",
 		Package:    p,
@@ -286,9 +291,27 @@ func (b *Builder) prioritizeAnalysisTool(all []*Action) {
 // HasAnalysisActions reports whether any analysis actions were created.
 func (b *Builder) HasAnalysisActions() bool { return len(b.analysis.actions) > 0 }

+// AnalysisRefs returns the references that apply to some root package
+// (see AnalysisVetAction), in order of first appearance.
+func (b *Builder) AnalysisRefs() []*load.VetRef { return b.analysis.refs }
+
 // analysisMeta is the actor for the analysismeta action.
-// It runs the tool's metadata query and plans the analysis.
-func (b *Builder) analysisMeta(ctx context.Context, a *Action) error {
+// It runs the tool's metadata query, plans the analysis,
+// and reports reference problems.
+func (b *Builder) analysisMeta(ctx context.Context, a *Action) (err error) {
+	// Report references' problems, in order, once planning ends.
+	defer func() {
+		var buf bytes.Buffer
+		for _, ref := range b.analysis.refs {
+			for _, msg := range ref.Problems {
+				fmt.Fprintf(&buf, "%s: %s %s: %s\n", ref.Position(), ref.Decl.Verb(), ref.Decl.Ref(), msg)
+			}
+		}
+		if buf.Len() > 0 {
+			err = cmp.Or(err, b.Shell(a).reportCmd("analysis references", "", buf.Bytes(), errors.New("analysis references dropped")))
+		}
+	}()
+
 	st := &b.analysis
 	st.toolPath = st.tool.BuiltTarget()
 	st.toolID = st.tool.buildID
@@ -512,8 +535,7 @@ func (b *Builder) planAnalysis(md *protocol.Metadata, driverID cache.ActionID, i
 	plan := &analysisPlan{
 		analyzers: make([]analyzerInfo, len(md.Analyzers)),
 		driverID:  driverID,
-		reported:  make(map[*Action]map[int]*reportedAnalyzer),
-		refErrs:   make(map[*Action][]string),
+		reported:  make(map[*Action]map[int]*load.VetRef),
 	}
 	for i, an := range md.Analyzers {
 		set := map[int]bool{i: true}
@@ -541,10 +563,19 @@ func (b *Builder) planAnalysis(md *protocol.Metadata, driverID cache.ActionID, i
 		return slices.Sorted(maps.Keys(set))
 	}

-	// Expand suites, apply selectors and negations, and compute
-	// the analyzers reported for each root package.
+	// Validate each reference against the metadata, once, recording
+	// its problems, and expand it to the members it selects.
+	members := make(map[*load.VetRef][]*protocol.Member)
+	for _, ref := range st.refs {
+		if !ref.ByName() {
+			members[ref] = resolveMembers(md, ref)
+		}
+	}
+
+	// Apply selectors and negations, and compute the analyzers
+	// reported for each root package.
 	for _, a := range st.roots {
-		plan.reported[a], plan.refErrs[a] = resolveAnalyzers(md, st.rootConfig[a])
+		plan.reported[a] = resolveAnalyzers(md, st.rootRefs[a], members)
 	}

 	// Compute the pass files needed from each analysisvet action:
@@ -609,99 +640,99 @@ func (b *Builder) planAnalysis(md *protocol.Metadata, driverID cache.ActionID, i
 }

 // resolveAnalyzers performs the dynamic stage of resolution for one
-// root package, whose references are described by config. Using
-// the tool's metadata, it expands suites, applies selectors, and
-// applies negations by Analyzer.Name. It returns the analyzers whose diagnostics are reported, by index, and
-// errors in the references.
-//
-// Validation is per reference: an invalid reference (or member) is
-// reported and dropped; the others still run.
-func resolveAnalyzers(md *protocol.Metadata, config *load.AnalysisConfig) (map[int]*reportedAnalyzer, []string) {
-	var errs []string
-	errorf := func(annot *load.AnalysisRef, format string, args ...any) {
-		errs = append(errs, annot.Errorf(format, args...).Error())
-	}
-
-	// members returns the valid members selected by reference
-	// annot, with their indexes and display names, reporting any
-	// errors.
-	type member struct {
-		index int
-		name  string
-	}
-	members := func(annot *load.AnalysisRef) []member {
-		v := md.Var(annot.Var.String())
-		if v == nil {
-			return nil // not linked (error reported statically)
-		}
-		if v.Error != "" {
-			errorf(annot, "%s", v.Error)
-			return nil
+// root package, whose references (see load.AnalyzersFor) are refs: it
+// enables the members of each positive reference, as computed by
+// [resolveMembers], and applies negations (for now, always disables
+// by name) by Analyzer.Name. It returns the analyzers whose
+// diagnostics are reported, by index, each with the most specific
+// reference that enabled it.
+func resolveAnalyzers(md *protocol.Metadata, refs []*load.VetRef, members map[*load.VetRef][]*protocol.Member) map[int]*load.VetRef {
+	// Enable the members of each positive reference. The first
+	// (most specific) enabling reference of each analyzer wins.
+	enabled := make(map[int]*load.VetRef)
+	for _, ref := range refs {
+		if !ref.Decl.Enable {
+			continue
 		}
-		if v.IsSuite != annot.IsSuite() {
-			if !v.IsSuite {
-				errorf(annot, "%s is an analyzer, not a suite (remove the brackets)", annot.Var)
-			} else {
-				errorf(annot, "%[1]s is a suite (use %[1]s[*] or select members by name)", annot.Var)
+		for _, m := range members[ref] {
+			if _, ok := enabled[m.Analyzer]; !ok {
+				enabled[m.Analyzer] = ref
 			}
-			return nil
 		}
-		var res []member
-		addMember := func(m *protocol.Member) {
-			name := annot.Var.String()
-			if v.IsSuite {
-				name += "[" + m.Name + "]"
-			}
-			if m.Analyzer < 0 {
-				msg := m.Error
-				if v.IsSuite {
-					msg = fmt.Sprintf("member %s: %s", m.Name, msg)
-				}
-				errorf(annot, "%s", msg)
-				return
-			}
-			res = append(res, member{m.Analyzer, name})
+	}
+
+	// Apply negations: a disable by name disables every enabled
+	// analyzer of that name.
+	// (This must be a separate pass after all the positive
+	// references, since a negation prevails over all of them.)
+	for _, ref := range refs {
+		if ref.Decl.Enable {
+			continue
 		}
-		if !annot.IsSuite() || annot.AllMembers() {
-			for _, m := range v.Members {
-				addMember(m)
-			}
-		} else {
-			for _, name := range annot.Members {
-				i := slices.IndexFunc(v.Members, func(m *protocol.Member) bool {
-					return m.Name == name
-				})
-				if i < 0 {
-					errorf(annot, "suite %s has no member named %s", annot.Var.String(), name)
-					continue
-				}
-				addMember(v.Members[i])
+		for h := range enabled {
+			if md.Analyzers[h].Name == ref.Decl.Name {
+				delete(enabled, h)
 			}
 		}
-		return res
 	}
+	return enabled
+}

-	// Enable the members of each positive reference. The first
-	// (most specific) enabling reference of each analyzer wins.
-	enabled := make(map[int]*reportedAnalyzer)
-	for _, annot := range config.Positive {
-		for _, m := range members(annot) {
-			if _, ok := enabled[m.index]; !ok {
-				enabled[m.index] = &reportedAnalyzer{name: m.name}
+// resolveMembers returns the valid members selected by the reference
+// (each with its index in md.Analyzers), recording its problems (see
+// load.VetRef.Problems). Validation is per reference: an invalid
+// reference (or member) is dropped; the others still run. A reference
+// whose variable is not linked selects nothing (its problem was
+// recorded statically).
+func resolveMembers(md *protocol.Metadata, ref *load.VetRef) []*protocol.Member {
+	problem := func(format string, args ...any) {
+		ref.Problems = append(ref.Problems, fmt.Sprintf(format, args...))
+	}
+	v := md.Var(ref.Decl.Var.String())
+	if v == nil {
+		return nil // not linked (problem recorded statically)
+	}
+	if v.Error != "" {
+		problem("%s", v.Error)
+		return nil
+	}
+	if v.IsSuite != ref.IsSuite() {
+		if !v.IsSuite {
+			problem("%s is an analyzer, not a suite (remove the brackets)", ref.Decl.Var)
+		} else {
+			problem("%[1]s is a suite (use %[1]s[*] or select members by name)", ref.Decl.Var)
+		}
+		return nil
+	}
+	var res []*protocol.Member
+	addMember := func(m *protocol.Member) {
+		if m.Analyzer < 0 {
+			if v.IsSuite {
+				problem("member %s: %s", m.Name, m.Error)
+			} else {
+				problem("%s", m.Error)
 			}
+			return
 		}
+		res = append(res, m)
 	}
-
-	// Apply negations: a negation by name disables every enabled
-	// analyzer of that name.
-	for _, annot := range config.Negative {
-		for h := range enabled {
-			if md.Analyzers[h].Name == annot.Name {
-				delete(enabled, h)
+	if !ref.IsSuite() || ref.AllMembers() {
+		for _, m := range v.Members {
+			addMember(m)
+		}
+	} else {
+		for _, name := range ref.Decl.Members {
+			i := slices.IndexFunc(v.Members, func(m *protocol.Member) bool {
+				return m.Name == name
+			})
+			if i < 0 {
+				problem("suite %s has no member named %s", ref.Decl.Var, name)
+				continue
 			}
+			addMember(v.Members[i])
 		}
 	}
-	return enabled, errs
+	return res
 }

 // analysisVet is the actor for an analysisvet action.
@@ -731,7 +762,7 @@ func (b *Builder) analysisVet(ctx context.Context, a *Action) error {
 		// Without the tool's metadata, the analysis cannot be
 		// planned, so show a placeholder command for each root
 		// package.
-		if _, ok := st.rootConfig[a]; ok {
+		if _, ok := st.rootRefs[a]; ok {
 			b.Shell(a).ShowCmd("", "%s %s # analyzers determined by -describe", st.toolPath, a.Objdir+"analysis.cfg")
 		}
 		return nil
@@ -1009,6 +1040,12 @@ func (b *Builder) analysisReport(ctx context.Context, r *Action) error {
 	if a.Actor == nil || a.Deps[0].Failed != nil {
 		return nil // built-in package, or build failed (reported elsewhere)
 	}
+	// A package some of whose references have problems fails,
+	// without an error of its own: the problems are reported once,
+	// by the analysismeta action. (A failure below takes precedence.)
+	if slices.ContainsFunc(b.analysis.rootRefs[a], func(ref *load.VetRef) bool { return len(ref.Problems) > 0 }) {
+		r.Failed = b.analysis.meta
+	}
 	plan := b.analysis.plan
 	if plan == nil {
 		return nil // tool or metadata query failed (reported elsewhere)
@@ -1018,29 +1055,21 @@ func (b *Builder) analysisReport(ctx context.Context, r *Action) error {
 	var buf bytes.Buffer
 	incomplete := false // some reported analyzer failed or was skipped

-	// Report errors in the references.
-	for _, msg := range plan.refErrs[a] {
-		fmt.Fprintf(&buf, "%s\n", msg)
-	}
-
 	// Report the diagnostics of the reported analyzers,
-	// ordered by name. (Type errors and failures are
+	// in analyzer order. (Type errors and failures are
 	// reported by the analysisvet action of the
 	// package in which they occur.)
-	indexes := slices.SortedFunc(maps.Keys(reported), func(x, y int) int {
-		return strings.Compare(reported[x].name, reported[y].name)
-	})
+	indexes := slices.Sorted(maps.Keys(reported))
 	res := analysisResultOf(a)
 	if res == nil {
 		// Analysis of the package failed (reported elsewhere).
 		incomplete = len(indexes) > 0
 	} else {
 		for _, index := range indexes {
-			en := reported[index]
 			out, ok := res.passes[index]
 			if !ok {
 				// Every reported analyzer is in plan.need[a].
-				return fmt.Errorf("internal error: no pass file for analyzer %s", en.name)
+				return fmt.Errorf("internal error: no pass file for analyzer %s", plan.analyzers[index].Name)
 			}
 			pf, err := protocol.ReadPass(out.file)
 			if err != nil {
diff --git a/src/cmd/go/testdata/script/test_analysis_vet.txt b/src/cmd/go/testdata/script/test_analysis_vet.txt
index 36d77bca9a..d5dccd5a5e 100644
--- a/src/cmd/go/testdata/script/test_analysis_vet.txt
+++ b/src/cmd/go/testdata/script/test_analysis_vet.txt
@@ -38,6 +38,11 @@ stderr 'unused.go:5:12: result of fmt.Sprint call not used'
 stderr 'notests.go:5:39: fmt.Sprintf format %d has arg "x" of wrong type string'
 stdout '^FAIL\s+example.com/m/notests \[build failed\]$'

+# The "importers" declarations of std (here, printf for the importers
+# of fmt) apply to external test packages too.
+! go test ./xtest
+stderr 'xtest_test.go:5:22: fmt.Sprintf format %d has arg "x" of wrong type string'
+
 # printf runs on dependencies too, so it recognizes calls to printf
 # wrappers declared in other packages (using facts).
 ! go test ./wrapcall
@@ -230,3 +235,11 @@ package wrapcall
 import "example.com/m/wrapper"

 func F() { wrapper.Logf("%d", "x") }
+-- xtest/xtest.go --
+package xtest
+-- xtest/xtest_test.go --
+package xtest_test
+
+import "fmt"
+
+var _ = fmt.Sprintf("%d", "x")
diff --git a/src/cmd/go/testdata/script/test_vet_goroot.txt b/src/cmd/go/testdata/script/test_vet_goroot.txt
new file mode 100644
index 0000000000..0595b1f2df
--- /dev/null
+++ b/src/cmd/go/testdata/script/test_vet_goroot.txt
@@ -0,0 +1,45 @@
+# Every package in GOROOT gets the vet checks that GOROOT/src/go.vet or
+# GOROOT/src/cmd/go.vet declares for ./... (the full vet suite), as all
+# packages in GOROOT did before go.vet files, including external test
+# packages, which are not Standard. Vendored packages, beneath vendor
+# directories, do not: like ./..., the declarations do not extend
+# beneath a vendor directory, so they get only go test's default checks.
+# (The vendored packages of cmd are not tested here: go test cmd/...
+# does not match them.)
+
+[short] skip 'builds and analyzes standard packages'
+[!compiler:gc] skip
+[GOOS:windows] skip 'the overlay JSON would need escaped backslashes'
+
+env GOEXPERIMENT=vetfiles
+
+# Each overlay file has a problem found by unusedresult, which is in the
+# full suite but not in go test's default set; stdvendor.go also has one
+# found by bools, which is in the default set.
+echo {"Replace":{"$GOROOT/src/strings/zz_test.go":"$WORK/gopath/src/xtest.go","$GOROOT/src/vendor/golang.org/x/net/http/httpguts/zz.go":"$WORK/gopath/src/stdvendor.go"}}
+cp stdout overlay.json
+
+# An external test package of std.
+! go test -overlay=overlay.json -run=^$ strings
+stderr 'xtest.go:5:13: result of fmt.Sprint call not used'
+
+# A vendored package of std gets the default checks (here,
+# bools), but not the full suite.
+! go test -overlay=overlay.json -run=^$ vendor/golang.org/x/net/http/httpguts
+stderr 'stdvendor.go:7:[0-9]+: redundant or: x == 1 \|\| x == 1'
+! stderr 'result of fmt.Sprint call not used'
+
+-- xtest.go --
+package strings_test
+
+import "fmt"
+
+func zz() { fmt.Sprint("x") }
+-- stdvendor.go --
+package httpguts
+
+import "fmt"
+
+func zz() { fmt.Sprint("x") }
+
+func zz2(x int) bool { return x == 1 || x == 1 }
diff --git a/src/cmd/go/testdata/script/test_vetfiles_std.txt b/src/cmd/go/testdata/script/test_vetfiles_std.txt
new file mode 100644
index 0000000000..f1d9d60c7e
--- /dev/null
+++ b/src/cmd/go/testdata/script/test_vetfiles_std.txt
@@ -0,0 +1,129 @@
+# Tests of go.vet files in go test for the standard library
+# (GOEXPERIMENT=vetfiles).
+# An overlay adds a go.vet file to GOROOT/src/fmt, and two
+# analyzers: zzcheck, in a top-level internal package of std
+# (internal/zzcheck), visible throughout std but not to user code,
+# and zzpublic, in a public package (fmt/zzpublic).
+
+[short] skip 'builds and runs an analysis tool'
+
+env GOEXPERIMENT=vetfiles
+
+echo {"Replace":{"$GOROOT/src/fmt/go.vet":"$WORK/gopath/src/fmt_go.vet","$GOROOT/src/internal/zzcheck/zzcheck.go":"$WORK/gopath/src/zzcheck.go","$GOROOT/src/fmt/zzpublic/zzpublic.go":"$WORK/gopath/src/zzpublic.go"}}
+cp stdout overlay.json
+
+# A "." declaration in std applies to the std package itself.
+# (The analyzer is in an internal package of std, which fmt can see.)
+! go test -overlay=overlay.json -run=^$ fmt
+stderr 'fmt[/\\]doc.go:\d+:1: zzcheck$'
+
+# An "importers" declaration in std applies to user packages that
+# import it, even if they cannot see the analyzer: both zzpublic and
+# zzcheck (internal to std) apply. The declarations of std are not
+# reported as provenance.
+! go test -overlay=overlay.json ./d
+stderr 'd.go:1:1: zzpublic$'
+stderr 'd.go:1:1: zzcheck$'
+
+# An explicit -vet flag overrides only the standard library's
+# configuration of the vet checks: the analyzers that it declares
+# outside the vet suite still apply.
+! go test -overlay=overlay.json -vet=all ./d
+stderr 'd.go:1:1: zzpublic$'
+stderr 'd.go:1:1: zzcheck$'
+
+# The go.vet files of user packages are not read: dquiet's attempt to
+# disable "zzcheck" has no effect.
+! go test -overlay=overlay.json ./dquiet
+stderr 'dquiet.go:1:1: zzcheck$'
+
+# The internal analyzer does apply to std importers of fmt.
+! go test -overlay=overlay.json -run=^$ log
+stderr 'log[/\\]log.go:\d+:1: zzcheck$'
+stderr 'log[/\\]log.go:\d+:1: zzpublic$'
+
+# Without the overlay, fmt's own declarations (printf) find nothing.
+go test ./d
+
+# The declarations of the standard library apply also to packages that
+# belong to no module.
+env GO111MODULE=off
+cd e
+! go test -overlay=$WORK/gopath/src/overlay.json .
+stderr 'e.go:1:1: zzpublic$'
+stderr 'e.go:1:1: zzcheck$'
+cd $WORK/gopath/src
+env GO111MODULE=
+
+# For now, a disable declaration must be by name, not by reference;
+# a file containing one is reported and ignored.
+echo {"Replace":{"$GOROOT/src/fmt/go.vet":"$WORK/gopath/src/fmt_disable_go.vet"}}
+cp stdout overlay_disable.json
+! go test -overlay=overlay_disable.json ./d
+stderr 'fmt[/\\]go.vet:1:1: disable . internal/analysis/suite/vet.Suite\[printf\]: disable by reference is not yet supported; disable by analyzer name'
+
+-- go.mod --
+module example.com/m
+
+go 1.26
+-- fmt_disable_go.vet --
+disable . internal/analysis/suite/vet.Suite[printf]
+-- fmt_go.vet --
+enable . internal/zzcheck.Analyzer
+enable importers internal/zzcheck.Analyzer
+enable importers fmt/zzpublic.Analyzer
+
+// The declarations are not imports: zzcheck (which imports fmt)
+// is not linked into fmt.
+-- zzcheck.go --
+// Package zzcheck defines a test analyzer in the standard library.
+package zzcheck
+
+import "go/analysis"
+
+var Analyzer = &analysis.Analyzer{
+	Name: "zzcheck",
+	Doc:  "report the analyzer name",
+	Run: func(pass *analysis.Pass) (any, error) {
+		pass.Reportf(pass.Files[0].Package, "%s", pass.Analyzer.Name)
+		return nil, nil
+	},
+}
+-- zzpublic.go --
+// Package zzpublic defines a public test analyzer in the standard library.
+package zzpublic
+
+import "go/analysis"
+
+var Analyzer = &analysis.Analyzer{
+	Name: "zzpublic",
+	Doc:  "report the analyzer name",
+	Run: func(pass *analysis.Pass) (any, error) {
+		pass.Reportf(pass.Files[0].Package, "%s", pass.Analyzer.Name)
+		return nil, nil
+	},
+}
+-- e/e.go --
+package e
+
+import "fmt"
+
+func F() { fmt.Println() }
+-- e/e_test.go --
+package e
+-- dquiet/dquiet.go --
+package dquiet
+
+import "fmt"
+
+func F() { fmt.Println() }
+-- dquiet/go.vet --
+disable . "zzcheck"
+-- d/d.go --
+package d
+
+import "fmt"
+
+func F() { fmt.Println() }
+-- d/d_test.go --
+package d
diff --git a/src/errors/go.vet b/src/errors/go.vet
new file mode 100644
index 0000000000..1b28d006c8
--- /dev/null
+++ b/src/errors/go.vet
@@ -0,0 +1,6 @@
+// Analyzers that go test runs (see go.dev/issue/82464).
+
+// In packages that import errors, directly or indirectly, go test
+// checks calls to errors.As using the errorsas analyzer.
+
+enable importers internal/analysis/suite/vet.Suite[errorsas]
diff --git a/src/fmt/go.vet b/src/fmt/go.vet
new file mode 100644
index 0000000000..df68483b29
--- /dev/null
+++ b/src/fmt/go.vet
@@ -0,0 +1,7 @@
+// Analyzers that go test runs (see go.dev/issue/82464).
+
+// In packages that import fmt, directly or indirectly, go test checks
+// calls to printf-like functions and their wrappers using the printf
+// analyzer.
+
+enable importers internal/analysis/suite/vet.Suite[printf]
diff --git a/src/go.vet b/src/go.vet
new file mode 100644
index 0000000000..203ee01836
--- /dev/null
+++ b/src/go.vet
@@ -0,0 +1,56 @@
+// This file declares the analyzers that go test runs on the packages
+// beneath this directory (see go.dev/issue/82464).
+
+// go test's default checks, which apply to every package that it
+// tests, wherever it is, are those enabled by this declaration, plus
+// those enabled by "importers" declarations in the go.vet files of the
+// standard packages whose use they check (e.g. printf, for importers of
+// fmt). The global scope is permitted only in this file.
+enable global internal/analysis/suite/vet.Suite[bools,buildtag,directive,ifaceassert,nilfunc,stdversion,stringintconv,tests]
+
+// TODO(adonovan): Decide which tests are enabled by default.
+// See golang.org/issue/18085.
+//
+// The other analyzers of the vet suite are not run by go test by
+// default (except on the packages of the Go distribution; see below).
+// To enable one for all packages, uncomment its declaration; but
+// consider instead an "importers" declaration in the go.vet file of
+// the package whose use it checks.
+//
+// enable global internal/analysis/suite/vet.Suite[appends]
+// enable global internal/analysis/suite/vet.Suite[asmdecl]
+// enable global internal/analysis/suite/vet.Suite[assign]
+// enable global internal/analysis/suite/vet.Suite[cgocall]
+// enable global internal/analysis/suite/vet.Suite[composites]
+// enable global internal/analysis/suite/vet.Suite[copylocks]           // importers of sync?
+// enable global internal/analysis/suite/vet.Suite[defers]
+// enable global internal/analysis/suite/vet.Suite[framepointer]
+// enable global internal/analysis/suite/vet.Suite[hostport]            // importers of net?
+// enable global internal/analysis/suite/vet.Suite[httpresponse]        // importers of net/http?
+// enable global internal/analysis/suite/vet.Suite[loopclosure]
+// enable global internal/analysis/suite/vet.Suite[lostcancel]
+// enable global internal/analysis/suite/vet.Suite[scannererr]          // importers of bufio?
+// enable global internal/analysis/suite/vet.Suite[shift]
+// enable global internal/analysis/suite/vet.Suite[sigchanyzer]         // importers of os?
+// enable global internal/analysis/suite/vet.Suite[sqlrowserr]          // importers of database/sql?
+// enable global internal/analysis/suite/vet.Suite[stdmethods]
+// enable global internal/analysis/suite/vet.Suite[structtag]
+// enable global internal/analysis/suite/vet.Suite[testinggoroutine]    // importers of testing?
+// enable global internal/analysis/suite/vet.Suite[timeformat]          // importers of time?
+// enable global internal/analysis/suite/vet.Suite[unmarshal]           // importers of encoding/{json,xml}?
+// enable global internal/analysis/suite/vet.Suite[unreachable]
+// enable global internal/analysis/suite/vet.Suite[unsafeptr]
+// enable global internal/analysis/suite/vet.Suite[unusedresult]
+// enable global internal/analysis/suite/vet.Suite[waitgroup]           // importers of sync?
+
+// The packages of the Go distribution are checked by go test with all
+// the analyzers of the vet suite, except those disabled below.
+enable ./... internal/analysis/suite/vet.Suite[*]
+
+// There is too much unsafe.Pointer code that unsafeptr does not like
+// in low-level packages; see go.dev/cl/176439, go.dev/issue/31916.
+disable ./... "unsafeptr"
+
+// During testing it is common to make changes, such as forced
+// returns, that make code unreachable; see go.dev/cl/240550.
+disable ./... "unreachable"
diff --git a/src/log/slog/go.vet b/src/log/slog/go.vet
new file mode 100644
index 0000000000..96a2855fdf
--- /dev/null
+++ b/src/log/slog/go.vet
@@ -0,0 +1,6 @@
+// Analyzers that go test runs (see go.dev/issue/82464).
+
+// In packages that import log/slog, directly or indirectly, go test
+// checks calls to slog functions using the slog analyzer.
+
+enable importers internal/analysis/suite/vet.Suite[slog]
diff --git a/src/sync/atomic/go.vet b/src/sync/atomic/go.vet
new file mode 100644
index 0000000000..c4bb27cc9a
--- /dev/null
+++ b/src/sync/atomic/go.vet
@@ -0,0 +1,6 @@
+// Analyzers that go test runs (see go.dev/issue/82464).
+
+// In packages that import sync/atomic, directly or indirectly, go
+// test checks for common mistakes using the atomic analyzer.
+
+enable importers internal/analysis/suite/vet.Suite[atomic]