|
| 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/analysisinternal" |
| 14 | + "golang.org/x/tools/internal/goplsexport" |
| 15 | +) |
| 16 | + |
| 17 | +var plusBuildAnalyzer = &analysis.Analyzer{ |
| 18 | + Name: "plusbuild", |
| 19 | + Doc: analysisinternal.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 init() { |
| 25 | + // Export to gopls until this is a published modernizer. |
| 26 | + goplsexport.PlusBuildModernizer = plusBuildAnalyzer |
| 27 | +} |
| 28 | + |
| 29 | +func plusbuild(pass *analysis.Pass) (any, error) { |
| 30 | + check := func(f *ast.File) { |
| 31 | + if !fileUses(pass.TypesInfo, f, "go1.18") { |
| 32 | + return |
| 33 | + } |
| 34 | + |
| 35 | + // When gofmt sees a +build comment, it adds a |
| 36 | + // preceding equivalent //go:build directive, so in |
| 37 | + // formatted files we can assume that a +build line is |
| 38 | + // part of a comment group that starts with a |
| 39 | + // //go:build line and is followed by a blank line. |
| 40 | + // |
| 41 | + // While we cannot delete comments from an AST and |
| 42 | + // expect consistent output in general, this specific |
| 43 | + // case--deleting only some lines from a comment |
| 44 | + // block--does format correctly. |
| 45 | + for _, g := range f.Comments { |
| 46 | + sawGoBuild := false |
| 47 | + for _, c := range g.List { |
| 48 | + if sawGoBuild && strings.HasPrefix(c.Text, "// +build ") { |
| 49 | + pass.Report(analysis.Diagnostic{ |
| 50 | + Pos: c.Pos(), |
| 51 | + End: c.End(), |
| 52 | + Message: "+build line is no longer needed", |
| 53 | + SuggestedFixes: []analysis.SuggestedFix{{ |
| 54 | + Message: "Remove obsolete +build line", |
| 55 | + TextEdits: []analysis.TextEdit{{ |
| 56 | + Pos: c.Pos(), |
| 57 | + End: c.End(), |
| 58 | + }}, |
| 59 | + }}, |
| 60 | + }) |
| 61 | + break |
| 62 | + } |
| 63 | + if strings.HasPrefix(c.Text, "//go:build ") { |
| 64 | + sawGoBuild = true |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + for _, f := range pass.Files { |
| 71 | + check(f) |
| 72 | + } |
| 73 | + for _, name := range pass.IgnoredFiles { |
| 74 | + if strings.HasSuffix(name, ".go") { |
| 75 | + f, err := parser.ParseFile(pass.Fset, name, nil, parser.ParseComments|parser.SkipObjectResolution) |
| 76 | + if err != nil { |
| 77 | + continue // parse error: ignore |
| 78 | + } |
| 79 | + check(f) |
| 80 | + } |
| 81 | + } |
| 82 | + return nil, nil |
| 83 | +} |
0 commit comments