| 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 appends defines an Analyzer that detects |
| 6 | // if there is only one variable in append. |
| 7 | package appends |
| 8 | |
| 9 | import ( |
| 10 | _ "embed" |
| 11 | "go/ast" |
| 12 | "go/types" |
| 13 | |
| 14 | "golang.org/x/tools/go/analysis" |
| 15 | "golang.org/x/tools/go/analysis/passes/inspect" |
| 16 | "golang.org/x/tools/go/ast/inspector" |
| 17 | "golang.org/x/tools/go/types/typeutil" |
| 18 | "golang.org/x/tools/internal/analysis/analyzerutil" |
| 19 | ) |
| 20 | |
| 21 | //go:embed doc.go |
| 22 | var doc string |
| 23 | |
| 24 | var Analyzer = &analysis.Analyzer{ |
| 25 | Name: "appends", |
| 26 | Doc: analyzerutil.MustExtractDoc(doc, "appends"), |
| 27 | URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/appends", |
| 28 | Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 29 | Run: run, |
| 30 | } |
| 31 | |
| 32 | func run(pass *analysis.Pass) (any, error) { |
| 33 | inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 34 | |
| 35 | nodeFilter := []ast.Node{ |
| 36 | (*ast.CallExpr)(nil), |
| 37 | } |
| 38 | inspect.Preorder(nodeFilter, func(n ast.Node) { |
| 39 | call := n.(*ast.CallExpr) |
| 40 | b, ok := typeutil.Callee(pass.TypesInfo, call).(*types.Builtin) |
| 41 | if ok && b.Name() == "append" && len(call.Args) == 1 { |
| 42 | pass.ReportRangef(call, "append with no values") |
| 43 | } |
| 44 | }) |
| 45 | |
| 46 | return nil, nil |
| 47 | } |