New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: go/ast: add DepthFirst iterator #66339
Comments
Change https://go.dev/cl/570680 mentions this issue: |
For the curious, it adds 10-15% to the cost of a trivial traversal. package ast_test
import (
"go/ast"
"go/parser"
"go/token"
"testing"
)
var file *ast.File
func init() {
file, _ = parser.ParseFile(token.NewFileSet(), "ast.go", nil, 0)
}
const k = 2
func BenchmarkInspect(b *testing.B) {
total := 0
for range b.N {
var nodes []ast.Node
ast.Inspect(file, func(n ast.Node) bool {
if n != nil {
total++
if total%k == 0 {
nodes = append(nodes, n)
}
}
return true
})
}
}
func BenchmarkRange(b *testing.B) {
total := 0
for range b.N {
var nodes []ast.Node
for n := range ast.DepthFirst(file) {
total++
if total%k == 0 {
nodes = append(nodes, n)
}
}
}
} |
This proposal has been added to the active column of the proposals project |
The name DepthFirst doesn't indicate whether its Preorder or Postorder. It sounds like we should call it Preorder. |
Have all remaining concerns about this proposal been addressed? The proposal is to add:
|
Proposal Details
Programs that use
go/ast
often need to make traversals over the tree to find all nodes of a given type (or types), or to search for a specific node. The existingast.Inspect
function allows them to do this, but it can impose a significant syntactic overhead. This example shows a use of Inspect to print the first interesting node, aborting the traversal once the node is found:We propose to add this function to go/ast:
which would allow the previous example to be simplified to:
cc @findleyr @griesemer
The text was updated successfully, but these errors were encountered: