-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinterface.go
More file actions
102 lines (88 loc) · 2.76 KB
/
Copy pathinterface.go
File metadata and controls
102 lines (88 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package aster
import (
"fmt"
"go/ast"
"strings"
)
type InterfaceType struct {
PackageType *PackageType
Name string `json:",omitempty"`
Funcs []*InterfaceFuncType
Docs []Comment
}
func (pkgType *PackageType) NewInterfaceType(astGenDecl *ast.GenDecl, typeSpec *ast.TypeSpec, astInterface *ast.InterfaceType) (*InterfaceType, error) {
interfaceType := &InterfaceType{
PackageType: pkgType,
Name: typeSpec.Name.String(),
}
if astInterface.Methods != nil {
interfaceType.Funcs = make([]*InterfaceFuncType, 0, astInterface.Methods.NumFields())
for _, methodField := range astInterface.Methods.List {
switch astExpr := methodField.Type.(type) {
case *ast.FuncType:
err := interfaceType.ParseInterfaceFuncType(methodField, astExpr)
if err != nil {
return nil, err
}
case *ast.Ident:
// 嵌入自己包的接口
// 在interface中嵌入的子interface
// TODO: 会导致无法拿到Interface的所有方法,需要额外处理。
// fmt.Println("NewInterfaceType(): 在interface中嵌入的子interface,会导致无法拿到Interface的所有方法,需要额外处理。")
case *ast.SelectorExpr:
// 嵌入其他包的接口
// 在interface中嵌入的子interface
// TODO: 会导致无法拿到Interface的所有方法,需要额外处理。
// fmt.Println("NewInterfaceType(): 在interface中嵌入的子interface,会导致无法拿到Interface的所有方法,需要额外处理。")
default:
return nil, fmt.Errorf("NewInterfaceType()未处理的MethodField: %T", astExpr)
}
}
}
if astGenDecl.Doc != nil {
interfaceType.Docs = make([]Comment, 0, len(astGenDecl.Doc.List))
for _, doc := range astGenDecl.Doc.List {
interfaceType.Docs = append(interfaceType.Docs, doc.Text)
}
}
return interfaceType, nil
}
func (this *InterfaceType) ParseInterfaceFuncType(astField *ast.Field, astFuncType *ast.FuncType) error {
funcType, err := NewInterfaceFuncType(astField, astFuncType)
if err == nil {
this.Funcs = append(this.Funcs, funcType)
}
return err
}
func (this *InterfaceType) String() string {
sb := strings.Builder{}
for _, doc := range this.Docs {
sb.WriteString(doc)
}
sb.WriteString("type " + this.Name + " interface {\n")
for _, fun := range this.Funcs {
sb.WriteString("\t" + fun.Name + "(")
for i, paramType := range fun.Params {
sb.WriteString(paramType.GetDecl())
if i < len(fun.Params)-1 {
sb.WriteString(", ")
}
}
sb.WriteString(") ")
if len(fun.Results) > 1 {
sb.WriteString("(")
}
for i, resultType := range fun.Results {
sb.WriteString(resultType.GetDecl())
if i < len(fun.Results)-1 {
sb.WriteString(", ")
}
}
if len(fun.Results) > 1 {
sb.WriteString(")")
}
sb.WriteString("\n")
}
sb.WriteString("}\n")
return sb.String()
}