-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapiter.go
More file actions
52 lines (39 loc) · 995 Bytes
/
mapiter.go
File metadata and controls
52 lines (39 loc) · 995 Bytes
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
// mapiter provides a linter that reports code that iterates over a map.
package mapiter
import (
"go/ast"
"go/types"
"strings"
"golang.org/x/tools/go/analysis"
)
var Analyzer = &analysis.Analyzer{
Name: "mapiter",
Doc: "reports code that iterates over a map",
Run: run,
}
var includeTests bool
func init() {
Analyzer.Flags.BoolVar(&includeTests, "tests", true, "ignore _test.go files")
}
func run(pass *analysis.Pass) (interface{}, error) {
for _, file := range pass.Files {
if !includeTests && strings.HasSuffix(pass.Fset.File(file.Pos()).Name(), "_test.go") {
continue
}
ast.Inspect(file, func(n ast.Node) bool {
if n == nil {
return false
}
// Look for range expression
if r, ok := n.(*ast.RangeStmt); ok {
// Check if range value is a map
if _, ok := pass.TypesInfo.TypeOf(r.X).Underlying().(*types.Map); ok {
pass.Reportf(r.TokPos, "iterating over a map")
return false
}
}
return true
})
}
return nil, nil
}