| 1 | // Copyright 2023 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package methodsets defines an incremental, serializable index of |
| 6 | // method-set information that allows efficient 'implements' queries |
| 7 | // across packages of the workspace without using the type checker. |
| 8 | // |
| 9 | // This package provides only the "global" (all workspace) search; the |
| 10 | // "local" search within a given package uses a different |
| 11 | // implementation based on type-checker data structures for a single |
| 12 | // package plus variants; see ../implementation.go. |
| 13 | // The local algorithm is more precise as it tests function-local types too. |
| 14 | // |
| 15 | // A global index of function-local types is challenging since they |
| 16 | // may reference other local types, for which we would need to invent |
| 17 | // stable names, an unsolved problem described in passing in Go issue |
| 18 | // 57497. The global algorithm also does not index anonymous interface |
| 19 | // types, even outside function bodies. |
| 20 | // |
| 21 | // Consequently, global results are not symmetric: applying the |
| 22 | // operation twice may not get you back where you started. |
| 23 | package methodsets |
| 24 | |
| 25 | // DESIGN |
| 26 | // |
| 27 | // See https://go.dev/cl/452060 for a minimal exposition of the algorithm. |
| 28 | // |
| 29 | // For each method, we compute a fingerprint: a string representing |
| 30 | // the method name and type such that equal fingerprint strings mean |
| 31 | // identical method types. |
| 32 | // |
| 33 | // For efficiency, the fingerprint is reduced to a single bit |
| 34 | // of a uint64, so that the method set can be represented as |
| 35 | // the union of those method bits (a uint64 bitmask). |
| 36 | // Assignability thus reduces to a subset check on bitmasks |
| 37 | // followed by equality checks on fingerprints. |
| 38 | // |
| 39 | // In earlier experiments, using 128-bit masks instead of 64 reduced |
| 40 | // the number of candidates by about 2x. Using (like a Bloom filter) a |
| 41 | // different hash function to compute a second 64-bit mask and |
| 42 | // performing a second mask test reduced it by about 4x. |
| 43 | // Neither had much effect on the running time, presumably because a |
| 44 | // single 64-bit mask is quite effective. See CL 452060 for details. |
| 45 | |
| 46 | import ( |
| 47 | "go/token" |
| 48 | "go/types" |
| 49 | "hash/crc32" |
| 50 | "slices" |
| 51 | "sync" |
| 52 | "sync/atomic" |
| 53 | |
| 54 | "golang.org/x/tools/go/types/objectpath" |
| 55 | "golang.org/x/tools/gopls/internal/cache/metadata" |
| 56 | "golang.org/x/tools/gopls/internal/util/fingerprint" |
| 57 | "golang.org/x/tools/gopls/internal/util/frob" |
| 58 | "golang.org/x/tools/gopls/internal/util/safetoken" |
| 59 | ) |
| 60 | |
| 61 | // An Index records the non-empty method sets of all package-level |
| 62 | // types in a package in a form that permits assignability queries |
| 63 | // without the type checker. |
| 64 | type Index struct { |
| 65 | pkg gobPackage |
| 66 | PkgPath metadata.PackagePath |
| 67 | |
| 68 | // byObjectPath maps the object path of each method declared in |
| 69 | // this package to its position, for use by [Index.LocationOf]. |
| 70 | // It is derived from pkg (no external data needed) and built |
| 71 | // lazily on the first LocationOf call, since few packages are |
| 72 | // ever the target of a cross-package lookup but a single package |
| 73 | // may be queried many times (and may have a very large method |
| 74 | // set, so a linear scan per call would be costly). |
| 75 | byObjectPathOnce sync.Once |
| 76 | byObjectPath map[string]gobPosition |
| 77 | } |
| 78 | |
| 79 | // Decode decodes the given gob-encoded data as an Index. |
| 80 | func Decode(pkgpath metadata.PackagePath, data []byte) *Index { |
| 81 | return &Index{pkg: packageCodec.Decode(data), PkgPath: pkgpath} |
| 82 | } |
| 83 | |
| 84 | // Encode encodes the receiver as gob-encoded data. |
| 85 | func (index *Index) Encode() []byte { |
| 86 | return packageCodec.Encode(index.pkg) |
| 87 | } |
| 88 | |
| 89 | // NewIndex returns a new index of method-set information for all |
| 90 | // package-level types in the specified package. |
| 91 | func NewIndex(fset *token.FileSet, pkg *types.Package) *Index { |
| 92 | return new(indexBuilder).build(fset, pkg) |
| 93 | } |
| 94 | |
| 95 | // A Location records the extent of an identifier in byte-offset form. |
| 96 | // |
| 97 | // Conversion to protocol (UTF-16) form is done by the caller after a |
| 98 | // search, not during index construction. |
| 99 | type Location struct { |
| 100 | Filename string |
| 101 | Start, End int // byte offsets |
| 102 | } |
| 103 | |
| 104 | // A Key represents the method set of a given type in a form suitable |
| 105 | // to pass to the (*Index).Search method of many different Indexes. |
| 106 | type Key struct { |
| 107 | mset *gobMethodSet // note: lacks position information |
| 108 | } |
| 109 | |
| 110 | // KeyOf returns the search key for the method sets of a given type. |
| 111 | // It returns false if the type has no methods. |
| 112 | func KeyOf(t types.Type) (Key, bool) { |
| 113 | mset := methodSetInfo(t, nil) |
| 114 | if mset.Mask == 0 { |
| 115 | return Key{}, false // no methods |
| 116 | } |
| 117 | return Key{mset}, true |
| 118 | } |
| 119 | |
| 120 | // A Result reports a matching type or method in a method-set search. |
| 121 | type Result struct { |
| 122 | TypeName string // name of the named type |
| 123 | IsInterface bool // matched type (or method) is abstract |
| 124 | // Location is the location of the type or method declaration. |
| 125 | // For a method promoted from another package via embedding, Location |
| 126 | // is zero; the caller must resolve it via (PkgPath, ObjectPath), |
| 127 | // for example using [Index.LocationOf] on the declaring package's index. |
| 128 | Location Location |
| 129 | |
| 130 | // methods only: |
| 131 | PkgPath string // path of declaring package (may differ due to embedding) |
| 132 | ObjectPath objectpath.Path // path of method within declaring package |
| 133 | } |
| 134 | |
| 135 | // TypeRelation indicates the direction of subtyping relation, |
| 136 | // if any, between two types. |
| 137 | // |
| 138 | // It is a bitset, so that clients of Implementations may use |
| 139 | // Supertype|Subtype to request an undirected match. |
| 140 | type TypeRelation int8 |
| 141 | |
| 142 | const ( |
| 143 | Supertype TypeRelation = 0x1 |
| 144 | Subtype TypeRelation = 0x2 |
| 145 | ) |
| 146 | |
| 147 | // Search reports each type that implements (Supertype ∈ want) or is |
| 148 | // implemented by (Subtype ∈ want) the type that produced the search key. |
| 149 | // |
| 150 | // If method is non-nil, only that method of each type is reported. |
| 151 | // |
| 152 | // The result does not include the error.Error method. |
| 153 | // TODO(adonovan): give this special case a more systematic treatment. |
| 154 | func (index *Index) Search(key Key, want TypeRelation, method *types.Func) []Result { |
| 155 | var results []Result |
| 156 | for _, candidate := range index.pkg.MethodSets { |
| 157 | // Test the direction of the relation. |
| 158 | // The client may request either direction or both |
| 159 | // (e.g. when the client is References), |
| 160 | // and the Result reports each test independently; |
| 161 | // both tests succeed when comparing identical |
| 162 | // interface types. |
| 163 | var got TypeRelation |
| 164 | if want&Subtype != 0 && implements(candidate, key.mset) { |
| 165 | got |= Subtype |
| 166 | } |
| 167 | if want&Supertype != 0 && implements(key.mset, candidate) { |
| 168 | got |= Supertype |
| 169 | } |
| 170 | if got == 0 { |
| 171 | continue |
| 172 | } |
| 173 | |
| 174 | typeName := index.pkg.Strings[candidate.TypeName] |
| 175 | if method == nil { |
| 176 | results = append(results, Result{ |
| 177 | TypeName: typeName, |
| 178 | IsInterface: candidate.IsInterface, |
| 179 | Location: index.location(candidate.Posn), |
| 180 | }) |
| 181 | } else { |
| 182 | for _, m := range candidate.Methods { |
| 183 | if m.ID == method.Id() { |
| 184 | // Don't report error.Error among the results: |
| 185 | // it has no true source location, no package, |
| 186 | // and is excluded from the xrefs index. |
| 187 | if m.PkgPath == 0 || m.ObjectPath == 0 { |
| 188 | if m.ID != "Error" { |
| 189 | panic("missing info for" + m.ID) |
| 190 | } |
| 191 | continue |
| 192 | } |
| 193 | |
| 194 | results = append(results, Result{ |
| 195 | TypeName: typeName, |
| 196 | IsInterface: candidate.IsInterface, |
| 197 | Location: index.location(m.Posn), |
| 198 | PkgPath: index.pkg.Strings[m.PkgPath], |
| 199 | ObjectPath: objectpath.Path(index.pkg.Strings[m.ObjectPath]), |
| 200 | }) |
| 201 | break |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | return results |
| 207 | } |
| 208 | |
| 209 | // implements reports whether x implements y. |
| 210 | func implements(x, y *gobMethodSet) bool { |
| 211 | if !y.IsInterface { |
| 212 | return false |
| 213 | } |
| 214 | |
| 215 | // Fast path: neither method set is tricky, so all methods can |
| 216 | // be compared by equality of ID and Fingerprint, and the |
| 217 | // entire subset check can be done using the bit mask. |
| 218 | if !x.Tricky && !y.Tricky { |
| 219 | if x.Mask&y.Mask != y.Mask { |
| 220 | return false // x lacks a method of interface y |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | // At least one operand is tricky (e.g. contains a type parameter), |
| 225 | // so we must used tree-based matching (unification). |
| 226 | |
| 227 | // nonmatching reports whether interface method 'my' lacks |
| 228 | // a matching method in set x. (The sense is inverted for use |
| 229 | // with slice.ContainsFunc below.) |
| 230 | nonmatching := func(my *gobMethod) bool { |
| 231 | for _, mx := range x.Methods { |
| 232 | if mx.ID == my.ID { |
| 233 | var match bool |
| 234 | if !mx.Tricky && !my.Tricky { |
| 235 | // Fast path: neither method is tricky, |
| 236 | // so a string match is sufficient. |
| 237 | match = mx.Sum&my.Sum == my.Sum && mx.Fingerprint == my.Fingerprint |
| 238 | } else { |
| 239 | match = fingerprint.Matches(mx.parse(), my.parse()) |
| 240 | } |
| 241 | return !match |
| 242 | } |
| 243 | } |
| 244 | return true // method of y not found in x |
| 245 | } |
| 246 | |
| 247 | // Each interface method must have a match. |
| 248 | // (This would be more readable with a DeMorganized |
| 249 | // variant of ContainsFunc.) |
| 250 | return !slices.ContainsFunc(y.Methods, nonmatching) |
| 251 | } |
| 252 | |
| 253 | func (index *Index) location(posn gobPosition) Location { |
| 254 | return Location{ |
| 255 | Filename: index.pkg.Strings[posn.File], |
| 256 | Start: posn.Offset, |
| 257 | End: posn.Offset + posn.Len, |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | // LocationOf returns the location of the method declared in this |
| 262 | // package with the given object path, if any. |
| 263 | // |
| 264 | // It is used to resolve the location of a method promoted via |
| 265 | // embedding from another package: the embedding package's index |
| 266 | // records only (PkgPath, ObjectPath) for such a method, and the |
| 267 | // caller looks up the position here in the declaring package's |
| 268 | // index, where it is keyed by this package's own file contents |
| 269 | // (and so correctly invalidated when those contents change). |
| 270 | func (index *Index) LocationOf(path objectpath.Path) (Location, bool) { |
| 271 | index.byObjectPathOnce.Do(func() { |
| 272 | for _, mset := range index.pkg.MethodSets { |
| 273 | for _, m := range mset.Methods { |
| 274 | if m.Posn.File != 0 { // declared in this package |
| 275 | if index.byObjectPath == nil { |
| 276 | index.byObjectPath = make(map[string]gobPosition) |
| 277 | } |
| 278 | index.byObjectPath[index.pkg.Strings[m.ObjectPath]] = m.Posn |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | }) |
| 283 | posn, ok := index.byObjectPath[string(path)] |
| 284 | if !ok { |
| 285 | return Location{}, false |
| 286 | } |
| 287 | return index.location(posn), true |
| 288 | } |
| 289 | |
| 290 | // An indexBuilder builds an index for a single package. |
| 291 | type indexBuilder struct { |
| 292 | gobPackage |
| 293 | stringIndex map[string]int |
| 294 | } |
| 295 | |
| 296 | // build adds to the index all package-level named types of the specified package. |
| 297 | func (b *indexBuilder) build(fset *token.FileSet, pkg *types.Package) *Index { |
| 298 | _ = b.string("") // 0 => "" |
| 299 | |
| 300 | objectPos := func(obj types.Object) gobPosition { |
| 301 | posn := safetoken.StartPosition(fset, obj.Pos()) |
| 302 | return gobPosition{b.string(posn.Filename), posn.Offset, len(obj.Name())} |
| 303 | } |
| 304 | |
| 305 | objectpathFor := new(objectpath.Encoder).For |
| 306 | |
| 307 | // setindexInfo sets the (Posn, PkgPath, ObjectPath) fields for each method declaration. |
| 308 | setIndexInfo := func(m *gobMethod, method *types.Func) { |
| 309 | // error.Error has empty Position, PkgPath, and ObjectPath. |
| 310 | if method.Pkg() == nil { |
| 311 | return |
| 312 | } |
| 313 | |
| 314 | // Instantiations of generic methods don't have an |
| 315 | // object path, so we use the generic. |
| 316 | p, err := objectpathFor(method.Origin()) |
| 317 | if err != nil { |
| 318 | // This should never happen for a method of a package-level type. |
| 319 | // (It used to: see go.dev/issue70418.) |
| 320 | panic(err) |
| 321 | } |
| 322 | |
| 323 | // Record the position only for methods declared in this |
| 324 | // package, so that the index is independent of the byte |
| 325 | // offsets of imported source files. (Storing import |
| 326 | // positions would force the cache key for this index to |
| 327 | // incorporate the full content of all reachable |
| 328 | // dependencies, defeating coarser invalidation.) Methods |
| 329 | // promoted from other packages are instead located at |
| 330 | // query time via (PkgPath, ObjectPath); see [Index.LocationOf]. |
| 331 | if method.Pkg() == pkg { |
| 332 | m.Posn = objectPos(method) |
| 333 | } |
| 334 | m.PkgPath = b.string(method.Pkg().Path()) |
| 335 | // The object path is computed relative to method.Pkg(), |
| 336 | // which may be this package or (for promoted methods) an |
| 337 | // imported one. objectpath.For is deterministic given the |
| 338 | // package's structure (scope names, method/field |
| 339 | // orderings), and that structure is preserved by gopls's |
| 340 | // export-data roundtrip, so the path computed here matches |
| 341 | // the one computed in the declaring package's own index — |
| 342 | // the same invariant that the xrefs index relies on. |
| 343 | m.ObjectPath = b.string(string(p)) |
| 344 | } |
| 345 | |
| 346 | // We ignore aliases, though in principle they could define a |
| 347 | // struct{...} or interface{...} type, or an instantiation of |
| 348 | // a generic, that has a novel method set. |
| 349 | scope := pkg.Scope() |
| 350 | for _, name := range scope.Names() { |
| 351 | if tname, ok := scope.Lookup(name).(*types.TypeName); ok && !tname.IsAlias() { |
| 352 | if mset := methodSetInfo(tname.Type(), setIndexInfo); mset.Mask != 0 { |
| 353 | mset.TypeName = b.string(name) |
| 354 | mset.Posn = objectPos(tname) |
| 355 | // Only record types with non-trivial method sets. |
| 356 | b.MethodSets = append(b.MethodSets, mset) |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | return &Index{ |
| 362 | pkg: b.gobPackage, |
| 363 | PkgPath: metadata.PackagePath(pkg.Path()), |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | // string returns a small integer that encodes the string. |
| 368 | func (b *indexBuilder) string(s string) int { |
| 369 | i, ok := b.stringIndex[s] |
| 370 | if !ok { |
| 371 | i = len(b.Strings) |
| 372 | if b.stringIndex == nil { |
| 373 | b.stringIndex = make(map[string]int) |
| 374 | } |
| 375 | b.stringIndex[s] = i |
| 376 | b.Strings = append(b.Strings, s) |
| 377 | } |
| 378 | return i |
| 379 | } |
| 380 | |
| 381 | // methodSetInfo returns the method-set fingerprint of a type. |
| 382 | // It calls the optional setIndexInfo function for each gobMethod. |
| 383 | // This is used during index construction, but not search (KeyOf), |
| 384 | // to store extra information. |
| 385 | func methodSetInfo(t types.Type, setIndexInfo func(*gobMethod, *types.Func)) *gobMethodSet { |
| 386 | // For non-interface types, use *T |
| 387 | // (if T is not already a pointer) |
| 388 | // since it may have more methods. |
| 389 | mset := types.NewMethodSet(EnsurePointer(t)) |
| 390 | |
| 391 | // Convert the method set into a compact summary. |
| 392 | var mask uint64 |
| 393 | tricky := false |
| 394 | var buf []byte |
| 395 | methods := make([]*gobMethod, mset.Len()) |
| 396 | for i := 0; i < mset.Len(); i++ { |
| 397 | m := mset.At(i).Obj().(*types.Func) |
| 398 | // Generic methods do not participate in interface satisfaction. |
| 399 | if m.Signature().TypeParams().Len() > 0 { |
| 400 | continue |
| 401 | } |
| 402 | id := m.Id() |
| 403 | fp, isTricky := fingerprint.Encode(m.Signature()) |
| 404 | if isTricky { |
| 405 | tricky = true |
| 406 | } |
| 407 | buf = append(append(buf[:0], id...), fp...) |
| 408 | sum := crc32.ChecksumIEEE(buf) |
| 409 | methods[i] = &gobMethod{ID: id, Fingerprint: fp, Sum: sum, Tricky: isTricky} |
| 410 | if setIndexInfo != nil { |
| 411 | setIndexInfo(methods[i], m) // set Position, PkgPath, ObjectPath |
| 412 | } |
| 413 | mask |= 1 << uint64(((sum>>24)^(sum>>16)^(sum>>8)^sum)&0x3f) |
| 414 | } |
| 415 | return &gobMethodSet{ |
| 416 | IsInterface: types.IsInterface(t), |
| 417 | Tricky: tricky, |
| 418 | Mask: mask, |
| 419 | Methods: methods, |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | // EnsurePointer wraps T in a types.Pointer if T is a named, non-interface type. |
| 424 | // This is useful to make sure you consider a named type's full method set. |
| 425 | func EnsurePointer(T types.Type) types.Type { |
| 426 | if _, ok := types.Unalias(T).(*types.Named); ok && !types.IsInterface(T) { |
| 427 | return types.NewPointer(T) |
| 428 | } |
| 429 | |
| 430 | return T |
| 431 | } |
| 432 | |
| 433 | // -- serial format of index -- |
| 434 | |
| 435 | // (The name says gob but in fact we use frob.) |
| 436 | var packageCodec = frob.CodecFor[gobPackage]() |
| 437 | |
| 438 | // A gobPackage records the method set of each package-level type for a single package. |
| 439 | type gobPackage struct { |
| 440 | Strings []string // index of strings used by gobPosition.File, gobMethod.{Pkg,Object}Path |
| 441 | MethodSets []*gobMethodSet |
| 442 | } |
| 443 | |
| 444 | // A gobMethodSet records the method set of a single type. |
| 445 | type gobMethodSet struct { |
| 446 | TypeName int // name (string index) of the package-level type |
| 447 | Posn gobPosition |
| 448 | IsInterface bool |
| 449 | Tricky bool // at least one method is tricky; fingerprint must be parsed + unified |
| 450 | Mask uint64 // mask with 1 bit from each of methods[*].sum |
| 451 | Methods []*gobMethod |
| 452 | } |
| 453 | |
| 454 | // A gobMethod records the name, type, and position of a single method. |
| 455 | type gobMethod struct { |
| 456 | ID string // (*types.Func).Id() value of method |
| 457 | Fingerprint string // encoding of types as string of form "(params)(results)" |
| 458 | Sum uint32 // checksum of ID + fingerprint |
| 459 | Tricky bool // method type contains tricky features (type params, interface types) |
| 460 | |
| 461 | // index records only (zero in KeyOf; also for index of error.Error). |
| 462 | Posn gobPosition // location of method declaration; zero if PkgPath != this package (resolve via LocationOf) |
| 463 | PkgPath int // path of package containing method declaration |
| 464 | ObjectPath int // object path of method relative to PkgPath |
| 465 | |
| 466 | // internal fields (not serialized) |
| 467 | tree atomic.Pointer[fingerprint.Tree] // fingerprint tree, parsed on demand |
| 468 | } |
| 469 | |
| 470 | // A gobPosition records the file, offset, and length of an identifier. |
| 471 | type gobPosition struct { |
| 472 | File int // index into gobPackage.Strings |
| 473 | Offset, Len int // in bytes |
| 474 | } |
| 475 | |
| 476 | // parse returns the method's parsed fingerprint tree. |
| 477 | // It may return a new instance or a cached one. |
| 478 | func (m *gobMethod) parse() fingerprint.Tree { |
| 479 | ptr := m.tree.Load() |
| 480 | if ptr == nil { |
| 481 | tree := fingerprint.Parse(m.Fingerprint) |
| 482 | ptr = &tree |
| 483 | m.tree.Store(ptr) // may race; that's ok |
| 484 | } |
| 485 | return *ptr |
| 486 | } |