Skip to content

Commit f5f4fdf

Browse files
authored
Export Analyzer interface (#11)
Allows use of makezero in other linters
1 parent ead11f7 commit f5f4fdf

File tree

13 files changed

+149
-22
lines changed

13 files changed

+149
-22
lines changed

.circleci/config.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ version: 2
33
jobs:
44
build:
55
docker:
6-
- image: circleci/golang:1.12
6+
- image: cimg/go:1.17.7
77
steps:
88
- checkout
9-
- run: sudo apt-get -y -qq install python python-pip
9+
- run: sudo apt-get update && sudo apt-get -y -qq install python pip
1010
- run: pip install pre-commit
1111
- run: SKIP=no-commit-to-branch pre-commit run -a
1212
- run: go test ./...

.golangci.yml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
linters:
2-
enable-all: true
1+
linters: {}

.pre-commit-config.yaml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
repos:
22
- repo: https://github.com/golangci/golangci-lint
3-
rev: v1.17.1
3+
rev: v1.44.2
44
hooks:
55
- id: golangci-lint
6+
- repo: https://github.com/pre-commit/pre-commit-hooks
7+
rev: v4.1.0
8+
hooks:
9+
- id: trailing-whitespace

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# makezero
22

3+
[![CircleCI](https://circleci.com/gh/ashanbrown/makezero/tree/master.svg?style=svg)](https://circleci.com/gh/ashanbrown/makezero/tree/master)
4+
35
makezero is a Go static analysis tool to find slice declarations that are not initialized with zero length and are later
46
used with append.
57

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,5 @@ go 1.12
44

55
require (
66
github.com/stretchr/testify v1.4.0
7-
golang.org/x/tools v0.0.0-20190916130336-e45ffcd953cc
7+
golang.org/x/tools v0.1.9
88
)

go.sum

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,37 @@ github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8
22
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
33
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
44
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
5-
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
65
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
76
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
87
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
9-
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
8+
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
109
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
11-
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI=
10+
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
11+
golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38=
12+
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
13+
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
1214
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
13-
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
15+
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
1416
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
15-
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=
17+
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
1618
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
17-
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
19+
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
20+
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
21+
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
22+
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654 h1:id054HUawV2/6IGm2IV8KZQjqtwAOo2CYlOToYqa0d0=
23+
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
24+
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
1825
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
19-
golang.org/x/tools v0.0.0-20190916130336-e45ffcd953cc h1:+GB9/q0gCzmtaIl6WdoJFMS3lPwrR6rpcMyY6jfQHAw=
20-
golang.org/x/tools v0.0.0-20190916130336-e45ffcd953cc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
21-
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 h1:9zdDQZ7Thm29KFXgAX/+yaf3eVbP7djjWp/dXAppNCc=
26+
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
27+
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
28+
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
29+
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
30+
golang.org/x/tools v0.1.9 h1:j9KsMiaP1c3B0OTQGth0/k+miLGTgLsAFUCrF2vLcF8=
31+
golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
2232
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
33+
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
34+
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
35+
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
2336
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
2437
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
2538
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=

main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ func main() {
2929
}
3030
linter := makezero.NewLinter(*always)
3131

32-
var issues []makezero.Issue // nolint:prealloc // don't know how many there will be
32+
var issues []makezero.Issue
3333
for _, p := range pkgs {
3434
nodes := make([]ast.Node, 0, len(p.Syntax))
3535
for _, n := range p.Syntax {

makezero/makezero.go

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// makezero provides a linter for appends to slices initialized with non-zero length.
1+
// Package makezero provides a linter for appends to slices initialized with non-zero length.
22
package makezero
33

44
import (
@@ -13,27 +13,33 @@ import (
1313
)
1414

1515
// a decl might include multiple var,
16-
// so var name with decl make final uniq obj
16+
// so var name with decl make final uniq obj.
1717
type uniqDecl struct {
1818
varName string
1919
decl interface{}
2020
}
2121

2222
type Issue interface {
2323
Details() string
24+
Pos() token.Pos
2425
Position() token.Position
2526
String() string
2627
}
2728

2829
type AppendIssue struct {
2930
name string
31+
pos token.Pos
3032
position token.Position
3133
}
3234

3335
func (a AppendIssue) Details() string {
3436
return fmt.Sprintf("append to slice `%s` with non-zero initialized length", a.name)
3537
}
3638

39+
func (a AppendIssue) Pos() token.Pos {
40+
return a.pos
41+
}
42+
3743
func (a AppendIssue) Position() token.Position {
3844
return a.position
3945
}
@@ -42,13 +48,18 @@ func (a AppendIssue) String() string { return toString(a) }
4248

4349
type MustHaveNonZeroInitLenIssue struct {
4450
name string
51+
pos token.Pos
4552
position token.Position
4653
}
4754

4855
func (i MustHaveNonZeroInitLenIssue) Details() string {
4956
return fmt.Sprintf("slice `%s` does not have non-zero initial length", i.name)
5057
}
5158

59+
func (i MustHaveNonZeroInitLenIssue) Pos() token.Pos {
60+
return i.pos
61+
}
62+
5263
func (i MustHaveNonZeroInitLenIssue) Position() token.Position {
5364
return i.position
5465
}
@@ -81,7 +92,7 @@ func NewLinter(initialLengthMustBeZero bool) *Linter {
8192
}
8293

8394
func (l Linter) Run(fset *token.FileSet, info *types.Info, nodes ...ast.Node) ([]Issue, error) {
84-
var issues []Issue // nolint:prealloc // don't know how many there will be
95+
var issues []Issue
8596
for _, node := range nodes {
8697
var comments []*ast.CommentGroup
8798
if file, ok := node.(*ast.File); ok {
@@ -110,7 +121,12 @@ func (v *visitor) Visit(node ast.Node) ast.Visitor {
110121
if sliceIdent, ok := node.Args[0].(*ast.Ident); ok &&
111122
v.hasNonZeroInitialLength(sliceIdent) &&
112123
!v.hasNoLintOnSameLine(fun) {
113-
v.issues = append(v.issues, AppendIssue{name: sliceIdent.Name, position: v.fset.Position(fun.Pos())})
124+
v.issues = append(v.issues,
125+
AppendIssue{
126+
name: sliceIdent.Name,
127+
pos: fun.Pos(),
128+
position: v.fset.Position(fun.Pos()),
129+
})
114130
}
115131
case *ast.AssignStmt:
116132
for i, right := range node.Rhs {
@@ -130,6 +146,7 @@ func (v *visitor) Visit(node ast.Node) ast.Visitor {
130146
if v.initLenMustBeZero && !v.hasNoLintOnSameLine(fun) {
131147
v.issues = append(v.issues, MustHaveNonZeroInitLenIssue{
132148
name: v.textFor(left),
149+
pos: node.Pos(),
133150
position: v.fset.Position(node.Pos()),
134151
})
135152
}
@@ -201,7 +218,7 @@ func (v *visitor) isSlice(node ast.Node) bool {
201218
}
202219

203220
func (v *visitor) hasNoLintOnSameLine(node ast.Node) bool {
204-
var nolint = regexp.MustCompile(`^\s*nozero\b`)
221+
nolint := regexp.MustCompile(`^\s*nozero\b`)
205222
nodePos := v.fset.Position(node.Pos())
206223
for _, c := range v.comments {
207224
commentPos := v.fset.Position(c.Pos())

makezero/makezero_test.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,6 @@ func foo() {
6464
append(x, 1) //nozeroxxx
6565
}`, "append to slice `x` with non-zero initialized length at testing.go:7:3")
6666
})
67-
6867
})
6968

7069
t.Run("ignores more complex constructs than basic variables", func(t *testing.T) {

pkg/analyzer/analyzer.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package analyzer
2+
3+
import (
4+
"flag"
5+
"go/ast"
6+
7+
"github.com/ashanbrown/makezero/makezero"
8+
"golang.org/x/tools/go/analysis"
9+
)
10+
11+
type analyzer struct {
12+
always bool
13+
}
14+
15+
// NewAnalyzer returns a go/analysis-compatible analyzer
16+
// Set "-always" to report any non-empty slice initialization.
17+
func NewAnalyzer() *analysis.Analyzer {
18+
var flags flag.FlagSet
19+
a := analyzer{}
20+
flags.BoolVar(&a.always, "always", false, "report any non-empty slice initializations, regardless of intention")
21+
return &analysis.Analyzer{
22+
Name: "makezero",
23+
Doc: "detect unintended non-empty slice initializations",
24+
Run: a.runAnalysis,
25+
Flags: flags,
26+
}
27+
}
28+
29+
func (a *analyzer) runAnalysis(pass *analysis.Pass) (interface{}, error) {
30+
linter := makezero.NewLinter(a.always)
31+
nodes := make([]ast.Node, 0, len(pass.Files))
32+
for _, f := range pass.Files {
33+
nodes = append(nodes, f)
34+
}
35+
issues, err := linter.Run(pass.Fset, pass.TypesInfo, nodes...)
36+
if err != nil {
37+
return nil, err
38+
}
39+
reportIssues(pass, issues)
40+
return nil, nil
41+
}
42+
43+
func reportIssues(pass *analysis.Pass, issues []makezero.Issue) {
44+
for _, i := range issues {
45+
diag := analysis.Diagnostic{
46+
Pos: i.Pos(),
47+
Message: i.Details(),
48+
Category: "restriction",
49+
}
50+
pass.Report(diag)
51+
}
52+
}

pkg/analyzer/analyzer_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package analyzer_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/ashanbrown/makezero/pkg/analyzer"
7+
"golang.org/x/tools/go/analysis/analysistest"
8+
)
9+
10+
func TestAppend(t *testing.T) {
11+
testdata := analysistest.TestData()
12+
a := analyzer.NewAnalyzer()
13+
analysistest.Run(t, testdata, a, "./append")
14+
}
15+
16+
func TestAlways(t *testing.T) {
17+
testdata := analysistest.TestData()
18+
a := analyzer.NewAnalyzer()
19+
err := a.Flags.Set("always", "true")
20+
if err != nil {
21+
t.Fatalf("expected no error but got %q", err)
22+
}
23+
analysistest.Run(t, testdata, a, "./always")
24+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package always
2+
3+
import "fmt"
4+
5+
func Foo() {
6+
x := make([]int, 5) // want "slice `x` does not have non-zero initial length"
7+
fmt.Println(x)
8+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package append
2+
3+
import "fmt"
4+
5+
func Foo() {
6+
x := make([]int, 5)
7+
x = append(x, 1) // want "append to slice `x` with non-zero initialized length"
8+
fmt.Println(x)
9+
}

0 commit comments

Comments
 (0)