Created
June 26, 2016 20:07
-
-
Save huytd/3e871dbdf2a4a91c64dcd76e0c534eba to your computer and use it in GitHub Desktop.
Parse code using AST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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