src

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

s1033.go (1310B)


      1 package s1033
      2 
      3 import (
      4 	"go/ast"
      5 
      6 	"honnef.co/go/tools/analysis/code"
      7 	"honnef.co/go/tools/analysis/edit"
      8 	"honnef.co/go/tools/analysis/facts/generated"
      9 	"honnef.co/go/tools/analysis/lint"
     10 	"honnef.co/go/tools/analysis/report"
     11 	"honnef.co/go/tools/pattern"
     12 
     13 	"golang.org/x/tools/go/analysis"
     14 )
     15 
     16 var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
     17 	Analyzer: &analysis.Analyzer{
     18 		Name:     "S1033",
     19 		Run:      run,
     20 		Requires: append([]*analysis.Analyzer{generated.Analyzer}, code.RequiredAnalyzers...),
     21 	},
     22 	Doc: &lint.RawDocumentation{
     23 		Title:   `Unnecessary guard around call to \"delete\"`,
     24 		Text:    `Calling \'delete\' on a nil map is a no-op.`,
     25 		Since:   "2019.2",
     26 		MergeIf: lint.MergeIfAny,
     27 	},
     28 })
     29 
     30 var Analyzer = SCAnalyzer.Analyzer
     31 
     32 var checkGuardedDeleteQ = pattern.MustParse(`
     33 	(IfStmt
     34 		(AssignStmt
     35 			[(Ident "_") ok@(Ident _)]
     36 			":="
     37 			(IndexExpr m key))
     38 		ok
     39 		[call@(CallExpr (Builtin "delete") [m key])]
     40 		nil)`)
     41 
     42 func run(pass *analysis.Pass) (any, error) {
     43 	for node, m := range code.Matches(pass, checkGuardedDeleteQ) {
     44 		report.Report(pass, node, "unnecessary guard around call to delete",
     45 			report.ShortRange(),
     46 			report.FilterGenerated(),
     47 			report.Fixes(edit.Fix("Remove guard", edit.ReplaceWithNode(pass.Fset, node, m.State["call"].(ast.Node)))))
     48 	}
     49 	return nil, nil
     50 }