Debian Codegraph @

go/analysis/unitchecker/separate_test.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // Copyright 2023 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 unitchecker_test
6
7 // This file illustrates separate analysis with an example.
8
9 import (
10 "bytes"
11 "encoding/json"
12 "fmt"
13 "go/token"
14 "go/types"
15 "io"
16 "os"
17 "path/filepath"
18 "sort"
19 "strings"
20 "sync/atomic"
21 "testing"
22
23 "golang.org/x/tools/go/analysis"
24 "golang.org/x/tools/go/analysis/passes/printf"
25 "golang.org/x/tools/go/analysis/unitchecker"
26 "golang.org/x/tools/go/gcexportdata"
27 "golang.org/x/tools/go/packages"
28 "golang.org/x/tools/internal/testenv"
29 "golang.org/x/tools/internal/testfiles"
30 "golang.org/x/tools/txtar"
31 )
32
33 // TestExampleSeparateAnalysis demonstrates the principle of separate
34 // analysis, the distribution of units of type-checking and analysis
35 // work across several processes, using serialized summaries to
36 // communicate between them.
37 //
38 // It uses two different kinds of task, "manager" and "worker":
39 //
40 // - The manager computes the graph of package dependencies, and makes
41 // a request to the worker for each package. It does not parse,
42 // type-check, or analyze Go code. It is analogous "go vet".
43 //
44 // - The worker, which contains the Analyzers, reads each request,
45 // loads, parses, and type-checks the files of one package,
46 // applies all necessary analyzers to the package, then writes
47 // its results to a file. It is a unitchecker-based driver,
48 // analogous to the program specified by go vet -vettool= flag.
49 //
50 // In practice these would be separate executables, but for simplicity
51 // of this example they are provided by one executable in two
52 // different modes: the Example function is the manager, and the same
53 // executable invoked with ENTRYPOINT=worker is the worker.
54 // (See TestIntegration for how this happens.)
55 //
56 // Unfortunately this can't be a true Example because of the skip,
57 // which requires a testing.T.
58 func TestExampleSeparateAnalysis(t *testing.T) {
59 testenv.NeedsGoPackages(t)
60
61 // src is an archive containing a module with a printf mistake.
62 const src = `
63 -- go.mod --
64 module separate
65 go 1.18
66
67 -- main/main.go --
68 package main
69
70 import "separate/lib"
71
72 func main() {
73 lib.MyPrintf("%s", 123)
74 }
75
76 -- lib/lib.go --
77 package lib
78
79 import "fmt"
80
81 func MyPrintf(format string, args ...any) {
82 fmt.Printf(format, args...)
83 }
84 `
85
86 // Expand archive into tmp tree.
87 fs, err := txtar.FS(txtar.Parse([]byte(src)))
88 if err != nil {
89 t.Fatal(err)
90 }
91 tmpdir := testfiles.CopyToTmp(t, fs)
92
93 // Load metadata for the main package and all its dependencies.
94 cfg := &packages.Config{
95 Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | packages.NeedModule,
96 Dir: tmpdir,
97 Env: append(os.Environ(),
•98 "GO111MODULE=on", // needs Go module to work
99 "GOPROXY=off", // disable network
100 "GOWORK=off", // an ambient GOWORK value would break package loading
101 ),
102 Logf: t.Logf,
103 }
104 pkgs, err := packages.Load(cfg, "separate/main")
105 if err != nil {
106 t.Fatal(err)
107 }
108 // Stop if any package had a metadata error.
109 if packages.PrintErrors(pkgs) > 0 {
110 t.Fatal("there were errors among loaded packages")
111 }
112
113 // Now we have loaded the import graph,
114 // let's begin the proper work of the manager.
115
116 // Gather root packages. They will get all analyzers,
117 // whereas dependencies get only the subset that
118 // produce facts or are required by them.
119 roots := make(map[*packages.Package]bool)
120 for _, pkg := range pkgs {
121 roots[pkg] = true
122 }
123
124 // nextID generates sequence numbers for each unit of work.
125 // We use it to create names of temporary files.
126 var nextID atomic.Int32
127
128 var allDiagnostics []string
129
130 // Visit all packages in postorder: dependencies first.
131 // TODO(adonovan): opt: use parallel postorder.
132 packages.Visit(pkgs, nil, func(pkg *packages.Package) {
133 if pkg.PkgPath == "unsafe" {
134 return
135 }
136
137 // Choose a unique prefix for temporary files
138 // (.cfg .types .facts) produced by this package.
139 // We stow it in an otherwise unused field of
140 // Package so it can be accessed by our importers.
141 prefix := fmt.Sprintf("%s/%d", tmpdir, nextID.Add(1))
142 pkg.ExportFile = prefix
143
144 // Construct the request to the worker.
145 var (
146 importMap = make(map[string]string)
147 packageFile = make(map[string]string)
148 packageVetx = make(map[string]string)
149 )
150 for importPath, dep := range pkg.Imports {
151 importMap[importPath] = dep.PkgPath
152 if depPrefix := dep.ExportFile; depPrefix != "" { // skip "unsafe"
153 packageFile[dep.PkgPath] = depPrefix + ".types"
154 packageVetx[dep.PkgPath] = depPrefix + ".facts"
155 }
156 }
157 cfg := unitchecker.Config{
158 ID: pkg.ID,
159 ImportPath: pkg.PkgPath,
160 GoFiles: pkg.CompiledGoFiles,
161 NonGoFiles: pkg.OtherFiles,
162 IgnoredFiles: pkg.IgnoredFiles,
163 ImportMap: importMap,
164 PackageFile: packageFile,
165 PackageVetx: packageVetx,
166 VetxOnly: !roots[pkg],
167 VetxOutput: prefix + ".facts",
168 }
169 if pkg.Module != nil {
170 if v := pkg.Module.GoVersion; v != "" {
171 cfg.GoVersion = "go" + v
172 }
173 cfg.ModulePath = pkg.Module.Path
174 cfg.ModuleVersion = pkg.Module.Version
175 cfg.Module = analysisModuleFromPackagesModule(pkg.Module)
176 }
177
178 // Write the JSON configuration message to a file.
179 cfgData, err := json.Marshal(cfg)
180 if err != nil {
181 t.Fatalf("internal error in json.Marshal: %v", err)
182 }
183 cfgFile := prefix + ".cfg"
184 if err := os.WriteFile(cfgFile, cfgData, 0666); err != nil {
185 t.Fatal(err)
186 }
187
188 // Send the request to the worker.
189 cmd := testenv.Command(t, os.Args[0], "-json", cfgFile)
190 cmd.Stderr = os.Stderr
191 cmd.Stdout = new(bytes.Buffer)
192 cmd.Env = append(os.Environ(), "ENTRYPOINT=worker")
193 if err := cmd.Run(); err != nil {
194 t.Fatal(err)
195 }
196
197 // Parse JSON output and gather in allDiagnostics.
198 dec := json.NewDecoder(cmd.Stdout.(io.Reader))
199 for {
200 type jsonDiagnostic struct {
201 Posn string `json:"posn"`
202 Message string `json:"message"`
203 }
204 // 'results' maps Package.Path -> Analyzer.Name -> diagnostics
205 var results map[string]map[string][]jsonDiagnostic
206 if err := dec.Decode(&results); err != nil {
207 if err == io.EOF {
208 break
209 }
210 t.Fatalf("internal error decoding JSON: %v", err)
211 }
212 for _, result := range results {
213 for analyzer, diags := range result {
214 for _, diag := range diags {
215 rel := strings.ReplaceAll(diag.Posn, tmpdir, "")
216 rel = filepath.ToSlash(rel)
217 msg := fmt.Sprintf("%s: [%s] %s", rel, analyzer, diag.Message)
218 allDiagnostics = append(allDiagnostics, msg)
219 }
220 }
221 }
222 }
223 })
224
225 // Observe that the example produces a fact-based diagnostic
226 // from separate analysis of "main", "lib", and "fmt":
227
228 const want = `/main/main.go:6:16: [printf] separate/lib.MyPrintf format %s has arg 123 of wrong type int`
229 sort.Strings(allDiagnostics)
230 if got := strings.Join(allDiagnostics, "\n"); got != want {
231 t.Errorf("Got: %s\nWant: %s", got, want)
232 }
233 }
234
235 // -- worker process --
236
237 // worker is the main entry point for a unitchecker-based driver
238 // with only a single analyzer, for illustration.
239 func worker() {
240 // Currently the unitchecker API doesn't allow clients to
241 // control exactly how and where fact and type information
242 // is produced and consumed.
243 //
244 // So, for example, it assumes that type information has
245 // already been produced by the compiler, which is true when
246 // running under "go vet", but isn't necessary. It may be more
247 // convenient and efficient for a distributed analysis system
248 // if the worker generates both of them, which is the approach
249 // taken in this example; they could even be saved as two
250 // sections of a single file.
251 //
252 // Consequently, this test currently needs special access to
253 // private hooks in unitchecker to control how and where facts
254 // and types are produced and consumed. In due course this
255 // will become a respectable public API. In the meantime, it
256 // should at least serve as a demonstration of how one could
257 // fork unitchecker to achieve separate analysis without go vet.
258 unitchecker.SetTypeImportExport(makeTypesImporter, exportTypes)
259
260 unitchecker.Main(printf.Analyzer)
261 }
262
263 func makeTypesImporter(cfg *unitchecker.Config, fset *token.FileSet) types.Importer {
264 imports := make(map[string]*types.Package)
265 return importerFunc(func(importPath string) (*types.Package, error) {
266 // Resolve import path to package path (vendoring, etc)
267 path, ok := cfg.ImportMap[importPath]
268 if !ok {
269 return nil, fmt.Errorf("can't resolve import %q", path)
270 }
271 if path == "unsafe" {
272 return types.Unsafe, nil
273 }
274
275 // Find, read, and decode file containing type information.
276 file, ok := cfg.PackageFile[path]
277 if !ok {
278 return nil, fmt.Errorf("no package file for %q", path)
279 }
280 f, err := os.Open(file)
281 if err != nil {
282 return nil, err
283 }
284 defer f.Close() // ignore error
285 return gcexportdata.Read(f, fset, imports, path)
286 })
287 }
288
289 func exportTypes(cfg *unitchecker.Config, fset *token.FileSet, pkg *types.Package) error {
290 var out bytes.Buffer
291 if err := gcexportdata.Write(&out, fset, pkg); err != nil {
292 return err
293 }
294 typesFile := strings.TrimSuffix(cfg.VetxOutput, ".facts") + ".types"
295 return os.WriteFile(typesFile, out.Bytes(), 0666)
296 }
297
298 // -- helpers --
299
300 func analysisModuleFromPackagesModule(mod *packages.Module) *analysis.Module {
301 if mod == nil {
302 return nil
303 }
304 var modErr *analysis.ModuleError
305 if mod.Error != nil {
306 modErr = &analysis.ModuleError{Err: mod.Error.Err}
307 }
308 return &analysis.Module{
309 Path: mod.Path,
310 Version: mod.Version,
311 Replace: analysisModuleFromPackagesModule(mod.Replace),
312 Time: mod.Time,
313 Main: mod.Main,
314 Indirect: mod.Indirect,
315 Dir: mod.Dir,
316 GoMod: mod.GoMod,
317 GoVersion: mod.GoVersion,
318 Error: modErr,
319 }
320 }
321
322 type importerFunc func(path string) (*types.Package, error)
323
324 func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }