1
0
mirror of https://github.com/mgechev/revive.git synced 2025-11-25 22:12:38 +02:00

refactor: replaces calls to astutils.PickNodes with calls to astutils.SeekNode when possible (#1482)

This commit is contained in:
chavacava
2025-08-23 17:41:10 +02:00
committed by GitHub
parent ccf85a25e5
commit cf4901574e
7 changed files with 58 additions and 17 deletions

View File

@@ -152,6 +152,49 @@ func (p picker) Visit(node ast.Node) ast.Visitor {
return p
}
// SeekNode yields the first node selected by the given selector function in the AST subtree with root n.
// The function returns nil if no matching node is found in the subtree.
func SeekNode[T ast.Node](n ast.Node, selector func(n ast.Node) bool) T {
var result T
if n == nil {
return result
}
if selector == nil {
return result
}
onSelect := func(n ast.Node) {
result, _ = n.(T)
}
p := &seeker{selector: selector, onSelect: onSelect, found: false}
ast.Walk(p, n)
return result
}
type seeker struct {
selector func(n ast.Node) bool
onSelect func(n ast.Node)
found bool
}
func (s *seeker) Visit(node ast.Node) ast.Visitor {
if s.found {
return nil // stop visiting subtree
}
if s.selector(node) {
s.onSelect(node)
s.found = true
return nil // skip visiting node children
}
return s
}
var gofmtConfig = &printer.Config{Tabwidth: 8}
// GoFmt returns a string representation of an AST subtree.