| 1 | // Copyright 2018 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 objectpath defines a naming scheme for types.Objects |
| 6 | // (that is, named entities in Go programs) relative to their enclosing |
| 7 | // package. |
| 8 | // |
| 9 | // Type-checker objects are canonical, so they are usually identified by |
| 10 | // their address in memory (a pointer), but a pointer has meaning only |
| 11 | // within one address space. By contrast, objectpath names allow the |
| 12 | // identity of an object to be sent from one program to another, |
| 13 | // establishing a correspondence between types.Object variables that are |
| 14 | // distinct but logically equivalent. |
| 15 | // |
| 16 | // A single object may have multiple paths. In this example, |
| 17 | // |
| 18 | // type A struct{ X int } |
| 19 | // type B A |
| 20 | // |
| 21 | // the field X has two paths due to its membership of both A and B. |
| 22 | // The For(obj) function always returns one of these paths, arbitrarily |
| 23 | // but consistently. |
| 24 | package objectpath |
| 25 | |
| 26 | import ( |
| 27 | "encoding/binary" |
| 28 | "fmt" |
| 29 | "go/types" |
| 30 | "slices" |
| 31 | "strconv" |
| 32 | "strings" |
| 33 | |
| 34 | "golang.org/x/tools/internal/typesinternal" |
| 35 | ) |
| 36 | |
| 37 | // TODO(adonovan): think about generic aliases. |
| 38 | |
| 39 | // A Path is an opaque name that identifies a types.Object |
| 40 | // relative to its package. Conceptually, the name consists of a |
| 41 | // sequence of destructuring operations applied to the package scope |
| 42 | // to obtain the original object. |
| 43 | // The name does not include the package itself. |
| 44 | type Path string |
| 45 | |
| 46 | // Encoding |
| 47 | // |
| 48 | // An object path is a textual and (with training) human-readable encoding |
| 49 | // of a sequence of destructuring operators, starting from a types.Package. |
| 50 | // The sequences represent a path through the package/object/type graph. |
| 51 | // We classify these operators by their type: |
| 52 | // |
| 53 | // PO package->object Package.Scope.Lookup |
| 54 | // OT object->type Object.Type |
| 55 | // TT type->type Type.{Elem,Key,{,{,Recv}Type}Params,Results,Underlying,Rhs} [EKPRUTrCa] |
| 56 | // TO type->object Type.{At,Field,Method,Obj} [AFMO] |
| 57 | // |
| 58 | // All valid paths start with a package and end at an object |
| 59 | // and thus may be defined by the regular language: |
| 60 | // |
| 61 | // objectpath = PO (OT TT* TO)* |
| 62 | // |
| 63 | // The concrete encoding follows directly: |
| 64 | // - The only PO operator is Package.Scope.Lookup, which requires an identifier. |
| 65 | // - The only OT operator is Object.Type, |
| 66 | // which we encode as '.' because dot cannot appear in an identifier. |
| 67 | // - The TT operators are encoded as [EKPRUTrCa]; |
| 68 | // two of these ({,Recv}TypeParams) require an integer operand, |
| 69 | // which is encoded as a string of decimal digits. |
| 70 | // - The TO operators are encoded as [AFMO]; |
| 71 | // three of these (At,Field,Method) require an integer operand, |
| 72 | // which is encoded as a string of decimal digits. |
| 73 | // These indices are stable across different representations |
| 74 | // of the same package, even source and export data. |
| 75 | // The indices used are implementation specific and may not correspond to |
| 76 | // the argument to the go/types function. |
| 77 | // |
| 78 | // In the example below, |
| 79 | // |
| 80 | // package p |
| 81 | // |
| 82 | // type T interface { |
| 83 | // f() (a string, b struct{ X int }) |
| 84 | // } |
| 85 | // |
| 86 | // field X has the path "T.UM0.RA1.F0", |
| 87 | // representing the following sequence of operations: |
| 88 | // |
| 89 | // p.Lookup("T") T |
| 90 | // .Type().Underlying().Method(0). f |
| 91 | // .Type().Results().At(1) b |
| 92 | // .Type().Field(0) X |
| 93 | // |
| 94 | // The encoding is not maximally compact---every R or P is |
| 95 | // followed by an A, for example---but this simplifies the |
| 96 | // encoder and decoder. |
| 97 | const ( |
| 98 | // object->type operators |
| 99 | opType = '.' // .Type() (Object) |
| 100 | |
| 101 | // type->type operators |
| 102 | opElem = 'E' // .Elem() (Pointer, Slice, Array, Chan, Map) |
| 103 | opKey = 'K' // .Key() (Map) |
| 104 | opParams = 'P' // .Params() (Signature) |
| 105 | opResults = 'R' // .Results() (Signature) |
| 106 | opUnderlying = 'U' // .Underlying() (Named) |
| 107 | opTypeParam = 'T' // .TypeParams.At(i) (Named, Signature) |
| 108 | opRecvTypeParam = 'r' // .RecvTypeParams.At(i) (Signature) |
| 109 | opConstraint = 'C' // .Constraint() (TypeParam) |
| 110 | opRhs = 'a' // .Rhs() (Alias) |
| 111 | |
| 112 | // type->object operators |
| 113 | opAt = 'A' // .At(i) (Tuple) |
| 114 | opField = 'F' // .Field(i) (Struct) |
| 115 | opMethod = 'M' // .Method(i) (Named or Interface; not Struct: "promoted" names are ignored) |
| 116 | opObj = 'O' // .Obj() (Named, TypeParam) |
| 117 | ) |
| 118 | |
| 119 | // For is equivalent to new(Encoder).For(obj). |
| 120 | // |
| 121 | // It may be more efficient to reuse a single Encoder across several calls. |
| 122 | func For(obj types.Object) (Path, error) { |
| 123 | return new(Encoder).For(obj) |
| 124 | } |
| 125 | |
| 126 | // An Encoder amortizes the cost of encoding the paths of multiple objects. |
| 127 | // The zero value of an Encoder is ready to use. |
| 128 | type Encoder struct { |
| 129 | pkgIndex map[*types.Package]*pkgIndex |
| 130 | } |
| 131 | |
| 132 | // A traversal encapsulates the state of a single traversal of the object/type graph. |
| 133 | type traversal struct { |
| 134 | pkg *types.Package |
| 135 | ix *pkgIndex // non-nil if we are building the index |
| 136 | |
| 137 | target types.Object // the sought symbol (if ix == nil) |
| 138 | found Path // the found path (if ix == nil) |
| 139 | |
| 140 | // These maps are used to short circuit cycles through |
| 141 | // interface methods, such as occur in the following example: |
| 142 | // |
| 143 | // type I interface { f() interface{I} } |
| 144 | // |
| 145 | // See golang/go#68046 for details. |
| 146 | seenTParamNames map[*types.TypeName]bool // global cycle breaking through type parameters |
| 147 | seenMethods map[*types.Func]bool // global cycle breaking through recursive interfaces |
| 148 | } |
| 149 | |
| 150 | // A pkgIndex holds a compressed index of objectpaths of all symbols |
| 151 | // (fields, methods, params) requiring search for an entire package. |
| 152 | // |
| 153 | // The first time a search for a given package is requested, we simply |
| 154 | // traverse the type graph for the target object, maintaining the |
| 155 | // current object path as a stack. If we find the target object, we |
| 156 | // save the path and terminate the main loop (but it's not worth |
| 157 | // breaking out of the current recursion). |
| 158 | // |
| 159 | // On the second search (a pkgIndex exists but its data is nil), we |
| 160 | // build an index of the traversal, which we use for all subsequent |
| 161 | // searches. |
| 162 | // |
| 163 | // The traversal index is encoded in the data field as a list of records, |
| 164 | // one per node, in preorder. Records are of two types: |
| 165 | // |
| 166 | // - A record for a package-level object consists of a pair |
| 167 | // (parent, nameIndex uvarint), where parent is zero and |
| 168 | // nameIndex is the index of the object's name in the sorted |
| 169 | // pkg.Scope().Names() slice. |
| 170 | // |
| 171 | // - A record for a nested node (a segment of an object path) |
| 172 | // consists of (parent uvarint, op byte, index uvarint), where |
| 173 | // parent is the index of the record for the parent node, |
| 174 | // op is the destructuring operator, and index (if op = [AFMTr]) |
| 175 | // is its integer operand. |
| 176 | // |
| 177 | // Since data[0] = 0 all nodes have positive offsets. In effect the |
| 178 | // encoding is a trie in which each node stores one path segment |
| 179 | // and points to the node for its prefix. |
| 180 | // |
| 181 | // TODO(adonovan): opt: evaluate an only 2-level tree with nodes for |
| 182 | // package-level objects and the-rest-of-the-path. One calculation |
| 183 | // suggested that it might be similar speed but 30% more compact. |
| 184 | type pkgIndex struct { |
| 185 | pkg *types.Package |
| 186 | data []byte // encoding of traversal; nil if not yet constructed |
| 187 | scopeNames []string // memo of pkg.Scope().Names() to avoid O(n) alloc/sort at lookup |
| 188 | offsets map[types.Object]uint32 // each object's node offset within encoded traversal data |
| 189 | } |
| 190 | |
| 191 | // For returns the path to an object relative to its package, |
| 192 | // or an error if the object is not accessible from the package's Scope. |
| 193 | // |
| 194 | // The For function guarantees to return a path only for the following objects: |
| 195 | // - package-level types |
| 196 | // - exported package-level non-types |
| 197 | // - methods |
| 198 | // - parameter and result variables |
| 199 | // - struct fields |
| 200 | // These objects are sufficient to define the API of their package. |
| 201 | // The objects described by a package's export data are drawn from this set. |
| 202 | // |
| 203 | // The set of objects accessible from a package's Scope depends on |
| 204 | // whether the package was produced by type-checking syntax, or |
| 205 | // reading export data; the latter may have a smaller Scope since |
| 206 | // export data trims objects that are not reachable from an exported |
| 207 | // declaration. For example, the For function will return a path for |
| 208 | // an exported method of an unexported type that is not reachable |
| 209 | // from any public declaration; this path will cause the Object |
| 210 | // function to fail if called on a package loaded from export data. |
| 211 | // TODO(adonovan): is this a bug or feature? Should this package |
| 212 | // compute accessibility in the same way? |
| 213 | // |
| 214 | // For does not return a path for predeclared names, imported package |
| 215 | // names, local names, and unexported package-level names (except |
| 216 | // types). |
| 217 | // |
| 218 | // Example: given this definition, |
| 219 | // |
| 220 | // package p |
| 221 | // |
| 222 | // type T interface { |
| 223 | // f() (a string, b struct{ X int }) |
| 224 | // } |
| 225 | // |
| 226 | // For(X) would return a path that denotes the following sequence of operations: |
| 227 | // |
| 228 | // p.Scope().Lookup("T") (TypeName T) |
| 229 | // .Type().Underlying().Method(0). (method Func f) |
| 230 | // .Type().Results().At(1) (field Var b) |
| 231 | // .Type().Field(0) (field Var X) |
| 232 | // |
| 233 | // where p is the package (*types.Package) to which X belongs. |
| 234 | func (enc *Encoder) For(obj types.Object) (Path, error) { |
| 235 | pkg := obj.Pkg() |
| 236 | |
| 237 | // This table lists the cases of interest. |
| 238 | // |
| 239 | // Object Action |
| 240 | // ------ ------ |
| 241 | // nil reject |
| 242 | // builtin reject |
| 243 | // pkgname reject |
| 244 | // label reject |
| 245 | // var |
| 246 | // package-level accept |
| 247 | // func param/result accept |
| 248 | // local reject |
| 249 | // struct field accept |
| 250 | // const |
| 251 | // package-level accept |
| 252 | // local reject |
| 253 | // func |
| 254 | // package-level accept |
| 255 | // init functions reject |
| 256 | // concrete method accept |
| 257 | // interface method accept |
| 258 | // type |
| 259 | // package-level accept |
| 260 | // local reject |
| 261 | // |
| 262 | // The only accessible package-level objects are members of pkg itself. |
| 263 | // |
| 264 | // The cases are handled in four steps: |
| 265 | // |
| 266 | // 1. reject nil and builtin |
| 267 | // 2. accept package-level objects |
| 268 | // 3. reject obviously invalid objects |
| 269 | // 4. search the API for the path to the param/result/field/method. |
| 270 | |
| 271 | // 1. reference to nil or builtin? |
| 272 | if pkg == nil { |
| 273 | return "", fmt.Errorf("predeclared %s has no path", obj) |
| 274 | } |
| 275 | |
| 276 | // 2. package-level object? |
| 277 | if pkg.Scope().Lookup(obj.Name()) == obj { |
| 278 | // Only exported objects (and non-exported types) have a path. |
| 279 | // Non-exported types may be referenced by other objects. |
| 280 | if _, ok := obj.(*types.TypeName); !ok && !obj.Exported() { |
| 281 | return "", fmt.Errorf("no path for non-exported %v", obj) |
| 282 | } |
| 283 | return Path(obj.Name()), nil |
| 284 | } |
| 285 | |
| 286 | // 3. Not a package-level object. |
| 287 | // Reject obviously non-viable cases. |
| 288 | switch obj := obj.(type) { |
| 289 | case *types.TypeName: |
| 290 | if _, ok := types.Unalias(obj.Type()).(*types.TypeParam); !ok { |
| 291 | // With the exception of type parameters, only package-level type names |
| 292 | // have a path. |
| 293 | return "", fmt.Errorf("no path for %v", obj) |
| 294 | } |
| 295 | |
| 296 | case *types.Const, // Only package-level constants have a path. |
| 297 | *types.Label, // Labels are function-local. |
| 298 | *types.PkgName: // PkgNames are file-local. |
| 299 | return "", fmt.Errorf("no path for %v", obj) |
| 300 | |
| 301 | case *types.Var: |
| 302 | // A var, if not package-level, must be a |
| 303 | // parameter (incl. receiver) or result, or a struct field. |
| 304 | if obj.Kind() == types.LocalVar { |
| 305 | return "", fmt.Errorf("no path for local %v", obj) |
| 306 | } |
| 307 | |
| 308 | case *types.Func: |
| 309 | // A func, if not package-level, must be a method. |
| 310 | if recv := obj.Signature().Recv(); recv == nil { |
| 311 | return "", fmt.Errorf("func is not a method: %v", obj) |
| 312 | } |
| 313 | |
| 314 | if path, ok := enc.concreteMethod(obj); ok { |
| 315 | // Fast path for concrete methods that avoids looping over scope. |
| 316 | return path, nil |
| 317 | } |
| 318 | |
| 319 | default: |
| 320 | panic(obj) |
| 321 | } |
| 322 | |
| 323 | // 4. Search the object/type graph for the path to |
| 324 | // the var (field/param/result) or method. |
| 325 | ix, ok := enc.pkgIndex[pkg] |
| 326 | if !ok { |
| 327 | // First search: don't build an index, just traverse. |
| 328 | // This avoids allocation in [For], whose Encoder |
| 329 | // lives for a single call. |
| 330 | ix = &pkgIndex{pkg: pkg} |
| 331 | |
| 332 | if enc.pkgIndex == nil { |
| 333 | enc.pkgIndex = make(map[*types.Package]*pkgIndex) |
| 334 | } |
| 335 | enc.pkgIndex[pkg] = ix // build the index next time |
| 336 | |
| 337 | f := traversal{pkg: pkg, target: obj} |
| 338 | f.traverse() |
| 339 | |
| 340 | if f.found != "" { |
| 341 | return f.found, nil |
| 342 | } |
| 343 | } else { |
| 344 | // Second search: build an index while traversing. |
| 345 | if ix.data == nil { |
| 346 | ix.offsets = make(map[types.Object]uint32) |
| 347 | ix.data = []byte{0} // offset 0 is sentinel |
| 348 | (&traversal{pkg: pkg, ix: ix}).traverse() |
| 349 | } |
| 350 | |
| 351 | // Second and later searches: consult the index. |
| 352 | if offset, ok := ix.offsets[obj]; ok { |
| 353 | return ix.path(offset), nil |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | return "", fmt.Errorf("can't find path for %v in %s", obj, pkg.Path()) |
| 358 | } |
| 359 | |
| 360 | // traverse performs a complete traversal of all symbols reachable from the package. |
| 361 | func (tr *traversal) traverse() { |
| 362 | scope := tr.pkg.Scope() |
| 363 | names := scope.Names() |
| 364 | if tr.ix != nil { |
| 365 | tr.ix.scopeNames = names |
| 366 | } |
| 367 | |
| 368 | empty := make([]byte, 0, 48) // initial space for stack (ix == nil) |
| 369 | |
| 370 | // First inspect package-level type names. |
| 371 | // In the presence of path aliases, these give |
| 372 | // the best paths because non-types may |
| 373 | // refer to types, but not the reverse. |
| 374 | for i, name := range names { |
| 375 | if tr.found != "" { |
| 376 | return // found (ix == nil) |
| 377 | } |
| 378 | |
| 379 | obj := scope.Lookup(name) |
| 380 | if _, ok := obj.(*types.TypeName); !ok { |
| 381 | continue // handle non-types in second pass |
| 382 | } |
| 383 | |
| 384 | // emit (name, opType) |
| 385 | var path []byte |
| 386 | var offset uint32 |
| 387 | if tr.ix == nil { |
| 388 | path = append(empty, name...) |
| 389 | path = append(path, opType) |
| 390 | } else { |
| 391 | offset = tr.ix.emitPackageLevel(i) |
| 392 | tr.ix.offsets[obj] = offset |
| 393 | offset = tr.ix.emitPathSegment(offset, opType, -1) |
| 394 | } |
| 395 | |
| 396 | // A TypeName (for Named or Alias) may have type parameters. |
| 397 | switch t := obj.Type().(type) { |
| 398 | case *types.Alias: |
| 399 | tr.tparams(t.TypeParams(), path, offset, opTypeParam) |
| 400 | tr.typ(path, offset, opRhs, -1, t.Rhs()) |
| 401 | case *types.Named: |
| 402 | tr.tparams(t.TypeParams(), path, offset, opTypeParam) |
| 403 | tr.typ(path, offset, opUnderlying, -1, t.Underlying()) |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | // Then inspect everything else: |
| 408 | // exported non-types, and declared methods of defined types. |
| 409 | for i, name := range names { |
| 410 | if tr.found != "" { |
| 411 | return // found (ix == nil) |
| 412 | } |
| 413 | |
| 414 | obj := scope.Lookup(name) |
| 415 | |
| 416 | if tname, ok := obj.(*types.TypeName); !ok { |
| 417 | if obj.Exported() { |
| 418 | // exported non-type (const, var, func) |
| 419 | var path []byte |
| 420 | var offset uint32 |
| 421 | if tr.ix == nil { |
| 422 | path = append(empty, name...) |
| 423 | } else { |
| 424 | offset = tr.ix.emitPackageLevel(i) |
| 425 | tr.ix.offsets[obj] = offset |
| 426 | } |
| 427 | tr.typ(path, offset, opType, -1, obj.Type()) |
| 428 | } |
| 429 | |
| 430 | } else if T, ok := types.Unalias(tname.Type()).(*types.Named); ok { |
| 431 | // defined type |
| 432 | var path []byte |
| 433 | var offset uint32 |
| 434 | if tr.ix == nil { |
| 435 | path = append(empty, name...) |
| 436 | path = append(path, opType) |
| 437 | } else { |
| 438 | // Inv: map entry for obj was populated in first pass. |
| 439 | offset = tr.ix.emitPathSegment(tr.ix.offsets[obj], opType, -1) |
| 440 | } |
| 441 | |
| 442 | // Inspect declared methods of defined types. |
| 443 | // |
| 444 | // The method index here is always with respect |
| 445 | // to the underlying go/types data structures, |
| 446 | // which ultimately derives from source order |
| 447 | // and must be preserved by export data. |
| 448 | for i := 0; i < T.NumMethods(); i++ { |
| 449 | m := T.Method(i) |
| 450 | tr.object(path, offset, opMethod, i, m) |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | func (tr *traversal) visitType(path []byte, offset uint32, T types.Type) { |
| 457 | switch T := T.(type) { |
| 458 | case *types.Alias: |
| 459 | tr.typ(path, offset, opRhs, -1, T.Rhs()) |
| 460 | |
| 461 | case *types.Basic, *types.Named: |
| 462 | // Named types belonging to pkg were handled already, |
| 463 | // so T must belong to another package. No path. |
| 464 | return |
| 465 | |
| 466 | case *types.Pointer, *types.Slice, *types.Array, *types.Chan: |
| 467 | type hasElem interface{ Elem() types.Type } // note: includes Map |
| 468 | tr.typ(path, offset, opElem, -1, T.(hasElem).Elem()) |
| 469 | |
| 470 | case *types.Map: |
| 471 | tr.typ(path, offset, opKey, -1, T.Key()) |
| 472 | tr.typ(path, offset, opElem, -1, T.Elem()) |
| 473 | |
| 474 | case *types.Signature: |
| 475 | tr.tparams(T.RecvTypeParams(), path, offset, opRecvTypeParam) |
| 476 | tr.tparams(T.TypeParams(), path, offset, opTypeParam) |
| 477 | tr.typ(path, offset, opParams, -1, T.Params()) |
| 478 | tr.typ(path, offset, opResults, -1, T.Results()) |
| 479 | |
| 480 | case *types.Struct: |
| 481 | for i := 0; i < T.NumFields(); i++ { |
| 482 | tr.object(path, offset, opField, i, T.Field(i)) |
| 483 | } |
| 484 | |
| 485 | case *types.Tuple: |
| 486 | for i := 0; i < T.Len(); i++ { |
| 487 | tr.object(path, offset, opAt, i, T.At(i)) |
| 488 | } |
| 489 | |
| 490 | case *types.Interface: |
| 491 | for i := 0; i < T.NumMethods(); i++ { |
| 492 | m := T.Method(i) |
| 493 | if m.Pkg() != nil && m.Pkg() != tr.pkg { |
| 494 | continue // embedded method from another package |
| 495 | } |
| 496 | if !tr.seenMethods[m] { |
| 497 | if tr.seenMethods == nil { |
| 498 | tr.seenMethods = make(map[*types.Func]bool) |
| 499 | } |
| 500 | tr.seenMethods[m] = true |
| 501 | tr.object(path, offset, opMethod, i, m) |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | case *types.TypeParam: |
| 506 | tname := T.Obj() |
| 507 | if tname.Pkg() != nil && tname.Pkg() != tr.pkg { |
| 508 | return // type parameter from another package |
| 509 | } |
| 510 | if !tr.seenTParamNames[tname] { |
| 511 | if tr.seenTParamNames == nil { |
| 512 | tr.seenTParamNames = make(map[*types.TypeName]bool) |
| 513 | } |
| 514 | tr.seenTParamNames[tname] = true |
| 515 | tr.object(path, offset, opObj, -1, tname) |
| 516 | tr.typ(path, offset, opConstraint, -1, T.Constraint()) |
| 517 | } |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | func (tr *traversal) tparams(list *types.TypeParamList, path []byte, offset uint32, op byte) { |
| 522 | for i := 0; i < list.Len(); i++ { |
| 523 | tr.typ(path, offset, op, i, list.At(i)) |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | // typ descends the type graph edge (op, index), then proceeds to traverse type t. |
| 528 | func (tr *traversal) typ(path []byte, offset uint32, op byte, index int, t types.Type) { |
| 529 | if tr.ix == nil { |
| 530 | path = appendOpArg(path, op, index) |
| 531 | } else { |
| 532 | offset = tr.ix.emitPathSegment(offset, op, index) |
| 533 | } |
| 534 | tr.visitType(path, offset, t) |
| 535 | } |
| 536 | |
| 537 | // object descends the type graph edge (op, index), records object |
| 538 | // obj, then proceeds to traverse its type. |
| 539 | func (tr *traversal) object(path []byte, offset uint32, op byte, index int, obj types.Object) { |
| 540 | if tr.ix == nil { |
| 541 | path = appendOpArg(path, op, index) |
| 542 | if obj == tr.target && tr.found == "" { |
| 543 | tr.found = Path(path) |
| 544 | } |
| 545 | path = append(path, opType) |
| 546 | } else { |
| 547 | offset = tr.ix.emitPathSegment(offset, op, index) |
| 548 | if _, ok := tr.ix.offsets[obj]; !ok { |
| 549 | tr.ix.offsets[obj] = offset |
| 550 | } |
| 551 | offset = tr.ix.emitPathSegment(offset, opType, -1) |
| 552 | } |
| 553 | tr.visitType(path, offset, obj.Type()) |
| 554 | } |
| 555 | |
| 556 | // emitPackageLevel encodes a record for a package-level symbol, |
| 557 | // identified by its index in ix.scopeNames. |
| 558 | func (p *pkgIndex) emitPackageLevel(index int) uint32 { |
| 559 | off := uint32(len(p.data)) |
| 560 | p.data = append(p.data, 0) // zero varint => no parent |
| 561 | p.data = binary.AppendUvarint(p.data, uint64(index)) |
| 562 | return off |
| 563 | } |
| 564 | |
| 565 | // emitPathSegment emits a record for a non-initial object path segment. |
| 566 | func (p *pkgIndex) emitPathSegment(parent uint32, op byte, index int) uint32 { |
| 567 | off := uint32(len(p.data)) |
| 568 | p.data = binary.AppendUvarint(p.data, uint64(parent)) |
| 569 | p.data = append(p.data, op) |
| 570 | switch op { |
| 571 | case opAt, opField, opMethod, opTypeParam, opRecvTypeParam: |
| 572 | p.data = binary.AppendUvarint(p.data, uint64(index)) |
| 573 | } |
| 574 | return off |
| 575 | } |
| 576 | |
| 577 | // path returns the Path for the encoded node at the specified offset. |
| 578 | func (p *pkgIndex) path(offset uint32) Path { |
| 579 | var elems []string // path elements in reverse |
| 580 | for { |
| 581 | // Read parent index. |
| 582 | parent, n := binary.Uvarint(p.data[offset:]) |
| 583 | offset += uint32(n) |
| 584 | |
| 585 | if parent == 0 { |
| 586 | break // root (end of path) |
| 587 | } |
| 588 | |
| 589 | op := p.data[offset] |
| 590 | offset++ |
| 591 | |
| 592 | // The [AFMTr] operators have a numeric operand. |
| 593 | switch op { |
| 594 | case opAt, opField, opMethod, opTypeParam, opRecvTypeParam: |
| 595 | val, n := binary.Uvarint(p.data[offset:]) |
| 596 | offset += uint32(n) |
| 597 | elems = append(elems, strconv.Itoa(int(val))) |
| 598 | } |
| 599 | |
| 600 | elems = append(elems, string([]byte{op})) |
| 601 | |
| 602 | offset = uint32(parent) |
| 603 | } |
| 604 | idx, _ := binary.Uvarint(p.data[offset:]) |
| 605 | |
| 606 | // Convert index to Path string. |
| 607 | name := p.scopeNames[idx] |
| 608 | sz := len(name) |
| 609 | for _, elem := range elems { |
| 610 | sz += len(elem) |
| 611 | } |
| 612 | var buf strings.Builder |
| 613 | buf.Grow(sz) |
| 614 | buf.WriteString(name) |
| 615 | for _, elem := range slices.Backward(elems) { |
| 616 | buf.WriteString(elem) |
| 617 | } |
| 618 | return Path(buf.String()) |
| 619 | } |
| 620 | |
| 621 | // appendOpArg appends (op, index) to the object path. |
| 622 | // A negative index is ignored. |
| 623 | func appendOpArg(path []byte, op byte, index int) []byte { |
| 624 | path = append(path, op) |
| 625 | if index >= 0 { |
| 626 | path = strconv.AppendInt(path, int64(index), 10) |
| 627 | } |
| 628 | return path |
| 629 | } |
| 630 | |
| 631 | // concreteMethod returns the path for meth, which must have a non-nil receiver. |
| 632 | // The second return value indicates success and may be false if the method is |
| 633 | // an interface method or if it is an instantiated method. |
| 634 | // |
| 635 | // This function is just an optimization that avoids the general scope walking |
| 636 | // approach. You are expected to fall back to the general approach if this |
| 637 | // function fails. |
| 638 | func (enc *Encoder) concreteMethod(meth *types.Func) (Path, bool) { |
| 639 | // Concrete methods can only be declared on package-scoped named types. For |
| 640 | // that reason we can skip the expensive walk over the package scope: the |
| 641 | // path will always be package -> named type -> method. We can trivially get |
| 642 | // the type name from the receiver, and only have to look over the type's |
| 643 | // methods to find the method index. |
| 644 | // |
| 645 | // Methods on generic types require special consideration, however. Consider |
| 646 | // the following package: |
| 647 | // |
| 648 | // L1: type S[T any] struct{} |
| 649 | // L2: func (recv S[A]) Foo() { recv.Bar() } |
| 650 | // L3: func (recv S[B]) Bar() { } |
| 651 | // L4: type Alias = S[int] |
| 652 | // L5: func _[T any]() { var s S[int]; s.Foo() } |
| 653 | // |
| 654 | // The receivers of methods on generic types are instantiations. L2 and L3 |
| 655 | // instantiate S with the type-parameters A and B, which are scoped to the |
| 656 | // respective methods. L4 and L5 each instantiate S with int. Each of these |
| 657 | // instantiations has its own method set, full of methods (and thus objects) |
| 658 | // with receivers whose types are the respective instantiations. In other |
| 659 | // words, we have |
| 660 | // |
| 661 | // S[A].Foo, S[A].Bar |
| 662 | // S[B].Foo, S[B].Bar |
| 663 | // S[int].Foo, S[int].Bar |
| 664 | // |
| 665 | // We may thus be trying to produce object paths for any of these objects. |
| 666 | // |
| 667 | // S[A].Foo and S[B].Bar are the origin methods, and their paths are S.Foo |
| 668 | // and S.Bar, which are the paths that this function naturally produces. |
| 669 | // |
| 670 | // S[A].Bar, S[B].Foo, and both methods on S[int] are instantiations that |
| 671 | // don't correspond to the origin methods. For S[int], this is significant. |
| 672 | // The most precise object path for S[int].Foo, for example, is Alias.Foo, |
| 673 | // not S.Foo. Our function, however, would produce S.Foo, which would |
| 674 | // resolve to a different object. |
| 675 | // |
| 676 | // For S[A].Bar and S[B].Foo it could be argued that S.Bar and S.Foo are |
| 677 | // still the correct paths, since only the origin methods have meaningful |
| 678 | // paths. But this is likely only true for trivial cases and has edge cases. |
| 679 | // Since this function is only an optimization, we err on the side of giving |
| 680 | // up, deferring to the slower but definitely correct algorithm. Most users |
| 681 | // of objectpath will only be giving us origin methods, anyway, as referring |
| 682 | // to instantiated methods is usually not useful. |
| 683 | |
| 684 | if meth.Origin() != meth { |
| 685 | return "", false |
| 686 | } |
| 687 | |
| 688 | _, named := typesinternal.ReceiverNamed(meth.Signature().Recv()) |
| 689 | if named == nil { |
| 690 | return "", false |
| 691 | } |
| 692 | |
| 693 | if types.IsInterface(named) { |
| 694 | // Named interfaces don't have to be package-scoped |
| 695 | // |
| 696 | // TODO(dominikh): opt: if scope.Lookup(name) == named, then we can apply this optimization to interface |
| 697 | // methods, too, I think. |
| 698 | return "", false |
| 699 | } |
| 700 | |
| 701 | // Preallocate space for the name, opType, opMethod, and some digits. |
| 702 | name := named.Obj().Name() |
| 703 | path := make([]byte, 0, len(name)+8) |
| 704 | path = append(path, name...) |
| 705 | path = append(path, opType) |
| 706 | |
| 707 | // Method indices are w.r.t. the go/types data structures, |
| 708 | // ultimately deriving from source order, |
| 709 | // which is preserved by export data. |
| 710 | for i := 0; i < named.NumMethods(); i++ { |
| 711 | if named.Method(i) == meth { |
| 712 | path = appendOpArg(path, opMethod, i) |
| 713 | return Path(path), true |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | // Due to golang/go#59944, go/types fails to associate the receiver with |
| 718 | // certain methods on cgo types. |
| 719 | // |
| 720 | // TODO(rfindley): replace this panic once golang/go#59944 is fixed in all Go |
| 721 | // versions gopls supports. |
| 722 | return "", false |
| 723 | // panic(fmt.Sprintf("couldn't find method %s on type %s; methods: %#v", meth, named, enc.namedMethods(named))) |
| 724 | } |
| 725 | |
| 726 | // Object returns the object denoted by path p within the package pkg. |
| 727 | func Object(pkg *types.Package, p Path) (types.Object, error) { |
| 728 | pathstr := string(p) |
| 729 | if pathstr == "" { |
| 730 | return nil, fmt.Errorf("empty path") |
| 731 | } |
| 732 | |
| 733 | var pkgobj, suffix string |
| 734 | if dot := strings.IndexByte(pathstr, opType); dot < 0 { |
| 735 | pkgobj = pathstr |
| 736 | } else { |
| 737 | pkgobj = pathstr[:dot] |
| 738 | suffix = pathstr[dot:] // suffix starts with "." |
| 739 | } |
| 740 | |
| 741 | obj := pkg.Scope().Lookup(pkgobj) |
| 742 | if obj == nil { |
| 743 | return nil, fmt.Errorf("package %s does not contain %q", pkg.Path(), pkgobj) |
| 744 | } |
| 745 | |
| 746 | // abstraction of *types.{Pointer,Slice,Array,Chan,Map} |
| 747 | type hasElem interface { |
| 748 | Elem() types.Type |
| 749 | } |
| 750 | // abstraction of *types.{Named,Signature} |
| 751 | type hasTypeParams interface { |
| 752 | TypeParams() *types.TypeParamList |
| 753 | } |
| 754 | // abstraction of *types.{Alias,Named,TypeParam} |
| 755 | type hasObj interface { |
| 756 | Obj() *types.TypeName |
| 757 | } |
| 758 | |
| 759 | // The loop state is the pair (t, obj), |
| 760 | // exactly one of which is non-nil, initially obj. |
| 761 | // All suffixes start with '.' (the only object->type operation), |
| 762 | // followed by optional type->type operations, |
| 763 | // then a type->object operation. |
| 764 | // The cycle then repeats. |
| 765 | var t types.Type |
| 766 | for suffix != "" { |
| 767 | code := suffix[0] |
| 768 | suffix = suffix[1:] |
| 769 | |
| 770 | // Codes [AFMTr] have an integer operand. |
| 771 | var index int |
| 772 | switch code { |
| 773 | case opAt, opField, opMethod, opTypeParam, opRecvTypeParam: |
| 774 | rest := strings.TrimLeft(suffix, "0123456789") |
| 775 | numerals := suffix[:len(suffix)-len(rest)] |
| 776 | suffix = rest |
| 777 | i, err := strconv.Atoi(numerals) |
| 778 | if err != nil { |
| 779 | return nil, fmt.Errorf("invalid path: bad numeric operand %q for code %q", numerals, code) |
| 780 | } |
| 781 | index = int(i) |
| 782 | case opObj: |
| 783 | // no operand |
| 784 | default: |
| 785 | // The suffix must end with a type->object operation. |
| 786 | if suffix == "" { |
| 787 | return nil, fmt.Errorf("invalid path: ends with %q, want [AFMO]", code) |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | if code == opType { |
| 792 | if t != nil { |
| 793 | return nil, fmt.Errorf("invalid path: unexpected %q in type context", opType) |
| 794 | } |
| 795 | t = obj.Type() |
| 796 | obj = nil |
| 797 | continue |
| 798 | } |
| 799 | |
| 800 | if t == nil { |
| 801 | return nil, fmt.Errorf("invalid path: code %q in object context", code) |
| 802 | } |
| 803 | |
| 804 | // Inv: t != nil, obj == nil |
| 805 | |
| 806 | t = types.Unalias(t) |
| 807 | switch code { |
| 808 | case opElem: |
| 809 | hasElem, ok := t.(hasElem) // Pointer, Slice, Array, Chan, Map |
| 810 | if !ok { |
| 811 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want pointer, slice, array, chan or map)", code, t, t) |
| 812 | } |
| 813 | t = hasElem.Elem() |
| 814 | |
| 815 | case opKey: |
| 816 | mapType, ok := t.(*types.Map) |
| 817 | if !ok { |
| 818 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want map)", code, t, t) |
| 819 | } |
| 820 | t = mapType.Key() |
| 821 | |
| 822 | case opParams: |
| 823 | sig, ok := t.(*types.Signature) |
| 824 | if !ok { |
| 825 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want signature)", code, t, t) |
| 826 | } |
| 827 | t = sig.Params() |
| 828 | |
| 829 | case opResults: |
| 830 | sig, ok := t.(*types.Signature) |
| 831 | if !ok { |
| 832 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want signature)", code, t, t) |
| 833 | } |
| 834 | t = sig.Results() |
| 835 | |
| 836 | case opUnderlying: |
| 837 | named, ok := t.(*types.Named) |
| 838 | if !ok { |
| 839 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want named)", code, t, t) |
| 840 | } |
| 841 | t = named.Underlying() |
| 842 | |
| 843 | case opRhs: |
| 844 | if alias, ok := t.(*types.Alias); ok { |
| 845 | t = alias.Rhs() |
| 846 | } else if false { |
| 847 | // Now that go1.24 is assured, we should be able to |
| 848 | // replace this with "if true {", but it causes objectpath |
| 849 | // tests to fail. TODO(adonovan): investigate. |
| 850 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want alias)", code, t, t) |
| 851 | } |
| 852 | |
| 853 | case opTypeParam: |
| 854 | hasTypeParams, ok := t.(hasTypeParams) // Named, Signature |
| 855 | if !ok { |
| 856 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want named or signature)", code, t, t) |
| 857 | } |
| 858 | tparams := hasTypeParams.TypeParams() |
| 859 | if n := tparams.Len(); index >= n { |
| 860 | return nil, fmt.Errorf("type parameter index %d out of range [0-%d)", index, n) |
| 861 | } |
| 862 | t = tparams.At(index) |
| 863 | |
| 864 | case opRecvTypeParam: |
| 865 | sig, ok := t.(*types.Signature) // Signature |
| 866 | if !ok { |
| 867 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want signature)", code, t, t) |
| 868 | } |
| 869 | rtparams := sig.RecvTypeParams() |
| 870 | if n := rtparams.Len(); index >= n { |
| 871 | return nil, fmt.Errorf("receiver type parameter index %d out of range [0-%d)", index, n) |
| 872 | } |
| 873 | t = rtparams.At(index) |
| 874 | |
| 875 | case opConstraint: |
| 876 | tparam, ok := t.(*types.TypeParam) |
| 877 | if !ok { |
| 878 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want type parameter)", code, t, t) |
| 879 | } |
| 880 | t = tparam.Constraint() |
| 881 | |
| 882 | case opAt: |
| 883 | tuple, ok := t.(*types.Tuple) |
| 884 | if !ok { |
| 885 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want tuple)", code, t, t) |
| 886 | } |
| 887 | if n := tuple.Len(); index >= n { |
| 888 | return nil, fmt.Errorf("tuple index %d out of range [0-%d)", index, n) |
| 889 | } |
| 890 | obj = tuple.At(index) |
| 891 | t = nil |
| 892 | |
| 893 | case opField: |
| 894 | structType, ok := t.(*types.Struct) |
| 895 | if !ok { |
| 896 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want struct)", code, t, t) |
| 897 | } |
| 898 | if n := structType.NumFields(); index >= n { |
| 899 | return nil, fmt.Errorf("field index %d out of range [0-%d)", index, n) |
| 900 | } |
| 901 | obj = structType.Field(index) |
| 902 | t = nil |
| 903 | |
| 904 | case opMethod: |
| 905 | switch t := t.(type) { |
| 906 | case *types.Interface: |
| 907 | if index >= t.NumMethods() { |
| 908 | return nil, fmt.Errorf("method index %d out of range [0-%d)", index, t.NumMethods()) |
| 909 | } |
| 910 | obj = t.Method(index) // Id-ordered |
| 911 | |
| 912 | case *types.Named: |
| 913 | if index >= t.NumMethods() { |
| 914 | return nil, fmt.Errorf("method index %d out of range [0-%d)", index, t.NumMethods()) |
| 915 | } |
| 916 | obj = t.Method(index) |
| 917 | |
| 918 | default: |
| 919 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want interface or named)", code, t, t) |
| 920 | } |
| 921 | t = nil |
| 922 | |
| 923 | case opObj: |
| 924 | hasObj, ok := t.(hasObj) |
| 925 | if !ok { |
| 926 | return nil, fmt.Errorf("cannot apply %q to %s (got %T, want named or type param)", code, t, t) |
| 927 | } |
| 928 | obj = hasObj.Obj() |
| 929 | t = nil |
| 930 | |
| 931 | default: |
| 932 | return nil, fmt.Errorf("invalid path: unknown code %q", code) |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | if obj == nil { |
| 937 | panic(p) // path does not end in an object-valued operator |
| 938 | } |
| 939 | |
| 940 | if obj.Pkg() != pkg { |
| 941 | return nil, fmt.Errorf("path denotes %s, which belongs to a different package", obj) |
| 942 | } |
| 943 | |
| 944 | return obj, nil // success |
| 945 | } |