Skip to content

Instantly share code, notes, and snippets.

@huytd
Created June 26, 2016 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huytd/3e871dbdf2a4a91c64dcd76e0c534eba to your computer and use it in GitHub Desktop.
Save huytd/3e871dbdf2a4a91c64dcd76e0c534eba to your computer and use it in GitHub Desktop.
Parse code using AST
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func main() {
src := `package main
import (
"log"
"fmt"
)
func a() {
print("Yo")
}
func e() {
print("Lele")
}
a := 1
b := 2
print(a + b)
println("Hello World")
`
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", src, 0)
if err != nil {
print("ERROR: ", err.Error())
}
ast.Print(fset, f)
for _, section := range f.Decls {
if section, ok := section.(*ast.GenDecl); ok {
fmt.Println("-=> ", section.Tok)
}
if section, ok := section.(*ast.FuncDecl); ok {
fmt.Println("-=> func ", section.Name.Name, " - from: ", section.Type.Params.Opening, " to: ", section.Type.Params.Closing)
}
if section, ok := section.(*ast.BadDecl); ok {
fmt.Println("-=> Main from: ", section.From, " to: ", section.To)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment