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