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

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package protocol defines the types of the protocol between the go
     6  // command and the analysis tool that it synthesizes for go test, whose
     7  // driver is [internal/analysis/gotestchecker]. The tool performs two
     8  // operations: describe (tool -describe=FILE), whose result is a
     9  // [Metadata] file, and analyze (tool FILE), whose request is an
    10  // [AnalyzeRequest] and whose results include a pass file (see [Pass])
    11  // for each requested analyzer.
    12  //
    13  // The protocol is internal to the toolchain, not stable, and may be
    14  // changed at any time.
    15  //
    16  // This package is imported by the go command, so it must not depend on
    17  // the analysis framework (or go/types).
    18  package protocol
    19  
    20  import (
    21  	"bytes"
    22  	"encoding/binary"
    23  	"encoding/json"
    24  	"fmt"
    25  	"os"
    26  	"slices"
    27  	"strings"
    28  	"time"
    29  )
    30  
    31  // -- describe --
    32  
    33  // Metadata is the result of the tool's metadata query (tool
    34  // -describe=FILE), written by the tool as a JSON file.
    35  type Metadata struct {
    36  	// Vars describes each variable linked into the tool, in the
    37  	// order of the argument of gotestchecker.Main, which is sorted
    38  	// by Symbol (see [Metadata.Var]).
    39  	Vars []*VarInfo
    40  
    41  	// Analyzers describes every analyzer reachable from a valid
    42  	// member of a valid variable, in topological order
    43  	// (prerequisites first). Its indexes are the canonical
    44  	// numbering of analyzers, by which the protocol identifies
    45  	// them.
    46  	Analyzers []*Analyzer
    47  }
    48  
    49  // Var returns the description of the variable with the specified
    50  // symbol ("pkgpath.Var"), or nil if it was not linked into the tool.
    51  func (md *Metadata) Var(symbol string) *VarInfo {
    52  	i, ok := slices.BinarySearchFunc(md.Vars, symbol, func(v *VarInfo, symbol string) int {
    53  		return strings.Compare(v.Symbol, symbol)
    54  	})
    55  	if !ok {
    56  		return nil
    57  	}
    58  	return md.Vars[i]
    59  }
    60  
    61  // A VarInfo describes an analyzer or suite variable linked into the
    62  // tool.
    63  type VarInfo struct {
    64  	Symbol string // qualified name, "pkgpath.Var"
    65  
    66  	// Error, if non-empty, describes a problem that invalidates
    67  	// the whole variable: a value of the wrong type, a nil analyzer
    68  	// or suite element, or distinct members of a suite with the
    69  	// same Name.
    70  	Error string `json:",omitempty"`
    71  
    72  	// The remaining fields are undefined if there is an Error.
    73  
    74  	// IsSuite reports whether the variable is a suite
    75  	// ([]*analysis.Analyzer) rather than an analyzer
    76  	// (*analysis.Analyzer).
    77  	IsSuite bool
    78  
    79  	// Members lists the distinct analyzers of the variable: the
    80  	// analyzer itself, or the elements of the suite, in order.
    81  	Members []*Member `json:",omitempty"`
    82  }
    83  
    84  // A Member describes an analyzer that is a member of a variable.
    85  // Analyzer is -1 if and only if Error is non-empty.
    86  type Member struct {
    87  	Name string // Analyzer.Name
    88  
    89  	Analyzer int    // index in Metadata.Analyzers (-1 if not valid)
    90  	Error    string `json:",omitempty"` // first error in the member's Requires closure, if not valid
    91  }
    92  
    93  // An Analyzer describes an analyzer in the Requires closure of the valid
    94  // members. Its index in Metadata.Analyzers identifies it in the
    95  // protocol.
    96  type Analyzer struct {
    97  	Name     string
    98  	Doc      string
    99  	URL      string `json:",omitempty"`
   100  	RunFunc  string // run-time symbol name of the Run function (see runtime.Func.Name)
   101  	Requires []int  // indexes
   102  	Facts    bool   // whether this analyzer (not its prerequisites) uses facts
   103  }
   104  
   105  // -- analyze --
   106  
   107  // An AnalyzeRequest is a request to analyze one package (tool FILE),
   108  // written by the go command as a JSON file. The results are the files
   109  // that it names: types (TypeExport), type errors (TypeErrors), and a
   110  // pass file (see [Pass]) for each analyzer in Outputs.
   111  type AnalyzeRequest struct {
   112  	ID           string // import path, e.g. "fmt" (also for its test variant)
   113  	ImportPath   string
   114  	Dir          string
   115  	GoFiles      []string
   116  	NonGoFiles   []string
   117  	IgnoredFiles []string
   118  	ImportMap    map[string]string // maps import path to package path
   119  	GoVersion    string            // e.g. "go1.27"
   120  	GOARCH       string
   121  	Module       *Module
   122  
   123  	// TypeImports maps the package path of each direct import to
   124  	// the name of a file holding its (deep) export data.
   125  	TypeImports map[string]string
   126  
   127  	// TypeExport names the file to which the export data of this
   128  	// package should be written. It is empty if the go command
   129  	// already has it (in its cache) and needs only the results of
   130  	// analyzers (see Outputs).
   131  	TypeExport string
   132  
   133  	// TypeErrors names the file to which the type errors of this
   134  	// package (a JSON list of strings, perhaps empty) should be
   135  	// written. It is set if and only if TypeExport is: the type
   136  	// errors are a property of the package, reported once by the go
   137  	// command, not by each analyzer.
   138  	TypeErrors string
   139  
   140  	// Facts is a sparse mapping from the index of each analyzer
   141  	// that uses facts, and is in the Requires closure of Outputs, to a
   142  	// mapping from the package
   143  	// path of each direct import to the name of the pass file
   144  	// holding that analyzer's facts for that import. A missing
   145  	// entry denotes an empty fact set.
   146  	Facts map[int]map[string]string
   147  
   148  	// Outputs is a sparse mapping from the index of each required
   149  	// analyzer to the name of the file to which its [Pass] should be
   150  	// written: its facts, if it uses facts; its diagnostics, if it
   151  	// is in Report; or its failure. The tool runs these analyzers
   152  	// and their prerequisites.
   153  	Outputs map[int]string
   154  
   155  	// Report lists the indexes of the analyzers in Outputs whose
   156  	// diagnostics should be included in their pass files.
   157  	Report []int
   158  }
   159  
   160  // A Module describes the module to which a package belongs. Its JSON
   161  // encoding is that of a go/analysis.Module (and of the Module of
   162  // go list -json); this copy avoids a dependency on go/analysis.
   163  type Module struct {
   164  	Path      string       // module path
   165  	Version   string       // module version ("" if unknown, such as for workspace modules)
   166  	Replace   *Module      // replaced by this module
   167  	Time      *time.Time   // time version was created
   168  	Main      bool         // is this the main module?
   169  	Indirect  bool         // is this module only an indirect dependency of main module?
   170  	Dir       string       // directory holding files for this module, if any
   171  	GoMod     string       // path to go.mod file used when loading this module, if any
   172  	GoVersion string       // go version used in module (e.g. "go1.22.0")
   173  	Error     *ModuleError // error loading module
   174  }
   175  
   176  // A ModuleError holds errors loading a module; see [Module].
   177  type ModuleError struct {
   178  	Err string // the error itself
   179  }
   180  
   181  // -- pass file format --
   182  
   183  // A Pass holds the results of an analyzer on a package (a "pass"). A
   184  // pass file is the encoding of a Pass (see [WritePass]).
   185  //
   186  // A pass that failed or was skipped has no facts, and its dependent
   187  // passes (the same analyzer on importers, if it uses facts, and the
   188  // analyzers that require it on the same package) are skipped. Each
   189  // failure is reported once, by the go command, at the pass that
   190  // failed; a skipped pass is not reported, since its cause is.
   191  type Pass struct {
   192  	// Facts is the encoded fact set of the analyzer, which
   193  	// includes facts about dependencies ("deep"). It is nil if the
   194  	// analyzer uses no facts.
   195  	Facts []byte
   196  
   197  	// Failure records the failure of the analyzer on this package,
   198  	// if any: an error returned by Run, a panic in Run, or a fact
   199  	// that cannot be encoded. A failure prevents only the dependent
   200  	// passes; it does not stop the build.
   201  	Failure *Failure
   202  
   203  	// Skipped reports that the analyzer did not run on this package
   204  	// because the package has type errors, a prerequisite failed or
   205  	// was skipped, or (for an analyzer that uses facts) it failed or
   206  	// was skipped on a direct import.
   207  	Skipped bool
   208  
   209  	// Diagnostics holds the analyzer's diagnostics. It is empty
   210  	// unless the package's diagnostics are reported.
   211  	Diagnostics []*Diagnostic
   212  }
   213  
   214  // A Failure records the failure of an analyzer on a package: an
   215  // error returned by the analyzer, a panic in the analyzer, or a fact
   216  // that cannot be encoded.
   217  type Failure struct {
   218  	Package  string // ID of the package (its import path, e.g. "fmt")
   219  	Analyzer string // Name of the analyzer
   220  	Message  string
   221  }
   222  
   223  func (f *Failure) String() string {
   224  	return fmt.Sprintf("analysis of %s by %s failed: %s", f.Package, f.Analyzer, f.Message)
   225  }
   226  
   227  // A Diagnostic is the serialized form of an analysis.Diagnostic,
   228  // without suggested fixes.
   229  type Diagnostic struct {
   230  	Posn     string // "file:line:col"
   231  	End      string // "file:line:col", or ""
   232  	Category string
   233  	Message  string
   234  	URL      string
   235  }
   236  
   237  // A pass file has a fixed layout: a 4-byte magic number, a flags byte
   238  // (passSkipped), then the other three fields of the Pass, each as a
   239  // uvarint length followed by that many bytes:
   240  //
   241  //	passMagic
   242  //	flags         1 byte
   243  //	Facts         raw bytes (the encoded fact set)
   244  //	Failure       JSON, or empty if nil
   245  //	Diagnostics   JSON, or empty if none
   246  //
   247  // (We avoid gob, as it is nondeterministic; see go.dev/issue/82778.)
   248  const passMagic = "pass"
   249  
   250  const passSkipped = 1 << 0 // flag: Pass.Skipped
   251  
   252  // WritePass writes the pass to the named file.
   253  func WritePass(filename string, pass *Pass) error {
   254  	var failure, diags []byte
   255  	if pass.Failure != nil {
   256  		data, err := json.Marshal(pass.Failure)
   257  		if err != nil {
   258  			return err
   259  		}
   260  		failure = data
   261  	}
   262  	if len(pass.Diagnostics) > 0 {
   263  		data, err := json.Marshal(pass.Diagnostics)
   264  		if err != nil {
   265  			return err
   266  		}
   267  		diags = data
   268  	}
   269  	var flags byte
   270  	if pass.Skipped {
   271  		flags |= passSkipped
   272  	}
   273  	buf := append([]byte(passMagic), flags)
   274  	for _, field := range [][]byte{pass.Facts, failure, diags} {
   275  		buf = binary.AppendUvarint(buf, uint64(len(field)))
   276  		buf = append(buf, field...)
   277  	}
   278  	return os.WriteFile(filename, buf, 0666)
   279  }
   280  
   281  // ReadPass reads the named pass file.
   282  func ReadPass(filename string) (*Pass, error) {
   283  	data, err := os.ReadFile(filename)
   284  	if err != nil {
   285  		return nil, err
   286  	}
   287  	corrupt := func(msg string) (*Pass, error) {
   288  		return nil, fmt.Errorf("%s: corrupt analysis pass file: %s", filename, msg)
   289  	}
   290  	rest, ok := bytes.CutPrefix(data, []byte(passMagic))
   291  	if !ok {
   292  		return corrupt("bad magic number")
   293  	}
   294  	if len(rest) == 0 {
   295  		return corrupt("truncated")
   296  	}
   297  	flags := rest[0]
   298  	rest = rest[1:]
   299  	var fields [3][]byte
   300  	for i := range fields {
   301  		n, k := binary.Uvarint(rest)
   302  		if k <= 0 || uint64(len(rest)-k) < n {
   303  			return corrupt("truncated")
   304  		}
   305  		fields[i] = rest[k : k+int(n)]
   306  		rest = rest[k+int(n):]
   307  	}
   308  	if len(rest) > 0 {
   309  		return corrupt("trailing data")
   310  	}
   311  	pass := &Pass{Skipped: flags&passSkipped != 0}
   312  	if len(fields[0]) > 0 {
   313  		pass.Facts = fields[0]
   314  	}
   315  	if len(fields[1]) > 0 {
   316  		pass.Failure = new(Failure)
   317  		if err := json.Unmarshal(fields[1], pass.Failure); err != nil {
   318  			return corrupt(err.Error())
   319  		}
   320  	}
   321  	if len(fields[2]) > 0 {
   322  		if err := json.Unmarshal(fields[2], &pass.Diagnostics); err != nil {
   323  			return corrupt(err.Error())
   324  		}
   325  	}
   326  	return pass, nil
   327  }
   328  

View as plain text