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.
16 "golang.org/x/tools/internal/event"
17 "golang.org/x/tools/internal/lsp/protocol"
18 errors "golang.org/x/xerrors"
21 // IdentifierInfo holds information about an identifier in Go source.
22 type IdentifierInfo struct {
32 Declaration Declaration
36 // enclosing is an expression used to determine the link anchor for an
37 // identifier. If it's a named type, it should be exported.
44 type Declaration struct {
45 MappedRange []MappedRange
49 // typeSwitchImplicit indicates that the declaration is in an implicit
50 // type switch. Its type is the type of the variable on the right-hand
51 // side of the type switch.
52 typeSwitchImplicit types.Type
55 // Identifier returns identifier information for a position
56 // in a file, accounting for a potentially incomplete selector.
57 func Identifier(ctx context.Context, snapshot Snapshot, fh FileHandle, pos protocol.Position) (*IdentifierInfo, error) {
58 ctx, done := event.Start(ctx, "source.Identifier")
61 pkgs, err := snapshot.PackagesForFile(ctx, fh.URI(), TypecheckAll)
66 return nil, fmt.Errorf("no packages for file %v", fh.URI())
68 sort.Slice(pkgs, func(i, j int) bool {
69 return len(pkgs[i].CompiledGoFiles()) < len(pkgs[j].CompiledGoFiles())
72 for _, pkg := range pkgs {
73 pgf, err := pkg.File(fh.URI())
77 spn, err := pgf.Mapper.PointSpan(pos)
81 rng, err := spn.Range(pgf.Mapper.Converter)
85 var ident *IdentifierInfo
86 ident, findErr = findIdentifier(ctx, snapshot, pkg, pgf.File, rng.Start)
94 // ErrNoIdentFound is error returned when no identifer is found at a particular position
95 var ErrNoIdentFound = errors.New("no identifier found")
97 func findIdentifier(ctx context.Context, snapshot Snapshot, pkg Package, file *ast.File, pos token.Pos) (*IdentifierInfo, error) {
98 // Handle import specs separately, as there is no formal position for a
99 // package declaration.
100 if result, err := importSpec(snapshot, pkg, file, pos); result != nil || err != nil {
101 if snapshot.View().Options().ImportShortcut.ShowDefinition() {
106 path := pathEnclosingObjNode(file, pos)
108 return nil, ErrNoIdentFound
111 qf := Qualifier(file, pkg.GetTypes(), pkg.GetTypesInfo())
113 ident, _ := path[0].(*ast.Ident)
115 return nil, ErrNoIdentFound
117 // Special case for package declarations, since they have no
118 // corresponding types.Object.
119 if ident == file.Name {
120 rng, err := posToMappedRange(snapshot, pkg, file.Name.Pos(), file.Name.End())
124 var declAST *ast.File
125 for _, pgf := range pkg.CompiledGoFiles() {
126 if pgf.File.Doc != nil {
130 // If there's no package documentation, just use current file.
134 declRng, err := posToMappedRange(snapshot, pkg, declAST.Name.Pos(), declAST.Name.End())
138 return &IdentifierInfo{
139 Name: file.Name.Name,
145 Declaration: Declaration{
147 MappedRange: []MappedRange{declRng},
152 result := &IdentifierInfo{
157 enclosing: searchForEnclosing(pkg.GetTypesInfo(), path),
160 result.Name = result.ident.Name
162 if result.MappedRange, err = posToMappedRange(snapshot, pkg, result.ident.Pos(), result.ident.End()); err != nil {
166 result.Declaration.obj = pkg.GetTypesInfo().ObjectOf(result.ident)
167 if result.Declaration.obj == nil {
168 // If there was no types.Object for the declaration, there might be an
169 // implicit local variable declaration in a type switch.
170 if objs, typ := typeSwitchImplicits(pkg, path); len(objs) > 0 {
171 // There is no types.Object for the declaration of an implicit local variable,
172 // but all of the types.Objects associated with the usages of this variable can be
173 // used to connect it back to the declaration.
174 // Preserve the first of these objects and treat it as if it were the declaring object.
175 result.Declaration.obj = objs[0]
176 result.Declaration.typeSwitchImplicit = typ
178 // Probably a type error.
179 return nil, errors.Errorf("%w for ident %v", errNoObjectFound, result.Name)
183 // Handle builtins separately.
184 if result.Declaration.obj.Parent() == types.Universe {
185 builtin, err := snapshot.BuiltinPackage(ctx)
189 builtinObj := builtin.Package.Scope.Lookup(result.Name)
190 if builtinObj == nil {
191 return nil, fmt.Errorf("no builtin object for %s", result.Name)
193 decl, ok := builtinObj.Decl.(ast.Node)
195 return nil, errors.Errorf("no declaration for %s", result.Name)
197 result.Declaration.node = decl
199 // The builtin package isn't in the dependency graph, so the usual
200 // utilities won't work here.
201 rng := NewMappedRange(snapshot.FileSet(), builtin.ParsedFile.Mapper, decl.Pos(), decl.Pos()+token.Pos(len(result.Name)))
202 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
206 // (error).Error is a special case of builtin. Lots of checks to confirm
207 // that this is the builtin Error.
208 if obj := result.Declaration.obj; obj.Parent() == nil && obj.Pkg() == nil && obj.Name() == "Error" {
209 if _, ok := obj.Type().(*types.Signature); ok {
210 builtin, err := snapshot.BuiltinPackage(ctx)
214 // Look up "error" and then navigate to its only method.
215 // The Error method does not appear in the builtin package's scope.log.Pri
216 const errorName = "error"
217 builtinObj := builtin.Package.Scope.Lookup(errorName)
218 if builtinObj == nil {
219 return nil, fmt.Errorf("no builtin object for %s", errorName)
221 decl, ok := builtinObj.Decl.(ast.Node)
223 return nil, errors.Errorf("no declaration for %s", errorName)
225 spec, ok := decl.(*ast.TypeSpec)
227 return nil, fmt.Errorf("no type spec for %s", errorName)
229 iface, ok := spec.Type.(*ast.InterfaceType)
231 return nil, fmt.Errorf("%s is not an interface", errorName)
233 if iface.Methods.NumFields() != 1 {
234 return nil, fmt.Errorf("expected 1 method for %s, got %v", errorName, iface.Methods.NumFields())
236 method := iface.Methods.List[0]
237 if len(method.Names) != 1 {
238 return nil, fmt.Errorf("expected 1 name for %v, got %v", method, len(method.Names))
240 name := method.Names[0].Name
241 result.Declaration.node = method
242 rng := NewMappedRange(snapshot.FileSet(), builtin.ParsedFile.Mapper, method.Pos(), method.Pos()+token.Pos(len(name)))
243 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
248 // If the original position was an embedded field, we want to jump
249 // to the field's type definition, not the field's definition.
250 if v, ok := result.Declaration.obj.(*types.Var); ok && v.Embedded() {
251 // types.Info.Uses contains the embedded field's *types.TypeName.
252 if typeName := pkg.GetTypesInfo().Uses[ident]; typeName != nil {
253 result.Declaration.obj = typeName
257 rng, err := objToMappedRange(snapshot, pkg, result.Declaration.obj)
261 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
263 if result.Declaration.node, err = objToDecl(ctx, snapshot, pkg, result.Declaration.obj); err != nil {
266 typ := pkg.GetTypesInfo().TypeOf(result.ident)
271 result.Type.Object = typeToObject(typ)
272 if result.Type.Object != nil {
273 // Identifiers with the type "error" are a special case with no position.
274 if hasErrorType(result.Type.Object) {
277 if result.Type.MappedRange, err = objToMappedRange(snapshot, pkg, result.Type.Object); err != nil {
284 func searchForEnclosing(info *types.Info, path []ast.Node) types.Type {
285 for _, n := range path {
286 switch n := n.(type) {
287 case *ast.SelectorExpr:
288 if sel, ok := info.Selections[n]; ok {
289 recv := Deref(sel.Recv())
291 // Keep track of the last exported type seen.
292 var exported types.Type
293 if named, ok := recv.(*types.Named); ok && named.Obj().Exported() {
296 // We don't want the last element, as that's the field or
298 for _, index := range sel.Index()[:len(sel.Index())-1] {
299 if r, ok := recv.Underlying().(*types.Struct); ok {
300 recv = Deref(r.Field(index).Type())
301 if named, ok := recv.(*types.Named); ok && named.Obj().Exported() {
308 case *ast.CompositeLit:
309 if t, ok := info.Types[n]; ok {
313 if _, ok := n.Type.(*ast.StructType); ok {
314 if t, ok := info.Defs[n.Name]; ok {
323 func typeToObject(typ types.Type) types.Object {
324 switch typ := typ.(type) {
328 return typeToObject(typ.Elem())
334 func hasErrorType(obj types.Object) bool {
335 return types.IsInterface(obj.Type()) && obj.Pkg() == nil && obj.Name() == "error"
338 func objToDecl(ctx context.Context, snapshot Snapshot, srcPkg Package, obj types.Object) (ast.Decl, error) {
339 pgf, _, err := FindPosInPackage(snapshot, srcPkg, obj.Pos())
343 posToDecl, err := snapshot.PosToDecl(ctx, pgf)
347 return posToDecl[obj.Pos()], nil
350 // importSpec handles positions inside of an *ast.ImportSpec.
351 func importSpec(snapshot Snapshot, pkg Package, file *ast.File, pos token.Pos) (*IdentifierInfo, error) {
352 var imp *ast.ImportSpec
353 for _, spec := range file.Imports {
354 if spec.Path.Pos() <= pos && pos < spec.Path.End() {
361 importPath, err := strconv.Unquote(imp.Path.Value)
363 return nil, errors.Errorf("import path not quoted: %s (%v)", imp.Path.Value, err)
365 result := &IdentifierInfo{
370 if result.MappedRange, err = posToMappedRange(snapshot, pkg, imp.Path.Pos(), imp.Path.End()); err != nil {
373 // Consider the "declaration" of an import spec to be the imported package.
374 importedPkg, err := pkg.GetImport(importPath)
378 // Return all of the files in the package as the definition of the import spec.
379 for _, dst := range importedPkg.GetSyntax() {
380 rng, err := posToMappedRange(snapshot, pkg, dst.Pos(), dst.End())
384 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
387 result.Declaration.node = imp
391 // typeSwitchImplicits returns all the implicit type switch objects that
392 // correspond to the leaf *ast.Ident. It also returns the original type
393 // associated with the identifier (outside of a case clause).
394 func typeSwitchImplicits(pkg Package, path []ast.Node) ([]types.Object, types.Type) {
395 ident, _ := path[0].(*ast.Ident)
401 ts *ast.TypeSwitchStmt
402 assign *ast.AssignStmt
404 obj = pkg.GetTypesInfo().ObjectOf(ident)
407 // Walk our ancestors to determine if our leaf ident refers to a
408 // type switch variable, e.g. the "a" from "switch a := b.(type)".
410 for i := 1; i < len(path); i++ {
411 switch n := path[i].(type) {
412 case *ast.AssignStmt:
413 // Check if ident is the "a" in "a := foo.(type)". The "a" in
414 // this case has no types.Object, so check for ident equality.
415 if len(n.Lhs) == 1 && n.Lhs[0] == ident {
418 case *ast.CaseClause:
419 // Check if ident is a use of "a" within a case clause. Each
420 // case clause implicitly maps "a" to a different types.Object,
421 // so check if ident's object is the case clause's implicit
423 if obj != nil && pkg.GetTypesInfo().Implicits[n] == obj {
426 case *ast.TypeSwitchStmt:
427 // Look for the type switch that owns our previously found
428 // *ast.AssignStmt or *ast.CaseClause.
429 if n.Assign == assign {
434 for _, stmt := range n.Body.List {
445 // Our leaf ident refers to a type switch variable. Fan out to the
446 // type switch's implicit case clause objects.
447 var objs []types.Object
448 for _, cc := range ts.Body.List {
449 if ccObj := pkg.GetTypesInfo().Implicits[cc]; ccObj != nil {
450 objs = append(objs, ccObj)
453 // The right-hand side of a type switch should only have one
454 // element, and we need to track its type in order to generate
455 // hover information for implicit type switch variables.
457 if assign, ok := ts.Assign.(*ast.AssignStmt); ok && len(assign.Rhs) == 1 {
458 if rhs := assign.Rhs[0].(*ast.TypeAssertExpr); ok {
459 typ = pkg.GetTypesInfo().TypeOf(rhs.X)