-
Notifications
You must be signed in to change notification settings - Fork 17.8k
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
go/ast: add Preorder 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:
|
Based on the discussion above, this proposal seems like a likely accept. The proposal is to add:
|
No change in consensus, so accepted. 🎉 The proposal is to add:
|
Change https://go.dev/cl/585520 mentions this issue: |
Once yield returns false, ast.Preorder must not call yield on any more nodes. Even after the function passed to ast.Inspect returns false, it may be invoked again with a non-nil node. Therefore, we must explicitly truncate the inspection. For #66339 Change-Id: I2b01e4e96a2d7aca785467c15ab59da13208c161 Reviewed-on: https://go-review.googlesource.com/c/go/+/585520 Reviewed-by: Alan Donovan <[email protected]> Reviewed-by: Robert Griesemer <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]>
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: