This repository has been archived by the owner on Dec 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
offBy1_checker.go
66 lines (57 loc) · 1.64 KB
/
offBy1_checker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package checkers
import (
"go/ast"
"go/token"
"github.com/go-lintpack/lintpack"
"github.com/go-lintpack/lintpack/astwalk"
"github.com/go-toolsmith/astcast"
"github.com/go-toolsmith/astcopy"
"github.com/go-toolsmith/astequal"
"github.com/go-toolsmith/typep"
)
func init() {
var info lintpack.CheckerInfo
info.Name = "offBy1"
info.Tags = []string{"diagnostic", "experimental"}
info.Summary = "Detects various off-by-one kind of errors"
info.Before = `xs[len(xs)]`
info.After = `xs[len(xs)-1]`
collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker {
return astwalk.WalkerForExpr(&offBy1Checker{ctx: ctx})
})
}
type offBy1Checker struct {
astwalk.WalkHandler
ctx *lintpack.CheckerContext
}
func (c *offBy1Checker) VisitExpr(e ast.Expr) {
// TODO(Quasilyte): handle more off-by-1 patterns.
// TODO(Quasilyte): check whether go/analysis can help here.
// Detect s[len(s)] expressions that always panic.
// The correct form is s[len(s)-1].
indexExpr := astcast.ToIndexExpr(e)
indexed := indexExpr.X
if !typep.IsSlice(c.ctx.TypesInfo.TypeOf(indexed)) {
return
}
if !typep.SideEffectFree(c.ctx.TypesInfo, indexed) {
return
}
call := astcast.ToCallExpr(indexExpr.Index)
if astcast.ToIdent(call.Fun).Name != "len" {
return
}
if len(call.Args) != 1 || !astequal.Expr(call.Args[0], indexed) {
return
}
c.warnLenIndex(indexExpr)
}
func (c *offBy1Checker) warnLenIndex(cause *ast.IndexExpr) {
suggest := astcopy.IndexExpr(cause)
suggest.Index = &ast.BinaryExpr{
Op: token.SUB,
X: cause.Index,
Y: &ast.BasicLit{Value: "1"},
}
c.ctx.Warn(cause, "index expr always panics; maybe you wanted %s?", suggest)
}