// 61 }
}
+func ExamplePreorder() {
+ src := `
+package p
+
+func f(x, y int) {
+ print(x + y)
+}
+`
+
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, "", src, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ // Print identifiers in order
+ for n := range ast.Preorder(f) {
+ id, ok := n.(*ast.Ident)
+ if !ok {
+ continue
+ }
+ fmt.Println(id.Name)
+ }
+
+ // Output:
+ // p
+ // f
+ // x
+ // y
+ // int
+ // print
+ // x
+ // y
+}
+
// This example illustrates how to remove a variable declaration
// in a Go program while maintaining correct comment association
// using an ast.CommentMap.
package ast
-import "fmt"
+import (
+ "fmt"
+ "iter"
+)
// A Visitor's Visit method is invoked for each node encountered by [Walk].
// If the result visitor w is not nil, [Walk] visits each of the children
func Inspect(node Node, f func(Node) bool) {
Walk(inspector(f), node)
}
+
+// Preorder returns an iterator over all the nodes of the syntax tree
+// beneath (and including) the specified root, in depth-first
+// preorder.
+//
+// For greater control over the traversal of each subtree, use [Inspect].
+func Preorder(root Node) iter.Seq[Node] {
+ return func(yield func(Node) bool) {
+ ok := true
+ Inspect(root, func(n Node) bool {
+ if n != nil && !yield(n) {
+ ok = false
+ }
+ return ok
+ })
+ }
+}