| 1 | // Copyright 2025 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 modernize |
| 6 | |
| 7 | import ( |
| 8 | "go/ast" |
| 9 | "go/parser" |
| 10 | "strings" |
| 11 | |
| 12 | "golang.org/x/tools/go/analysis" |
| 13 | "golang.org/x/tools/internal/analysis/analyzerutil" |
| 14 | "golang.org/x/tools/internal/versions" |
| 15 | ) |
| 16 | |
| 17 | var PlusBuildAnalyzer = &analysis.Analyzer{ |
| 18 | Name: "plusbuild", |
| 19 | Doc: analyzerutil.MustExtractDoc(doc, "plusbuild"), |
| 20 | URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#plusbuild", |
| 21 | Run: plusbuild, |
| 22 | } |
| 23 | |
| 24 | func plusbuild(pass *analysis.Pass) (any, error) { |
| 25 | check := func(f *ast.File) { |
| 26 | // "//go:build" directives were added in go1.17, but |
| 27 | // we didn't start eliminating +build directives till go1.18. |
| 28 | if !analyzerutil.FileUsesGoVersion(pass, f, versions.Go1_18) { |
| 29 | return |
| 30 | } |
| 31 | |
| 32 | // When gofmt sees a +build comment, it adds a |
| 33 | // preceding equivalent //go:build directive, so in |
| 34 | // formatted files we can assume that a +build line is |
| 35 | // part of a comment group that starts with a |
| 36 | // //go:build line and is followed by a blank line. |
| 37 | // |
| 38 | // While we cannot delete comments from an AST and |
| 39 | // expect consistent output in general, this specific |
| 40 | // case--deleting only some lines from a comment |
| 41 | // block--does format correctly. |
| 42 | for _, g := range f.Comments { |
| 43 | sawGoBuild := false |
| 44 | for _, c := range g.List { |
| 45 | if sawGoBuild && strings.HasPrefix(c.Text, "// +build ") { |
| 46 | pass.Report(analysis.Diagnostic{ |
| 47 | Pos: c.Pos(), |
| 48 | End: c.End(), |
| 49 | Message: "+build line is no longer needed", |
| 50 | SuggestedFixes: []analysis.SuggestedFix{{ |
| 51 | Message: "Remove obsolete +build line", |
| 52 | TextEdits: []analysis.TextEdit{{ |
| 53 | Pos: c.Pos(), |
| 54 | End: c.End(), |
| 55 | }}, |
| 56 | }}, |
| 57 | }) |
| 58 | break |
| 59 | } |
| 60 | if strings.HasPrefix(c.Text, "//go:build ") { |
| 61 | sawGoBuild = true |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | for _, f := range pass.Files { |
| 68 | check(f) |
| 69 | } |
| 70 | for _, name := range pass.IgnoredFiles { |
| 71 | if strings.HasSuffix(name, ".go") { |
| 72 | f, err := parser.ParseFile(pass.Fset, name, nil, parser.ParseComments|parser.SkipObjectResolution) |
| 73 | if err != nil { |
| 74 | continue // parse error: ignore |
| 75 | } |
| 76 | check(f) |
| 77 | } |
| 78 | } |
| 79 | return nil, nil |
| 80 | } |