From cb89a4cc78c225c1c07e474f37ea3daa2942a4cc Mon Sep 17 00:00:00 2001 From: chavacava Date: Sat, 7 Dec 2024 11:49:13 +0100 Subject: [PATCH] refactor (rule/datarace): replace AST walker by iteration over declarations (#1162) --- rule/datarace.go | 61 ++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 33 deletions(-) diff --git a/rule/datarace.go b/rule/datarace.go index 21a7a706e..d95775d91 100644 --- a/rule/datarace.go +++ b/rule/datarace.go @@ -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 {