ast: gettings fields of an embedded type from another package (SelectorExpr)

307 views
Skip to first unread message

bsr

unread,
Nov 2, 2015, 10:56:26 PM11/2/15
to golang-nuts
Hello,

I am trying to use go generate with an embedded type, which is imported from another package. But, I am not sure how to walk further the AST.

package "one"

type Entity struct {
  Id string
}

//-------------------

package "two"

import "one"
  
type Person struct {
  one.Entity
  Name string
}



func buildField(expr ast.Expr, name string) error {
  switch ident := expr.(type) {
case *ast.Ident:
        ...
        case *ast.SelectorExpr:
if pkgIdent, ok := ident.X.(*ast.Ident); ok {
                 
                   println(pkgIdent.Name, ident.Sel.Name)   //=> "one" "entity"

                  // how to get struct entity and its fields (Id) from here ??
       }
 }

}

one I get an external package and the type info  as shown above, how to get the fields in Entity type which is in another package?

any pointers to help me proceed is appreciated.

thanks.
bsr

bsr

unread,
Nov 3, 2015, 9:07:05 AM11/3/15
to golang-nuts
I guess I need to parse the file contained the embedded type and not available in "SelectorExpr". Please let me know otherwise.

adon...@google.com

unread,
Nov 3, 2015, 4:59:29 PM11/3/15
to golang-nuts
You can't do that without the type checker, go/types.  Take a look at the golang.org/x/tools/cmd/gorename tool for an example of how to traverse type-checked ASTs.
Reply all
Reply to author
Forward
0 new messages