goast/util.go

54 lines
1.4 KiB
Go

package goast
import "go/ast"
// getKVFromImportSpec get import name and package path from *ast.ImportSpec
func getKVFromImportSpec(impt *ast.ImportSpec) (string, string) {
var name string
if impt.Name != nil {
name = impt.Name.Name
}
pkg := impt.Path.Value
return name, pkg
}
// getKVFromValueSpec get const/variable name and value from *ast.ValueSpec
func getKVFromValueSpec(spec *ast.ValueSpec) (string, string) {
name := spec.Names[0].Name
var value string
switch spec.Values[0].(type) {
case *ast.BasicLit:
value = spec.Values[0].(*ast.BasicLit).Value
case *ast.CallExpr:
value = "@call"
}
return name, value
}
// getKVFromTypeSpec get type name and base type from *ast.TypeSpec
func getKVFromTypeSpec(spec *ast.TypeSpec) (string, string) {
name := spec.Name.Name
var value string
switch spec.Type.(type) {
case *ast.Ident:
value = spec.Type.(*ast.Ident).Name
case *ast.StructType:
value = "@raw"
}
return name, value
}
// getMethodNameFromReceiveField get method type and receiver name from Recv field
func getMethodNameFromReceiveField(recv *ast.FieldList) (string, string) {
var methodType, receiver string
switch recv.List[0].Type.(type) {
case *ast.Ident:
methodType = recv.List[0].Type.(*ast.Ident).Name
case *ast.StarExpr:
methodType = recv.List[0].Type.(*ast.StarExpr).X.(*ast.Ident).Name
}
receiver = recv.List[0].Names[0].Name
return methodType, receiver
}