Skip to content

Commit

Permalink
internal/lsp: Refactor to share logic with rename
Browse files Browse the repository at this point in the history
If a package is being operated on, getPackage returns that package information; otherwise nil.

Change-Id: I881056510b8d6862c274a7532fdfbc840c938468
Reviewed-on: https://go-review.googlesource.com/c/tools/+/418791
TryBot-Result: Gopher Robot <gobot@golang.org>
gopls-CI: kokoro <noreply+kokoro@google.com>
Run-TryBot: Dylan Le <dungtuanle@google.com>
Reviewed-by: Robert Findley <rfindley@google.com>
  • Loading branch information
Dylan Le committed Jul 25, 2022
1 parent 4375b29 commit 2a6393f
Showing 1 changed file with 14 additions and 13 deletions.
27 changes: 14 additions & 13 deletions internal/lsp/source/references.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/lsp/bug"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/lsp/safetoken"
"golang.org/x/tools/internal/span"
)

Expand All @@ -32,6 +31,18 @@ type ReferenceInfo struct {
isDeclaration bool
}

// isInPackageName reports whether the file's package name surrounds the
// given position pp (e.g. "foo" surrounds the cursor in "package foo").
func isInPackageName(ctx context.Context, s Snapshot, f FileHandle, pgf *ParsedGoFile, pp protocol.Position) (bool, error) {
// Find position of the package name declaration
cursorPos, err := pgf.Mapper.Pos(pp)
if err != nil {
return false, err
}

return pgf.File.Name.Pos() <= cursorPos && cursorPos <= pgf.File.Name.End(), nil
}

// References returns a list of references for a given identifier within the packages
// containing i.File. Declarations appear first in the result.
func References(ctx context.Context, s Snapshot, f FileHandle, pp protocol.Position, includeDeclaration bool) ([]*ReferenceInfo, error) {
Expand All @@ -44,23 +55,13 @@ func References(ctx context.Context, s Snapshot, f FileHandle, pp protocol.Posit
return nil, err
}

cursorOffset, err := pgf.Mapper.Offset(pp)
if err != nil {
return nil, err
}

packageName := pgf.File.Name.Name // from package decl
packageNameStart, err := safetoken.Offset(pgf.Tok, pgf.File.Name.Pos())
if err != nil {
return nil, err
}

packageNameEnd, err := safetoken.Offset(pgf.Tok, pgf.File.Name.End())
inPackageName, err := isInPackageName(ctx, s, f, pgf, pp)
if err != nil {
return nil, err
}

if packageNameStart <= cursorOffset && cursorOffset < packageNameEnd {
if inPackageName {
renamingPkg, err := s.PackageForFile(ctx, f.URI(), TypecheckAll, NarrowestPackage)
if err != nil {
return nil, err
Expand Down

0 comments on commit 2a6393f

Please sign in to comment.