Inspired by ast matcher. There are four different basic categories of matchers:
- Node Matchers: Matchers that match a specific type of AST node.
- Attributive Matchers: Matchers that match attributes on AST nodes.
- Logical Matchers: Matchers that allow logic between matchers.
- Traversal Matchers: Matchers that allow traversal between AST nodes.
Find ‘ShortVarDecl’ from a file, and binding these to ‘bindID’.
package main
import (
"fmt"
"go/parser"
"go/printer"
"go/token"
"log"
"os"
"github.com/helloyi/goastch"
. "github.com/helloyi/goastch/goastcher"
)
func main() {
g := HasDescendant(ShortVarDecl(Anything()).Bind("bindID"))
src := `package foo
func bar() {
a := []int{}
var b []int
c := []string{}
}`
fset := token.NewFileSet()
file, _ := parser.ParseFile(fset, "example", src, 0)
bindings, err := goastch.Find(file, nil, g)
if err != nil {
log.Fatalln(err)
}
for key, list := range bindings {
for _, node := range list {
fmt.Printf("%s: ", key)
_ = printer.Fprint(os.Stdout, fset, node)
fmt.Println()
}
}
}