SHARE
TWEET

Untitled

a guest Oct 21st, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "go/ast"
  6.     "go/parser"
  7.     "go/token"
  8.     "os"
  9. )
  10.  
  11. func main() {
  12.     fileset := token.NewFileSet()
  13.     files, err := parser.ParseDir(fileset, "./testfiles", filterNothing, 0)
  14.     if err != nil {
  15.         panic(err)
  16.     }
  17.  
  18.     for filename, astPackage := range files {
  19.         fmt.Printf("directory: %+v\n", filename)
  20.         fmt.Printf("package: %+v\n", astPackage.Name)
  21.  
  22.         for filename, file := range astPackage.Files {
  23.             fmt.Printf("file: %s\n", filename)
  24.             for _, dec := range file.Decls {
  25.                 parseDec(dec)
  26.             }
  27.         }
  28.     }
  29. }
  30.  
  31. func parseDec(dec ast.Decl) {
  32.     switch decType := dec.(type) {
  33.     case *ast.GenDecl:
  34.         parseGenDecl(dec)
  35.     case *ast.FuncDecl:
  36.         parseFuncDecl(dec)
  37.     default:
  38.         panic(fmt.Sprintf("unsupported decType %s", decType))
  39.     }
  40. }
  41.  
  42. func parseFuncDecl(dec ast.Decl) {
  43.     funcDec := dec.(*ast.FuncDecl)
  44.     fmt.Printf("function definition for %s\n", funcDec.Name)
  45. }
  46.  
  47. func parseGenDecl(dec ast.Decl) {
  48.     typeDec := dec.(*ast.GenDecl)
  49.  
  50.     fmt.Printf("Token: %s\n", typeDec.Tok)
  51.     switch typeDec.Tok {
  52.     case token.TYPE:
  53.         fmt.Println("typedef")
  54.         for _, spec := range typeDec.Specs {
  55.             typeSpec := spec.(*ast.TypeSpec)
  56.             fmt.Printf("%+v", typeSpec)
  57.         }
  58.     case token.VAR:
  59.         fmt.Println("variable")
  60.     case token.CONST:
  61.         fmt.Println("constant")
  62.     default:
  63.         panic("unsupported type " + typeDec.Tok.String())
  64.     }
  65. }
  66.  
  67. func filterNothing(info os.FileInfo) bool {
  68.     return true
  69. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top