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

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gotestchecker
     6  
     7  // This file defines the analyzer graph, its validation, and the
     8  // metadata query (-describe), whose result is a [protocol.Metadata].
     9  
    10  import (
    11  	"encoding/json"
    12  	"fmt"
    13  	"go/analysis"
    14  	"internal/analysis/gotestchecker/protocol"
    15  	"log"
    16  	"os"
    17  	"reflect"
    18  	"runtime"
    19  	"strings"
    20  	"unicode"
    21  )
    22  
    23  // writeMetadata writes the metadata for the specified variables to
    24  // the named file.
    25  func writeMetadata(filename string, vars []Var) error {
    26  	g := newGraph(vars)
    27  	analyzers := []*protocol.Analyzer{}
    28  	for _, a := range g.analyzers {
    29  		var requires []int
    30  		for _, req := range a.Requires {
    31  			requires = append(requires, g.index[req])
    32  		}
    33  		run := runFunc(a)
    34  		analyzers = append(analyzers, &protocol.Analyzer{
    35  			Name:     a.Name,
    36  			Doc:      a.Doc,
    37  			URL:      a.URL,
    38  			RunFunc:  run,
    39  			Requires: requires,
    40  			Facts:    len(a.FactTypes) > 0,
    41  		})
    42  	}
    43  	md := &protocol.Metadata{
    44  		Vars:      g.vars,
    45  		Analyzers: analyzers,
    46  	}
    47  	data, err := json.Marshal(md)
    48  	if err != nil {
    49  		log.Fatal(err) // can't happen
    50  	}
    51  	return os.WriteFile(filename, data, 0666)
    52  }
    53  
    54  // A graph is the validated graph of analyzers reachable from the
    55  // variables (see [validate]).
    56  type graph struct {
    57  	vars      []*protocol.VarInfo        // description of each variable, by position in the argument of Main
    58  	analyzers []*analysis.Analyzer       // valid analyzers (Requires-closed) in canonical order
    59  	index     map[*analysis.Analyzer]int // index of each analyzer in order (its identifier in the protocol)
    60  }
    61  
    62  // newGraph computes the graph of analyzers reachable (via
    63  // Analyzer.Requires) from the specified variables. We assume vars are
    64  // initialized deterministically so the graph is the same on each
    65  // execution.
    66  func newGraph(vars []Var) *graph {
    67  	g := &graph{
    68  		vars:  make([]*protocol.VarInfo, len(vars)),
    69  		index: make(map[*analysis.Analyzer]int),
    70  	}
    71  
    72  	// add ensures 'a' and its Requires dependencies
    73  	// are in the canonical analyzer ordering.
    74  	var add func(a *analysis.Analyzer)
    75  	add = func(a *analysis.Analyzer) {
    76  		if _, ok := g.index[a]; !ok {
    77  			for _, req := range a.Requires {
    78  				add(req)
    79  			}
    80  			g.index[a] = len(g.analyzers)
    81  			g.analyzers = append(g.analyzers, a)
    82  		}
    83  	}
    84  
    85  	// Validate each variable and each member's Requires closure,
    86  	// and add the valid members (and their Requires closures) to
    87  	// the canonical order.
    88  	for i, v := range vars {
    89  		info := &protocol.VarInfo{Symbol: v.Symbol}
    90  		g.vars[i] = info
    91  		analyzers, isSuite, err := varAnalyzers(v.Value)
    92  		if err != nil {
    93  			info.Error = err.Error() // invalid Var.Value
    94  			continue
    95  		}
    96  		info.IsSuite = isSuite
    97  		for _, a := range analyzers {
    98  			if err := validate(a); err != "" {
    99  				// invalid analyzer graph
   100  				info.Members = append(info.Members, &protocol.Member{Name: a.Name, Analyzer: -1, Error: err})
   101  				continue
   102  			}
   103  			// Valid: Add it to canonical ordering.
   104  			add(a)
   105  			info.Members = append(info.Members, &protocol.Member{
   106  				Name:     a.Name,
   107  				Analyzer: g.index[a],
   108  			})
   109  		}
   110  	}
   111  	return g
   112  }
   113  
   114  // varAnalyzers returns the distinct analyzers of a variable's value
   115  // (the analyzer itself, or the elements of the suite, in order), and
   116  // whether it is a suite.
   117  func varAnalyzers(value any) ([]*analysis.Analyzer, bool, error) {
   118  	switch value := value.(type) {
   119  	case *analysis.Analyzer:
   120  		if value == nil {
   121  			return nil, false, fmt.Errorf("analyzer is nil")
   122  		}
   123  		return []*analysis.Analyzer{value}, false, nil
   124  
   125  	case []*analysis.Analyzer:
   126  		var (
   127  			analyzers []*analysis.Analyzer
   128  			seen      = make(map[*analysis.Analyzer]bool)
   129  			byName    = make(map[string]bool)
   130  		)
   131  		for i, a := range value {
   132  			if a == nil {
   133  				return nil, false, fmt.Errorf("suite element %d is nil", i)
   134  			}
   135  			if seen[a] {
   136  				// Repeated elements (by pointer) are one member.
   137  				continue
   138  			}
   139  			seen[a] = true
   140  			if byName[a.Name] {
   141  				return nil, false, fmt.Errorf("suite contains distinct analyzers named %q", a.Name)
   142  			}
   143  			byName[a.Name] = true
   144  			analyzers = append(analyzers, a)
   145  		}
   146  		return analyzers, true, nil
   147  	}
   148  
   149  	return nil, false, fmt.Errorf("variable has type %T, want *go/analysis.Analyzer or []*go/analysis.Analyzer", value)
   150  }
   151  
   152  // validate checks the Requires-closure of a single member analyzer,
   153  // and returns the first error found, or "".
   154  //
   155  // Unlike [golang.org/x/tools/go/analysis.Validate], each member (and
   156  // its Requires closure) is validated separately, so that each error
   157  // is attributable to a single member of a single variable, and thus
   158  // to the annotations that enable it. This ensures compositionality:
   159  // if go test X and go test Y succeed, then so does go test X Y, even
   160  // though the latter builds a single tool containing the analyzers of
   161  // both.
   162  func validate(root *analysis.Analyzer) string {
   163  	var err string
   164  	errorf := func(format string, args ...any) bool {
   165  		err = fmt.Sprintf(format, args...)
   166  		return false
   167  	}
   168  
   169  	// coloring for cycle check
   170  	const (
   171  		white = iota
   172  		grey
   173  		black
   174  	)
   175  	color := make(map[*analysis.Analyzer]uint8)
   176  
   177  	// In its cache keys for pass files, the go command identifies
   178  	// an analyzer by its Name and Run function so distinct
   179  	// analyzers that share both ("evil twins") must not appear in
   180  	// one Requires closure. (See planAnalysis function in go
   181  	// test.)
   182  	//
   183  	// Twins in different Requires-closures are not detected: this is
   184  	// unsound, but the tool cannot distinguish two closures of the
   185  	// same func literal.
   186  	//
   187  	// Neither Name nor the Run function name unique, but they are
   188  	// both nearly unique, and their collisions are uncorrelated.
   189  	// That is, when Analyzer.Names conflict, it is usually
   190  	// between unrelated packages from different authors, so the
   191  	// Analyzer.Run functions have different symbols; and when two
   192  	// closely-related analyzers use the same Run function, their
   193  	// author invariably gives them different names.
   194  	// Evil twins thus do not arise by accident.
   195  	type twinKey struct{ name, run string }
   196  	twins := make(map[twinKey]bool)
   197  
   198  	var visit func(a *analysis.Analyzer, path []string) bool
   199  	visit = func(a *analysis.Analyzer, path []string) bool {
   200  		if a == nil {
   201  			return errorf("nil analyzer in Requires (via %s)", strings.Join(path, " -> "))
   202  		}
   203  		descr := func() string {
   204  			return fmt.Sprintf("analyzer %q (via %s)", a.Name, strings.Join(path, " -> "))
   205  		}
   206  		path = append(path, a.Name)
   207  		switch color[a] {
   208  		case grey:
   209  			return errorf("%s has cycle in Requires graph", descr())
   210  		case black:
   211  			return true
   212  		}
   213  		color[a] = grey
   214  
   215  		if !validIdent(a.Name) {
   216  			return errorf("%s has an invalid name", descr())
   217  		}
   218  		if a.Doc == "" {
   219  			return errorf("%s is undocumented", descr())
   220  		}
   221  		if a.Run == nil {
   222  			return errorf("%s has nil Run", descr())
   223  		}
   224  		k := twinKey{a.Name, runFunc(a)}
   225  		if twins[k] {
   226  			return errorf("%s and another Analyzer conflict in both Name and Run function (%s)", descr(), k.run)
   227  		}
   228  		twins[k] = true
   229  
   230  		// Unlike analysis.Validate, Analyzer.FactTypes need
   231  		// not be unique across analyzers: our fact encoding
   232  		// segregates fact by their analyzers.
   233  		for _, f := range a.FactTypes {
   234  			if t := reflect.TypeOf(f); t == nil || t.Kind() != reflect.Pointer {
   235  				return errorf("%s has fact type %v, which is not a pointer", descr(), t)
   236  			}
   237  		}
   238  
   239  		// Analyzer.Flags are ignored.
   240  
   241  		for _, req := range a.Requires {
   242  			if !visit(req, path) {
   243  				return false
   244  			}
   245  		}
   246  		color[a] = black
   247  		return true
   248  	}
   249  	visit(root, nil)
   250  	return err
   251  }
   252  
   253  // runFunc returns the symbol name of the analyzer's Run function.
   254  func runFunc(a *analysis.Analyzer) string {
   255  	return runtime.FuncForPC(reflect.ValueOf(a.Run).Pointer()).Name()
   256  }
   257  
   258  func validIdent(name string) bool {
   259  	for i, r := range name {
   260  		if !(r == '_' || unicode.IsLetter(r) || i > 0 && unicode.IsDigit(r)) {
   261  			return false
   262  		}
   263  	}
   264  	return name != ""
   265  }
   266  

View as plain text