src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

sa4022.go (1042B)


      1 package sa4022
      2 
      3 import (
      4 	"honnef.co/go/tools/analysis/code"
      5 	"honnef.co/go/tools/analysis/lint"
      6 	"honnef.co/go/tools/analysis/report"
      7 	"honnef.co/go/tools/pattern"
      8 
      9 	"golang.org/x/tools/go/analysis"
     10 )
     11 
     12 var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
     13 	Analyzer: &analysis.Analyzer{
     14 		Name:     "SA4022",
     15 		Run:      run,
     16 		Requires: code.RequiredAnalyzers,
     17 	},
     18 	Doc: &lint.RawDocumentation{
     19 		Title:    `Comparing the address of a variable against nil`,
     20 		Text:     `Code such as \"if &x == nil\" is meaningless, because taking the address of a variable always yields a non-nil pointer.`,
     21 		Since:    "2020.1",
     22 		Severity: lint.SeverityWarning,
     23 		MergeIf:  lint.MergeIfAny,
     24 	},
     25 })
     26 
     27 var Analyzer = SCAnalyzer.Analyzer
     28 
     29 var CheckAddressIsNilQ = pattern.MustParse(
     30 	`(BinaryExpr
     31 		(UnaryExpr "&" _)
     32 		(Or "==" "!=")
     33 		(Builtin "nil"))`)
     34 
     35 func run(pass *analysis.Pass) (any, error) {
     36 	for node := range code.Matches(pass, CheckAddressIsNilQ) {
     37 		report.Report(pass, node, "the address of a variable cannot be nil")
     38 	}
     39 	return nil, nil
     40 }