Skip to content

Commit

Permalink
refactor (rule/datarace): replace AST walker by iteration over declar…
Browse files Browse the repository at this point in the history
…ations (#1162)
  • Loading branch information
chavacava authored Dec 7, 2024
1 parent 8f54012 commit cb89a4c
Showing 1 changed file with 28 additions and 33 deletions.
61 changes: 28 additions & 33 deletions rule/datarace.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,50 +11,45 @@ import (
type DataRaceRule struct{}

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

ast.Walk(w, file.AST)
funcResults := funcDecl.Type.Results

return failures
}
returnIDs := map[*ast.Object]struct{}{}
if funcResults != nil {
returnIDs = r.ExtractReturnIDs(funcResults.List)
}

// Name returns the rule name.
func (*DataRaceRule) Name() string {
return "datarace"
}
onFailure := func(failure lint.Failure) {
failures = append(failures, failure)
}

type lintDataRaces struct {
onFailure func(failure lint.Failure)
go122for bool
}
fl := &lintFunctionForDataRaces{
onFailure: onFailure,
returnIDs: returnIDs,
rangeIDs: map[*ast.Object]struct{}{},
go122for: isGo122,
}

func (w lintDataRaces) Visit(n ast.Node) ast.Visitor {
node, ok := n.(*ast.FuncDecl)
if !ok {
return w // not function declaration
ast.Walk(fl, funcDecl.Body)
}
if node.Body == nil {
return nil // empty body
}

results := node.Type.Results

returnIDs := map[*ast.Object]struct{}{}
if results != nil {
returnIDs = w.ExtractReturnIDs(results.List)
}
fl := &lintFunctionForDataRaces{onFailure: w.onFailure, returnIDs: returnIDs, rangeIDs: map[*ast.Object]struct{}{}, go122for: w.go122for}
ast.Walk(fl, node.Body)
return failures
}

return nil
// Name returns the rule name.
func (*DataRaceRule) Name() string {
return "datarace"
}

func (lintDataRaces) ExtractReturnIDs(fields []*ast.Field) map[*ast.Object]struct{} {
func (*DataRaceRule) ExtractReturnIDs(fields []*ast.Field) map[*ast.Object]struct{} {
r := map[*ast.Object]struct{}{}
for _, f := range fields {
for _, id := range f.Names {
Expand Down

0 comments on commit cb89a4c

Please sign in to comment.