Skip to content

Instantly share code, notes, and snippets.

@zupzup
Created July 14, 2017 12:46
Show Gist options
  • Save zupzup/2c7d2baef1120933ef7b2f1360e2e5a0 to your computer and use it in GitHub Desktop.
Save zupzup/2c7d2baef1120933ef7b2f1360e2e5a0 to your computer and use it in GitHub Desktop.
Example for Basic AST Traversal in Go
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"log"
"os"
)
func main() {
fset := token.NewFileSet()
node, err := parser.ParseFile(fset, "test.go", nil, parser.ParseComments)
if err != nil {
log.Fatal(err)
}
fmt.Println("########### Manual Iteration ###########")
fmt.Println("Imports:")
for _, i := range node.Imports {
fmt.Println(i.Path.Value)
}
fmt.Println("Comments:")
for _, c := range node.Comments {
fmt.Print(c.Text())
}
fmt.Println("Functions:")
for _, f := range node.Decls {
fn, ok := f.(*ast.FuncDecl)
if !ok {
continue
}
fmt.Println(fn.Name.Name)
}
fmt.Println("########### Inspect ###########")
ast.Inspect(node, func(n ast.Node) bool {
// Find Return Statements
ret, ok := n.(*ast.ReturnStmt)
if ok {
fmt.Printf("return statement found on line %d:\n\t", fset.Position(ret.Pos()).Line)
printer.Fprint(os.Stdout, fset, ret)
return true
}
// Find Functions
fn, ok := n.(*ast.FuncDecl)
if ok {
var exported string
if fn.Name.IsExported() {
exported = "exported "
}
fmt.Printf("%sfunction declaration found on line %d: \n\t%s\n", exported, fset.Position(fn.Pos()).Line, fn.Name.Name)
return true
}
return true
})
fmt.Println()
}
package main
import "fmt"
import "strings"
func main() {
hello := "Hello"
world := "World"
words := []string{hello, world}
SayHello(words)
}
// SayHello says Hello
func SayHello(words []string) {
fmt.Println(joinStrings(words))
}
// joinStrings joins strings
func joinStrings(words []string) string {
return strings.Join(words, ", ")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment