| 1 | // Copyright 2018 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 analysistest provides utilities for testing analyzers. |
| 6 | package analysistest |
| 7 | |
| 8 | import ( |
| 9 | "bytes" |
| 10 | "fmt" |
| 11 | "go/ast" |
| 12 | "go/format" |
| 13 | "go/token" |
| 14 | "go/types" |
| 15 | "log" |
| 16 | "maps" |
| 17 | "os" |
| 18 | "path/filepath" |
| 19 | "regexp" |
| 20 | "runtime" |
| 21 | "slices" |
| 22 | "sort" |
| 23 | "strconv" |
| 24 | "strings" |
| 25 | "testing" |
| 26 | "text/scanner" |
| 27 | |
| 28 | "golang.org/x/tools/go/analysis" |
| 29 | "golang.org/x/tools/go/analysis/checker" |
| 30 | "golang.org/x/tools/go/analysis/internal" |
| 31 | "golang.org/x/tools/go/packages" |
| 32 | "golang.org/x/tools/internal/analysis/driverutil" |
| 33 | "golang.org/x/tools/internal/diff" |
| 34 | "golang.org/x/tools/internal/testenv" |
| 35 | "golang.org/x/tools/txtar" |
| 36 | ) |
| 37 | |
| 38 | // WriteFiles is a helper function that creates a temporary directory |
| 39 | // and populates it with a GOPATH-style project using filemap (which |
| 40 | // maps file names to contents). On success it returns the name of the |
| 41 | // directory and a cleanup function to delete it. |
| 42 | // |
| 43 | // TODO(adonovan): provide a newer version that accepts a testing.T, |
| 44 | // calls T.TempDir, and calls T.Fatal on any error, avoiding the need |
| 45 | // to return cleanup or err: |
| 46 | // |
| 47 | // func WriteFilesToTmp(t *testing.T filemap map[string]string) string |
| 48 | func WriteFiles(filemap map[string]string) (dir string, cleanup func(), err error) { |
| 49 | gopath, err := os.MkdirTemp("", "analysistest") |
| 50 | if err != nil { |
| 51 | return "", nil, err |
| 52 | } |
| 53 | cleanup = func() { os.RemoveAll(gopath) } |
| 54 | |
| 55 | for name, content := range filemap { |
| 56 | filename := filepath.Join(gopath, "src", name) |
| 57 | os.MkdirAll(filepath.Dir(filename), 0777) // ignore error |
| 58 | if err := os.WriteFile(filename, []byte(content), 0666); err != nil { |
| 59 | cleanup() |
| 60 | return "", nil, err |
| 61 | } |
| 62 | } |
| 63 | return gopath, cleanup, nil |
| 64 | } |
| 65 | |
| 66 | // TestData returns the effective filename of |
| 67 | // the program's "testdata" directory. |
| 68 | // This function may be overridden by projects using |
| 69 | // an alternative build system (such as Blaze) that |
| 70 | // does not run a test in its package directory. |
| 71 | var TestData = func() string { |
| 72 | testdata, err := filepath.Abs("testdata") |
| 73 | if err != nil { |
| 74 | log.Fatal(err) |
| 75 | } |
| 76 | return testdata |
| 77 | } |
| 78 | |
| 79 | // Testing is an abstraction of a *testing.T. |
| 80 | type Testing interface { |
| 81 | Errorf(format string, args ...any) |
| 82 | } |
| 83 | |
| 84 | // RunWithSuggestedFixes behaves like Run, but additionally applies |
| 85 | // suggested fixes and verifies their output. |
| 86 | // |
| 87 | // It uses golden files, placed alongside each source file, to express |
| 88 | // the desired output: the expected transformation of file example.go |
| 89 | // is specified in file example.go.golden. |
| 90 | // |
| 91 | // Golden files may be of two forms: a plain Go source file, or a |
| 92 | // txtar archive. |
| 93 | // |
| 94 | // A plain Go source file indicates the expected result of applying |
| 95 | // all suggested fixes to the original file. |
| 96 | // |
| 97 | // A txtar archive specifies, in each section, the expected result of |
| 98 | // applying all suggested fixes of a given message to the original |
| 99 | // file; the name of the archive section is the fix's message. In this |
| 100 | // way, the various alternative fixes offered by a single diagnostic |
| 101 | // can be tested independently. Here's an example: |
| 102 | // |
| 103 | // -- turn into single negation -- |
| 104 | // package pkg |
| 105 | // |
| 106 | // func fn(b1, b2 bool) { |
| 107 | // if !b1 { // want `negating a boolean twice` |
| 108 | // println() |
| 109 | // } |
| 110 | // } |
| 111 | // |
| 112 | // -- remove double negation -- |
| 113 | // package pkg |
| 114 | // |
| 115 | // func fn(b1, b2 bool) { |
| 116 | // if b1 { // want `negating a boolean twice` |
| 117 | // println() |
| 118 | // } |
| 119 | // } |
| 120 | // |
| 121 | // # Conflicts |
| 122 | // |
| 123 | // Regardless of the form of the golden file, it is possible for |
| 124 | // multiple fixes to conflict, either because they overlap, or are |
| 125 | // close enough together that the particular diff algorithm cannot |
| 126 | // separate them. |
| 127 | // |
| 128 | // RunWithSuggestedFixes uses a simple three-way merge to accumulate |
| 129 | // fixes, similar to a git merge. The merge algorithm may be able to |
| 130 | // coalesce identical edits, for example duplicate imports of the same |
| 131 | // package. (Bear in mind that this is an editorial decision. In |
| 132 | // general, coalescing identical edits may not be correct: consider |
| 133 | // two statements that increment the same counter.) |
| 134 | // |
| 135 | // If there are conflicts, the test fails. In any case, the |
| 136 | // non-conflicting edits will be compared against the expected output. |
| 137 | // In this situation, we recommend that you increase the textual |
| 138 | // separation between conflicting parts or, if that fails, split |
| 139 | // your tests into smaller parts. |
| 140 | // |
| 141 | // If a diagnostic offers multiple fixes for the same problem, they |
| 142 | // are almost certain to conflict, so in this case you should define |
| 143 | // the expected output using a multi-section txtar file as described |
| 144 | // above. |
| 145 | func RunWithSuggestedFixes(t Testing, dir string, a *analysis.Analyzer, patterns ...string) []*Result { |
| 146 | results := Run(t, dir, a, patterns...) |
| 147 | |
| 148 | // If the immediate caller of RunWithSuggestedFixes is in |
| 149 | // x/tools, we apply stricter checks as required by gopls. |
| 150 | inTools := false |
| 151 | { |
| 152 | var pcs [1]uintptr |
| 153 | n := runtime.Callers(1, pcs[:]) |
| 154 | frames := runtime.CallersFrames(pcs[:n]) |
| 155 | fr, _ := frames.Next() |
| 156 | if fr.Func != nil && strings.HasPrefix(fr.Func.Name(), "golang.org/x/tools/") { |
| 157 | inTools = true |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | generated := make(map[*token.File]bool) |
| 162 | |
| 163 | // Process each result (package) separately, matching up the suggested |
| 164 | // fixes into a diff, which we will compare to the .golden file. We have |
| 165 | // to do this per-result in case a file appears in two packages, such as in |
| 166 | // packages with tests, where mypkg/a.go will appear in both mypkg and |
| 167 | // mypkg.test. In that case, the analyzer may suggest the same set of |
| 168 | // changes to a.go for each package. If we merge all the results, those |
| 169 | // changes get doubly applied, which will cause conflicts or mismatches. |
| 170 | // Validating the results separately means as long as the two analyses |
| 171 | // don't produce conflicting suggestions for a single file, everything |
| 172 | // should match up. |
| 173 | for _, result := range results { |
| 174 | act := result.Action |
| 175 | |
| 176 | // Compute set of generated files. |
| 177 | for _, file := range internal.ActionPass(act).Files { |
| 178 | // Memoize, since there may be many actions |
| 179 | // for the same package (list of files). |
| 180 | tokFile := act.Package.Fset.File(file.Pos()) |
| 181 | if _, seen := generated[tokFile]; !seen { |
| 182 | generated[tokFile] = ast.IsGenerated(file) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | // For each fix, split its edits by file and convert to diff form. |
| 187 | var ( |
| 188 | // fixEdits: message -> fixes -> filename -> edits |
| 189 | // |
| 190 | // TODO(adonovan): this mapping assumes fix.Messages |
| 191 | // are unique across analyzers, whereas they are only |
| 192 | // unique within a given Diagnostic. |
| 193 | fixEdits = make(map[string][]map[string][]diff.Edit) |
| 194 | allFilenames = make(map[string]bool) |
| 195 | ) |
| 196 | for _, diag := range act.Diagnostics { |
| 197 | // Fixes are validated upon creation in Pass.Report. |
| 198 | fixloop: |
| 199 | for _, fix := range diag.SuggestedFixes { |
| 200 | // Assert that lazy fixes have a Category (#65578, #65087). |
| 201 | if inTools && len(fix.TextEdits) == 0 && diag.Category == "" { |
| 202 | t.Errorf("missing Diagnostic.Category for SuggestedFix without TextEdits (gopls requires the category for the name of the fix command") |
| 203 | } |
| 204 | |
| 205 | // Skip any fix that edits a generated file. |
| 206 | for _, edit := range fix.TextEdits { |
| 207 | file := act.Package.Fset.File(edit.Pos) |
| 208 | if generated[file] { |
| 209 | continue fixloop |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | // Convert edits to diff form. |
| 214 | // Group fixes by message and file. |
| 215 | edits := make(map[string][]diff.Edit) |
| 216 | for _, edit := range fix.TextEdits { |
| 217 | file := act.Package.Fset.File(edit.Pos) |
| 218 | allFilenames[file.Name()] = true |
| 219 | edits[file.Name()] = append(edits[file.Name()], diff.Edit{ |
| 220 | Start: file.Offset(edit.Pos), |
| 221 | End: file.Offset(edit.End), |
| 222 | New: string(edit.NewText), |
| 223 | }) |
| 224 | } |
| 225 | fixEdits[fix.Message] = append(fixEdits[fix.Message], edits) |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | merge := func(file, message string, x, y []diff.Edit) []diff.Edit { |
| 230 | z, ok := diff.Merge(x, y) |
| 231 | if !ok { |
| 232 | t.Errorf("in file %s, conflict applying fix %q", file, message) |
| 233 | return x // discard y |
| 234 | } |
| 235 | return z |
| 236 | } |
| 237 | |
| 238 | // Because the checking is driven by original |
| 239 | // filenames, there is no way to express that a fix |
| 240 | // (e.g. extract declaration) creates a new file. |
| 241 | for _, filename := range slices.Sorted(maps.Keys(allFilenames)) { |
| 242 | // Read the original file. |
| 243 | content, err := os.ReadFile(filename) |
| 244 | if err != nil { |
| 245 | t.Errorf("error reading %s: %v", filename, err) |
| 246 | continue |
| 247 | } |
| 248 | |
| 249 | // check checks that the accumulated edits applied |
| 250 | // to the original content yield the wanted content. |
| 251 | check := func(prefix string, accumulated []diff.Edit, want []byte) { |
| 252 | if err := applyDiffsAndCompare(result.Pass.Pkg, filename, content, want, accumulated); err != nil { |
| 253 | t.Errorf("%s: %s", prefix, err) |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | // Read the golden file. It may have one of two forms: |
| 258 | // (1) A txtar archive with one section per fix title, |
| 259 | // including all fixes of just that title. |
| 260 | // (2) The expected output for file.Name after all (?) fixes are applied. |
| 261 | // This form requires that no diagnostic has multiple fixes. |
| 262 | ar, err := txtar.ParseFile(filename + ".golden") |
| 263 | if err != nil { |
| 264 | t.Errorf("error reading %s.golden: %v", filename, err) |
| 265 | continue |
| 266 | } |
| 267 | if len(ar.Files) > 0 { |
| 268 | // Form #1: one archive section per kind of suggested fix. |
| 269 | if len(ar.Comment) > 0 { |
| 270 | // Disallow the combination of comment and archive sections. |
| 271 | t.Errorf("%s.golden has leading comment; we don't know what to do with it", filename) |
| 272 | continue |
| 273 | } |
| 274 | |
| 275 | // Each archive section is named for a fix.Message. |
| 276 | // Accumulate the parts of the fix that apply to the current file, |
| 277 | // using a simple three-way merge, discarding conflicts, |
| 278 | // then apply the merged edits and compare to the archive section. |
| 279 | for _, section := range ar.Files { |
| 280 | message, want := section.Name, section.Data |
| 281 | var accumulated []diff.Edit |
| 282 | for _, fix := range fixEdits[message] { |
| 283 | accumulated = merge(filename, message, accumulated, fix[filename]) |
| 284 | } |
| 285 | check(fmt.Sprintf("all fixes of message %q", message), accumulated, want) |
| 286 | } |
| 287 | |
| 288 | } else { |
| 289 | // Form #2: all suggested fixes are represented by a single file. |
| 290 | want := ar.Comment |
| 291 | var accumulated []diff.Edit |
| 292 | for _, message := range slices.Sorted(maps.Keys(fixEdits)) { |
| 293 | for _, fix := range fixEdits[message] { |
| 294 | accumulated = merge(filename, message, accumulated, fix[filename]) |
| 295 | } |
| 296 | } |
| 297 | check("all fixes", accumulated, want) |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | return results |
| 303 | } |
| 304 | |
| 305 | // applyDiffsAndCompare applies edits to original and compares the results against |
| 306 | // want after formatting both. fileName is use solely for error reporting. |
| 307 | func applyDiffsAndCompare(pkg *types.Package, filename string, original, want []byte, edits []diff.Edit) error { |
| 308 | // Relativize filename, for tidier errors. |
| 309 | if cwd, err := os.Getwd(); err == nil { |
| 310 | if rel, err := filepath.Rel(cwd, filename); err == nil { |
| 311 | filename = rel |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | if len(edits) == 0 { |
| 316 | return fmt.Errorf("%s: no edits", filename) |
| 317 | } |
| 318 | fixedBytes, err := diff.ApplyBytes(original, edits) |
| 319 | if err != nil { |
| 320 | return fmt.Errorf("%s: error applying fixes: %v (see possible explanations at RunWithSuggestedFixes)", filename, err) |
| 321 | } |
| 322 | fixed, err := driverutil.FormatSourceRemoveImports(pkg, fixedBytes) |
| 323 | if err != nil { |
| 324 | return fmt.Errorf("%s: error formatting resulting source: %v\n%s", filename, err, fixedBytes) |
| 325 | } |
| 326 | |
| 327 | want, err = format.Source(want) |
| 328 | if err != nil { |
| 329 | return fmt.Errorf("%s.golden: error formatting golden file: %v\n%s", filename, err, fixed) |
| 330 | } |
| 331 | |
| 332 | // Keep error reporting logic below consistent with |
| 333 | // TestScript in ../internal/checker/fix_test.go! |
| 334 | |
| 335 | unified := func(xlabel, ylabel string, x, y []byte) string { |
| 336 | x = append(slices.Clip(bytes.TrimSpace(x)), '\n') |
| 337 | y = append(slices.Clip(bytes.TrimSpace(y)), '\n') |
| 338 | return diff.Unified(xlabel, ylabel, string(x), string(y)) |
| 339 | } |
| 340 | |
| 341 | if diff := unified(filename+" (fixed)", filename+" (want)", fixed, want); diff != "" { |
| 342 | return fmt.Errorf("unexpected %s content:\n"+ |
| 343 | "-- original --\n%s\n"+ |
| 344 | "-- fixed --\n%s\n"+ |
| 345 | "-- want --\n%s\n"+ |
| 346 | "-- diff original fixed --\n%s\n"+ |
| 347 | "-- diff fixed want --\n%s", |
| 348 | filename, |
| 349 | original, |
| 350 | fixed, |
| 351 | want, |
| 352 | unified(filename+" (original)", filename+" (fixed)", original, fixed), |
| 353 | diff) |
| 354 | } |
| 355 | return nil |
| 356 | } |
| 357 | |
| 358 | // Run applies an analysis to the packages denoted by the "go list" patterns. |
| 359 | // |
| 360 | // It loads the packages from the specified |
| 361 | // directory using golang.org/x/tools/go/packages, runs the analysis on |
| 362 | // them, and checks that each analysis emits the expected diagnostics |
| 363 | // and facts specified by the contents of '// want ...' comments in the |
| 364 | // package's source files. It treats a comment of the form |
| 365 | // "//...// want..." or "/*...// want... */" as if it starts at 'want'. |
| 366 | // |
| 367 | // If the directory contains a go.mod file, Run treats it as the root of the |
| 368 | // Go module in which to work. Otherwise, Run treats it as the root of a |
| 369 | // GOPATH-style tree, with package contained in the src subdirectory. |
| 370 | // |
| 371 | // An expectation of a Diagnostic is specified by a string literal |
| 372 | // containing a regular expression that must match the diagnostic |
| 373 | // message. For example: |
| 374 | // |
| 375 | // fmt.Printf("%s", 1) // want `cannot provide int 1 to %s` |
| 376 | // |
| 377 | // An expectation of a Fact associated with an object is specified by |
| 378 | // 'name:"pattern"', where name is the name of the object, which must be |
| 379 | // declared on the same line as the comment, and pattern is a regular |
| 380 | // expression that must match the string representation of the fact, |
| 381 | // fmt.Sprint(fact). For example: |
| 382 | // |
| 383 | // func panicf(format string, args interface{}) { // want panicf:"printfWrapper" |
| 384 | // |
| 385 | // Package facts are specified by the name "package" and appear on |
| 386 | // line 1 of the first source file of the package. |
| 387 | // |
| 388 | // A single 'want' comment may contain a mixture of diagnostic and fact |
| 389 | // expectations, including multiple facts about the same object: |
| 390 | // |
| 391 | // // want "diag" "diag2" x:"fact1" x:"fact2" y:"fact3" |
| 392 | // |
| 393 | // Unexpected diagnostics and facts, and unmatched expectations, are |
| 394 | // reported as errors to the Testing. |
| 395 | // |
| 396 | // Run reports an error to the Testing if loading or analysis failed. |
| 397 | // Run also returns a Result for each package for which analysis was |
| 398 | // attempted, even if unsuccessful. It is safe for a test to ignore all |
| 399 | // the results, but a test may use it to perform additional checks. |
| 400 | func Run(t Testing, dir string, a *analysis.Analyzer, patterns ...string) []*Result { |
| 401 | if t, ok := t.(testing.TB); ok { |
| 402 | testenv.NeedsGoPackages(t) |
| 403 | } |
| 404 | |
| 405 | pkgs, err := loadPackages(dir, patterns...) |
| 406 | if err != nil { |
| 407 | t.Errorf("loading %s: %v", patterns, err) |
| 408 | return nil |
| 409 | } |
| 410 | |
| 411 | // Print parse and type errors to the test log. |
| 412 | // (Do not print them to stderr, which would pollute |
| 413 | // the log in cases where the tests pass.) |
| 414 | if t, ok := t.(testing.TB); ok && !a.RunDespiteErrors { |
| 415 | packages.Visit(pkgs, nil, func(pkg *packages.Package) { |
| 416 | for _, err := range pkg.Errors { |
| 417 | t.Log(err) |
| 418 | } |
| 419 | }) |
| 420 | } |
| 421 | |
| 422 | res, err := checker.Analyze([]*analysis.Analyzer{a}, pkgs, nil) |
| 423 | if err != nil { |
| 424 | t.Errorf("Analyze: %v", err) |
| 425 | return nil |
| 426 | } |
| 427 | |
| 428 | var results []*Result |
| 429 | for _, act := range res.Roots { |
| 430 | if act.Err != nil { |
| 431 | t.Errorf("error analyzing %s: %v", act, act.Err) |
| 432 | } else { |
| 433 | check(t, dir, act) |
| 434 | } |
| 435 | |
| 436 | // Compute legacy map of facts relating to this package. |
| 437 | facts := make(map[types.Object][]analysis.Fact) |
| 438 | for _, objFact := range act.AllObjectFacts() { |
| 439 | if obj := objFact.Object; obj.Pkg() == act.Package.Types { |
| 440 | facts[obj] = append(facts[obj], objFact.Fact) |
| 441 | } |
| 442 | } |
| 443 | for _, pkgFact := range act.AllPackageFacts() { |
| 444 | if pkgFact.Package == act.Package.Types { |
| 445 | facts[nil] = append(facts[nil], pkgFact.Fact) |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | // Construct the legacy result. |
| 450 | results = append(results, &Result{ |
| 451 | Pass: internal.ActionPass(act), // may be nil |
| 452 | Diagnostics: act.Diagnostics, |
| 453 | Facts: facts, |
| 454 | Result: act.Result, |
| 455 | Err: act.Err, |
| 456 | Action: act, |
| 457 | }) |
| 458 | } |
| 459 | return results |
| 460 | } |
| 461 | |
| 462 | // A Result holds the result of applying an analyzer to a package. |
| 463 | // |
| 464 | // Facts contains only facts associated with the package and its objects. |
| 465 | // |
| 466 | // This internal type was inadvertently and regrettably exposed |
| 467 | // through a public type alias. It is essentially redundant with |
| 468 | // [checker.Action], but must be retained for compatibility. Clients may |
| 469 | // access the public fields of the Pass but must not invoke any of |
| 470 | // its "verbs", since the pass is already complete. |
| 471 | type Result struct { |
| 472 | Action *checker.Action |
| 473 | |
| 474 | // legacy fields (do not use) |
| 475 | Facts map[types.Object][]analysis.Fact // nil key => package fact |
| 476 | Pass *analysis.Pass // nil => action not executed |
| 477 | Diagnostics []analysis.Diagnostic // see Action.Diagnostics |
| 478 | Result any // see Action.Result |
| 479 | Err error // see Action.Err |
| 480 | } |
| 481 | |
| 482 | // loadPackages uses go/packages to load a specified packages (from source, with |
| 483 | // dependencies) from dir, which is the root of a GOPATH-style project tree. |
| 484 | // loadPackages returns an error if any package had an error, or the pattern |
| 485 | // matched no packages. |
| 486 | func loadPackages(dir string, patterns ...string) ([]*packages.Package, error) { |
| 487 | env := []string{"GOPATH=" + dir, "GO111MODULE=off", "GOWORK=off"} // GOPATH mode |
| 488 | |
| 489 | // Undocumented module mode. Will be replaced by something better. |
| 490 | if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { |
| 491 | gowork := filepath.Join(dir, "go.work") |
| 492 | if _, err := os.Stat(gowork); err != nil { |
| 493 | gowork = "off" |
| 494 | } |
| 495 | |
| 496 | env = []string{"GO111MODULE=on", "GOPROXY=off", "GOWORK=" + gowork} // module mode |
| 497 | } |
| 498 | |
| 499 | // packages.Load loads the real standard library, not a minimal |
| 500 | // fake version, which would be more efficient, especially if we |
| 501 | // have many small tests that import, say, net/http. |
| 502 | // However there is no easy way to make go/packages to consume |
| 503 | // a list of packages we generate and then do the parsing and |
| 504 | // typechecking, though this feature seems to be a recurring need. |
| 505 | |
| 506 | mode := packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | |
| 507 | packages.NeedTypes | packages.NeedTypesSizes | packages.NeedSyntax | packages.NeedTypesInfo | |
| 508 | packages.NeedDeps | packages.NeedModule |
| 509 | cfg := &packages.Config{ |
| 510 | Mode: mode, |
| 511 | Dir: dir, |
| 512 | Tests: true, |
| 513 | Env: append(os.Environ(), env...), |
| 514 | } |
| 515 | pkgs, err := packages.Load(cfg, patterns...) |
| 516 | if err != nil { |
| 517 | return nil, err |
| 518 | } |
| 519 | |
| 520 | // If any named package couldn't be loaded at all |
| 521 | // (e.g. the Name field is unset), fail fast. |
| 522 | for _, pkg := range pkgs { |
| 523 | if pkg.Name == "" { |
| 524 | return nil, fmt.Errorf("failed to load %q: Errors=%v", |
| 525 | pkg.PkgPath, pkg.Errors) |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | if len(pkgs) == 0 { |
| 530 | return nil, fmt.Errorf("no packages matched %s", patterns) |
| 531 | } |
| 532 | return pkgs, nil |
| 533 | } |
| 534 | |
| 535 | // check inspects an analysis pass on which the analysis has already |
| 536 | // been run, and verifies that all reported diagnostics and facts match |
| 537 | // specified by the contents of "// want ..." comments in the package's |
| 538 | // source files, which must have been parsed with comments enabled. |
| 539 | func check(t Testing, gopath string, act *checker.Action) { |
| 540 | type key struct { |
| 541 | file string |
| 542 | line int |
| 543 | } |
| 544 | |
| 545 | want := make(map[key][]expectation) |
| 546 | |
| 547 | // processComment parses expectations out of comments. |
| 548 | processComment := func(filename string, linenum int, text string) { |
| 549 | text = strings.TrimSpace(text) |
| 550 | |
| 551 | // Any comment starting with "want" is treated |
| 552 | // as an expectation, even without following whitespace. |
| 553 | if rest, ok := strings.CutPrefix(text, "want"); ok { |
| 554 | lineDelta, expects, err := parseExpectations(rest) |
| 555 | if err != nil { |
| 556 | t.Errorf("%s:%d: in 'want' comment: %s", filename, linenum, err) |
| 557 | return |
| 558 | } |
| 559 | if expects != nil { |
| 560 | want[key{filename, linenum + lineDelta}] = expects |
| 561 | } |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | // Extract 'want' comments from parsed Go files. |
| 566 | for _, f := range act.Package.Syntax { |
| 567 | for _, cgroup := range f.Comments { |
| 568 | for _, c := range cgroup.List { |
| 569 | |
| 570 | text := strings.TrimPrefix(c.Text, "//") |
| 571 | if text == c.Text { // not a //-comment. |
| 572 | text = strings.TrimPrefix(text, "/*") |
| 573 | text = strings.TrimSuffix(text, "*/") |
| 574 | } |
| 575 | |
| 576 | // Hack: treat a comment of the form "//...// want..." |
| 577 | // or "/*...// want... */ |
| 578 | // as if it starts at 'want'. |
| 579 | // This allows us to add comments on comments, |
| 580 | // as required when testing the buildtag analyzer. |
| 581 | if i := strings.Index(text, "// want"); i >= 0 { |
| 582 | text = text[i+len("// "):] |
| 583 | } |
| 584 | |
| 585 | // It's tempting to compute the filename |
| 586 | // once outside the loop, but it's |
| 587 | // incorrect because it can change due |
| 588 | // to //line directives. |
| 589 | posn := act.Package.Fset.Position(c.Pos()) |
| 590 | filename := sanitize(gopath, posn.Filename) |
| 591 | processComment(filename, posn.Line, text) |
| 592 | } |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | // Extract 'want' comments from non-Go files. |
| 597 | // TODO(adonovan): we may need to handle //line directives. |
| 598 | files := act.Package.OtherFiles |
| 599 | |
| 600 | // Hack: these analyzers need to extract expectations from |
| 601 | // all configurations, so include the files are usually |
| 602 | // ignored. (This was previously a hack in the respective |
| 603 | // analyzers' tests.) |
| 604 | switch act.Analyzer.Name { |
| 605 | case "buildtag", "directive", "plusbuild": |
| 606 | files = slices.Concat(files, act.Package.IgnoredFiles) |
| 607 | } |
| 608 | |
| 609 | for _, filename := range files { |
| 610 | data, err := os.ReadFile(filename) |
| 611 | if err != nil { |
| 612 | t.Errorf("can't read '// want' comments from %s: %v", filename, err) |
| 613 | continue |
| 614 | } |
| 615 | filename := sanitize(gopath, filename) |
| 616 | linenum := 0 |
| 617 | for line := range strings.SplitSeq(string(data), "\n") { |
| 618 | linenum++ |
| 619 | |
| 620 | // Hack: treat a comment of the form "//...// want..." |
| 621 | // or "/*...// want... */ |
| 622 | // as if it starts at 'want'. |
| 623 | // This allows us to add comments on comments, |
| 624 | // as required when testing the buildtag analyzer. |
| 625 | if i := strings.Index(line, "// want"); i >= 0 { |
| 626 | line = line[i:] |
| 627 | } |
| 628 | |
| 629 | if i := strings.Index(line, "//"); i >= 0 { |
| 630 | line = line[i+len("//"):] |
| 631 | processComment(filename, linenum, line) |
| 632 | } |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | checkMessage := func(posn token.Position, kind, name, message string) { |
| 637 | posn.Filename = sanitize(gopath, posn.Filename) |
| 638 | k := key{posn.Filename, posn.Line} |
| 639 | expects := want[k] |
| 640 | var unmatched []string |
| 641 | for i, exp := range expects { |
| 642 | if exp.kind == kind && exp.name == name { |
| 643 | if exp.rx.MatchString(message) { |
| 644 | // matched: remove the expectation. |
| 645 | expects[i] = expects[len(expects)-1] |
| 646 | expects = expects[:len(expects)-1] |
| 647 | want[k] = expects |
| 648 | return |
| 649 | } |
| 650 | unmatched = append(unmatched, fmt.Sprintf("%#q", exp.rx)) |
| 651 | } |
| 652 | } |
| 653 | if unmatched == nil { |
| 654 | t.Errorf("%v: unexpected %s: %v", posn, kind, message) |
| 655 | } else { |
| 656 | t.Errorf("%v: %s %q does not match pattern %s", |
| 657 | posn, kind, message, strings.Join(unmatched, " or ")) |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | // Check the diagnostics match expectations. |
| 662 | for _, f := range act.Diagnostics { |
| 663 | // TODO(matloob): Support ranges in analysistest. |
| 664 | posn := act.Package.Fset.Position(f.Pos) |
| 665 | checkMessage(posn, "diagnostic", "", f.Message) |
| 666 | } |
| 667 | |
| 668 | // Check the facts match expectations. |
| 669 | // We check only facts relating to the current package. |
| 670 | // |
| 671 | // We report errors in lexical order for determinism. |
| 672 | // (It's only deterministic within each file, not across files, |
| 673 | // because go/packages does not guarantee file.Pos is ascending |
| 674 | // across the files of a single compilation unit.) |
| 675 | |
| 676 | // package facts: reported at start of first file |
| 677 | for _, pkgFact := range act.AllPackageFacts() { |
| 678 | if pkgFact.Package == act.Package.Types { |
| 679 | posn := act.Package.Fset.Position(act.Package.Syntax[0].Pos()) |
| 680 | posn.Line, posn.Column = 1, 1 |
| 681 | checkMessage(posn, "fact", "package", fmt.Sprint(pkgFact)) |
| 682 | } |
| 683 | } |
| 684 | |
| 685 | // object facts: reported at line of object declaration |
| 686 | objFacts := act.AllObjectFacts() |
| 687 | sort.Slice(objFacts, func(i, j int) bool { |
| 688 | return objFacts[i].Object.Pos() < objFacts[j].Object.Pos() |
| 689 | }) |
| 690 | for _, objFact := range objFacts { |
| 691 | if obj := objFact.Object; obj.Pkg() == act.Package.Types { |
| 692 | posn := act.Package.Fset.Position(obj.Pos()) |
| 693 | checkMessage(posn, "fact", obj.Name(), fmt.Sprint(objFact.Fact)) |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | // Reject surplus expectations. |
| 698 | // |
| 699 | // Sometimes an Analyzer reports two similar diagnostics on a |
| 700 | // line with only one expectation. The reader may be confused by |
| 701 | // the error message. |
| 702 | // TODO(adonovan): print a better error: |
| 703 | // "got 2 diagnostics here; each one needs its own expectation". |
| 704 | var surplus []string |
| 705 | for key, expects := range want { |
| 706 | for _, exp := range expects { |
| 707 | err := fmt.Sprintf("%s:%d: no %s was reported matching %#q", key.file, key.line, exp.kind, exp.rx) |
| 708 | surplus = append(surplus, err) |
| 709 | } |
| 710 | } |
| 711 | sort.Strings(surplus) |
| 712 | for _, err := range surplus { |
| 713 | t.Errorf("%s", err) |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | type expectation struct { |
| 718 | kind string // either "fact" or "diagnostic" |
| 719 | name string // name of object to which fact belongs, or "package" ("fact" only) |
| 720 | rx *regexp.Regexp |
| 721 | } |
| 722 | |
| 723 | func (ex expectation) String() string { |
| 724 | return fmt.Sprintf("%s %s:%q", ex.kind, ex.name, ex.rx) // for debugging |
| 725 | } |
| 726 | |
| 727 | // parseExpectations parses the content of a "// want ..." comment |
| 728 | // and returns the expectations, a mixture of diagnostics ("rx") and |
| 729 | // facts (name:"rx"). |
| 730 | func parseExpectations(text string) (lineDelta int, expects []expectation, err error) { |
| 731 | var scanErr string |
| 732 | sc := new(scanner.Scanner).Init(strings.NewReader(text)) |
| 733 | sc.Error = func(s *scanner.Scanner, msg string) { |
| 734 | scanErr = msg // e.g. bad string escape |
| 735 | } |
| 736 | sc.Mode = scanner.ScanIdents | scanner.ScanStrings | scanner.ScanRawStrings | scanner.ScanInts |
| 737 | |
| 738 | scanRegexp := func(tok rune) (*regexp.Regexp, error) { |
| 739 | if tok != scanner.String && tok != scanner.RawString { |
| 740 | return nil, fmt.Errorf("got %s, want regular expression", |
| 741 | scanner.TokenString(tok)) |
| 742 | } |
| 743 | pattern, _ := strconv.Unquote(sc.TokenText()) // can't fail |
| 744 | return regexp.Compile(pattern) |
| 745 | } |
| 746 | |
| 747 | for { |
| 748 | tok := sc.Scan() |
| 749 | switch tok { |
| 750 | case '+': |
| 751 | tok = sc.Scan() |
| 752 | if tok != scanner.Int { |
| 753 | return 0, nil, fmt.Errorf("got +%s, want +Int", scanner.TokenString(tok)) |
| 754 | } |
| 755 | lineDelta, _ = strconv.Atoi(sc.TokenText()) |
| 756 | case scanner.String, scanner.RawString: |
| 757 | rx, err := scanRegexp(tok) |
| 758 | if err != nil { |
| 759 | return 0, nil, err |
| 760 | } |
| 761 | expects = append(expects, expectation{"diagnostic", "", rx}) |
| 762 | |
| 763 | case scanner.Ident: |
| 764 | name := sc.TokenText() |
| 765 | tok = sc.Scan() |
| 766 | if tok != ':' { |
| 767 | return 0, nil, fmt.Errorf("got %s after %s, want ':'", |
| 768 | scanner.TokenString(tok), name) |
| 769 | } |
| 770 | tok = sc.Scan() |
| 771 | rx, err := scanRegexp(tok) |
| 772 | if err != nil { |
| 773 | return 0, nil, err |
| 774 | } |
| 775 | expects = append(expects, expectation{"fact", name, rx}) |
| 776 | |
| 777 | case scanner.EOF: |
| 778 | if scanErr != "" { |
| 779 | return 0, nil, fmt.Errorf("%s", scanErr) |
| 780 | } |
| 781 | return lineDelta, expects, nil |
| 782 | |
| 783 | default: |
| 784 | return 0, nil, fmt.Errorf("unexpected %s", scanner.TokenString(tok)) |
| 785 | } |
| 786 | } |
| 787 | } |
| 788 | |
| 789 | // sanitize removes the GOPATH portion of the filename, |
| 790 | // typically a gnarly /tmp directory, and returns the rest. |
| 791 | func sanitize(gopath, filename string) string { |
| 792 | prefix := gopath + string(os.PathSeparator) + "src" + string(os.PathSeparator) |
| 793 | return filepath.ToSlash(strings.TrimPrefix(filename, prefix)) |
| 794 | } |