-
Notifications
You must be signed in to change notification settings - Fork 90
/
implemented.go
111 lines (94 loc) · 2.64 KB
/
implemented.go
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
103
104
105
106
107
108
109
110
111
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"strings"
)
// implementedFuncs returns list of Func which already implemented.
func implementedFuncs(fns []Func, recv string, srcDir string) (map[string]bool, error) {
// determine name of receiver type
recvType := getReceiverType(recv)
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, srcDir, nil, 0)
if err != nil {
return nil, err
}
implemented := make(map[string]bool)
// getReceiver returns title of struct to which belongs the method
getReceiver := func(mf *ast.FuncDecl) string {
if mf.Recv == nil {
return ""
}
for _, v := range mf.Recv.List {
switch xv := v.Type.(type) {
case *ast.StarExpr:
switch xxv := xv.X.(type) {
case *ast.Ident:
return xxv.Name
case *ast.IndexExpr: // type with one type parameter.
if si, ok := xxv.X.(*ast.Ident); ok {
return si.Name
}
case *ast.IndexListExpr: // type with mutiple type parameters.
if si, ok := xxv.X.(*ast.Ident); ok {
return si.Name
}
}
case *ast.Ident:
return xv.Name
}
}
return ""
}
// Convert fns to a map, to prevent accidental quadratic behavior.
want := make(map[string]bool)
for _, fn := range fns {
want[fn.Name] = true
}
// finder is a walker func which will be called for each element in the source code of package
// but we are interested in funcs only with receiver same to typeTitle
finder := func(n ast.Node) bool {
x, ok := n.(*ast.FuncDecl)
if !ok {
return true
}
if getReceiver(x) != recvType {
return true
}
name := x.Name.String()
if want[name] {
implemented[name] = true
}
return true
}
for _, pkg := range pkgs {
for _, f := range pkg.Files {
ast.Inspect(f, finder)
}
}
return implemented, nil
}
// getReceiverType returns type name of receiver or fatal if receiver is invalid.
// ex: for definition "r *SomeType" will return "SomeType"
func getReceiverType(recv string) string {
var recvType string
// VSCode adds a trailing space to receiver (it runs impl like: impl 'r *Receiver ' io.Writer)
// so we have to remove spaces.
recv = strings.TrimSpace(recv)
// Remove type parameters. They can contain spaces too, for example 'r *Receiver[T, U]'.
recv, _, _ = strings.Cut(recv, "[")
parts := strings.Split(recv, " ")
switch len(parts) {
case 1: // (SomeType)
recvType = parts[0]
case 2: // (x SomeType)
recvType = parts[1]
default:
fatal(fmt.Sprintf("invalid receiver: %q", recv))
}
// Pointer to receiver should be removed too for comparison purpose.
// But don't worry definition of default receiver won't be changed.
return strings.TrimPrefix(recvType, "*")
}