github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/internal/lsp/source/identifier.go (about) 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 source 6 7 import ( 8 "context" 9 "fmt" 10 "go/ast" 11 "go/parser" 12 "go/token" 13 "go/types" 14 "sort" 15 "strconv" 16 17 "github.com/powerman/golang-tools/go/ast/astutil" 18 "github.com/powerman/golang-tools/internal/event" 19 "github.com/powerman/golang-tools/internal/lsp/protocol" 20 "github.com/powerman/golang-tools/internal/span" 21 "github.com/powerman/golang-tools/internal/typeparams" 22 errors "golang.org/x/xerrors" 23 ) 24 25 // IdentifierInfo holds information about an identifier in Go source. 26 type IdentifierInfo struct { 27 Name string 28 Snapshot Snapshot 29 MappedRange 30 31 Type struct { 32 MappedRange 33 Object types.Object 34 } 35 36 Inferred *types.Signature 37 38 Declaration Declaration 39 40 ident *ast.Ident 41 42 // For struct fields or embedded interfaces, enclosing is the object 43 // corresponding to the outer type declaration, if it is exported, for use in 44 // documentation links. 45 enclosing *types.TypeName 46 47 pkg Package 48 qf types.Qualifier 49 } 50 51 func (i *IdentifierInfo) IsImport() bool { 52 _, ok := i.Declaration.node.(*ast.ImportSpec) 53 return ok 54 } 55 56 type Declaration struct { 57 MappedRange []MappedRange 58 59 // The typechecked node. 60 node ast.Node 61 62 // Optional: the fully parsed node, to be used for formatting in cases where 63 // node has missing information. This could be the case when node was parsed 64 // in ParseExported mode. 65 fullDecl ast.Decl 66 67 // The typechecked object. 68 obj types.Object 69 70 // typeSwitchImplicit indicates that the declaration is in an implicit 71 // type switch. Its type is the type of the variable on the right-hand 72 // side of the type switch. 73 typeSwitchImplicit types.Type 74 } 75 76 // Identifier returns identifier information for a position 77 // in a file, accounting for a potentially incomplete selector. 78 func Identifier(ctx context.Context, snapshot Snapshot, fh FileHandle, pos protocol.Position) (*IdentifierInfo, error) { 79 ctx, done := event.Start(ctx, "source.Identifier") 80 defer done() 81 82 pkgs, err := snapshot.PackagesForFile(ctx, fh.URI(), TypecheckAll, false) 83 if err != nil { 84 return nil, err 85 } 86 if len(pkgs) == 0 { 87 return nil, fmt.Errorf("no packages for file %v", fh.URI()) 88 } 89 sort.Slice(pkgs, func(i, j int) bool { 90 // Prefer packages with a more complete parse mode. 91 if pkgs[i].ParseMode() != pkgs[j].ParseMode() { 92 return pkgs[i].ParseMode() > pkgs[j].ParseMode() 93 } 94 return len(pkgs[i].CompiledGoFiles()) < len(pkgs[j].CompiledGoFiles()) 95 }) 96 var findErr error 97 for _, pkg := range pkgs { 98 pgf, err := pkg.File(fh.URI()) 99 if err != nil { 100 return nil, err 101 } 102 spn, err := pgf.Mapper.PointSpan(pos) 103 if err != nil { 104 return nil, err 105 } 106 rng, err := spn.Range(pgf.Mapper.Converter) 107 if err != nil { 108 return nil, err 109 } 110 var ident *IdentifierInfo 111 ident, findErr = findIdentifier(ctx, snapshot, pkg, pgf, rng.Start) 112 if findErr == nil { 113 return ident, nil 114 } 115 } 116 return nil, findErr 117 } 118 119 // ErrNoIdentFound is error returned when no identifier is found at a particular position 120 var ErrNoIdentFound = errors.New("no identifier found") 121 122 func findIdentifier(ctx context.Context, snapshot Snapshot, pkg Package, pgf *ParsedGoFile, pos token.Pos) (*IdentifierInfo, error) { 123 file := pgf.File 124 // Handle import specs separately, as there is no formal position for a 125 // package declaration. 126 if result, err := importSpec(snapshot, pkg, file, pos); result != nil || err != nil { 127 return result, err 128 } 129 path := pathEnclosingObjNode(file, pos) 130 if path == nil { 131 return nil, ErrNoIdentFound 132 } 133 134 qf := Qualifier(file, pkg.GetTypes(), pkg.GetTypesInfo()) 135 136 ident, _ := path[0].(*ast.Ident) 137 if ident == nil { 138 return nil, ErrNoIdentFound 139 } 140 // Special case for package declarations, since they have no 141 // corresponding types.Object. 142 if ident == file.Name { 143 rng, err := posToMappedRange(snapshot, pkg, file.Name.Pos(), file.Name.End()) 144 if err != nil { 145 return nil, err 146 } 147 var declAST *ast.File 148 for _, pgf := range pkg.CompiledGoFiles() { 149 if pgf.File.Doc != nil { 150 declAST = pgf.File 151 } 152 } 153 // If there's no package documentation, just use current file. 154 if declAST == nil { 155 declAST = file 156 } 157 declRng, err := posToMappedRange(snapshot, pkg, declAST.Name.Pos(), declAST.Name.End()) 158 if err != nil { 159 return nil, err 160 } 161 return &IdentifierInfo{ 162 Name: file.Name.Name, 163 ident: file.Name, 164 MappedRange: rng, 165 pkg: pkg, 166 qf: qf, 167 Snapshot: snapshot, 168 Declaration: Declaration{ 169 node: declAST.Name, 170 MappedRange: []MappedRange{declRng}, 171 }, 172 }, nil 173 } 174 175 result := &IdentifierInfo{ 176 Snapshot: snapshot, 177 qf: qf, 178 pkg: pkg, 179 ident: ident, 180 enclosing: searchForEnclosing(pkg.GetTypesInfo(), path), 181 } 182 183 result.Name = result.ident.Name 184 var err error 185 if result.MappedRange, err = posToMappedRange(snapshot, pkg, result.ident.Pos(), result.ident.End()); err != nil { 186 return nil, err 187 } 188 189 result.Declaration.obj = pkg.GetTypesInfo().ObjectOf(result.ident) 190 if result.Declaration.obj == nil { 191 // If there was no types.Object for the declaration, there might be an 192 // implicit local variable declaration in a type switch. 193 if objs, typ := typeSwitchImplicits(pkg, path); len(objs) > 0 { 194 // There is no types.Object for the declaration of an implicit local variable, 195 // but all of the types.Objects associated with the usages of this variable can be 196 // used to connect it back to the declaration. 197 // Preserve the first of these objects and treat it as if it were the declaring object. 198 result.Declaration.obj = objs[0] 199 result.Declaration.typeSwitchImplicit = typ 200 } else { 201 // Probably a type error. 202 return nil, errors.Errorf("%w for ident %v", errNoObjectFound, result.Name) 203 } 204 } 205 206 // Handle builtins separately. 207 if result.Declaration.obj.Parent() == types.Universe { 208 builtin, err := snapshot.BuiltinFile(ctx) 209 if err != nil { 210 return nil, err 211 } 212 builtinObj := builtin.File.Scope.Lookup(result.Name) 213 if builtinObj == nil { 214 return nil, fmt.Errorf("no builtin object for %s", result.Name) 215 } 216 decl, ok := builtinObj.Decl.(ast.Node) 217 if !ok { 218 return nil, errors.Errorf("no declaration for %s", result.Name) 219 } 220 result.Declaration.node = decl 221 if typeSpec, ok := decl.(*ast.TypeSpec); ok { 222 // Find the GenDecl (which has the doc comments) for the TypeSpec. 223 result.Declaration.fullDecl = findGenDecl(builtin.File, typeSpec) 224 } 225 226 // The builtin package isn't in the dependency graph, so the usual 227 // utilities won't work here. 228 rng := NewMappedRange(snapshot.FileSet(), builtin.Mapper, decl.Pos(), decl.Pos()+token.Pos(len(result.Name))) 229 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng) 230 return result, nil 231 } 232 233 // (error).Error is a special case of builtin. Lots of checks to confirm 234 // that this is the builtin Error. 235 if obj := result.Declaration.obj; obj.Parent() == nil && obj.Pkg() == nil && obj.Name() == "Error" { 236 if _, ok := obj.Type().(*types.Signature); ok { 237 builtin, err := snapshot.BuiltinFile(ctx) 238 if err != nil { 239 return nil, err 240 } 241 // Look up "error" and then navigate to its only method. 242 // The Error method does not appear in the builtin package's scope.log.Pri 243 const errorName = "error" 244 builtinObj := builtin.File.Scope.Lookup(errorName) 245 if builtinObj == nil { 246 return nil, fmt.Errorf("no builtin object for %s", errorName) 247 } 248 decl, ok := builtinObj.Decl.(ast.Node) 249 if !ok { 250 return nil, errors.Errorf("no declaration for %s", errorName) 251 } 252 spec, ok := decl.(*ast.TypeSpec) 253 if !ok { 254 return nil, fmt.Errorf("no type spec for %s", errorName) 255 } 256 iface, ok := spec.Type.(*ast.InterfaceType) 257 if !ok { 258 return nil, fmt.Errorf("%s is not an interface", errorName) 259 } 260 if iface.Methods.NumFields() != 1 { 261 return nil, fmt.Errorf("expected 1 method for %s, got %v", errorName, iface.Methods.NumFields()) 262 } 263 method := iface.Methods.List[0] 264 if len(method.Names) != 1 { 265 return nil, fmt.Errorf("expected 1 name for %v, got %v", method, len(method.Names)) 266 } 267 name := method.Names[0].Name 268 result.Declaration.node = method 269 rng := NewMappedRange(snapshot.FileSet(), builtin.Mapper, method.Pos(), method.Pos()+token.Pos(len(name))) 270 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng) 271 return result, nil 272 } 273 } 274 275 // If the original position was an embedded field, we want to jump 276 // to the field's type definition, not the field's definition. 277 if v, ok := result.Declaration.obj.(*types.Var); ok && v.Embedded() { 278 // types.Info.Uses contains the embedded field's *types.TypeName. 279 if typeName := pkg.GetTypesInfo().Uses[ident]; typeName != nil { 280 result.Declaration.obj = typeName 281 } 282 } 283 284 rng, err := objToMappedRange(snapshot, pkg, result.Declaration.obj) 285 if err != nil { 286 return nil, err 287 } 288 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng) 289 290 declPkg, err := FindPackageFromPos(ctx, snapshot, result.Declaration.obj.Pos()) 291 if err != nil { 292 return nil, err 293 } 294 if result.Declaration.node, err = snapshot.PosToDecl(ctx, declPkg, result.Declaration.obj.Pos()); err != nil { 295 return nil, err 296 } 297 // Ensure that we have the full declaration, in case the declaration was 298 // parsed in ParseExported and therefore could be missing information. 299 if result.Declaration.fullDecl, err = fullNode(snapshot, result.Declaration.obj, declPkg); err != nil { 300 return nil, err 301 } 302 typ := pkg.GetTypesInfo().TypeOf(result.ident) 303 if typ == nil { 304 return result, nil 305 } 306 307 result.Inferred = inferredSignature(pkg.GetTypesInfo(), ident) 308 309 result.Type.Object = typeToObject(typ) 310 if result.Type.Object != nil { 311 // Identifiers with the type "error" are a special case with no position. 312 if hasErrorType(result.Type.Object) { 313 return result, nil 314 } 315 if result.Type.MappedRange, err = objToMappedRange(snapshot, pkg, result.Type.Object); err != nil { 316 return nil, err 317 } 318 } 319 return result, nil 320 } 321 322 // findGenDecl determines the parent ast.GenDecl for a given ast.Spec. 323 func findGenDecl(f *ast.File, spec ast.Spec) *ast.GenDecl { 324 for _, decl := range f.Decls { 325 if genDecl, ok := decl.(*ast.GenDecl); ok { 326 if genDecl.Pos() <= spec.Pos() && genDecl.End() >= spec.End() { 327 return genDecl 328 } 329 } 330 } 331 return nil 332 } 333 334 // fullNode tries to extract the full spec corresponding to obj's declaration. 335 // If the package was not parsed in full, the declaration file will be 336 // re-parsed to ensure it has complete syntax. 337 func fullNode(snapshot Snapshot, obj types.Object, pkg Package) (ast.Decl, error) { 338 // declaration in a different package... make sure we have full AST information. 339 tok := snapshot.FileSet().File(obj.Pos()) 340 uri := span.URIFromPath(tok.Name()) 341 pgf, err := pkg.File(uri) 342 if err != nil { 343 return nil, err 344 } 345 file := pgf.File 346 pos := obj.Pos() 347 if pgf.Mode != ParseFull { 348 fset := snapshot.FileSet() 349 file2, _ := parser.ParseFile(fset, tok.Name(), pgf.Src, parser.AllErrors|parser.ParseComments) 350 if file2 != nil { 351 offset, err := Offset(tok, obj.Pos()) 352 if err != nil { 353 return nil, err 354 } 355 file = file2 356 tok2 := fset.File(file2.Pos()) 357 pos = tok2.Pos(offset) 358 } 359 } 360 path, _ := astutil.PathEnclosingInterval(file, pos, pos) 361 for _, n := range path { 362 if decl, ok := n.(ast.Decl); ok { 363 return decl, nil 364 } 365 } 366 return nil, nil 367 } 368 369 // inferredSignature determines the resolved non-generic signature for an 370 // identifier in an instantiation expression. 371 // 372 // If no such signature exists, it returns nil. 373 func inferredSignature(info *types.Info, id *ast.Ident) *types.Signature { 374 inst := typeparams.GetInstances(info)[id] 375 sig, _ := inst.Type.(*types.Signature) 376 return sig 377 } 378 379 func searchForEnclosing(info *types.Info, path []ast.Node) *types.TypeName { 380 for _, n := range path { 381 switch n := n.(type) { 382 case *ast.SelectorExpr: 383 if sel, ok := info.Selections[n]; ok { 384 recv := Deref(sel.Recv()) 385 386 // Keep track of the last exported type seen. 387 var exported *types.TypeName 388 if named, ok := recv.(*types.Named); ok && named.Obj().Exported() { 389 exported = named.Obj() 390 } 391 // We don't want the last element, as that's the field or 392 // method itself. 393 for _, index := range sel.Index()[:len(sel.Index())-1] { 394 if r, ok := recv.Underlying().(*types.Struct); ok { 395 recv = Deref(r.Field(index).Type()) 396 if named, ok := recv.(*types.Named); ok && named.Obj().Exported() { 397 exported = named.Obj() 398 } 399 } 400 } 401 return exported 402 } 403 case *ast.CompositeLit: 404 if t, ok := info.Types[n]; ok { 405 if named, _ := t.Type.(*types.Named); named != nil { 406 return named.Obj() 407 } 408 } 409 case *ast.TypeSpec: 410 if _, ok := n.Type.(*ast.StructType); ok { 411 if t, ok := info.Defs[n.Name]; ok { 412 if tname, _ := t.(*types.TypeName); tname != nil { 413 return tname 414 } 415 } 416 } 417 } 418 } 419 return nil 420 } 421 422 func typeToObject(typ types.Type) types.Object { 423 switch typ := typ.(type) { 424 case *types.Named: 425 return typ.Obj() 426 case *types.Pointer: 427 return typeToObject(typ.Elem()) 428 case *types.Array: 429 return typeToObject(typ.Elem()) 430 case *types.Slice: 431 return typeToObject(typ.Elem()) 432 case *types.Chan: 433 return typeToObject(typ.Elem()) 434 case *types.Signature: 435 // Try to find a return value of a named type. If there's only one 436 // such value, jump to its type definition. 437 var res types.Object 438 439 results := typ.Results() 440 for i := 0; i < results.Len(); i++ { 441 obj := typeToObject(results.At(i).Type()) 442 if obj == nil || hasErrorType(obj) { 443 // Skip builtins. 444 continue 445 } 446 if res != nil { 447 // The function/method must have only one return value of a named type. 448 return nil 449 } 450 451 res = obj 452 } 453 return res 454 default: 455 return nil 456 } 457 } 458 459 func hasErrorType(obj types.Object) bool { 460 return types.IsInterface(obj.Type()) && obj.Pkg() == nil && obj.Name() == "error" 461 } 462 463 // importSpec handles positions inside of an *ast.ImportSpec. 464 func importSpec(snapshot Snapshot, pkg Package, file *ast.File, pos token.Pos) (*IdentifierInfo, error) { 465 var imp *ast.ImportSpec 466 for _, spec := range file.Imports { 467 if spec.Path.Pos() <= pos && pos < spec.Path.End() { 468 imp = spec 469 } 470 } 471 if imp == nil { 472 return nil, nil 473 } 474 importPath, err := strconv.Unquote(imp.Path.Value) 475 if err != nil { 476 return nil, errors.Errorf("import path not quoted: %s (%v)", imp.Path.Value, err) 477 } 478 result := &IdentifierInfo{ 479 Snapshot: snapshot, 480 Name: importPath, 481 pkg: pkg, 482 } 483 if result.MappedRange, err = posToMappedRange(snapshot, pkg, imp.Path.Pos(), imp.Path.End()); err != nil { 484 return nil, err 485 } 486 // Consider the "declaration" of an import spec to be the imported package. 487 importedPkg, err := pkg.GetImport(importPath) 488 if err != nil { 489 return nil, err 490 } 491 // Return all of the files in the package as the definition of the import spec. 492 for _, dst := range importedPkg.GetSyntax() { 493 rng, err := posToMappedRange(snapshot, pkg, dst.Pos(), dst.End()) 494 if err != nil { 495 return nil, err 496 } 497 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng) 498 } 499 500 result.Declaration.node = imp 501 return result, nil 502 } 503 504 // typeSwitchImplicits returns all the implicit type switch objects that 505 // correspond to the leaf *ast.Ident. It also returns the original type 506 // associated with the identifier (outside of a case clause). 507 func typeSwitchImplicits(pkg Package, path []ast.Node) ([]types.Object, types.Type) { 508 ident, _ := path[0].(*ast.Ident) 509 if ident == nil { 510 return nil, nil 511 } 512 513 var ( 514 ts *ast.TypeSwitchStmt 515 assign *ast.AssignStmt 516 cc *ast.CaseClause 517 obj = pkg.GetTypesInfo().ObjectOf(ident) 518 ) 519 520 // Walk our ancestors to determine if our leaf ident refers to a 521 // type switch variable, e.g. the "a" from "switch a := b.(type)". 522 Outer: 523 for i := 1; i < len(path); i++ { 524 switch n := path[i].(type) { 525 case *ast.AssignStmt: 526 // Check if ident is the "a" in "a := foo.(type)". The "a" in 527 // this case has no types.Object, so check for ident equality. 528 if len(n.Lhs) == 1 && n.Lhs[0] == ident { 529 assign = n 530 } 531 case *ast.CaseClause: 532 // Check if ident is a use of "a" within a case clause. Each 533 // case clause implicitly maps "a" to a different types.Object, 534 // so check if ident's object is the case clause's implicit 535 // object. 536 if obj != nil && pkg.GetTypesInfo().Implicits[n] == obj { 537 cc = n 538 } 539 case *ast.TypeSwitchStmt: 540 // Look for the type switch that owns our previously found 541 // *ast.AssignStmt or *ast.CaseClause. 542 if n.Assign == assign { 543 ts = n 544 break Outer 545 } 546 547 for _, stmt := range n.Body.List { 548 if stmt == cc { 549 ts = n 550 break Outer 551 } 552 } 553 } 554 } 555 if ts == nil { 556 return nil, nil 557 } 558 // Our leaf ident refers to a type switch variable. Fan out to the 559 // type switch's implicit case clause objects. 560 var objs []types.Object 561 for _, cc := range ts.Body.List { 562 if ccObj := pkg.GetTypesInfo().Implicits[cc]; ccObj != nil { 563 objs = append(objs, ccObj) 564 } 565 } 566 // The right-hand side of a type switch should only have one 567 // element, and we need to track its type in order to generate 568 // hover information for implicit type switch variables. 569 var typ types.Type 570 if assign, ok := ts.Assign.(*ast.AssignStmt); ok && len(assign.Rhs) == 1 { 571 if rhs := assign.Rhs[0].(*ast.TypeAssertExpr); ok { 572 typ = pkg.GetTypesInfo().TypeOf(rhs.X) 573 } 574 } 575 return objs, typ 576 }