Debian Codegraph @

simple/s1010/s1010.go

raw
1 package s1010
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: "S1010",
19 Run: run,
20 Requires: append([]*analysis.Analyzer{generated.Analyzer}, code.RequiredAnalyzers...),
21 },
22 Doc: &lint.RawDocumentation{
23 Title: `Omit default slice index`,
24 Text: `When slicing, the second index defaults to the length of the value,
25 making \'s[n:len(s)]\' and \'s[n:]\' equivalent.`,
26 Since: "2017.1",
27 MergeIf: lint.MergeIfAny,
28 },
29 })
30
31 var Analyzer = SCAnalyzer.Analyzer
32
33 var checkSlicingQ = pattern.MustParse(`(SliceExpr x@(Object _) low (CallExpr (Builtin "len") [x]) nil)`)
34
35 func run(pass *analysis.Pass) (any, error) {
36 for node := range code.Matches(pass, checkSlicingQ) {
37 expr := node.(*ast.SliceExpr)
38 report.Report(pass, expr.High,
39 "should omit second index in slice, s[a:len(s)] is identical to s[a:]",
40 report.FilterGenerated(),
41 report.Fixes(edit.Fix("Simplify slice expression", edit.Delete(expr.High))))
42 }
43 return nil, nil
44 }