Skip to content

Commit cb89a4c

Browse files
authored
refactor (rule/datarace): replace AST walker by iteration over declarations (#1162)
1 parent 8f54012 commit cb89a4c

File tree

1 file changed

+28
-33
lines changed

1 file changed

+28
-33
lines changed

rule/datarace.go

Lines changed: 28 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -11,50 +11,45 @@ import (
1111
type DataRaceRule struct{}
1212

1313
// Apply applies the rule to given file.
14-
func (*DataRaceRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
14+
func (r *DataRaceRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
15+
isGo122 := file.Pkg.IsAtLeastGo122()
1516
var failures []lint.Failure
16-
onFailure := func(failure lint.Failure) {
17-
failures = append(failures, failure)
18-
}
19-
w := lintDataRaces{onFailure: onFailure, go122for: file.Pkg.IsAtLeastGo122()}
17+
for _, decl := range file.AST.Decls {
18+
funcDecl, ok := decl.(*ast.FuncDecl)
19+
if !ok || funcDecl.Body == nil {
20+
continue // not function declaration or empty function
21+
}
2022

21-
ast.Walk(w, file.AST)
23+
funcResults := funcDecl.Type.Results
2224

23-
return failures
24-
}
25+
returnIDs := map[*ast.Object]struct{}{}
26+
if funcResults != nil {
27+
returnIDs = r.ExtractReturnIDs(funcResults.List)
28+
}
2529

26-
// Name returns the rule name.
27-
func (*DataRaceRule) Name() string {
28-
return "datarace"
29-
}
30+
onFailure := func(failure lint.Failure) {
31+
failures = append(failures, failure)
32+
}
3033

31-
type lintDataRaces struct {
32-
onFailure func(failure lint.Failure)
33-
go122for bool
34-
}
34+
fl := &lintFunctionForDataRaces{
35+
onFailure: onFailure,
36+
returnIDs: returnIDs,
37+
rangeIDs: map[*ast.Object]struct{}{},
38+
go122for: isGo122,
39+
}
3540

36-
func (w lintDataRaces) Visit(n ast.Node) ast.Visitor {
37-
node, ok := n.(*ast.FuncDecl)
38-
if !ok {
39-
return w // not function declaration
41+
ast.Walk(fl, funcDecl.Body)
4042
}
41-
if node.Body == nil {
42-
return nil // empty body
43-
}
44-
45-
results := node.Type.Results
4643

47-
returnIDs := map[*ast.Object]struct{}{}
48-
if results != nil {
49-
returnIDs = w.ExtractReturnIDs(results.List)
50-
}
51-
fl := &lintFunctionForDataRaces{onFailure: w.onFailure, returnIDs: returnIDs, rangeIDs: map[*ast.Object]struct{}{}, go122for: w.go122for}
52-
ast.Walk(fl, node.Body)
44+
return failures
45+
}
5346

54-
return nil
47+
// Name returns the rule name.
48+
func (*DataRaceRule) Name() string {
49+
return "datarace"
5550
}
5651

57-
func (lintDataRaces) ExtractReturnIDs(fields []*ast.Field) map[*ast.Object]struct{} {
52+
func (*DataRaceRule) ExtractReturnIDs(fields []*ast.Field) map[*ast.Object]struct{} {
5853
r := map[*ast.Object]struct{}{}
5954
for _, f := range fields {
6055
for _, id := range f.Names {

0 commit comments

Comments
 (0)