Debian Codegraph @

go/analysis/unitchecker/separate_test.go

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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 "GOPROXY=off", // disable network
99 "GOWORK=off", // an ambient GOWORK value would break package loading
100 ),
101 Logf: t.Logf,
102 }
103 pkgs, err := packages.Load(cfg, "separate/main")
104 if err != nil {
105 t.Fatal(err)
106 }
107 // Stop if any package had a metadata error.
108 if packages.PrintErrors(pkgs) > 0 {
109 t.Fatal("there were errors among loaded packages")
110 }
111
112 // Now we have loaded the import graph,
113 // let's begin the proper work of the manager.
114
115 // Gather root packages. They will get all analyzers,
116 // whereas dependencies get only the subset that
117 // produce facts or are required by them.
118 roots := make(map[*packages.Package]bool)
119 for _, pkg := range pkgs {
120 roots[pkg] = true
121 }
122
123 // nextID generates sequence numbers for each unit of work.
124 // We use it to create names of temporary files.
125 var nextID atomic.Int32
126
127 var allDiagnostics []string
128
129 // Visit all packages in postorder: dependencies first.
130 // TODO(adonovan): opt: use parallel postorder.
131 packages.Visit(pkgs, nil, func(pkg *packages.Package) {
132 if pkg.PkgPath == "unsafe" {
133 return
134 }
135
136 // Choose a unique prefix for temporary files
137 // (.cfg .types .facts) produced by this package.
138 // We stow it in an otherwise unused field of
139 // Package so it can be accessed by our importers.
140 prefix := fmt.Sprintf("%s/%d", tmpdir, nextID.Add(1))
141 pkg.ExportFile = prefix
142
143 // Construct the request to the worker.
144 var (
145 importMap = make(map[string]string)
146 packageFile = make(map[string]string)
147 packageVetx = make(map[string]string)
148 )
149 for importPath, dep := range pkg.Imports {
150 importMap[importPath] = dep.PkgPath
151 if depPrefix := dep.ExportFile; depPrefix != "" { // skip "unsafe"
152 packageFile[dep.PkgPath] = depPrefix + ".types"
153 packageVetx[dep.PkgPath] = depPrefix + ".facts"
154 }
155 }
156 cfg := unitchecker.Config{
157 ID: pkg.ID,
158 ImportPath: pkg.PkgPath,
159 GoFiles: pkg.CompiledGoFiles,
160 NonGoFiles: pkg.OtherFiles,
161 IgnoredFiles: pkg.IgnoredFiles,
162 ImportMap: importMap,
163 PackageFile: packageFile,
164 PackageVetx: packageVetx,
165 VetxOnly: !roots[pkg],
166 VetxOutput: prefix + ".facts",
167 }
168 if pkg.Module != nil {
169 if v := pkg.Module.GoVersion; v != "" {
170 cfg.GoVersion = "go" + v
171 }
172 cfg.ModulePath = pkg.Module.Path
173 cfg.ModuleVersion = pkg.Module.Version
174 cfg.Module = analysisModuleFromPackagesModule(pkg.Module)
175 }
176
177 // Write the JSON configuration message to a file.
178 cfgData, err := json.Marshal(cfg)
179 if err != nil {
180 t.Fatalf("internal error in json.Marshal: %v", err)
181 }
182 cfgFile := prefix + ".cfg"
183 if err := os.WriteFile(cfgFile, cfgData, 0666); err != nil {
184 t.Fatal(err)
185 }
186
187 // Send the request to the worker.
188 cmd := testenv.Command(t, os.Args[0], "-json", cfgFile)
189 cmd.Stderr = os.Stderr
190 cmd.Stdout = new(bytes.Buffer)
191 cmd.Env = append(os.Environ(), "ENTRYPOINT=worker")
192 if err := cmd.Run(); err != nil {
193 t.Fatal(err)
194 }
195
196 // Parse JSON output and gather in allDiagnostics.
197 dec := json.NewDecoder(cmd.Stdout.(io.Reader))
198 for {
199 type jsonDiagnostic struct {
200 Posn string `json:"posn"`
201 Message string `json:"message"`
202 }
203 // 'results' maps Package.Path -> Analyzer.Name -> diagnostics
204 var results map[string]map[string][]jsonDiagnostic
205 if err := dec.Decode(&results); err != nil {
206 if err == io.EOF {
207 break
208 }
209 t.Fatalf("internal error decoding JSON: %v", err)
210 }
211 for _, result := range results {
212 for analyzer, diags := range result {
213 for _, diag := range diags {
214 rel := strings.ReplaceAll(diag.Posn, tmpdir, "")
215 rel = filepath.ToSlash(rel)
216 msg := fmt.Sprintf("%s: [%s] %s", rel, analyzer, diag.Message)
217 allDiagnostics = append(allDiagnostics, msg)
218 }
219 }
220 }
221 }
222 })
223
224 // Observe that the example produces a fact-based diagnostic
225 // from separate analysis of "main", "lib", and "fmt":
226
227 const want = `/main/main.go:6:16: [printf] separate/lib.MyPrintf format %s has arg 123 of wrong type int`
228 sort.Strings(allDiagnostics)
229 if got := strings.Join(allDiagnostics, "\n"); got != want {
230 t.Errorf("Got: %s\nWant: %s", got, want)
231 }
232 }
233
234 // -- worker process --
235
236 // worker is the main entry point for a unitchecker-based driver
237 // with only a single analyzer, for illustration.
238 func worker() {
239 // Currently the unitchecker API doesn't allow clients to
240 // control exactly how and where fact and type information
241 // is produced and consumed.
242 //
243 // So, for example, it assumes that type information has
244 // already been produced by the compiler, which is true when
245 // running under "go vet", but isn't necessary. It may be more
246 // convenient and efficient for a distributed analysis system
247 // if the worker generates both of them, which is the approach
248 // taken in this example; they could even be saved as two
249 // sections of a single file.
250 //
251 // Consequently, this test currently needs special access to
252 // private hooks in unitchecker to control how and where facts
253 // and types are produced and consumed. In due course this
254 // will become a respectable public API. In the meantime, it
255 // should at least serve as a demonstration of how one could
256 // fork unitchecker to achieve separate analysis without go vet.
257 unitchecker.SetTypeImportExport(makeTypesImporter, exportTypes)
258
259 unitchecker.Main(printf.Analyzer)
260 }
261
262 func makeTypesImporter(cfg *unitchecker.Config, fset *token.FileSet) types.Importer {
263 imports := make(map[string]*types.Package)
264 return importerFunc(func(importPath string) (*types.Package, error) {
265 // Resolve import path to package path (vendoring, etc)
266 path, ok := cfg.ImportMap[importPath]
267 if !ok {
268 return nil, fmt.Errorf("can't resolve import %q", path)
269 }
270 if path == "unsafe" {
271 return types.Unsafe, nil
272 }
273
274 // Find, read, and decode file containing type information.
275 file, ok := cfg.PackageFile[path]
276 if !ok {
277 return nil, fmt.Errorf("no package file for %q", path)
278 }
279 f, err := os.Open(file)
280 if err != nil {
281 return nil, err
282 }
283 defer f.Close() // ignore error
284 return gcexportdata.Read(f, fset, imports, path)
285 })
286 }
287
288 func exportTypes(cfg *unitchecker.Config, fset *token.FileSet, pkg *types.Package) error {
289 var out bytes.Buffer
290 if err := gcexportdata.Write(&out, fset, pkg); err != nil {
291 return err
292 }
293 typesFile := strings.TrimSuffix(cfg.VetxOutput, ".facts") + ".types"
294 return os.WriteFile(typesFile, out.Bytes(), 0666)
295 }
296
297 // -- helpers --
298
299 func analysisModuleFromPackagesModule(mod *packages.Module) *analysis.Module {
300 if mod == nil {
301 return nil
302 }
303 var modErr *analysis.ModuleError
304 if mod.Error != nil {
305 modErr = &analysis.ModuleError{Err: mod.Error.Err}
306 }
307 return &analysis.Module{
308 Path: mod.Path,
309 Version: mod.Version,
310 Replace: analysisModuleFromPackagesModule(mod.Replace),
311 Time: mod.Time,
312 Main: mod.Main,
313 Indirect: mod.Indirect,
314 Dir: mod.Dir,
315 GoMod: mod.GoMod,
316 GoVersion: mod.GoVersion,
317 Error: modErr,
318 }
319 }
320
321 type importerFunc func(path string) (*types.Package, error)
322
323 func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }