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

     1  package sa1011
     2  
     3  import (
     4  	"go/constant"
     5  	"unicode/utf8"
     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:     "SA1011",
    17  		Requires: []*analysis.Analyzer{buildir.Analyzer},
    18  		Run:      callcheck.Analyzer(checkUTF8CutsetRules),
    19  	},
    20  	Doc: &lint.Documentation{
    21  		Title:    `Various methods in the \"strings\" package expect valid UTF-8, but invalid input is provided`,
    22  		Since:    "2017.1",
    23  		Severity: lint.SeverityError,
    24  		MergeIf:  lint.MergeIfAny,
    25  	},
    26  })
    27  
    28  var Analyzer = SCAnalyzer.Analyzer
    29  
    30  var checkUTF8CutsetRules = map[string]callcheck.Check{
    31  	"strings.IndexAny":     check,
    32  	"strings.LastIndexAny": check,
    33  	"strings.ContainsAny":  check,
    34  	"strings.Trim":         check,
    35  	"strings.TrimLeft":     check,
    36  	"strings.TrimRight":    check,
    37  }
    38  
    39  func check(call *callcheck.Call) {
    40  	arg := call.Args[1]
    41  	if c := callcheck.ExtractConstExpectKind(arg.Value, constant.String); c != nil {
    42  		s := constant.StringVal(c.Value)
    43  		if !utf8.ValidString(s) {
    44  			arg.Invalid("argument is not a valid UTF-8 encoded string")
    45  		}
    46  	}
    47  }