Skip to content

Commit

Permalink
Inspect and Preorder for walking (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
UnstoppableMango authored Feb 11, 2025
1 parent 85c58db commit caee8f5
Show file tree
Hide file tree
Showing 2 changed files with 592 additions and 1 deletion.
32 changes: 31 additions & 1 deletion ast/walk.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package ast

import "go/ast"
import (
"go/ast"
"iter"
)

type Visitor = ast.Visitor

Expand Down Expand Up @@ -48,3 +51,30 @@ func Walk(v Visitor, node Node) {
walkList(v, n.Else)
}
}

type inspector func(Node) bool

// Visit implements ast.Visitor.
func (i inspector) Visit(node ast.Node) (w ast.Visitor) {
if i(node) {
return i
} else {
return nil
}
}

func Inspect(node Node, f func(Node) bool) {
Walk(inspector(f), node)
}

func Preorder(root Node) iter.Seq[Node] {
return func(yield func(Node) bool) {
ok := true
Inspect(root, func(n Node) bool {
if n != nil {
ok = ok && yield(n)
}
return ok
})
}
}
Loading

0 comments on commit caee8f5

Please sign in to comment.