github.com/chrislusf/greenpack@v3.7.1-0.20170911073826-ad5bd10b7c47+incompatible/cmd/addzid/gettype.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"go/ast"
     6  )
     7  
     8  // recursively extract the go type as a string
     9  func GetTypeAsString(ty ast.Expr, sofar string, goTypeSeq []string) (string, string, []string) {
    10  	//p("debug: in GetTypeAsSTring, ty = %#v", ty)
    11  	switch x := ty.(type) {
    12  
    13  	case (*ast.StarExpr):
    14  		return GetTypeAsString(ty.(*ast.StarExpr).X, sofar+"*", append(goTypeSeq, "*"))
    15  
    16  	case (*ast.Ident):
    17  		return sofar, ty.(*ast.Ident).Name, append(goTypeSeq, ty.(*ast.Ident).Name)
    18  
    19  	case (*ast.ArrayType):
    20  		// slice or array
    21  		return GetTypeAsString(ty.(*ast.ArrayType).Elt, sofar+"[]", append(goTypeSeq, "[]"))
    22  	case (*ast.SelectorExpr):
    23  		//p("debug: SelectorExpr case! x.X=%#v, x.Sel=%#v", x.X, x.Sel)
    24  		if ident, ok := x.X.(*ast.Ident); ok {
    25  			//p("debug: constructing '%s'", ident.Name+"."+x.Sel.Name)
    26  			return sofar, ident.Name + "." + x.Sel.Name, goTypeSeq
    27  		}
    28  	case (*ast.MapType):
    29  		//p("debug: MapType case! x.Key=%#v, x.Value=%#v", x.Key, x.Value)
    30  
    31  		_, k, _ := GetTypeAsString(x.Key, "", []string{})
    32  		_, v, _ := GetTypeAsString(x.Value, "", []string{})
    33  
    34  		m := fmt.Sprintf("map[%s]%s", k, v)
    35  		//p("debug: constructing m='%s' from k='%s', v='%s'", m, k, v)
    36  		return sofar, m, goTypeSeq
    37  	}
    38  
    39  	return sofar, "", goTypeSeq
    40  }