Golang go/ast.GenDecl type examples

package go/ast

A GenDecl node (generic declaration node) represents an import, constant, type or variable declaration. A valid Lparen position (Lparen.Line > 0) indicates a parenthesized declaration.

Golang go/ast.GenDecl type usage examples

Example 1:

 func getExportedDeclarationsForFile(path string) ([]string, error) {
  fset := token.NewFileSet()
  tree, err := parser.ParseFile(fset, path, nil, 0)
  if err != nil {
 return []string{}, err
  }
  declarations := []string{}
  ast.FileExports(tree)
  for _, decl := range tree.Decls {
 switch x := decl.(type) {
 case *ast.GenDecl:
 switch s := x.Specs[0].(type) {
 case *ast.ValueSpec:
 declarations = append(declarations, s.Names[0].Name)
 }
 case *ast.FuncDecl:
 declarations = append(declarations, x.Name.Name)
 }
  }
  return declarations, nil
 }

Example 2:

 func importsForRootNode(rootNode *ast.File) (imports *ast.GenDecl, err error) {
  for _, declaration := range rootNode.Decls {
 decl, ok := declaration.(*ast.GenDecl)
 if !ok || len(decl.Specs) == 0 {
 continue
 }
 _, ok = decl.Specs[0].(*ast.ImportSpec)
 if ok {
 imports = decl
 return
 }
  }
  err = errors.New(fmt.Sprintf("Could not find imports for root node:\n\t%#v\n", rootNode))
  return
 }

References :

https://github.com/onsi/ginkgo/blob/master/ginkgo/nodot/nodot.go

https://github.com/onsi/ginkgo/blob/master/ginkgo/convert/import.go

http://golang.org/pkg/go/ast/#GenDecl

Advertisement