From 2a6393fe54b36af368a3d319f92cd3b1efee7741 Mon Sep 17 00:00:00 2001 From: Dylan Le Date: Thu, 21 Jul 2022 14:30:30 -0400 Subject: [PATCH] internal/lsp: Refactor to share logic with rename 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 gopls-CI: kokoro Run-TryBot: Dylan Le Reviewed-by: Robert Findley --- internal/lsp/source/references.go | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/internal/lsp/source/references.go b/internal/lsp/source/references.go index a1643fbec6c..2bbdc0741ca 100644 --- a/internal/lsp/source/references.go +++ b/internal/lsp/source/references.go @@ -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" ) @@ -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) { @@ -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