1
0
mirror of https://github.com/golang/go synced 2024-11-19 02:04:42 -07:00
go/internal/lsp/source/references.go
Suzy Mueller bca362e842 internal/lsp: add find all references
This change implements the find all references feature by finding all of
the uses and definitions of the identifier within the current package.

Testing for references is done using "refs" in the testdata files and
marking the references in the package.

Change-Id: Ieb44b68608e940df5f65c3052eb9ec974f6fae6c
Reviewed-on: https://go-review.googlesource.com/c/tools/+/181122
Run-TryBot: Suzy Mueller <suzmue@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-06-10 19:06:22 +00:00

57 lines
1.4 KiB
Go

package source
import (
"context"
"fmt"
"go/ast"
"golang.org/x/tools/internal/span"
)
// ReferenceInfo holds information about reference to an identifier in Go source.
type ReferenceInfo struct {
Name string
Range span.Range
ident *ast.Ident
}
// References returns a list of references for a given identifier within a package.
func (i *IdentifierInfo) References(ctx context.Context) ([]*ReferenceInfo, error) {
pkg := i.File.GetPackage(ctx)
if pkg == nil || pkg.IsIllTyped() {
return nil, fmt.Errorf("package for %s is ill typed", i.File.URI())
}
pkgInfo := pkg.GetTypesInfo()
if pkgInfo == nil {
return nil, fmt.Errorf("package %s has no types info", pkg.PkgPath())
}
// If the object declaration is nil, assume it is an import spec and do not look for references.
declObj := i.decl.obj
if declObj == nil {
return []*ReferenceInfo{}, nil
}
var references []*ReferenceInfo
for ident, obj := range pkgInfo.Defs {
if obj == declObj {
references = append(references, &ReferenceInfo{
Name: ident.Name,
Range: span.NewRange(i.File.FileSet(), ident.Pos(), ident.End()),
ident: ident,
})
}
}
for ident, obj := range pkgInfo.Uses {
if obj == declObj {
references = append(references, &ReferenceInfo{
Name: ident.Name,
Range: span.NewRange(i.File.FileSet(), ident.Pos(), ident.End()),
ident: ident,
})
}
}
return references, nil
}