Commit 146327d7b3 for golang
commit 146327d7b3b7d696269e8754eb2d890eb9596fe2
Author: Alan Donovan <adonovan@google.com>
Date: Wed Nov 25 15:30:10 2026 -0500
cmd/go/internal/vetfile: parse go.vet files
This CL adds a new package, vetfile, with a parser for go.vet
files, which declare the analyzers that go test runs on the
packages under test under GOEXPERIMENT=vetfiles.
They use the base syntax (and parser) of go.mod.
Parse returns the {en,dis}able declarations of a file,
or, like modfile.Parse, an error (a modfile.ErrorList) reporting
every problem if any declaration is invalid. Read reads, parses, and
caches the go.vet file of a directory, and validates its
declarations in that directory.
This package also defines the directory structure that
determines which go.vet files are relevant to a package
(EnclosingDirs) and the rule for internal
packages that governs the references they contain
(Visible).
A follow-up CL will use it to configure the vet suite on std.
For #82464
Change-Id: I78f3ff7f1c3c1880cfaee200c2f3dab06dabcd4b
Reviewed-on: https://go-review.googlesource.com/c/go/+/866033
Reviewed-by: Michael Matloob <matloob@golang.org>
Reviewed-by: PJ Malloy <pjmalloy@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
diff --git a/src/cmd/dist/buildtool.go b/src/cmd/dist/buildtool.go
index 3fac7385e9..2d8d1f0671 100644
--- a/src/cmd/dist/buildtool.go
+++ b/src/cmd/dist/buildtool.go
@@ -84,6 +84,7 @@ var bootstrapDirs = []string{
"cmd/go/internal/vcscmd",
"cmd/go/internal/version",
"cmd/go/internal/vet",
+ "cmd/go/internal/vetfile",
"cmd/go/internal/web",
"cmd/go/internal/work",
"cmd/go/internal/workcmd",
diff --git a/src/cmd/go/internal/vetfile/vetfile.go b/src/cmd/go/internal/vetfile/vetfile.go
new file mode 100644
index 0000000000..53cf0db9b8
--- /dev/null
+++ b/src/cmd/go/internal/vetfile/vetfile.go
@@ -0,0 +1,495 @@
+// 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 vetfile defines the syntax of go.vet files, whose
+// directives enable analyzers in go test (GOEXPERIMENT=vetfiles), and
+// the directory structure that determines the packages to which they
+// apply. See ../load/vetfile.go for the resolution of the
+// declarations that apply to a package.
+//
+// The [File] type and [Parse] function depend on nothing else in the
+// go command so that they may eventually move to the [modfile] package.
+package vetfile
+
+import (
+ "errors"
+ "fmt"
+ "go/token"
+ "iter"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "cmd/go/internal/base"
+ "cmd/go/internal/cfg"
+ "cmd/go/internal/fsys"
+ "cmd/go/internal/search"
+ "cmd/go/internal/str"
+ "cmd/internal/par"
+
+ "golang.org/x/mod/modfile"
+ "golang.org/x/mod/module"
+)
+
+// Name is the base name of all go.vet files, which hold the analysis
+// declarations of its directory (which need not contain a Go package).
+const Name = "go.vet"
+
+// A File is the parsed form of a go.vet file.
+type File struct {
+ Filename string // name of the file, for display
+ Decls []*Decl // declarations, in order
+}
+
+// A Decl is a declaration in a go.vet file such as:
+//
+// enable ./... example.com/db/check.Query
+//
+// Each declaration is of the form:
+//
+// VERB SCOPE REF
+//
+// where:
+//
+// - VERB is "enable" or "disable";
+// - SCOPE is ".", "./...", or "importers" (not for disable), or
+// "global" (not for disable, and only in GOROOT/src/go.vet); and
+// - REF is "pkg.Var", "pkg.Var[*]", or "pkg.Var[A,B,...]".
+//
+// A disable declaration may instead name analyzers by their
+// Analyzer.Name, as a quoted string (e.g. `disable . "printf"`);
+// since names are not unique, this disables every analyzer of that
+// name. (An unquoted operand is always a reference, so a reference
+// that lacks its package path is an error, not a disable by name.)
+//
+// Declarations may also be grouped in blocks, as in go.mod:
+//
+// enable (
+// ./... example.com/check.Housekeeping
+// importers example.com/check.Query
+// )
+type Decl struct {
+ Enable bool // enable or disable
+ Scope string // ".", "./...", "importers", or "global"
+ Var Var // the referenced variable
+ Members []string // nil for an analyzer (pkg.Var); ["*"] or names for a suite (pkg.Var[...])
+ Name string // for a disable by name: the Analyzer.Name (Var and Members are empty)
+
+ File *File // the declaring file, or nil for a synthesized declaration (e.g. from the -vet flag)
+ Pos modfile.Position // position of the declaration's first token, within File
+ Syntax *modfile.Line
+}
+
+// Filename returns the name of the declaring file, or "" for a
+// synthesized declaration.
+func (decl *Decl) Filename() string {
+ if decl.File == nil {
+ return ""
+ }
+ return decl.File.Filename
+}
+
+// Position returns the position of the declaration as "file:line:col",
+// or "" for a synthesized declaration.
+func (decl *Decl) Position() string {
+ return formatPos(decl.File, decl.Pos)
+}
+
+// Verb returns "enable" or "disable".
+func (decl *Decl) Verb() string {
+ if decl.Enable {
+ return "enable"
+ }
+ return "disable"
+}
+
+// Ref returns the reference as written, e.g. "pkgpath.Var[A,B]", or
+// the quoted analyzer name of a disable by name.
+func (decl *Decl) Ref() string {
+ if decl.Name != "" {
+ return strconv.Quote(decl.Name)
+ }
+ ref := decl.Var.String()
+ if decl.Members != nil {
+ ref += "[" + strings.Join(decl.Members, ",") + "]"
+ }
+ return ref
+}
+
+func (decl *Decl) String() string {
+ return decl.Verb() + " " + decl.Scope + " " + decl.Ref()
+}
+
+// A Var identifies an exported analyzer or suite variable,
+// pkgpath.Name, referenced by a declaration.
+type Var struct {
+ PkgPath string
+ Name string
+}
+
+func (v Var) String() string { return v.PkgPath + "." + v.Name }
+
+// formatPos formats a position within a file as "file:line:col", or
+// "file" if pos is zero, or "" if file is nil. The column is in runes,
+// as in go.mod errors.
+func formatPos(file *File, pos modfile.Position) string {
+ switch {
+ case file == nil:
+ return ""
+ case pos.Line == 0:
+ return file.Filename
+ case pos.LineRune == 0:
+ return fmt.Sprintf("%s:%d", file.Filename, pos.Line)
+ default:
+ return fmt.Sprintf("%s:%d:%d", file.Filename, pos.Line, pos.LineRune)
+ }
+}
+
+// Read reads the go.vet file in directory dir, whose import path is
+// dirPath, and which belongs to the standard library if std (see
+// [InStd]), and returns it parsed and validated.
+//
+// If the file cannot be read, the error is that of the file system;
+// if there is no file, it satisfies errors.Is(err, fs.ErrNotExist).
+// If the file is invalid, the error is a [modfile.ErrorList]
+// (see [Parse]), and there is no File.
+//
+// The result is cached by dir (since the file of a directory applies
+// to every package beneath it) so all callers must agree on the dirPath
+// and std values for a given dir.
+//
+// The file's display name is shortened by [base.ShortPath].
+//
+// Callers must not mutate the File.
+func Read(dir, dirPath string, std bool) (*File, error) {
+ return readCache.Do(dir, func() (*File, error) {
+ filename := filepath.Join(dir, Name)
+ data, err := fsys.ReadFile(filename)
+ if err != nil {
+ return nil, err
+ }
+ f, errs := parse(base.ShortPath(filename), data)
+
+ // Check per-directory validity.
+ for _, d := range f.Decls {
+ // "global" scope may only be used in the root go.vet.
+ if d.Scope == "global" && !(std && dirPath == "") {
+ addError(&errs, f.Filename, d.Pos,
+ fmt.Errorf("'global' scope is permitted only in GOROOT/src/go.vet"))
+ }
+
+ // A pkgpath.Var symbol reference must be to an accessible package.
+ if d.Name == "" && !Visible(dirPath, std, d.Var.PkgPath) {
+ addError(&errs, f.Filename, d.Pos,
+ fmt.Errorf("%s %s: use of internal package %s not allowed",
+ d.Verb(), d.Ref(), d.Var.PkgPath))
+ }
+ }
+
+ if len(errs) > 0 {
+ return nil, errs
+ }
+ return f, nil
+ })
+}
+
+func addError(errs *modfile.ErrorList, filename string, pos modfile.Position, err error) {
+ *errs = append(*errs, modfile.Error{Filename: filename, Pos: pos, Err: err})
+}
+
+var readCache par.ErrCache[string, *File] // see Read; keyed by directory
+
+// Parse parses a go.vet file.
+//
+// Lexical structure follows go.mod files. Spaces are not significant:
+// "pkg.Var [A, B] " equals "pkg.Var[A,B]". See [Decl] for declaration
+// syntax.
+//
+// As with [modfile.Parse], any error is fatal: if the file is not
+// valid, Parse returns no File, and an error, a [modfile.ErrorList],
+// that reports every problem found.
+//
+// TODO(adonovan): move to golang.org/x/mod/modfile.ParseVet.
+// Also, improve fidelity of start/end x line/column reporting.
+func Parse(filename string, data []byte) (*File, error) {
+ file, errs := parse(filename, data)
+ if len(errs) > 0 {
+ return nil, errs
+ }
+ return file, nil
+}
+
+// parse is like [Parse] but returns, in addition to the errors, a
+// File holding the well-formed declarations, which [Read] validates.
+// If the go.mod parser rejects the file, the File has no
+// declarations.
+func parse(filename string, data []byte) (*File, modfile.ErrorList) {
+ var (
+ file = &File{Filename: filename}
+ errs modfile.ErrorList
+ )
+
+ f, err := modfile.ParseLax(filename, data, nil)
+ if err != nil {
+ if list, ok := errors.AsType[modfile.ErrorList](err); ok {
+ return file, list
+ }
+ addError(&errs, filename, modfile.Position{}, err) // whole file
+ return file, errs
+ }
+
+ parseLine := func(verb string, line *modfile.Line, args []string) {
+ d, err := parseDecl(verb, args)
+ if err != nil {
+ addError(&errs, filename, line.Start, err)
+ return
+ }
+ d.File = file
+ d.Pos = line.Start
+ d.Syntax = line
+ file.Decls = append(file.Decls, d)
+ }
+ for _, stmt := range f.Syntax.Stmt {
+ switch x := stmt.(type) {
+ case *modfile.Line:
+ parseLine(x.Token[0], x, x.Token[1:])
+ case *modfile.LineBlock: // e.g. "enable ( ... )"
+ if len(x.Token) > 1 || !isVerb(x.Token[0]) {
+ addError(&errs, filename, x.Start, fmt.Errorf("unknown block type: %s", x.Token[0]))
+ continue
+ }
+ for _, line := range x.Line {
+ parseLine(x.Token[0], line, line.Token)
+ }
+ }
+ }
+ return file, errs
+}
+
+func isVerb(verb string) bool { return verb == "enable" || verb == "disable" }
+
+// parseDecl parses a declaration with the specified verb and
+// operands (tokens). The result has no file or position.
+func parseDecl(verb string, args []string) (*Decl, error) {
+ if !isVerb(verb) {
+ return nil, fmt.Errorf("unknown directive: %s (want enable or disable)", verb)
+ }
+ // A reference is a name, optionally followed by a bracketed
+ // member list, which the lexer splits into tokens.
+ if len(args) < 2 {
+ return nil, fmt.Errorf("malformed %s declaration: want scope and reference (e.g. %q)", verb, verb+" . example.com/check.Analyzer")
+ }
+ if len(args) > 2 && args[2] != "[" {
+ return nil, fmt.Errorf("malformed %s declaration: extra operand %q (want scope and reference)", verb, args[2])
+ }
+
+ d := &Decl{Enable: verb == "enable", Scope: args[0]}
+ switch d.Scope {
+ case ".", "./...":
+ case "importers", "global":
+ if !d.Enable {
+ return nil, fmt.Errorf("disable does not accept scope %q (want . or ./...)", d.Scope)
+ }
+ default:
+ if !d.Enable {
+ return nil, fmt.Errorf("invalid scope %q in disable declaration (want . or ./...)", d.Scope)
+ }
+ return nil, fmt.Errorf("invalid scope %q in enable declaration (want ., ./..., or importers)", d.Scope)
+ }
+
+ // TODO(adonovan): parse the member list from the tokens
+ // directly (name, "[", A, ",", B, "]") instead of joining them
+ // and splitting the result again.
+ ref := strings.Join(args[1:], "")
+
+ // A quoted string is an Analyzer.Name, permitted only in
+ // disable declarations.
+ if ref != "" && (ref[0] == '"' || ref[0] == '`') {
+ if d.Enable {
+ return nil, fmt.Errorf("invalid reference %s: enable requires a qualified name pkgpath.Var (analyzer names may be used only in disable)", ref)
+ }
+ name, err := strconv.Unquote(ref)
+ if err != nil {
+ return nil, fmt.Errorf("invalid analyzer name %s: want a quoted identifier", ref)
+ }
+ if !token.IsIdentifier(name) {
+ return nil, fmt.Errorf("invalid analyzer name %s: not an identifier", ref)
+ }
+ d.Name = name
+ return d, nil
+ }
+
+ // suite? e.g. pkg.Var[x,y,z]
+ name, list, ok := strings.Cut(ref, "[")
+ if ok {
+ list, ok = strings.CutSuffix(list, "]")
+ if !ok {
+ return nil, fmt.Errorf("invalid reference %q: missing ']'", ref)
+ }
+ if list == "*" {
+ d.Members = []string{"*"}
+ } else {
+ d.Members = strings.Split(list, ",")
+ seen := make(map[string]bool)
+ for _, m := range d.Members {
+ if m == "" {
+ return nil, fmt.Errorf("invalid reference %q: empty member name", ref)
+ }
+ if !token.IsIdentifier(m) {
+ return nil, fmt.Errorf("invalid reference %q: invalid member name %q", ref, m)
+ }
+ if seen[m] {
+ return nil, fmt.Errorf("invalid reference %q: duplicate member name %q", ref, m)
+ }
+ seen[m] = true
+ }
+ }
+ }
+ d.Var.PkgPath, d.Var.Name, ok = cutLast(name, ".")
+ if !ok {
+ if !d.Enable && token.IsIdentifier(ref) {
+ // Perhaps a name was intended.
+ return nil, fmt.Errorf("invalid reference %q: want qualified name pkgpath.Var (to disable analyzers by name, quote it: %q)", ref, ref)
+ }
+ return nil, fmt.Errorf("invalid reference %q: want qualified name pkgpath.Var", ref)
+ }
+ if d.Var.PkgPath == "" {
+ return nil, fmt.Errorf("invalid reference %q: empty package path", ref)
+ }
+ if err := module.CheckImportPath(d.Var.PkgPath); err != nil {
+ return nil, fmt.Errorf("invalid reference %q: %v", ref, err)
+ }
+ if !token.IsIdentifier(d.Var.Name) || !token.IsExported(d.Var.Name) {
+ return nil, fmt.Errorf("invalid reference %q: %q is not an exported identifier", ref, d.Var.Name)
+ }
+ return d, nil
+}
+
+// EnclosingDirs returns the sequence of (dir, import path) pairs for
+// successively enclosing directories, starting with (pkgdir, pkgPath),
+// that may hold a go.vet file whose "." or "./..." declarations could
+// apply to the specified package. (A "." declaration applies only in
+// pkgdir itself.)
+//
+// The sequence ends at the root of the package's module, whose path is
+// modPath; for a package in GOROOT, the root is GOROOT/src/cmd (path
+// "cmd") or GOROOT/src (path ""). It ends early at a directory that
+// ./... would not cross: a vendor or testdata directory, or one whose
+// name begins with "." or "_". It is empty for a package in no module.
+//
+// For example, for package example.com/m/a/b in directory /home/u/m/a/b
+// of module example.com/m, the sequence is:
+//
+// /home/u/m/a/b example.com/m/a/b
+// /home/u/m/a example.com/m/a
+// /home/u/m example.com/m
+//
+// Had a been named testdata, the sequence would end at /home/u/m/a.
+func EnclosingDirs(pkgdir, pkgPath, modPath string) iter.Seq2[string, string] {
+ return func(yield func(dir, path string) bool) {
+ pkgdir := filepath.Clean(pkgdir)
+ root, ok := treeRoot(pkgdir, pkgPath, modPath)
+ if !ok {
+ return
+ }
+ // Walk up the directory tree and the import path together.
+ dir, path := pkgdir, pkgPath
+ for yield(dir, path) && path != root && descends(filepath.Base(dir)) {
+ dir, path = filepath.Dir(dir), parentPath(path)
+ }
+ }
+}
+
+// treeRoot returns the import path of the root of the tree of the
+// package in pkgdir, whose import path is pkgPath, and whose module
+// path is modPath. It returns false if the package is in no tree.
+func treeRoot(pkgdir, pkgPath, modPath string) (root string, ok bool) {
+ std := InStd(pkgdir, pkgPath)
+ switch {
+ case std && str.HasPathPrefix(pkgPath, "cmd"):
+ root = "cmd" // GOROOT/src/cmd
+ case std:
+ root = "" // GOROOT/src
+ case modPath != "":
+ root = modPath
+ default:
+ return "", false // not in a module
+ }
+ return root, str.HasPathPrefix(pkgPath, root)
+}
+
+// InStd reports whether the package in pkgdir, whose import path is
+// pkgPath, belongs to the standard library (std or cmd): its path is
+// that of a standard package and it is in GOROOT/src. (The module
+// loader's test, loadPkg.inStd, is the same.) So a main module whose
+// path happens to lack a dot does not belong to it; nor, when cmd is
+// the main module, do the packages vendored into GOROOT/src/cmd/vendor,
+// whose paths are then those of their modules.
+//
+// This is a property of a package, and so of its tree: the go.vet
+// files of a package's directory and its ancestors (see
+// [EnclosingDirs]) belong to the standard library if the package does.
+func InStd(pkgdir, pkgPath string) bool {
+ return search.IsStandardImportPath(pkgPath) &&
+ str.HasFilePathPrefix(filepath.Clean(pkgdir), filepath.Clean(cfg.GOROOTsrc))
+}
+
+// descends reports whether the ./... pattern descends into a
+// directory of the specified name.
+func descends(name string) bool {
+ return name != "vendor" && name != "testdata" && name[0] != '.' && name[0] != '_'
+}
+
+// parentPath returns the import path of the parent of the directory
+// whose import path is path. The parent of a top-level directory of
+// std (e.g. "fmt") is GOROOT/src, whose import path is "".
+func parentPath(path string) string {
+ if i := strings.LastIndexByte(path, '/'); i >= 0 {
+ return path[:i]
+ }
+ return ""
+}
+
+// Visible reports whether the package whose import path is
+// pkgPath is visible, by the rule for internal packages, from the
+// directory whose import path is from. fromStd reports whether that
+// directory belongs to the standard library (see [InStd]), whose
+// top-level internal packages are visible throughout the standard
+// library.
+//
+// A reference in a go.vet file must be visible from the file's
+// directory. (An "importers" declaration applies to every importer,
+// even one from which its analyzer is not visible; such an importer
+// can disable the analyzer by name.)
+//
+// (The logic is that of load.disallowInternal, which applies to
+// imports, specialized to import paths.)
+//
+// TODO(adonovan): move load.findInternal into this package (or str)
+// so that disallowInternal and Visible share it.
+func Visible(from string, fromStd bool, pkgPath string) bool {
+ // The final "internal" element governs.
+ parent, _, ok := cutLast("/"+pkgPath+"/", "/internal/")
+ switch {
+ case !ok:
+ return true // not internal
+ case parent == "":
+ return fromStd // top-level internal package of std
+ default:
+ return str.HasPathPrefix(from, parent[len("/"):])
+ }
+}
+
+// cutLast slices s around the last instance of sep, returning the text
+// before and after sep. The found result reports whether sep appears
+// in s. If sep does not appear in s, cutLast returns s, "", false.
+//
+// TODO(adonovan): use strings.CutLast once the bootstrap toolchain is
+// go1.27 or later.
+func cutLast(s, sep string) (before, after string, found bool) {
+ if i := strings.LastIndex(s, sep); i >= 0 {
+ return s[:i], s[i+len(sep):], true
+ }
+ return s, "", false
+}
diff --git a/src/cmd/go/internal/vetfile/vetfile_test.go b/src/cmd/go/internal/vetfile/vetfile_test.go
new file mode 100644
index 0000000000..b7bbfdb6c0
--- /dev/null
+++ b/src/cmd/go/internal/vetfile/vetfile_test.go
@@ -0,0 +1,272 @@
+// 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 vetfile
+
+import (
+ "errors"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "cmd/go/internal/cfg"
+
+ "golang.org/x/mod/modfile"
+)
+
+func TestParseDecl(t *testing.T) {
+ for _, test := range []struct {
+ text string // a go.vet file containing (at most) one declaration
+ want string // formatted first decl (or "" if empty) on success; or substring of expected error
+ }{
+ // successful single declarations
+ {text: "enable . example.com/c.A", want: "enable . example.com/c.A"},
+ {text: "enable ./... example.com/c.A", want: "enable ./... example.com/c.A"},
+ {text: "enable importers example.com/c.A", want: "enable importers example.com/c.A"},
+ {text: "enable\t.\texample.com/c.A", want: "enable . example.com/c.A"},
+ {text: "disable . example.com/c.A", want: "disable . example.com/c.A"},
+ {text: "disable ./... example.com/c.A", want: "disable ./... example.com/c.A"},
+ {text: "enable . example.com/c.Suite[*]", want: "enable . example.com/c.Suite[*]"},
+ {text: "enable . example.com/c.Suite[A,B]", want: "enable . example.com/c.Suite[A,B]"},
+ {text: "enable . example.com/c.Suite [A, B]", want: "enable . example.com/c.Suite[A,B]"},
+ {text: "disable . example.com/c.Suite[A]", want: "disable . example.com/c.Suite[A]"},
+ {text: "enable . fmt/internal/x.A", want: "enable . fmt/internal/x.A"},
+ {text: "enable . example.com/a.b/c.A", want: "enable . example.com/a.b/c.A"},
+ {text: "enable . example.com/c.A // comment", want: "enable . example.com/c.A"},
+ {text: "enable (\n\t. example.com/c.A\n)", want: "enable . example.com/c.A"},
+ {text: `disable . "printf"`, want: "disable . \"printf\""},
+ {text: "disable . `printf`", want: "disable . \"printf\""},
+ {text: `disable ./... "printf"`, want: "disable ./... \"printf\""},
+ {text: "enable . example.com/c.S[A] ", want: "enable . example.com/c.S[A]"},
+
+ // empty files
+ {text: "// enable . example.com/c.A", want: ""},
+ {text: "", want: ""},
+
+ // errors
+ {text: "enable", want: "malformed enable declaration"},
+ {text: "enable .", want: "malformed enable declaration: want scope and reference"},
+ {text: "enable . a.B c", want: `malformed enable declaration: extra operand "c"`},
+ {text: "disable", want: "malformed disable declaration"},
+ {text: "enable everywhere example.com/c.A", want: `invalid scope "everywhere" in enable declaration`},
+ {text: "enable .. example.com/c.A", want: `invalid scope ".." in enable declaration`},
+ {text: "disable importers example.com/c.A", want: `disable does not accept scope "importers"`},
+ {text: "disable everywhere example.com/c.A", want: `invalid scope "everywhere" in disable declaration`},
+ {text: "enable . A", want: "want qualified name pkgpath.Var"},
+ {text: `enable . "printf"`, want: "analyzer names may be used only in disable"},
+ {text: `enable importers "printf"`, want: "analyzer names may be used only in disable"},
+ {text: `disable importers "printf"`, want: `disable does not accept scope "importers"`},
+ {text: "disable . printf[A]", want: "want qualified name pkgpath.Var"},
+ {text: "disable . print-f", want: "want qualified name pkgpath.Var"},
+ {text: "disable . printf", want: `want qualified name pkgpath.Var (to disable analyzers by name, quote it: "printf")`},
+ {text: `disable . "print-f"`, want: "not an identifier"},
+ {text: `disable . "printf"[A]`, want: "want a quoted identifier"},
+ {text: "enable . .A", want: "empty package path"},
+ {text: "enable . example.com/c.a", want: `"a" is not an exported identifier`},
+ {text: "enable . example.com/c.", want: `"" is not an exported identifier`},
+ {text: "enable . example.com/c.A-B", want: `"A-B" is not an exported identifier`},
+ {text: "enable . example.com/c.S[", want: "missing ']'"},
+ {text: "enable . example.com/c.S[A", want: "missing ']'"},
+ {text: "enable . example.com/c.S[]", want: "empty member name"},
+ {text: "enable . example.com/c.S[A,]", want: "empty member name"},
+ {text: "enable . example.com/c.S[,A]", want: "empty member name"},
+ {text: "enable . example.com/c.S[A,,B]", want: "empty member name"},
+ {text: "enable . example.com/c.S[A,A]", want: `duplicate member name "A"`},
+ {text: "enable . example.com/c.S[A,*]", want: `invalid member name "*"`},
+ {text: "enable . example.com/c.S[1]", want: `invalid member name "1"`},
+ {text: "enable . example.com/c.S[A]x", want: "missing ']'"},
+ {text: "enable . example com/c.A", want: "malformed enable declaration"},
+ {text: "enable . /abs.A", want: "invalid reference"},
+ {text: `enable . "example.com/c.A"`, want: "invalid reference"},
+ {text: "enabler . example.com/c.A", want: "unknown directive: enabler"},
+ {text: "frobnicate (\n\t. example.com/c.A\n)", want: "unknown block type: frobnicate"},
+ {text: "enable . example.com/c.A /* comment */", want: "mod files must use // comments"},
+ } {
+ file, err := Parse("go.vet", []byte(test.text))
+ if err != nil {
+ got := err.Error()
+ if !strings.Contains(got, test.want) {
+ t.Errorf("Parse(%q) = %#q, want substring %q", test.text, got, test.want)
+ }
+ continue
+ }
+ if len(file.Decls) != 1 {
+ if test.want != "" {
+ t.Errorf("Parse(%q) returned %d declarations (want 1)", test.text, len(file.Decls))
+ }
+ continue
+ }
+ got := file.Decls[0].String()
+ if got != test.want {
+ t.Errorf("Parse(%q) = %#q, want %#q", test.text, got, test.want)
+ }
+ }
+}
+
+func TestParse(t *testing.T) {
+ const src = `// Analyzers for this tree.
+
+enable . example.com/c.A
+// A doc comment.
+disable ./... example.com/c.S[X]
+
+enable (
+ importers example.com/c.B
+ ./... example.com/c.C // suffix comment
+)
+`
+ f, err := Parse("dir/go.vet", []byte(src))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []string
+ for _, d := range f.Decls {
+ got = append(got, d.Position()+" "+d.String())
+ }
+ want := []string{
+ "dir/go.vet:3:1 enable . example.com/c.A",
+ "dir/go.vet:5:1 disable ./... example.com/c.S[X]",
+ "dir/go.vet:8:2 enable importers example.com/c.B",
+ "dir/go.vet:9:2 enable ./... example.com/c.C",
+ }
+ if !slices.Equal(got, want) {
+ t.Errorf("references = %q, want %q", got, want)
+ }
+}
+
+// TestParseErrors checks that any invalid declaration causes Parse
+// to fail, reporting every one.
+func TestParseErrors(t *testing.T) {
+ const src = `enable . example.com/c.A
+enable bad example.com/c.A
+enable (
+ . example.com/c.b
+)
+`
+ f, err := Parse("dir/go.vet", []byte(src))
+ if f != nil {
+ t.Errorf("Parse returned a File (%d decls) despite errors", len(f.Decls))
+ }
+ list, ok := errors.AsType[modfile.ErrorList](err)
+ if !ok {
+ t.Fatalf("Parse error = %v (%T), want modfile.ErrorList", err, err)
+ }
+ var got []string
+ for _, e := range list {
+ got = append(got, e.Error())
+ }
+ want := []string{
+ `dir/go.vet:2: invalid scope "bad" in enable declaration (want ., ./..., or importers)`,
+ `dir/go.vet:4:2: invalid reference "example.com/c.b": "b" is not an exported identifier`,
+ }
+ if !slices.Equal(got, want) {
+ t.Errorf("errors = %q, want %q", got, want)
+ }
+}
+
+func TestEnclosingDirs(t *testing.T) {
+ // Directories beneath $GOROOT/src are relative to cfg.GOROOTsrc.
+ fromSlash := func(dir string) string {
+ if rest, ok := strings.CutPrefix(dir, "$GOROOT/src"); ok {
+ return filepath.Join(cfg.GOROOTsrc, filepath.FromSlash(rest))
+ }
+ return filepath.FromSlash(dir)
+ }
+ for _, test := range []struct {
+ pkgdir, pkgPath, modPath string
+ want []string // "dir=path"
+ }{
+ {"/m", "example.com/m", "example.com/m", []string{"/m=example.com/m"}},
+ {"/m/a/b", "example.com/m/a/b", "example.com/m", []string{"/m/a/b=example.com/m/a/b", "/m/a=example.com/m/a", "/m=example.com/m"}},
+ {"/gopath/pkg/mod/example.com/m@v1.0.0/a", "example.com/m/a", "example.com/m", []string{"/gopath/pkg/mod/example.com/m@v1.0.0/a=example.com/m/a", "/gopath/pkg/mod/example.com/m@v1.0.0=example.com/m"}},
+ {"/m/a/testdata/b", "example.com/m/a/testdata/b", "example.com/m", []string{"/m/a/testdata/b=example.com/m/a/testdata/b", "/m/a/testdata=example.com/m/a/testdata"}},
+ {"/m/_x/b", "example.com/m/_x/b", "example.com/m", []string{"/m/_x/b=example.com/m/_x/b", "/m/_x=example.com/m/_x"}},
+ {"/w/vendor/example.com/m/a", "example.com/m/a", "example.com/m", []string{"/w/vendor/example.com/m/a=example.com/m/a", "/w/vendor/example.com/m=example.com/m"}},
+ {"/w/vendor/example.com/m/a", "example.com/w/vendor/example.com/m/a", "example.com/w", []string{"/w/vendor/example.com/m/a=example.com/w/vendor/example.com/m/a", "/w/vendor/example.com/m=example.com/w/vendor/example.com/m", "/w/vendor/example.com=example.com/w/vendor/example.com", "/w/vendor=example.com/w/vendor"}},
+ {"$GOROOT/src/fmt", "fmt", "", []string{"$GOROOT/src/fmt=fmt", "$GOROOT/src="}},
+ {"$GOROOT/src/fmt", "fmt", "std", []string{"$GOROOT/src/fmt=fmt", "$GOROOT/src="}}, // std is the main module
+ {"$GOROOT/src/a/testdata/b", "a/testdata/b", "", []string{"$GOROOT/src/a/testdata/b=a/testdata/b", "$GOROOT/src/a/testdata=a/testdata"}},
+ {"$GOROOT/src/cmd/go/internal/load", "cmd/go/internal/load", "", []string{"$GOROOT/src/cmd/go/internal/load=cmd/go/internal/load", "$GOROOT/src/cmd/go/internal=cmd/go/internal", "$GOROOT/src/cmd/go=cmd/go", "$GOROOT/src/cmd=cmd"}},
+ // Vendored packages of std and cmd, like those of any module,
+ // are not subject to the declarations above the vendor directory.
+ {"$GOROOT/src/vendor/golang.org/x/a", "vendor/golang.org/x/a", "", []string{"$GOROOT/src/vendor/golang.org/x/a=vendor/golang.org/x/a", "$GOROOT/src/vendor/golang.org/x=vendor/golang.org/x", "$GOROOT/src/vendor/golang.org=vendor/golang.org", "$GOROOT/src/vendor=vendor"}},
+ {"$GOROOT/src/cmd/vendor/golang.org/x/mod/a", "cmd/vendor/golang.org/x/mod/a", "", []string{"$GOROOT/src/cmd/vendor/golang.org/x/mod/a=cmd/vendor/golang.org/x/mod/a", "$GOROOT/src/cmd/vendor/golang.org/x/mod=cmd/vendor/golang.org/x/mod", "$GOROOT/src/cmd/vendor/golang.org/x=cmd/vendor/golang.org/x", "$GOROOT/src/cmd/vendor/golang.org=cmd/vendor/golang.org", "$GOROOT/src/cmd/vendor=cmd/vendor"}}, // cmd is not the main module
+ {"$GOROOT/src/cmd/vendor/golang.org/x/mod/a", "golang.org/x/mod/a", "golang.org/x/mod", []string{"$GOROOT/src/cmd/vendor/golang.org/x/mod/a=golang.org/x/mod/a", "$GOROOT/src/cmd/vendor/golang.org/x/mod=golang.org/x/mod"}}, // cmd is the main module
+ {"/m/a", "example.com/mx/a", "example.com/m", nil}, // not within module
+ {"/m", "example.com/m", "", nil}, // no module
+ {"/m", "m", "", nil}, // no module (standard-looking path outside GOROOT)
+ } {
+ var want []string
+ for _, d := range test.want {
+ dir, path, _ := strings.Cut(d, "=")
+ want = append(want, fromSlash(dir)+"="+path)
+ }
+ var got []string
+ for dir, path := range EnclosingDirs(fromSlash(test.pkgdir), test.pkgPath, test.modPath) {
+ got = append(got, dir+"="+path)
+ }
+ if !slices.Equal(got, want) {
+ t.Errorf("EnclosingDirs(%q, %q, %q) = %q, want %q", test.pkgdir, test.pkgPath, test.modPath, got, want)
+ }
+ }
+}
+
+func TestInStd(t *testing.T) {
+ // Directories beneath $GOROOT/src are relative to cfg.GOROOTsrc.
+ fromSlash := func(dir string) string {
+ if rest, ok := strings.CutPrefix(dir, "$GOROOT/src"); ok {
+ return filepath.Join(cfg.GOROOTsrc, filepath.FromSlash(rest))
+ }
+ return filepath.FromSlash(dir)
+ }
+ for _, test := range []struct {
+ pkgdir, pkgPath string
+ want bool
+ }{
+ {"$GOROOT/src/fmt", "fmt", true},
+ {"$GOROOT/src/cmd/go", "cmd/go", true},
+ {"$GOROOT/src/vendor/golang.org/x/net/dns", "vendor/golang.org/x/net/dns", true},
+ {"$GOROOT/src/cmd/vendor/golang.org/x/mod/a", "cmd/vendor/golang.org/x/mod/a", true}, // cmd is not the main module
+ {"$GOROOT/src/cmd/vendor/golang.org/x/mod/a", "golang.org/x/mod/a", false}, // cmd is the main module
+ {"/m/a", "m/a", false}, // dot-free main module
+ {"/m/a", "example.com/m/a", false},
+ } {
+ if got := InStd(fromSlash(test.pkgdir), test.pkgPath); got != test.want {
+ t.Errorf("InStd(%q, %q) = %t, want %t", test.pkgdir, test.pkgPath, got, test.want)
+ }
+ }
+}
+
+func TestVisible(t *testing.T) {
+ for _, test := range []struct {
+ from string
+ fromStd bool
+ pkg string
+ want bool
+ }{
+ {"example.com/m/x", false, "example.com/c", true}, // not internal
+ {"example.com/m", false, "example.com/m/internal/c", true}, // parent itself
+ {"example.com/m/x/y", false, "example.com/m/internal/c", true}, // beneath parent
+ {"example.com/mx", false, "example.com/m/internal/c", false}, // not a path prefix
+ {"example.com/other", false, "example.com/m/internal/c", false}, // elsewhere
+ {"example.com/m/p/q", false, "example.com/m/p/internal", true}, // .../internal
+ {"example.com/m/q", false, "example.com/m/p/internal", false}, //
+ {"example.com/m/p", false, "example.com/m/internal/a/internal/b", false}, // final internal governs
+ {"example.com/m/internal/a/x", false, "example.com/m/internal/a/internal/b", true},
+ {"fmt", true, "internal/vet/printf", true}, // std top-level internal, from std
+ {"", true, "internal/vet/printf", true}, // GOROOT/src itself
+ {"example.com/m", false, "internal/vet/printf", false}, // ...from user code
+ {"fmt", true, "fmt/internal/zz", true}, //
+ {"log", true, "fmt/internal/zz", false}, // std, but outside fmt
+ {"cmd/go", true, "cmd/internal/x", true}, //
+ {"fmt", true, "cmd/internal/x", false}, //
+ {"fmt", true, "internal", true}, // top-level internal itself
+ {"example.com/m", false, "internal", false}, //
+ } {
+ if got := Visible(test.from, test.fromStd, test.pkg); got != test.want {
+ t.Errorf("Visible(%q, %t, %q) = %t, want %t", test.from, test.fromStd, test.pkg, got, test.want)
+ }
+ }
+}