github.com/amarpal/go-tools@v0.0.0-20240422043104-40142f59f616/staticcheck/sa4021/sa4021.go (about)

     1  package sa4021
     2  
     3  import (
     4  	"go/ast"
     5  
     6  	"github.com/amarpal/go-tools/analysis/code"
     7  	"github.com/amarpal/go-tools/analysis/facts/generated"
     8  	"github.com/amarpal/go-tools/analysis/lint"
     9  	"github.com/amarpal/go-tools/analysis/report"
    10  	"github.com/amarpal/go-tools/pattern"
    11  
    12  	"golang.org/x/tools/go/analysis"
    13  	"golang.org/x/tools/go/analysis/passes/inspect"
    14  )
    15  
    16  var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
    17  	Analyzer: &analysis.Analyzer{
    18  		Name:     "SA4021",
    19  		Run:      run,
    20  		Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer},
    21  	},
    22  	Doc: &lint.Documentation{
    23  		Title:    `\"x = append(y)\" is equivalent to \"x = y\"`,
    24  		Since:    "2019.2",
    25  		Severity: lint.SeverityWarning,
    26  		MergeIf:  lint.MergeIfAny,
    27  	},
    28  })
    29  
    30  var Analyzer = SCAnalyzer.Analyzer
    31  
    32  var checkSingleArgAppendQ = pattern.MustParse(`(CallExpr (Builtin "append") [_])`)
    33  
    34  func run(pass *analysis.Pass) (interface{}, error) {
    35  	fn := func(node ast.Node) {
    36  		_, ok := code.Match(pass, checkSingleArgAppendQ, node)
    37  		if !ok {
    38  			return
    39  		}
    40  		report.Report(pass, node, "x = append(y) is equivalent to x = y", report.FilterGenerated())
    41  	}
    42  	code.Preorder(pass, fn, (*ast.CallExpr)(nil))
    43  	return nil, nil
    44  }