-
Notifications
You must be signed in to change notification settings - Fork 7
/
implementations.go
320 lines (263 loc) · 8.33 KB
/
implementations.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package impls
import (
"fmt"
"go/ast"
"go/types"
"strings"
"github.com/sourcegraph/scip-go/internal/handler"
"github.com/sourcegraph/scip-go/internal/loader"
"github.com/sourcegraph/scip-go/internal/lookup"
"github.com/sourcegraph/scip-go/internal/output"
"github.com/sourcegraph/scip/bindings/go/scip"
"golang.org/x/tools/container/intsets"
"golang.org/x/tools/go/packages"
)
type canonicalMethod string
type scipSymbol string
type ImplDef struct {
// The corresponding scip symbol, generated via previous iteration over the AST
Symbol *scip.SymbolInformation
Pkg *packages.Package
Ident *ast.Ident
Methods map[canonicalMethod]*scip.SymbolInformation
// IsExportedIdent bool
// IsExportedType bool
// IsAliasType bool
}
func findImplementations(concreteTypes map[string]ImplDef, interfaces map[string]ImplDef, symbols *lookup.Global) {
// Create a unique mapping of method -> int
// Then we'll use sparse sets to lookup whether things duck type or not
allMethods := map[canonicalMethod]int{}
for _, iface := range interfaces {
for method := range iface.Methods {
if _, ok := allMethods[method]; !ok {
allMethods[method] = len(allMethods)
}
}
}
for _, ty := range concreteTypes {
for method := range ty.Methods {
if _, ok := allMethods[method]; !ok {
allMethods[method] = len(allMethods)
}
}
}
// Create a map of method names to corresponding interfaces
interfaceToMethodSet := map[*scip.SymbolInformation]*intsets.Sparse{}
for _, iface := range interfaces {
if iface.Ident == nil {
continue
}
methodSet := &intsets.Sparse{}
for method := range iface.Methods {
methodSet.Insert(allMethods[method])
}
interfaceToMethodSet[iface.Symbol] = methodSet
}
for _, ty := range concreteTypes {
pos := ty.Ident.Pos()
sym, ok := symbols.GetSymbolInformation(ty.Pkg, pos)
if !ok {
panic(fmt.Sprintf("Could not find symbol for %s", ty.Symbol))
}
methodSet := &intsets.Sparse{}
for method := range ty.Methods {
methodSet.Insert(allMethods[method])
}
tyImpls := implementationsForType(ty, methodSet, interfaceToMethodSet)
for _, impl := range tyImpls {
implDef, ok := interfaces[impl.Symbol]
if !ok {
fmt.Println(fmt.Sprintf("Could not find interface %s", impl.Symbol))
continue
}
// Add implementation details for the struct & interface relationship
sym.Relationships = append(sym.Relationships, &scip.Relationship{
Symbol: impl.Symbol,
IsImplementation: true,
})
// For all methods, add imlementation details as well
for name, implMethod := range implDef.Methods {
tyMethodInfo, ok := ty.Methods[name]
if !ok {
continue
}
tyMethodInfo.Relationships = append(tyMethodInfo.Relationships, &scip.Relationship{
Symbol: implMethod.Symbol,
IsImplementation: true,
})
}
}
}
}
func AddImplementationRelationships(pkgs loader.PackageLookup, allPackages loader.PackageLookup, symbols *lookup.Global) {
output.WithProgress("Indexing Implementations", func() error {
localInterfaces, localTypes, err := extractInterfacesAndConcreteTypes(pkgs, symbols)
if err != nil {
return err
}
remotePackages := make(loader.PackageLookup)
for pkgID, pkg := range allPackages {
if _, ok := pkgs[pkgID]; ok {
continue
}
remotePackages[pkgID] = pkg
}
remoteInterfaces, _, err := extractInterfacesAndConcreteTypes(remotePackages, symbols)
if err != nil {
return err
}
// local type -> local interface
findImplementations(localTypes, localInterfaces, symbols)
// local type -> remote interface
findImplementations(localTypes, remoteInterfaces, symbols)
// TODO(author: tjdevries, issue: https://github.com/sourcegraph/scip-go/issues/64)
// We should consider what this would even look like?
// I don't think this makes sense the current way that we are emitting
// implementations. You wouldn't even catch these anyways when uploading
// remote type -> local interface
// findImplementations(remoteTypes, localInterfaces, symbols)
return nil
})
}
func implementationsForType(ty ImplDef, tyMethods *intsets.Sparse, interfaceToMethodSet map[*scip.SymbolInformation]*intsets.Sparse) (matching []*scip.SymbolInformation) {
// Empty type - skip it.
if len(ty.Methods) == 0 {
return
}
for symbol, methods := range interfaceToMethodSet {
if methods.SubsetOf(tyMethods) {
matching = append(matching, symbol)
}
}
return matching
}
func extractInterfacesAndConcreteTypes(pkgs loader.PackageLookup, symbols *lookup.Global) (interfaces map[string]ImplDef, concreteTypes map[string]ImplDef, err error) {
interfaces = map[string]ImplDef{}
concreteTypes = map[string]ImplDef{}
for _, pkg := range pkgs {
// Builtin isn't the same as standard library, that is for builtin types
// We don't need to check those for implemenations.
if pkg.Name == "builtin" {
continue
}
if pkg == nil || pkg.TypesInfo == nil {
panic(fmt.Sprintf("nill types info %s", pkg.Name))
}
pkgSymbols := symbols.GetPackage(pkg)
if pkgSymbols == nil {
fmt.Println("No symbols for package:", pkg.Name)
continue
}
for ident, obj := range pkg.TypesInfo.Defs {
if obj == nil {
continue
}
// fmt.Printf("extracting: %s %s %T\n", ident.Name, obj.Name(), obj)
// We ignore aliases 'type M = N' to avoid duplicate reporting
// of the Named type N.
obj, ok := obj.(*types.TypeName)
if !ok {
continue
}
objType, ok := obj.Type().(*types.Named)
if !ok {
continue
}
symbol, ok := pkgSymbols.Get(obj.Pos())
if !ok {
if obj.Exported() {
handler.Println("No symbol for:", ident.Name, obj.Pkg(), obj.Id())
}
continue
}
methods := listMethods(objType)
// ignore interfaces that are empty. they are too
// plentiful and don't provide useful intelligence.
if len(methods) == 0 {
continue
}
canonicalizedMethods := map[canonicalMethod]*scip.SymbolInformation{}
for _, m := range methods {
// sym, ok := pkgSymbols.Get(m.Obj().Pos())
sym, ok, err := symbols.GetSymbolOfObject(m.Obj())
if err != nil {
handler.ErrOrPanic("Error while looking for symbol %s | %s", err, m.Obj())
continue
}
if !ok {
// panic(fmt.Sprintf("Could not find symbol for %s", m.Obj()))
continue
}
canonicalizedMethods[canonicalizeMethod(m)] = sym
}
d := ImplDef{
Symbol: symbol,
Pkg: pkg,
Ident: ident,
Methods: canonicalizedMethods,
}
if types.IsInterface(objType) {
interfaces[d.Symbol.Symbol] = d
} else {
concreteTypes[d.Symbol.Symbol] = d
}
}
}
return
}
// listMethods returns the method set for a named type T
// merged with all the methods of *T that have different names than
// the methods of T.
//
// Copied from https://github.com/golang/tools/blob/1a7ca93429f83e087f7d44d35c0e9ea088fc722e/cmd/godex/print.go#L355
func listMethods(T *types.Named) []*types.Selection {
// method set for T
mset := types.NewMethodSet(T)
var res []*types.Selection
for i, n := 0, mset.Len(); i < n; i++ {
res = append(res, mset.At(i))
}
// add all *T methods with names different from T methods
pmset := types.NewMethodSet(types.NewPointer(T))
for i, n := 0, pmset.Len(); i < n; i++ {
pm := pmset.At(i)
if obj := pm.Obj(); mset.Lookup(obj.Pkg(), obj.Name()) == nil {
res = append(res, pm)
}
}
return res
}
// Returns a string representation of a method that can be used as a key for finding matches in interfaces.
func canonicalizeMethod(m *types.Selection) canonicalMethod {
builder := strings.Builder{}
writeTuple := func(t *types.Tuple) {
for i := 0; i < t.Len(); i++ {
builder.WriteString(t.At(i).Type().String())
}
}
signature := m.Type().(*types.Signature)
// if an object is not exported, then we need to make the canonical
// representation of the object not able to match any other representations
if !m.Obj().Exported() {
builder.WriteString(m.Obj().Pkg().Path())
builder.WriteString(":")
}
builder.WriteString(m.Obj().Name())
builder.WriteString("(")
writeTuple(signature.Params())
builder.WriteString(")")
returnTypes := signature.Results()
returnLen := returnTypes.Len()
if returnLen == 0 {
// Don't add anything
} else if returnLen == 1 {
builder.WriteString(" ")
writeTuple(returnTypes)
} else {
builder.WriteString(" (")
writeTuple(returnTypes)
builder.WriteString(")")
}
return canonicalMethod(builder.String())
}