Debian Codegraph @

go/analysis/internal/checker/fix_test.go

raw symbols SCIP
1 // Copyright 2022 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 checker_test
6
7 import (
8 "bytes"
9 "flag"
10 "fmt"
11 "go/ast"
12 "go/token"
13 "log"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "regexp"
18 "runtime"
19 "slices"
20 "strings"
21 "testing"
22
23 "golang.org/x/tools/go/analysis"
24 "golang.org/x/tools/go/analysis/checker"
25 "golang.org/x/tools/go/analysis/multichecker"
26 "golang.org/x/tools/go/analysis/passes/inspect"
27 "golang.org/x/tools/go/ast/inspector"
28 "golang.org/x/tools/go/packages"
29 "golang.org/x/tools/internal/diff"
30 "golang.org/x/tools/internal/expect"
31 "golang.org/x/tools/internal/testenv"
32 "golang.org/x/tools/internal/testfiles"
33 "golang.org/x/tools/txtar"
34 )
35
36 func TestMain(m *testing.M) {
37 // If the CHECKER_TEST_CHILD environment variable is set,
38 // this process should behave like a multichecker.
39 // Analyzers are selected by flags.
40 if _, ok := os.LookupEnv("CHECKER_TEST_CHILD"); ok {
41 multichecker.Main(
42 markerAnalyzer,
43 noendAnalyzer,
44 renameAnalyzer,
45 relatedAnalyzer,
46 )
47 panic("unreachable")
48 }
49
50 // ordinary test
51 flag.Parse()
52 os.Exit(m.Run())
53 }
54
55 const (
56 exitCodeSuccess = 0 // success (no diagnostics, or successful -fix)
57 exitCodeFailed = 1 // analysis failed to run
58 exitCodeDiagnostics = 3 // diagnostics were reported (and no -fix)
59 )
60
61 // TestReportInvalidDiagnostic tests that a call to pass.Report with
62 // certain kind of invalid diagnostic (e.g. conflicting fixes)
63 // promptly results in a panic.
64 func TestReportInvalidDiagnostic(t *testing.T) {
65 testenv.NeedsGoPackages(t)
66
67 // Load the errors package.
68 cfg := &packages.Config{Mode: packages.LoadAllSyntax}
69 initial, err := packages.Load(cfg, "errors")
70 if err != nil {
71 t.Fatal(err)
72 }
73
74 for _, test := range []struct {
75 name string
76 want string
77 diag func(pos token.Pos) analysis.Diagnostic
78 }{
79 // Diagnostic has two alternative fixes with the same Message.
80 {
81 "duplicate message",
82 `analyzer "a" suggests two fixes with same Message \(fix\)`,
83 func(pos token.Pos) analysis.Diagnostic {
84 return analysis.Diagnostic{
85 Pos: pos,
86 Message: "oops",
87 SuggestedFixes: []analysis.SuggestedFix{
88 {Message: "fix"},
89 {Message: "fix"},
90 },
91 }
92 },
93 },
94 // TextEdit has invalid Pos.
95 {
96 "bad Pos",
97 `analyzer "a" suggests invalid fix .*: no token.File for TextEdit.Pos .0.`,
98 func(pos token.Pos) analysis.Diagnostic {
99 return analysis.Diagnostic{
100 Pos: pos,
101 Message: "oops",
102 SuggestedFixes: []analysis.SuggestedFix{
103 {
104 Message: "fix",
105 TextEdits: []analysis.TextEdit{{}},
106 },
107 },
108 }
109 },
110 },
111 // TextEdit has invalid End.
112 {
113 "End < Pos",
114 `analyzer "a" suggests invalid fix .*: TextEdit.Pos .* > TextEdit.End .*`,
115 func(pos token.Pos) analysis.Diagnostic {
116 return analysis.Diagnostic{
117 Pos: pos,
118 Message: "oops",
119 SuggestedFixes: []analysis.SuggestedFix{
120 {
121 Message: "fix",
122 TextEdits: []analysis.TextEdit{{
123 Pos: pos + 2,
124 End: pos,
125 }},
126 },
127 },
128 }
129 },
130 },
131 // Two TextEdits overlap.
132 {
133 "overlapping edits",
134 `analyzer "a" suggests invalid fix .*: overlapping edits to .*errors.go \(1:1-1:3 and 1:2-1:4\)`,
135 func(pos token.Pos) analysis.Diagnostic {
136 return analysis.Diagnostic{
137 Pos: pos,
138 Message: "oops",
139 SuggestedFixes: []analysis.SuggestedFix{
140 {
141 Message: "fix",
142 TextEdits: []analysis.TextEdit{
143 {Pos: pos, End: pos + 2},
144 {Pos: pos + 1, End: pos + 3},
145 },
146 },
147 },
148 }
149 },
150 },
151 } {
152 t.Run(test.name, func(t *testing.T) {
153 reached := false
154 a := &analysis.Analyzer{Name: "a", Doc: "doc", Run: func(pass *analysis.Pass) (any, error) {
155 reached = true
156 panics(t, test.want, func() {
157 pos := pass.Files[0].FileStart
158 pass.Report(test.diag(pos))
159 })
160 return nil, nil
161 }}
162 if _, err := checker.Analyze([]*analysis.Analyzer{a}, initial, &checker.Options{}); err != nil {
163 t.Fatalf("Analyze failed: %v", err)
164 }
165 if !reached {
166 t.Error("analyzer was never invoked")
167 }
168 })
169 }
170 }
171
172 // TestScript runs script-driven tests in testdata/*.txt.
173 // Each file is a txtar archive, expanded to a temporary directory.
174 //
175 // The comment section of the archive is a script, with the following
176 // commands:
177 //
178 // # comment
179 // ignored
180 // blank line
181 // ignored
182 // skip k=v...
183 // Skip the test if any k=v string is a substring of the string
184 // "GOOS=darwin GOARCH=arm64" appropriate to the current build.
185 // checker args...
186 // Run the checker command with the specified space-separated
187 // arguments; this fork+execs the [TestMain] function above.
188 // If the archive has a "stdout" section, its contents must
189 // match the stdout output of the checker command.
190 // Do NOT use this for testing -diff: tests should not
191 // rely on the particulars of the diff algorithm.
192 // exit int
193 // Assert that previous checker command had this exit code.
194 // stderr regexp
195 // Assert that stderr output from previous checker run matches this pattern.
196 //
197 // The script must include at least one 'checker' command.
198 func TestScript(t *testing.T) {
199 testenv.NeedsExec(t)
200 testenv.NeedsGoPackages(t)
201
202 txtfiles, err := filepath.Glob("testdata/*.txt")
203 if err != nil {
204 t.Fatal(err)
205 }
206 for _, txtfile := range txtfiles {
207 t.Run(txtfile, func(t *testing.T) {
208 t.Parallel()
209
210 // Expand archive into tmp tree.
211 ar, err := txtar.ParseFile(txtfile)
212 if err != nil {
213 t.Fatal(err)
214 }
215 fs, err := txtar.FS(ar)
216 if err != nil {
217 t.Fatal(err)
218 }
219 dir := testfiles.CopyToTmp(t, fs)
220
221 // Parse txtar comment as a script.
222 const noExitCode = -999
223 var (
224 // state variables operated on by script
225 lastExitCode = noExitCode
226 lastStderr string
227 )
228 for i, line := range strings.Split(string(ar.Comment), "\n") {
229 line = strings.TrimSpace(line)
230 if line == "" || line[0] == '#' {
231 continue // skip blanks and comments
232 }
233
234 command, rest, _ := strings.Cut(line, " ")
235 prefix := fmt.Sprintf("%s:%d: %s", txtfile, i+1, command) // for error messages
236 switch command {
237 case "checker":
238 cmd := exec.Command(os.Args[0], strings.Fields(rest)...)
239 cmd.Dir = dir
240 cmd.Stdout = new(strings.Builder)
241 cmd.Stderr = new(strings.Builder)
242 cmd.Env = append(os.Environ(), "CHECKER_TEST_CHILD=1", "GOPROXY=off")
243 if err := cmd.Run(); err != nil {
244 if err, ok := err.(*exec.ExitError); ok {
245 lastExitCode = err.ExitCode()
246 // fall through
247 } else {
248 t.Fatalf("%s: failed to execute checker: %v (%s)", prefix, err, cmd)
249 }
250 } else {
251 lastExitCode = 0 // success
252 }
253
254 // Eliminate nondeterministic strings from the output.
255 clean := func(x any) string {
256 s := fmt.Sprint(x)
257 pwd, _ := os.Getwd()
258 if realDir, err := filepath.EvalSymlinks(dir); err == nil {
259 // Work around checker's packages.Load failing to
260 // set Config.Dir to dir, causing the filenames
261 // of loaded packages not to be a subdir of dir.
262 s = strings.ReplaceAll(s, realDir, dir)
263 }
264 s = strings.ReplaceAll(s, dir, string(os.PathSeparator)+"TMP")
265 s = strings.ReplaceAll(s, pwd, string(os.PathSeparator)+"PWD")
266 s = strings.ReplaceAll(s, cmd.Path, filepath.Base(cmd.Path))
267 return s
268 }
269
270 lastStderr = clean(cmd.Stderr)
271 stdout := clean(cmd.Stdout)
272
273 // Detect bad markers out of band:
274 // though they cause a non-zero exit,
275 // that may be expected.
276 if strings.Contains(lastStderr, badMarker) {
277 t.Errorf("marker analyzer encountered errors; stderr=%s", lastStderr)
278 }
279
280 // debugging
281 if false {
282 t.Logf("%s: $ %s\nstdout:\n%s\nstderr:\n%s", prefix, clean(cmd), stdout, lastStderr)
283 }
284
285 // Keep error reporting logic below consistent with
286 // applyDiffsAndCompare in ../../analysistest/analysistest.go!
287
288 unified := func(xlabel, ylabel string, x, y []byte) string {
289 x = append(slices.Clip(bytes.TrimSpace(x)), '\n')
290 y = append(slices.Clip(bytes.TrimSpace(y)), '\n')
291 return diff.Unified(xlabel, ylabel, string(x), string(y))
292 }
293
294 // Check stdout, if there's a section of that name.
295 //
296 // Do not use this for testing -diff! It exposes tests to the
297 // internals of our (often suboptimal) diff algorithm.
298 // Instead, use the want/ mechanism.
299 if f := section(ar, "stdout"); f != nil {
300 got, want := []byte(stdout), f.Data
301 if diff := unified("got", "want", got, want); diff != "" {
302 t.Errorf("%s: unexpected stdout: -- got --\n%s-- want --\n%s-- diff --\n%s",
303 prefix,
304 got, want, diff)
305 }
306 }
307
308 for _, f := range ar.Files {
309 // For each file named want/X, assert that the
310 // current content of X now equals want/X.
311 if filename, ok := strings.CutPrefix(f.Name, "want/"); ok {
312 fixed, err := os.ReadFile(filepath.Join(dir, filename))
313 if err != nil {
314 t.Errorf("reading %s: %v", filename, err)
315 continue
316 }
317 var original []byte
318 if f := section(ar, filename); f != nil {
319 original = f.Data
320 }
321 want := f.Data
322 if diff := unified(filename+" (fixed)", filename+" (want)", fixed, want); diff != "" {
323 t.Errorf("%s: unexpected %s content:\n"+
324 "-- original --\n%s\n"+
325 "-- fixed --\n%s\n"+
326 "-- want --\n%s\n"+
327 "-- diff original fixed --\n%s\n"+
328 "-- diff fixed want --\n%s",
329 prefix, filename,
330 original,
331 fixed,
332 want,
333 unified(filename+" (original)", filename+" (fixed)", original, fixed),
334 diff)
335 }
336 }
337 }
338
339 case "skip":
340 config := fmt.Sprintf("GOOS=%s GOARCH=%s", runtime.GOOS, runtime.GOARCH)
341 for word := range strings.FieldsSeq(rest) {
342 if strings.Contains(config, word) {
343 t.Skip(word)
344 }
345 }
346
347 case "exit":
348 if lastExitCode == noExitCode {
349 t.Fatalf("%s: no prior 'checker' command", prefix)
350 }
351 var want int
352 if _, err := fmt.Sscanf(rest, "%d", &want); err != nil {
353 t.Fatalf("%s: requires one numeric operand", prefix)
354 }
355 if want != lastExitCode {
356 // plan9 ExitCode() currently only returns 0 for success or 1 for failure
357 if !(runtime.GOOS == "plan9" && want != exitCodeSuccess && lastExitCode != exitCodeSuccess) {
358 t.Errorf("%s: exit code was %d, want %d", prefix, lastExitCode, want)
359 }
360 }
361
362 case "stderr":
363 if lastExitCode == noExitCode {
364 t.Fatalf("%s: no prior 'checker' command", prefix)
365 }
366 if matched, err := regexp.MatchString(rest, lastStderr); err != nil {
367 t.Fatalf("%s: invalid regexp: %v", prefix, err)
368 } else if !matched {
369 t.Errorf("%s: output didn't match pattern %q:\n%s", prefix, rest, lastStderr)
370 }
371
372 default:
373 t.Errorf("%s: unknown command", prefix)
374 }
375 }
376 if lastExitCode == noExitCode {
377 t.Errorf("test script contains no 'checker' command")
378 }
379 })
380 }
381 }
382
383 const badMarker = "[bad marker]"
384
385 // The marker analyzer generates fixes from @marker annotations in the
386 // source. Each marker is of the form:
387 //
388 // @message("pattern", "replacement)
389 //
390 // The "message" is used for both the Diagnostic.Message and
391 // SuggestedFix.Message field. Multiple markers with the same
392 // message form a single diagnostic and fix with a list of textedits.
393 //
394 // The "pattern" is a regular expression that must match on the
395 // current line (though it may extend beyond if the pattern starts
396 // with "(?s)"), and whose extent forms the TextEdit.{Pos,End}
397 // deletion. If the pattern contains one subgroup, its range will be
398 // used; this allows contextual matching.
399 //
400 // The "replacement" is a literal string that forms the
401 // TextEdit.NewText.
402 //
403 // Fixes are applied in the order they are first mentioned in the
404 // source.
405 var markerAnalyzer = &analysis.Analyzer{
406 Name: "marker",
407 Doc: "doc",
408 Requires: []*analysis.Analyzer{inspect.Analyzer},
409 Run: func(pass *analysis.Pass) (_ any, err error) {
410 // Errors returned by this analyzer cause the
411 // checker command to exit non-zero, but that
412 // may be the expected outcome for other reasons
413 // (e.g. there were diagnostics).
414 //
415 // So, we report these errors out of band by logging
416 // them with a special badMarker string that the
417 // TestScript harness looks for, to ensure that the
418 // test fails in that case.
419 defer func() {
420 if err != nil {
421 log.Printf("%s: %v", badMarker, err)
422 }
423 }()
424
425 // Parse all notes in the files.
426 var keys []string
427 edits := make(map[string][]analysis.TextEdit)
428 for _, file := range pass.Files {
429 tokFile := pass.Fset.File(file.FileStart)
430 content, err := pass.ReadFile(tokFile.Name())
431 if err != nil {
432 return nil, err
433 }
434 notes, err := expect.ExtractGo(tokFile, file)
435 if err != nil {
436 return nil, err
437 }
438 for _, note := range notes {
439 edit, err := markerEdit(tokFile, content, note)
440 if err != nil {
441 return nil, fmt.Errorf("%s: %v", tokFile.Position(note.Pos), err)
442 }
443 // Preserve note order as it determines fix order.
444 if edits[note.Name] == nil {
445 keys = append(keys, note.Name)
446 }
447 edits[note.Name] = append(edits[note.Name], edit)
448 }
449 }
450
451 // Report each fix in its own Diagnostic.
452 for _, key := range keys {
453 edits := edits[key]
454 // debugging
455 if false {
456 log.Printf("%s: marker: @%s: %+v", pass.Fset.Position(edits[0].Pos), key, edits)
457 }
458 pass.Report(analysis.Diagnostic{
459 Pos: edits[0].Pos,
460 End: edits[0].Pos,
461 Message: key,
462 SuggestedFixes: []analysis.SuggestedFix{{
463 Message: key,
464 TextEdits: edits,
465 }},
466 })
467 }
468 return nil, nil
469 },
470 }
471
472 // markerEdit returns the TextEdit denoted by note.
473 func markerEdit(tokFile *token.File, content []byte, note *expect.Note) (analysis.TextEdit, error) {
474 if len(note.Args) != 2 {
475 return analysis.TextEdit{}, fmt.Errorf("got %d args, want @%s(pattern, replacement)", len(note.Args), note.Name)
476 }
477
478 pattern, ok := note.Args[0].(string)
479 if !ok {
480 return analysis.TextEdit{}, fmt.Errorf("got %T for pattern, want string", note.Args[0])
481 }
482 rx, err := regexp.Compile(pattern)
483 if err != nil {
484 return analysis.TextEdit{}, fmt.Errorf("invalid pattern regexp: %v", err)
485 }
486
487 // Match the pattern against the current line.
488 lineStart := tokFile.LineStart(tokFile.Position(note.Pos).Line)
489 lineStartOff := tokFile.Offset(lineStart)
490 lineEndOff := tokFile.Offset(note.Pos)
491 matches := rx.FindSubmatchIndex(content[lineStartOff:])
492 if len(matches) == 0 {
493 return analysis.TextEdit{}, fmt.Errorf("no match for regexp %q", rx)
494 }
495 var start, end int // line-relative offset
496 switch len(matches) {
497 case 2:
498 // no subgroups: return the range of the regexp expression
499 start, end = matches[0], matches[1]
500 case 4:
501 // one subgroup: return its range
502 start, end = matches[2], matches[3]
503 default:
504 return analysis.TextEdit{}, fmt.Errorf("invalid location regexp %q: expect either 0 or 1 subgroups, got %d", rx, len(matches)/2-1)
505 }
506 if start > lineEndOff-lineStartOff {
507 // The start of the match must be between the start of the line and the
508 // marker position (inclusive).
509 return analysis.TextEdit{}, fmt.Errorf("no matching range found starting on the current line")
510 }
511
512 replacement, ok := note.Args[1].(string)
513 if !ok {
514 return analysis.TextEdit{}, fmt.Errorf("second argument must be pattern, got %T", note.Args[1])
515 }
516
517 // debugging: show matched portion
518 if false {
519 log.Printf("%s: %s: r%q (%q) -> %q",
520 tokFile.Position(note.Pos),
521 note.Name,
522 pattern,
523 content[lineStartOff+start:lineStartOff+end],
524 replacement)
525 }
526
527 return analysis.TextEdit{
528 Pos: lineStart + token.Pos(start),
529 End: lineStart + token.Pos(end),
530 NewText: []byte(replacement),
531 }, nil
532 }
533
534 var renameAnalyzer = &analysis.Analyzer{
535 Name: "rename",
536 Requires: []*analysis.Analyzer{inspect.Analyzer},
537 Doc: "renames symbols named bar to baz",
538 RunDespiteErrors: true,
539 Run: func(pass *analysis.Pass) (any, error) {
540 const (
541 from = "bar"
542 to = "baz"
543 )
544 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
545 nodeFilter := []ast.Node{(*ast.Ident)(nil)}
546 inspect.Preorder(nodeFilter, func(n ast.Node) {
547 ident := n.(*ast.Ident)
548 if ident.Name == from {
549 msg := fmt.Sprintf("renaming %q to %q", from, to)
550 pass.Report(analysis.Diagnostic{
551 Pos: ident.Pos(),
552 End: ident.End(),
553 Message: msg,
554 SuggestedFixes: []analysis.SuggestedFix{{
555 Message: msg,
556 TextEdits: []analysis.TextEdit{{
557 Pos: ident.Pos(),
558 End: ident.End(),
559 NewText: []byte(to),
560 }},
561 }},
562 })
563 }
564 })
565 return nil, nil
566 },
567 }
568
569 var noendAnalyzer = &analysis.Analyzer{
570 Name: "noend",
571 Doc: "inserts /*hello*/ before first decl",
572 Run: func(pass *analysis.Pass) (any, error) {
573 decl := pass.Files[0].Decls[0]
574 pass.Report(analysis.Diagnostic{
575 Pos: decl.Pos(),
576 End: token.NoPos,
577 Message: "say hello",
578 SuggestedFixes: []analysis.SuggestedFix{{
579 Message: "say hello",
580 TextEdits: []analysis.TextEdit{{
581 Pos: decl.Pos(),
582 End: token.NoPos,
583 NewText: []byte("/*hello*/"),
584 }},
585 }},
586 })
587 return nil, nil
588 },
589 }
590
591 var relatedAnalyzer = &analysis.Analyzer{
592 Name: "related",
593 Doc: "reports a Diagnostic with RelatedInformaiton",
594 Run: func(pass *analysis.Pass) (any, error) {
595 decl := pass.Files[0].Decls[0]
596 pass.Report(analysis.Diagnostic{
597 Pos: decl.Pos(),
598 End: decl.Pos() + 1,
599 Message: "decl starts here",
600 Related: []analysis.RelatedInformation{{
601 Message: "decl ends here",
602 Pos: decl.End() - 1,
603 End: decl.End(),
604 }},
605 })
606 return nil, nil
607 },
608 }
609
610 // panics asserts that f() panics with with a value whose printed form matches the regexp want.
611 func panics(t *testing.T, want string, f func()) {
612 defer func() {
613 if x := recover(); x == nil {
614 t.Errorf("function returned normally, wanted panic")
615 } else if m, err := regexp.MatchString(want, fmt.Sprint(x)); err != nil {
616 t.Errorf("panics: invalid regexp %q", want)
617 } else if !m {
618 t.Errorf("function panicked with value %q, want match for %q", x, want)
619 }
620 }()
621 f()
622 }
623
624 // section returns the named archive section, or nil.
625 func section(ar *txtar.Archive, name string) *txtar.File {
626 for i, f := range ar.Files {
627 if f.Name == name {
628 return &ar.Files[i]
629 }
630 }
631 return nil
632 }