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

     1  package sa1000
     2  
     3  import (
     4  	"go/constant"
     5  	"regexp"
     6  
     7  	"github.com/amarpal/go-tools/analysis/callcheck"
     8  	"github.com/amarpal/go-tools/analysis/lint"
     9  	"github.com/amarpal/go-tools/internal/passes/buildir"
    10  
    11  	"golang.org/x/tools/go/analysis"
    12  )
    13  
    14  var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
    15  	Analyzer: &analysis.Analyzer{
    16  		Name:     "SA1000",
    17  		Requires: []*analysis.Analyzer{buildir.Analyzer},
    18  		Run:      callcheck.Analyzer(rules),
    19  	},
    20  	Doc: &lint.Documentation{
    21  		Title:    `Invalid regular expression`,
    22  		Since:    "2017.1",
    23  		Severity: lint.SeverityError,
    24  		MergeIf:  lint.MergeIfAny,
    25  	},
    26  })
    27  
    28  var Analyzer = SCAnalyzer.Analyzer
    29  
    30  var rules = map[string]callcheck.Check{
    31  	"regexp.MustCompile": check,
    32  	"regexp.Compile":     check,
    33  	"regexp.Match":       check,
    34  	"regexp.MatchReader": check,
    35  	"regexp.MatchString": check,
    36  }
    37  
    38  func check(call *callcheck.Call) {
    39  	arg := call.Args[0]
    40  	if c := callcheck.ExtractConstExpectKind(arg.Value, constant.String); c != nil {
    41  		s := constant.StringVal(c.Value)
    42  		if _, err := regexp.Compile(s); err != nil {
    43  			arg.Invalid(err.Error())
    44  		}
    45  	}
    46  }