From 37590b385d564de6d3b0aedae2b5821b3f357d1d Mon Sep 17 00:00:00 2001 From: Robert Findley Date: Tue, 19 Apr 2022 18:08:06 -0400 Subject: [PATCH] gopls: remove usage of golang.org/x/xerrors As of golang/go#50827, gopls no longer supports building at 1.12, and so usage of golang.org/x/xerrors can be replaced with the native support for error wrapping introduced in Go 1.13. Remove this usage as a step toward eliminating the xerrors dependency from x/tools. For golang/go#52442 Change-Id: Ibf459cc72402a30a6c2735dc620f76ed8a5e2525 Reviewed-on: https://go-review.googlesource.com/c/tools/+/401097 Run-TryBot: Robert Findley gopls-CI: kokoro TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor --- internal/lsp/cache/analysis.go | 15 +++--- internal/lsp/cache/check.go | 10 ++-- internal/lsp/cache/errors.go | 3 +- internal/lsp/cache/load.go | 12 ++--- internal/lsp/cache/parse.go | 13 +++-- internal/lsp/cache/pkg.go | 6 +-- internal/lsp/cache/session.go | 13 +++-- internal/lsp/cache/snapshot.go | 10 ++-- internal/lsp/cache/view.go | 5 +- internal/lsp/cache/workspace.go | 8 +-- internal/lsp/cmd/capabilities_test.go | 6 +-- internal/lsp/cmd/check.go | 3 +- internal/lsp/cmd/cmd.go | 5 +- internal/lsp/cmd/definition.go | 13 +++-- internal/lsp/cmd/format.go | 7 ++- internal/lsp/cmd/imports.go | 5 +- internal/lsp/cmd/links.go | 3 +- internal/lsp/cmd/prepare_rename.go | 4 +- internal/lsp/cmd/remote.go | 2 +- internal/lsp/cmd/rename.go | 5 +- internal/lsp/cmd/serve.go | 4 +- internal/lsp/cmd/suggested_fix.go | 5 +- internal/lsp/code_action.go | 3 +- internal/lsp/command.go | 14 +++--- internal/lsp/debug/serve.go | 4 +- internal/lsp/diagnostics.go | 2 +- internal/lsp/fake/editor.go | 50 +++++++++---------- internal/lsp/fake/sandbox.go | 8 +-- internal/lsp/fake/workdir.go | 15 +++--- internal/lsp/fake/workdir_windows.go | 3 +- internal/lsp/general.go | 5 +- internal/lsp/lsprpc/autostart_default.go | 6 +-- internal/lsp/lsprpc/autostart_posix.go | 8 ++- internal/lsp/lsprpc/binder.go | 5 +- internal/lsp/lsprpc/dialer.go | 7 ++- internal/lsp/lsprpc/lsprpc.go | 15 +++--- internal/lsp/lsprpc/middleware.go | 4 +- internal/lsp/mod/hover.go | 7 ++- internal/lsp/progress/progress.go | 6 +-- internal/lsp/protocol/protocol.go | 3 +- internal/lsp/protocol/span.go | 3 +- internal/lsp/protocol/tsclient.go | 4 +- internal/lsp/protocol/tsserver.go | 14 +++--- internal/lsp/protocol/typescript/code.ts | 3 +- internal/lsp/semantic.go | 10 ++-- internal/lsp/server.go | 3 +- internal/lsp/source/call_hierarchy.go | 2 +- internal/lsp/source/completion/completion.go | 5 +- internal/lsp/source/completion/format.go | 2 +- internal/lsp/source/completion/package.go | 4 +- .../lsp/source/completion/postfix_snippets.go | 3 +- internal/lsp/source/fix.go | 3 +- internal/lsp/source/highlight.go | 9 ++-- internal/lsp/source/hover.go | 6 +-- internal/lsp/source/identifier.go | 10 ++-- internal/lsp/source/implementation.go | 7 ++- internal/lsp/source/known_packages.go | 4 +- internal/lsp/source/options.go | 5 +- internal/lsp/source/references.go | 2 +- internal/lsp/source/rename.go | 15 +++--- internal/lsp/source/signature_help.go | 16 +++--- internal/lsp/source/source_test.go | 2 +- internal/lsp/source/symbols.go | 3 +- internal/lsp/source/util.go | 11 ++-- internal/lsp/source/view.go | 2 +- internal/lsp/text_synchronization.go | 12 ++--- internal/lsp/work/completion.go | 11 ++-- internal/lsp/work/hover.go | 12 ++--- internal/lsp/workspace.go | 6 +-- 69 files changed, 239 insertions(+), 272 deletions(-) diff --git a/internal/lsp/cache/analysis.go b/internal/lsp/cache/analysis.go index b5aebcc3cfb..e882fb46f07 100644 --- a/internal/lsp/cache/analysis.go +++ b/internal/lsp/cache/analysis.go @@ -21,7 +21,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/memoize" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) func (s *snapshot) Analyze(ctx context.Context, id string, analyzers []*source.Analyzer) ([]*source.Diagnostic, error) { @@ -96,7 +95,7 @@ func (s *snapshot) actionHandle(ctx context.Context, id PackageID, a *analysis.A return act, nil } if len(ph.key) == 0 { - return nil, errors.Errorf("actionHandle: no key for package %s", id) + return nil, fmt.Errorf("actionHandle: no key for package %s", id) } pkg, err := ph.check(ctx, s) if err != nil { @@ -162,10 +161,10 @@ func (act *actionHandle) analyze(ctx context.Context, snapshot *snapshot) ([]*so } data, ok := d.(*actionData) if !ok { - return nil, nil, errors.Errorf("unexpected type for %s:%s", act.pkg.ID(), act.analyzer.Name) + return nil, nil, fmt.Errorf("unexpected type for %s:%s", act.pkg.ID(), act.analyzer.Name) } if data == nil { - return nil, nil, errors.Errorf("unexpected nil analysis for %s:%s", act.pkg.ID(), act.analyzer.Name) + return nil, nil, fmt.Errorf("unexpected nil analysis for %s:%s", act.pkg.ID(), act.analyzer.Name) } return data.diagnostics, data.result, data.err } @@ -192,7 +191,7 @@ func execAll(ctx context.Context, snapshot *snapshot, actions []*actionHandle) ( } data, ok := v.(*actionData) if !ok { - return errors.Errorf("unexpected type for %s: %T", act, v) + return fmt.Errorf("unexpected type for %s: %T", act, v) } mu.Lock() @@ -212,7 +211,7 @@ func runAnalysis(ctx context.Context, snapshot *snapshot, analyzer *analysis.Ana } defer func() { if r := recover(); r != nil { - data.err = errors.Errorf("analysis %s for package %s panicked: %v", analyzer.Name, pkg.PkgPath(), r) + data.err = fmt.Errorf("analysis %s for package %s panicked: %v", analyzer.Name, pkg.PkgPath(), r) } }() @@ -327,7 +326,7 @@ func runAnalysis(ctx context.Context, snapshot *snapshot, analyzer *analysis.Ana analysisinternal.SetTypeErrors(pass, pkg.typeErrors) if pkg.IsIllTyped() { - data.err = errors.Errorf("analysis skipped due to errors in package") + data.err = fmt.Errorf("analysis skipped due to errors in package") return data } data.result, data.err = pass.Analyzer.Run(pass) @@ -336,7 +335,7 @@ func runAnalysis(ctx context.Context, snapshot *snapshot, analyzer *analysis.Ana } if got, want := reflect.TypeOf(data.result), pass.Analyzer.ResultType; got != want { - data.err = errors.Errorf( + data.err = fmt.Errorf( "internal error: on package %s, analyzer %s returned a result of type %v, but declared ResultType %v", pass.Pkg.Path(), pass.Analyzer, got, want) return data diff --git a/internal/lsp/cache/check.go b/internal/lsp/cache/check.go index f1668635406..fdc49087ae7 100644 --- a/internal/lsp/cache/check.go +++ b/internal/lsp/cache/check.go @@ -7,6 +7,7 @@ package cache import ( "bytes" "context" + "errors" "fmt" "go/ast" "go/types" @@ -29,7 +30,6 @@ import ( "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/internal/typesinternal" - errors "golang.org/x/xerrors" ) type packageHandleKey string @@ -144,7 +144,7 @@ func (s *snapshot) buildPackageHandle(ctx context.Context, id PackageID, mode so func (s *snapshot) buildKey(ctx context.Context, id PackageID, mode source.ParseMode) (*packageHandle, map[PackagePath]*packageHandle, error) { m := s.getMetadata(id) if m == nil { - return nil, nil, errors.Errorf("no metadata for %s", id) + return nil, nil, fmt.Errorf("no metadata for %s", id) } goFiles, err := s.parseGoHandles(ctx, m.GoFiles, mode) if err != nil { @@ -291,7 +291,7 @@ func (ph *packageHandle) ID() string { func (ph *packageHandle) cached(g *memoize.Generation) (*pkg, error) { v := ph.handle.Cached(g) if v == nil { - return nil, errors.Errorf("no cached type information for %s", ph.m.PkgPath) + return nil, fmt.Errorf("no cached type information for %s", ph.m.PkgPath) } data := v.(*packageData) return data.pkg, data.err @@ -494,7 +494,7 @@ func doTypeCheck(ctx context.Context, snapshot *snapshot, m *Metadata, mode sour if found { return pkg, nil } - return nil, errors.Errorf("no parsed files for package %s, expected: %v, errors: %v", pkg.m.PkgPath, pkg.compiledGoFiles, m.Errors) + return nil, fmt.Errorf("no parsed files for package %s, expected: %v, errors: %v", pkg.m.PkgPath, pkg.compiledGoFiles, m.Errors) } cfg := &types.Config{ @@ -511,7 +511,7 @@ func doTypeCheck(ctx context.Context, snapshot *snapshot, m *Metadata, mode sour return nil, snapshot.missingPkgError(ctx, pkgPath) } if !source.IsValidImport(string(m.PkgPath), string(dep.m.PkgPath)) { - return nil, errors.Errorf("invalid use of internal package %s", pkgPath) + return nil, fmt.Errorf("invalid use of internal package %s", pkgPath) } depPkg, err := dep.check(ctx, snapshot) if err != nil { diff --git a/internal/lsp/cache/errors.go b/internal/lsp/cache/errors.go index a9e296d17ba..08db103e7c3 100644 --- a/internal/lsp/cache/errors.go +++ b/internal/lsp/cache/errors.go @@ -21,7 +21,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/typesinternal" - errors "golang.org/x/xerrors" ) func goPackagesErrorDiagnostics(snapshot *snapshot, pkg *pkg, e packages.Error) ([]*source.Diagnostic, error) { @@ -75,7 +74,7 @@ func goPackagesErrorDiagnostics(snapshot *snapshot, pkg *pkg, e packages.Error) func parseErrorDiagnostics(snapshot *snapshot, pkg *pkg, errList scanner.ErrorList) ([]*source.Diagnostic, error) { // The first parser error is likely the root cause of the problem. if errList.Len() <= 0 { - return nil, errors.Errorf("no errors in %v", errList) + return nil, fmt.Errorf("no errors in %v", errList) } e := errList[0] pgf, err := pkg.File(span.URIFromPath(e.Pos.Filename)) diff --git a/internal/lsp/cache/load.go b/internal/lsp/cache/load.go index 2095dc61b17..41b1ad55d37 100644 --- a/internal/lsp/cache/load.go +++ b/internal/lsp/cache/load.go @@ -7,6 +7,7 @@ package cache import ( "context" "crypto/sha256" + "errors" "fmt" "io/ioutil" "os" @@ -24,7 +25,6 @@ import ( "golang.org/x/tools/internal/memoize" "golang.org/x/tools/internal/packagesinternal" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // load calls packages.Load for the given scopes, updating package metadata, @@ -135,7 +135,7 @@ func (s *snapshot) load(ctx context.Context, allowNetwork bool, scopes ...interf if err == nil { err = fmt.Errorf("no packages returned") } - return errors.Errorf("%v: %w", err, source.PackagesLoadError) + return fmt.Errorf("%v: %w", err, source.PackagesLoadError) } for _, pkg := range pkgs { if !containsDir || s.view.Options().VerboseOutput { @@ -152,7 +152,7 @@ func (s *snapshot) load(ctx context.Context, allowNetwork bool, scopes ...interf // Special case for the builtin package, as it has no dependencies. if pkg.PkgPath == "builtin" { if len(pkg.GoFiles) != 1 { - return errors.Errorf("only expected 1 file for builtin, got %v", len(pkg.GoFiles)) + return fmt.Errorf("only expected 1 file for builtin, got %v", len(pkg.GoFiles)) } s.setBuiltin(pkg.GoFiles[0]) continue @@ -213,7 +213,7 @@ You can work with multiple modules by opening each one as a workspace folder. Improvements to this workflow will be coming soon, and you can learn more here: https://github.com/golang/tools/blob/master/gopls/doc/workspace.md.` return &source.CriticalError{ - MainError: errors.Errorf(msg), + MainError: fmt.Errorf(msg), DiagList: s.applyCriticalErrorToFiles(ctx, msg, openFiles), } } @@ -249,7 +249,7 @@ You can learn more here: https://github.com/golang/tools/blob/master/gopls/doc/w } if len(srcDiags) != 0 { return &source.CriticalError{ - MainError: errors.Errorf(`You are working in a nested module. + MainError: fmt.Errorf(`You are working in a nested module. Please open it as a separate workspace folder. Learn more: https://github.com/golang/tools/blob/master/gopls/doc/workspace.md.`), DiagList: srcDiags, @@ -374,7 +374,7 @@ func (s *snapshot) setMetadataLocked(ctx context.Context, pkgPath PackagePath, p pkgPath = PackagePath(string(pkgPath) + suffix) } if _, ok := seen[id]; ok { - return nil, errors.Errorf("import cycle detected: %q", id) + return nil, fmt.Errorf("import cycle detected: %q", id) } // Recreate the metadata rather than reusing it to avoid locking. m := &Metadata{ diff --git a/internal/lsp/cache/parse.go b/internal/lsp/cache/parse.go index 3e86cd5e767..496ec062e90 100644 --- a/internal/lsp/cache/parse.go +++ b/internal/lsp/cache/parse.go @@ -26,7 +26,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/memoize" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // parseKey uniquely identifies a parsed Go file. @@ -249,7 +248,7 @@ func parseGo(ctx context.Context, fset *token.FileSet, fh source.FileHandle, mod ext := filepath.Ext(fh.URI().Filename()) if ext != ".go" && ext != "" { // files generated by cgo have no extension - return &parseGoData{err: errors.Errorf("cannot parse non-Go file %s", fh.URI())} + return &parseGoData{err: fmt.Errorf("cannot parse non-Go file %s", fh.URI())} } src, err := fh.Read() if err != nil { @@ -686,7 +685,7 @@ func fixAST(ctx context.Context, n ast.Node, tok *token.File, src []byte) (fixed // Recursively fix in our fixed node. _ = fixAST(ctx, parent, tok, src) } else { - err = errors.Errorf("unable to parse defer or go from *ast.BadStmt: %v", err) + err = fmt.Errorf("unable to parse defer or go from *ast.BadStmt: %v", err) } return false case *ast.BadExpr: @@ -1339,17 +1338,17 @@ func parseStmt(pos token.Pos, src []byte) (ast.Stmt, error) { // best-effort behavior, whereas ParseExpr fails hard on any error. fakeFile, err := parser.ParseFile(token.NewFileSet(), "", fileSrc, 0) if fakeFile == nil { - return nil, errors.Errorf("error reading fake file source: %v", err) + return nil, fmt.Errorf("error reading fake file source: %v", err) } // Extract our expression node from inside the fake file. if len(fakeFile.Decls) == 0 { - return nil, errors.Errorf("error parsing fake file: %v", err) + return nil, fmt.Errorf("error parsing fake file: %v", err) } fakeDecl, _ := fakeFile.Decls[0].(*ast.FuncDecl) if fakeDecl == nil || len(fakeDecl.Body.List) == 0 { - return nil, errors.Errorf("no statement in %s: %v", src, err) + return nil, fmt.Errorf("no statement in %s: %v", src, err) } stmt := fakeDecl.Body.List[0] @@ -1371,7 +1370,7 @@ func parseExpr(pos token.Pos, src []byte) (ast.Expr, error) { exprStmt, ok := stmt.(*ast.ExprStmt) if !ok { - return nil, errors.Errorf("no expr in %s: %v", src, err) + return nil, fmt.Errorf("no expr in %s: %v", src, err) } return exprStmt.X, nil diff --git a/internal/lsp/cache/pkg.go b/internal/lsp/cache/pkg.go index 0c7bf74d3b1..1217ec29fd4 100644 --- a/internal/lsp/cache/pkg.go +++ b/internal/lsp/cache/pkg.go @@ -5,6 +5,7 @@ package cache import ( + "fmt" "go/ast" "go/scanner" "go/types" @@ -12,7 +13,6 @@ import ( "golang.org/x/mod/module" "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // pkg contains the type information needed by the source package. @@ -70,7 +70,7 @@ func (p *pkg) File(uri span.URI) (*source.ParsedGoFile, error) { return gf, nil } } - return nil, errors.Errorf("no parsed file for %s in %v", uri, p.m.ID) + return nil, fmt.Errorf("no parsed file for %s in %v", uri, p.m.ID) } func (p *pkg) GetSyntax() []*ast.File { @@ -106,7 +106,7 @@ func (p *pkg) GetImport(pkgPath string) (source.Package, error) { return imp, nil } // Don't return a nil pointer because that still satisfies the interface. - return nil, errors.Errorf("no imported package for %s", pkgPath) + return nil, fmt.Errorf("no imported package for %s", pkgPath) } func (p *pkg) MissingDependencies() []string { diff --git a/internal/lsp/cache/session.go b/internal/lsp/cache/session.go index e86ed25cb4e..5575acab1e9 100644 --- a/internal/lsp/cache/session.go +++ b/internal/lsp/cache/session.go @@ -18,7 +18,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/xcontext" - errors "golang.org/x/xerrors" ) type Session struct { @@ -404,7 +403,7 @@ func (s *Session) dropView(ctx context.Context, v *View) (int, error) { return i, nil } } - return -1, errors.Errorf("view %s for %v not found", v.Name(), v.Folder()) + return -1, fmt.Errorf("view %s for %v not found", v.Name(), v.Folder()) } func (s *Session) ModifyFiles(ctx context.Context, changes []source.FileModification) error { @@ -614,7 +613,7 @@ func (s *Session) updateOverlays(ctx context.Context, changes []source.FileModif kind = source.FileKindForLang(c.LanguageID) default: if !ok { - return nil, errors.Errorf("updateOverlays: modifying unopened overlay %v", c.URI) + return nil, fmt.Errorf("updateOverlays: modifying unopened overlay %v", c.URI) } kind = o.kind } @@ -648,10 +647,10 @@ func (s *Session) updateOverlays(ctx context.Context, changes []source.FileModif case source.Save: // Make sure the version and content (if present) is the same. if false && o.version != version { // Client no longer sends the version - return nil, errors.Errorf("updateOverlays: saving %s at version %v, currently at %v", c.URI, c.Version, o.version) + return nil, fmt.Errorf("updateOverlays: saving %s at version %v, currently at %v", c.URI, c.Version, o.version) } if c.Text != nil && o.hash != hash { - return nil, errors.Errorf("updateOverlays: overlay %s changed on save", c.URI) + return nil, fmt.Errorf("updateOverlays: overlay %s changed on save", c.URI) } sameContentOnDisk = true default: @@ -676,10 +675,10 @@ func (s *Session) updateOverlays(ctx context.Context, changes []source.FileModif if c.Action == source.Open { view, err := s.ViewOf(o.uri) if err != nil { - return nil, errors.Errorf("updateOverlays: finding view for %s: %v", o.uri, err) + return nil, fmt.Errorf("updateOverlays: finding view for %s: %v", o.uri, err) } if kind := view.FileKind(o); kind == source.UnknownKind { - return nil, errors.Errorf("updateOverlays: unknown file kind for %s", o.uri) + return nil, fmt.Errorf("updateOverlays: unknown file kind for %s", o.uri) } } diff --git a/internal/lsp/cache/snapshot.go b/internal/lsp/cache/snapshot.go index c7ea4835177..2860c97296c 100644 --- a/internal/lsp/cache/snapshot.go +++ b/internal/lsp/cache/snapshot.go @@ -7,6 +7,7 @@ package cache import ( "bytes" "context" + "errors" "fmt" "go/ast" "go/token" @@ -35,7 +36,6 @@ import ( "golang.org/x/tools/internal/packagesinternal" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/typesinternal" - errors "golang.org/x/xerrors" ) type snapshot struct { @@ -511,7 +511,7 @@ func (s *snapshot) PackageForFile(ctx context.Context, uri span.URI, mode source } if len(phs) < 1 { - return nil, errors.Errorf("no packages") + return nil, fmt.Errorf("no packages") } ph := phs[0] @@ -528,7 +528,7 @@ func (s *snapshot) PackageForFile(ctx context.Context, uri span.URI, mode source } } if ph == nil { - return nil, errors.Errorf("no packages in input") + return nil, fmt.Errorf("no packages in input") } return ph.check(ctx, s) @@ -2268,7 +2268,7 @@ func (s *snapshot) BuiltinFile(ctx context.Context) (*source.ParsedGoFile, error s.mu.Unlock() if builtin == "" { - return nil, errors.Errorf("no builtin package for view %s", s.view.name) + return nil, fmt.Errorf("no builtin package for view %s", s.view.name) } fh, err := s.GetFile(ctx, builtin) @@ -2425,7 +2425,7 @@ func buildWorkspaceSumFile(ctx context.Context, modFiles map[span.URI]struct{}, continue } if err != nil { - return nil, errors.Errorf("reading go sum: %w", err) + return nil, fmt.Errorf("reading go sum: %w", err) } if err := readGoSum(allSums, sumURI.Filename(), data); err != nil { return nil, err diff --git a/internal/lsp/cache/view.go b/internal/lsp/cache/view.go index cd879860a2c..17bdc40065d 100644 --- a/internal/lsp/cache/view.go +++ b/internal/lsp/cache/view.go @@ -31,7 +31,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/xcontext" - errors "golang.org/x/xerrors" ) type View struct { @@ -729,7 +728,7 @@ func (v *View) invalidateContent(ctx context.Context, changes map[span.URI]*file func (s *Session) getWorkspaceInformation(ctx context.Context, folder span.URI, options *source.Options) (*workspaceInformation, error) { if err := checkPathCase(folder.Filename()); err != nil { - return nil, errors.Errorf("invalid workspace folder path: %w; check that the casing of the configured workspace folder path agrees with the casing reported by the operating system", err) + return nil, fmt.Errorf("invalid workspace folder path: %w; check that the casing of the configured workspace folder path agrees with the casing reported by the operating system", err) } var err error inv := gocommand.Invocation{ @@ -810,7 +809,7 @@ func findWorkspaceRoot(ctx context.Context, folder span.URI, fs source.FileSourc for _, basename := range patterns { dir, err := findRootPattern(ctx, folder, basename, fs) if err != nil { - return "", errors.Errorf("finding %s: %w", basename, err) + return "", fmt.Errorf("finding %s: %w", basename, err) } if dir != "" { return dir, nil diff --git a/internal/lsp/cache/workspace.go b/internal/lsp/cache/workspace.go index f6c270e78fb..669ce9290c9 100644 --- a/internal/lsp/cache/workspace.go +++ b/internal/lsp/cache/workspace.go @@ -6,6 +6,7 @@ package cache import ( "context" + "errors" "fmt" "os" "path/filepath" @@ -18,7 +19,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/xcontext" - errors "golang.org/x/xerrors" ) // workspaceSource reports how the set of active modules has been derived. @@ -491,7 +491,7 @@ func getLegacyModules(ctx context.Context, root span.URI, fs source.FileSource) func parseGoWork(ctx context.Context, root, uri span.URI, contents []byte, fs source.FileSource) (*modfile.File, map[span.URI]struct{}, error) { workFile, err := modfile.ParseWork(uri.Filename(), contents, nil) if err != nil { - return nil, nil, errors.Errorf("parsing go.work: %w", err) + return nil, nil, fmt.Errorf("parsing go.work: %w", err) } modFiles := make(map[span.URI]struct{}) for _, dir := range workFile.Use { @@ -520,12 +520,12 @@ func parseGoWork(ctx context.Context, root, uri span.URI, contents []byte, fs so func parseGoplsMod(root, uri span.URI, contents []byte) (*modfile.File, map[span.URI]struct{}, error) { modFile, err := modfile.Parse(uri.Filename(), contents, nil) if err != nil { - return nil, nil, errors.Errorf("parsing gopls.mod: %w", err) + return nil, nil, fmt.Errorf("parsing gopls.mod: %w", err) } modFiles := make(map[span.URI]struct{}) for _, replace := range modFile.Replace { if replace.New.Version != "" { - return nil, nil, errors.Errorf("gopls.mod: replaced module %q@%q must not have version", replace.New.Path, replace.New.Version) + return nil, nil, fmt.Errorf("gopls.mod: replaced module %q@%q must not have version", replace.New.Path, replace.New.Version) } // The resulting modfile must use absolute paths, so that it can be // written to a temp directory. diff --git a/internal/lsp/cmd/capabilities_test.go b/internal/lsp/cmd/capabilities_test.go index 70db8d7d33e..1d01b4bd0d7 100644 --- a/internal/lsp/cmd/capabilities_test.go +++ b/internal/lsp/cmd/capabilities_test.go @@ -6,6 +6,7 @@ package cmd import ( "context" + "fmt" "io/ioutil" "os" "path/filepath" @@ -14,7 +15,6 @@ import ( "golang.org/x/tools/internal/lsp" "golang.org/x/tools/internal/lsp/cache" "golang.org/x/tools/internal/lsp/protocol" - errors "golang.org/x/xerrors" ) // TestCapabilities does some minimal validation of the server's adherence to the LSP. @@ -156,11 +156,11 @@ func validateCapabilities(result *protocol.InitializeResult) error { // If the client sends "false" for RenameProvider.PrepareSupport, // the server must respond with a boolean. if v, ok := result.Capabilities.RenameProvider.(bool); !ok { - return errors.Errorf("RenameProvider must be a boolean if PrepareSupport is false (got %T)", v) + return fmt.Errorf("RenameProvider must be a boolean if PrepareSupport is false (got %T)", v) } // The same goes for CodeActionKind.ValueSet. if v, ok := result.Capabilities.CodeActionProvider.(bool); !ok { - return errors.Errorf("CodeActionSupport must be a boolean if CodeActionKind.ValueSet has length 0 (got %T)", v) + return fmt.Errorf("CodeActionSupport must be a boolean if CodeActionKind.ValueSet has length 0 (got %T)", v) } return nil } diff --git a/internal/lsp/cmd/check.go b/internal/lsp/cmd/check.go index 566924aa635..9a136699270 100644 --- a/internal/lsp/cmd/check.go +++ b/internal/lsp/cmd/check.go @@ -10,7 +10,6 @@ import ( "fmt" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // check implements the check verb for gopls. @@ -65,7 +64,7 @@ func (c *check) Run(ctx context.Context, args ...string) error { for _, d := range file.diagnostics { spn, err := file.mapper.RangeSpan(d.Range) if err != nil { - return errors.Errorf("Could not convert position %v for %q", d.Range, d.Message) + return fmt.Errorf("Could not convert position %v for %q", d.Range, d.Message) } fmt.Printf("%v: %v\n", spn, d.Message) } diff --git a/internal/lsp/cmd/cmd.go b/internal/lsp/cmd/cmd.go index d48398d0dcc..06e1d5f03cd 100644 --- a/internal/lsp/cmd/cmd.go +++ b/internal/lsp/cmd/cmd.go @@ -32,7 +32,6 @@ import ( "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/tool" "golang.org/x/tools/internal/xcontext" - errors "golang.org/x/xerrors" ) // Application is the main application as passed to tool.Main @@ -540,7 +539,7 @@ func (c *cmdClient) getFile(ctx context.Context, uri span.URI) *cmdFile { fname := uri.Filename() content, err := ioutil.ReadFile(fname) if err != nil { - file.err = errors.Errorf("getFile: %v: %v", uri, err) + file.err = fmt.Errorf("getFile: %v: %v", uri, err) return file } f := c.fset.AddFile(fname, -1, len(content)) @@ -580,7 +579,7 @@ func (c *connection) AddFile(ctx context.Context, uri span.URI) *cmdFile { }, } if err := c.Server.DidOpen(ctx, p); err != nil { - file.err = errors.Errorf("%v: %v", uri, err) + file.err = fmt.Errorf("%v: %v", uri, err) } return file } diff --git a/internal/lsp/cmd/definition.go b/internal/lsp/cmd/definition.go index f3c71b671f7..44e6fc8c717 100644 --- a/internal/lsp/cmd/definition.go +++ b/internal/lsp/cmd/definition.go @@ -16,7 +16,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/tool" - errors "golang.org/x/xerrors" ) // A Definition is the result of a 'definition' query. @@ -98,29 +97,29 @@ func (d *definition) Run(ctx context.Context, args ...string) error { } locs, err := conn.Definition(ctx, &p) if err != nil { - return errors.Errorf("%v: %v", from, err) + return fmt.Errorf("%v: %v", from, err) } if len(locs) == 0 { - return errors.Errorf("%v: not an identifier", from) + return fmt.Errorf("%v: not an identifier", from) } q := protocol.HoverParams{ TextDocumentPositionParams: tdpp, } hover, err := conn.Hover(ctx, &q) if err != nil { - return errors.Errorf("%v: %v", from, err) + return fmt.Errorf("%v: %v", from, err) } if hover == nil { - return errors.Errorf("%v: not an identifier", from) + return fmt.Errorf("%v: not an identifier", from) } file = conn.AddFile(ctx, fileURI(locs[0].URI)) if file.err != nil { - return errors.Errorf("%v: %v", from, file.err) + return fmt.Errorf("%v: %v", from, file.err) } definition, err := file.mapper.Span(locs[0]) if err != nil { - return errors.Errorf("%v: %v", from, err) + return fmt.Errorf("%v: %v", from, err) } description := strings.TrimSpace(hover.Contents.Value) result := &Definition{ diff --git a/internal/lsp/cmd/format.go b/internal/lsp/cmd/format.go index 2d0f3f7c37d..5e17ed4a570 100644 --- a/internal/lsp/cmd/format.go +++ b/internal/lsp/cmd/format.go @@ -14,7 +14,6 @@ import ( "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // format implements the format verb for gopls. @@ -68,18 +67,18 @@ func (c *format) Run(ctx context.Context, args ...string) error { return err } if loc.Range.Start != loc.Range.End { - return errors.Errorf("only full file formatting supported") + return fmt.Errorf("only full file formatting supported") } p := protocol.DocumentFormattingParams{ TextDocument: protocol.TextDocumentIdentifier{URI: loc.URI}, } edits, err := conn.Formatting(ctx, &p) if err != nil { - return errors.Errorf("%v: %v", spn, err) + return fmt.Errorf("%v: %v", spn, err) } sedits, err := source.FromProtocolEdits(file.mapper, edits) if err != nil { - return errors.Errorf("%v: %v", spn, err) + return fmt.Errorf("%v: %v", spn, err) } formatted := diff.ApplyEdits(string(file.mapper.Content), sedits) printIt := true diff --git a/internal/lsp/cmd/imports.go b/internal/lsp/cmd/imports.go index 215c57f11f0..49778603d23 100644 --- a/internal/lsp/cmd/imports.go +++ b/internal/lsp/cmd/imports.go @@ -15,7 +15,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/tool" - errors "golang.org/x/xerrors" ) // imports implements the import verb for gopls. @@ -67,7 +66,7 @@ func (t *imports) Run(ctx context.Context, args ...string) error { }, }) if err != nil { - return errors.Errorf("%v: %v", from, err) + return fmt.Errorf("%v: %v", from, err) } var edits []protocol.TextEdit for _, a := range actions { @@ -82,7 +81,7 @@ func (t *imports) Run(ctx context.Context, args ...string) error { } sedits, err := source.FromProtocolEdits(file.mapper, edits) if err != nil { - return errors.Errorf("%v: %v", edits, err) + return fmt.Errorf("%v: %v", edits, err) } newContent := diff.ApplyEdits(string(file.mapper.Content), sedits) diff --git a/internal/lsp/cmd/links.go b/internal/lsp/cmd/links.go index d49aabb6f8f..1c48c8c50b9 100644 --- a/internal/lsp/cmd/links.go +++ b/internal/lsp/cmd/links.go @@ -14,7 +14,6 @@ import ( "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/tool" - errors "golang.org/x/xerrors" ) // links implements the links verb for gopls. @@ -64,7 +63,7 @@ func (l *links) Run(ctx context.Context, args ...string) error { }, }) if err != nil { - return errors.Errorf("%v: %v", from, err) + return fmt.Errorf("%v: %v", from, err) } if l.JSON { enc := json.NewEncoder(os.Stdout) diff --git a/internal/lsp/cmd/prepare_rename.go b/internal/lsp/cmd/prepare_rename.go index aef0477e844..44a192b5be3 100644 --- a/internal/lsp/cmd/prepare_rename.go +++ b/internal/lsp/cmd/prepare_rename.go @@ -6,13 +6,13 @@ package cmd import ( "context" + "errors" "flag" "fmt" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/tool" - errors "golang.org/x/xerrors" ) // prepareRename implements the prepare_rename verb for gopls. @@ -67,7 +67,7 @@ func (r *prepareRename) Run(ctx context.Context, args ...string) error { } result, err := conn.PrepareRename(ctx, &p) if err != nil { - return errors.Errorf("prepare_rename failed: %w", err) + return fmt.Errorf("prepare_rename failed: %w", err) } if result == nil { return ErrInvalidRenamePosition diff --git a/internal/lsp/cmd/remote.go b/internal/lsp/cmd/remote.go index f71113576df..0f4c7216444 100644 --- a/internal/lsp/cmd/remote.go +++ b/internal/lsp/cmd/remote.go @@ -7,6 +7,7 @@ package cmd import ( "context" "encoding/json" + "errors" "flag" "fmt" "log" @@ -14,7 +15,6 @@ import ( "golang.org/x/tools/internal/lsp/command" "golang.org/x/tools/internal/lsp/lsprpc" - errors "golang.org/x/xerrors" ) type remote struct { diff --git a/internal/lsp/cmd/rename.go b/internal/lsp/cmd/rename.go index b0a22a1b43a..9411275949f 100644 --- a/internal/lsp/cmd/rename.go +++ b/internal/lsp/cmd/rename.go @@ -18,7 +18,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/tool" - errors "golang.org/x/xerrors" ) // rename implements the rename verb for gopls. @@ -97,7 +96,7 @@ func (r *rename) Run(ctx context.Context, args ...string) error { // convert LSP-style edits to []diff.TextEdit cuz Spans are handy renameEdits, err := source.FromProtocolEdits(cmdFile.mapper, edits[uri]) if err != nil { - return errors.Errorf("%v: %v", edits, err) + return fmt.Errorf("%v: %v", edits, err) } newContent := diff.ApplyEdits(string(cmdFile.mapper.Content), renameEdits) @@ -106,7 +105,7 @@ func (r *rename) Run(ctx context.Context, args ...string) error { fmt.Fprintln(os.Stderr, filename) if r.Preserve { if err := os.Rename(filename, filename+".orig"); err != nil { - return errors.Errorf("%v: %v", edits, err) + return fmt.Errorf("%v: %v", edits, err) } } ioutil.WriteFile(filename, []byte(newContent), 0644) diff --git a/internal/lsp/cmd/serve.go b/internal/lsp/cmd/serve.go index f6e26839755..1c229a422b4 100644 --- a/internal/lsp/cmd/serve.go +++ b/internal/lsp/cmd/serve.go @@ -6,6 +6,7 @@ package cmd import ( "context" + "errors" "flag" "fmt" "io" @@ -20,7 +21,6 @@ import ( "golang.org/x/tools/internal/lsp/lsprpc" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/tool" - errors "golang.org/x/xerrors" ) // Serve is a struct that exposes the configurable parts of the LSP server as @@ -98,7 +98,7 @@ func (s *Serve) Run(ctx context.Context, args ...string) error { var err error ss, err = lsprpc.NewForwarder(s.app.Remote, s.remoteArgs) if err != nil { - return errors.Errorf("creating forwarder: %w", err) + return fmt.Errorf("creating forwarder: %w", err) } } else { ss = lsprpc.NewStreamServer(cache.New(s.app.options), isDaemon) diff --git a/internal/lsp/cmd/suggested_fix.go b/internal/lsp/cmd/suggested_fix.go index df14631da52..c6f26e2d685 100644 --- a/internal/lsp/cmd/suggested_fix.go +++ b/internal/lsp/cmd/suggested_fix.go @@ -15,7 +15,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/tool" - errors "golang.org/x/xerrors" ) // suggestedFix implements the fix verb for gopls. @@ -92,7 +91,7 @@ func (s *suggestedFix) Run(ctx context.Context, args ...string) error { } actions, err := conn.CodeAction(ctx, &p) if err != nil { - return errors.Errorf("%v: %v", from, err) + return fmt.Errorf("%v: %v", from, err) } var edits []protocol.TextEdit for _, a := range actions { @@ -139,7 +138,7 @@ func (s *suggestedFix) Run(ctx context.Context, args ...string) error { sedits, err := source.FromProtocolEdits(file.mapper, edits) if err != nil { - return errors.Errorf("%v: %v", edits, err) + return fmt.Errorf("%v: %v", edits, err) } newContent := diff.ApplyEdits(string(file.mapper.Content), sedits) diff --git a/internal/lsp/code_action.go b/internal/lsp/code_action.go index 7ddf8129648..9d78e3c9ac9 100644 --- a/internal/lsp/code_action.go +++ b/internal/lsp/code_action.go @@ -18,7 +18,6 @@ import ( "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) func (s *Server) codeAction(ctx context.Context, params *protocol.CodeActionParams) ([]protocol.CodeAction, error) { @@ -287,7 +286,7 @@ func extractionFixes(ctx context.Context, snapshot source.Snapshot, pkg source.P } _, pgf, err := source.GetParsedFile(ctx, snapshot, fh, source.NarrowestPackage) if err != nil { - return nil, errors.Errorf("getting file for Identifier: %w", err) + return nil, fmt.Errorf("getting file for Identifier: %w", err) } srng, err := pgf.Mapper.RangeToSpanRange(rng) if err != nil { diff --git a/internal/lsp/command.go b/internal/lsp/command.go index 072ee08e805..5636f87808d 100644 --- a/internal/lsp/command.go +++ b/internal/lsp/command.go @@ -8,6 +8,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "io/ioutil" @@ -28,7 +29,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/xcontext" - errors "golang.org/x/xerrors" ) func (s *Server) executeCommand(ctx context.Context, params *protocol.ExecuteCommandParams) (interface{}, error) { @@ -83,7 +83,7 @@ func (c *commandHandler) run(ctx context.Context, cfg commandConfig, run command } } if len(unsaved) > 0 { - return errors.Errorf("All files must be saved first (unsaved: %v).", unsaved) + return fmt.Errorf("All files must be saved first (unsaved: %v).", unsaved) } } var deps commandDeps @@ -384,7 +384,7 @@ func (c *commandHandler) RunTests(ctx context.Context, args command.RunTestsArgs forURI: args.URI, }, func(ctx context.Context, deps commandDeps) error { if err := c.runTests(ctx, deps.snapshot, deps.work, args.URI, args.Tests, args.Benchmarks); err != nil { - return errors.Errorf("running tests failed: %w", err) + return fmt.Errorf("running tests failed: %w", err) } return nil }) @@ -689,15 +689,15 @@ func (c *commandHandler) GenerateGoplsMod(ctx context.Context, args command.URIA defer release() modFile, err := snapshot.BuildGoplsMod(ctx) if err != nil { - return errors.Errorf("getting workspace mod file: %w", err) + return fmt.Errorf("getting workspace mod file: %w", err) } content, err := modFile.Format() if err != nil { - return errors.Errorf("formatting mod file: %w", err) + return fmt.Errorf("formatting mod file: %w", err) } filename := filepath.Join(snapshot.View().Folder().Filename(), "gopls.mod") if err := ioutil.WriteFile(filename, content, 0644); err != nil { - return errors.Errorf("writing mod file: %w", err) + return fmt.Errorf("writing mod file: %w", err) } return nil }) @@ -788,7 +788,7 @@ func (c *commandHandler) StartDebugging(ctx context.Context, args command.Debugg } listenedAddr, err := di.Serve(ctx, addr) if err != nil { - return result, errors.Errorf("starting debug server: %w", err) + return result, fmt.Errorf("starting debug server: %w", err) } result.URLs = []string{"http://" + listenedAddr} return result, nil diff --git a/internal/lsp/debug/serve.go b/internal/lsp/debug/serve.go index b6dba60ab49..97790fc18ed 100644 --- a/internal/lsp/debug/serve.go +++ b/internal/lsp/debug/serve.go @@ -8,6 +8,7 @@ import ( "archive/zip" "bytes" "context" + "errors" "fmt" "html/template" "io" @@ -39,7 +40,6 @@ import ( "golang.org/x/tools/internal/lsp/debug/tag" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/lsp/source" - errors "golang.org/x/xerrors" ) type contextKeyType int @@ -436,7 +436,7 @@ func (i *Instance) SetLogFile(logfile string, isDaemon bool) (func(), error) { } f, err := os.Create(logfile) if err != nil { - return nil, errors.Errorf("unable to create log file: %w", err) + return nil, fmt.Errorf("unable to create log file: %w", err) } closeLog = func() { defer f.Close() diff --git a/internal/lsp/diagnostics.go b/internal/lsp/diagnostics.go index 3bf81226c4f..3c67ad67603 100644 --- a/internal/lsp/diagnostics.go +++ b/internal/lsp/diagnostics.go @@ -7,6 +7,7 @@ package lsp import ( "context" "crypto/sha256" + "errors" "fmt" "os" "path/filepath" @@ -24,7 +25,6 @@ import ( "golang.org/x/tools/internal/lsp/work" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/xcontext" - errors "golang.org/x/xerrors" ) // diagnosticSource differentiates different sources of diagnostics. diff --git a/internal/lsp/fake/editor.go b/internal/lsp/fake/editor.go index 91aea225111..06b90bb84e5 100644 --- a/internal/lsp/fake/editor.go +++ b/internal/lsp/fake/editor.go @@ -7,6 +7,7 @@ package fake import ( "bufio" "context" + "errors" "fmt" "os" "path" @@ -19,7 +20,6 @@ import ( "golang.org/x/tools/internal/lsp/command" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // Editor is a fake editor client. It keeps track of client state and can be @@ -172,7 +172,7 @@ func (e *Editor) Stats() CallCounts { func (e *Editor) Shutdown(ctx context.Context) error { if e.Server != nil { if err := e.Server.Shutdown(ctx); err != nil { - return errors.Errorf("Shutdown: %w", err) + return fmt.Errorf("Shutdown: %w", err) } } return nil @@ -184,7 +184,7 @@ func (e *Editor) Exit(ctx context.Context) error { // Not all LSP clients issue the exit RPC, but we do so here to ensure that // we gracefully handle it on multi-session servers. if err := e.Server.Exit(ctx); err != nil { - return errors.Errorf("Exit: %w", err) + return fmt.Errorf("Exit: %w", err) } } return nil @@ -204,7 +204,7 @@ func (e *Editor) Close(ctx context.Context) error { // connection closed itself return nil case <-ctx.Done(): - return errors.Errorf("connection not closed: %w", ctx.Err()) + return fmt.Errorf("connection not closed: %w", ctx.Err()) } } @@ -319,14 +319,14 @@ func (e *Editor) initialize(ctx context.Context, workspaceFolders []string) erro if e.Server != nil { resp, err := e.Server.Initialize(ctx, params) if err != nil { - return errors.Errorf("initialize: %w", err) + return fmt.Errorf("initialize: %w", err) } e.mu.Lock() e.serverCapabilities = resp.Capabilities e.mu.Unlock() if err := e.Server.Initialized(ctx, &protocol.InitializedParams{}); err != nil { - return errors.Errorf("initialized: %w", err) + return fmt.Errorf("initialized: %w", err) } } // TODO: await initial configuration here, or expect gopls to manage that? @@ -419,7 +419,7 @@ func (e *Editor) createBuffer(ctx context.Context, path string, dirty bool, cont if err := e.Server.DidOpen(ctx, &protocol.DidOpenTextDocumentParams{ TextDocument: item, }); err != nil { - return errors.Errorf("DidOpen: %w", err) + return fmt.Errorf("DidOpen: %w", err) } e.callsMu.Lock() e.calls.DidOpen++ @@ -476,7 +476,7 @@ func (e *Editor) CloseBuffer(ctx context.Context, path string) error { if err := e.Server.DidClose(ctx, &protocol.DidCloseTextDocumentParams{ TextDocument: e.textDocumentIdentifier(path), }); err != nil { - return errors.Errorf("DidClose: %w", err) + return fmt.Errorf("DidClose: %w", err) } e.callsMu.Lock() e.calls.DidClose++ @@ -495,10 +495,10 @@ func (e *Editor) textDocumentIdentifier(path string) protocol.TextDocumentIdenti // the filesystem. func (e *Editor) SaveBuffer(ctx context.Context, path string) error { if err := e.OrganizeImports(ctx, path); err != nil { - return errors.Errorf("organizing imports before save: %w", err) + return fmt.Errorf("organizing imports before save: %w", err) } if err := e.FormatBuffer(ctx, path); err != nil { - return errors.Errorf("formatting before save: %w", err) + return fmt.Errorf("formatting before save: %w", err) } return e.SaveBufferWithoutActions(ctx, path) } @@ -523,11 +523,11 @@ func (e *Editor) SaveBufferWithoutActions(ctx context.Context, path string) erro TextDocument: docID, Reason: protocol.Manual, }); err != nil { - return errors.Errorf("WillSave: %w", err) + return fmt.Errorf("WillSave: %w", err) } } if err := e.sandbox.Workdir.WriteFile(ctx, path, content); err != nil { - return errors.Errorf("writing %q: %w", path, err) + return fmt.Errorf("writing %q: %w", path, err) } buf.dirty = false @@ -541,7 +541,7 @@ func (e *Editor) SaveBufferWithoutActions(ctx context.Context, path string) erro params.Text = &content } if err := e.Server.DidSave(ctx, params); err != nil { - return errors.Errorf("DidSave: %w", err) + return fmt.Errorf("DidSave: %w", err) } e.callsMu.Lock() e.calls.DidSave++ @@ -565,7 +565,7 @@ func contentPosition(content string, offset int) (Pos, error) { line++ } if err := scanner.Err(); err != nil { - return Pos{}, errors.Errorf("scanning content: %w", err) + return Pos{}, fmt.Errorf("scanning content: %w", err) } // Scan() will drop the last line if it is empty. Correct for this. if (strings.HasSuffix(content, "\n") || content == "") && offset == start { @@ -745,7 +745,7 @@ func (e *Editor) setBufferContentLocked(ctx context.Context, path string, dirty } if e.Server != nil { if err := e.Server.DidChange(ctx, params); err != nil { - return errors.Errorf("DidChange: %w", err) + return fmt.Errorf("DidChange: %w", err) } e.callsMu.Lock() e.calls.DidChange++ @@ -766,7 +766,7 @@ func (e *Editor) GoToDefinition(ctx context.Context, path string, pos Pos) (stri resp, err := e.Server.Definition(ctx, params) if err != nil { - return "", Pos{}, errors.Errorf("definition: %w", err) + return "", Pos{}, fmt.Errorf("definition: %w", err) } return e.extractFirstPathAndPos(ctx, resp) } @@ -783,7 +783,7 @@ func (e *Editor) GoToTypeDefinition(ctx context.Context, path string, pos Pos) ( resp, err := e.Server.TypeDefinition(ctx, params) if err != nil { - return "", Pos{}, errors.Errorf("type definition: %w", err) + return "", Pos{}, fmt.Errorf("type definition: %w", err) } return e.extractFirstPathAndPos(ctx, resp) } @@ -799,7 +799,7 @@ func (e *Editor) extractFirstPathAndPos(ctx context.Context, locs []protocol.Loc newPos := fromProtocolPosition(locs[0].Range.Start) if !e.HasBuffer(newPath) { if err := e.OpenFile(ctx, newPath); err != nil { - return "", Pos{}, errors.Errorf("OpenFile: %w", err) + return "", Pos{}, fmt.Errorf("OpenFile: %w", err) } } return newPath, newPos, nil @@ -812,7 +812,7 @@ func (e *Editor) Symbol(ctx context.Context, query string) ([]SymbolInformation, resp, err := e.Server.Symbol(ctx, params) if err != nil { - return nil, errors.Errorf("symbol: %w", err) + return nil, fmt.Errorf("symbol: %w", err) } var res []SymbolInformation for _, si := range resp { @@ -847,7 +847,7 @@ func (e *Editor) OrganizeImports(ctx context.Context, path string) error { func (e *Editor) RefactorRewrite(ctx context.Context, path string, rng *protocol.Range) error { applied, err := e.applyCodeActions(ctx, path, rng, nil, protocol.RefactorRewrite) if applied == 0 { - return errors.Errorf("no refactorings were applied") + return fmt.Errorf("no refactorings were applied") } return err } @@ -856,7 +856,7 @@ func (e *Editor) RefactorRewrite(ctx context.Context, path string, rng *protocol func (e *Editor) ApplyQuickFixes(ctx context.Context, path string, rng *protocol.Range, diagnostics []protocol.Diagnostic) error { applied, err := e.applyCodeActions(ctx, path, rng, diagnostics, protocol.SourceFixAll, protocol.QuickFix) if applied == 0 { - return errors.Errorf("no quick fixes were applied") + return fmt.Errorf("no quick fixes were applied") } return err } @@ -871,7 +871,7 @@ func (e *Editor) ApplyCodeAction(ctx context.Context, action protocol.CodeAction } edits := convertEdits(change.Edits) if err := e.EditBuffer(ctx, path, edits); err != nil { - return errors.Errorf("editing buffer %q: %w", path, err) + return fmt.Errorf("editing buffer %q: %w", path, err) } } // Execute any commands. The specification says that commands are @@ -901,7 +901,7 @@ func (e *Editor) applyCodeActions(ctx context.Context, path string, rng *protoco applied := 0 for _, action := range actions { if action.Title == "" { - return 0, errors.Errorf("empty title for code action") + return 0, fmt.Errorf("empty title for code action") } var match bool for _, o := range only { @@ -984,7 +984,7 @@ func (e *Editor) FormatBuffer(ctx context.Context, path string) error { params.TextDocument.URI = e.sandbox.Workdir.URI(path) resp, err := e.Server.Formatting(ctx, params) if err != nil { - return errors.Errorf("textDocument/formatting: %w", err) + return fmt.Errorf("textDocument/formatting: %w", err) } e.mu.Lock() defer e.mu.Unlock() @@ -1222,7 +1222,7 @@ func (e *Editor) Hover(ctx context.Context, path string, pos Pos) (*protocol.Mar resp, err := e.Server.Hover(ctx, params) if err != nil { - return nil, Pos{}, errors.Errorf("hover: %w", err) + return nil, Pos{}, fmt.Errorf("hover: %w", err) } if resp == nil { return nil, Pos{}, nil diff --git a/internal/lsp/fake/sandbox.go b/internal/lsp/fake/sandbox.go index 86e91c8f138..b4395646bc6 100644 --- a/internal/lsp/fake/sandbox.go +++ b/internal/lsp/fake/sandbox.go @@ -6,6 +6,7 @@ package fake import ( "context" + "errors" "fmt" "io/ioutil" "os" @@ -15,7 +16,6 @@ import ( "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/testenv" "golang.org/x/tools/txtar" - errors "golang.org/x/xerrors" ) // Sandbox holds a collection of temporary resources to use for working with Go @@ -147,7 +147,7 @@ func Tempdir(files map[string][]byte) (string, error) { } for name, data := range files { if err := WriteFileData(name, data, RelativeTo(dir)); err != nil { - return "", errors.Errorf("writing to tempdir: %w", err) + return "", fmt.Errorf("writing to tempdir: %w", err) } } return dir, nil @@ -245,7 +245,7 @@ func (sb *Sandbox) RunGoCommand(ctx context.Context, dir, verb string, args []st gocmdRunner := &gocommand.Runner{} stdout, stderr, _, err := gocmdRunner.RunRaw(ctx, inv) if err != nil { - return errors.Errorf("go command failed (stdout: %s) (stderr: %s): %v", stdout.String(), stderr.String(), err) + return fmt.Errorf("go command failed (stdout: %s) (stderr: %s): %v", stdout.String(), stderr.String(), err) } // Since running a go command may result in changes to workspace files, // check if we need to send any any "watched" file events. @@ -254,7 +254,7 @@ func (sb *Sandbox) RunGoCommand(ctx context.Context, dir, verb string, args []st // for benchmarks. Consider refactoring. if sb.Workdir != nil && checkForFileChanges { if err := sb.Workdir.CheckForFileChanges(ctx); err != nil { - return errors.Errorf("checking for file changes: %w", err) + return fmt.Errorf("checking for file changes: %w", err) } } return nil diff --git a/internal/lsp/fake/workdir.go b/internal/lsp/fake/workdir.go index ddef95ca19b..734f5fd8197 100644 --- a/internal/lsp/fake/workdir.go +++ b/internal/lsp/fake/workdir.go @@ -19,7 +19,6 @@ import ( "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // FileEvent wraps the protocol.FileEvent so that it can be associated with a @@ -57,7 +56,7 @@ func WriteFileData(path string, content []byte, rel RelativeTo) error { content = bytes.ReplaceAll(content, []byte("$SANDBOX_WORKDIR"), []byte(rel)) fp := rel.AbsPath(path) if err := os.MkdirAll(filepath.Dir(fp), 0755); err != nil { - return errors.Errorf("creating nested directory: %w", err) + return fmt.Errorf("creating nested directory: %w", err) } backoff := 1 * time.Millisecond for { @@ -68,7 +67,7 @@ func WriteFileData(path string, content []byte, rel RelativeTo) error { backoff *= 2 continue } - return errors.Errorf("writing %q: %w", path, err) + return fmt.Errorf("writing %q: %w", path, err) } return nil } @@ -127,7 +126,7 @@ func (w *Workdir) writeInitialFiles(files map[string][]byte) error { w.files = map[string]fileID{} for name, data := range files { if err := WriteFileData(name, data, w.RelativeTo); err != nil { - return errors.Errorf("writing to workdir: %w", err) + return fmt.Errorf("writing to workdir: %w", err) } fp := w.AbsPath(name) @@ -140,7 +139,7 @@ func (w *Workdir) writeInitialFiles(files map[string][]byte) error { // between identifiers are considered to be benign. fi, err := os.Stat(fp) if err != nil { - return errors.Errorf("reading file info: %v", err) + return fmt.Errorf("reading file info: %v", err) } w.files[name] = fileID{ @@ -226,7 +225,7 @@ func (w *Workdir) ChangeFilesOnDisk(ctx context.Context, events []FileEvent) err case protocol.Deleted: fp := w.AbsPath(e.Path) if err := os.Remove(fp); err != nil { - return errors.Errorf("removing %q: %w", e.Path, err) + return fmt.Errorf("removing %q: %w", e.Path, err) } case protocol.Changed, protocol.Created: if _, err := w.writeFile(ctx, e.Path, e.Content); err != nil { @@ -242,7 +241,7 @@ func (w *Workdir) ChangeFilesOnDisk(ctx context.Context, events []FileEvent) err func (w *Workdir) RemoveFile(ctx context.Context, path string) error { fp := w.AbsPath(path) if err := os.RemoveAll(fp); err != nil { - return errors.Errorf("removing %q: %w", path, err) + return fmt.Errorf("removing %q: %w", path, err) } w.fileMu.Lock() defer w.fileMu.Unlock() @@ -301,7 +300,7 @@ func (w *Workdir) writeFile(ctx context.Context, path, content string) (FileEven fp := w.AbsPath(path) _, err := os.Stat(fp) if err != nil && !os.IsNotExist(err) { - return FileEvent{}, errors.Errorf("checking if %q exists: %w", path, err) + return FileEvent{}, fmt.Errorf("checking if %q exists: %w", path, err) } var changeType protocol.FileChangeType if os.IsNotExist(err) { diff --git a/internal/lsp/fake/workdir_windows.go b/internal/lsp/fake/workdir_windows.go index ed2b4bb36ff..bcd18b7a226 100644 --- a/internal/lsp/fake/workdir_windows.go +++ b/internal/lsp/fake/workdir_windows.go @@ -5,9 +5,8 @@ package fake import ( + "errors" "syscall" - - errors "golang.org/x/xerrors" ) func init() { diff --git a/internal/lsp/general.go b/internal/lsp/general.go index 1e5063559c0..3da03e3fc34 100644 --- a/internal/lsp/general.go +++ b/internal/lsp/general.go @@ -20,14 +20,13 @@ import ( "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) func (s *Server) initialize(ctx context.Context, params *protocol.ParamInitialize) (*protocol.InitializeResult, error) { s.stateMu.Lock() if s.state >= serverInitializing { defer s.stateMu.Unlock() - return nil, errors.Errorf("%w: initialize called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state) + return nil, fmt.Errorf("%w: initialize called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state) } s.state = serverInitializing s.stateMu.Unlock() @@ -170,7 +169,7 @@ func (s *Server) initialized(ctx context.Context, params *protocol.InitializedPa s.stateMu.Lock() if s.state >= serverInitialized { defer s.stateMu.Unlock() - return errors.Errorf("%w: initialized called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state) + return fmt.Errorf("%w: initialized called while server in %v state", jsonrpc2.ErrInvalidRequest, s.state) } s.state = serverInitialized s.stateMu.Unlock() diff --git a/internal/lsp/lsprpc/autostart_default.go b/internal/lsp/lsprpc/autostart_default.go index b23a1e50882..59a76dc2f9f 100644 --- a/internal/lsp/lsprpc/autostart_default.go +++ b/internal/lsp/lsprpc/autostart_default.go @@ -5,9 +5,9 @@ package lsprpc import ( - exec "golang.org/x/sys/execabs" + "fmt" - errors "golang.org/x/xerrors" + exec "golang.org/x/sys/execabs" ) var ( @@ -19,7 +19,7 @@ var ( func runRemote(cmd *exec.Cmd) error { daemonize(cmd) if err := cmd.Start(); err != nil { - return errors.Errorf("starting remote gopls: %w", err) + return fmt.Errorf("starting remote gopls: %w", err) } return nil } diff --git a/internal/lsp/lsprpc/autostart_posix.go b/internal/lsp/lsprpc/autostart_posix.go index d5644e2b685..948d44fcedf 100644 --- a/internal/lsp/lsprpc/autostart_posix.go +++ b/internal/lsp/lsprpc/autostart_posix.go @@ -19,8 +19,6 @@ import ( "syscall" exec "golang.org/x/sys/execabs" - - "golang.org/x/xerrors" ) func init() { @@ -81,7 +79,7 @@ func verifyRemoteOwnershipPosix(network, address string) (bool, error) { if os.IsNotExist(err) { return true, nil } - return false, xerrors.Errorf("checking socket owner: %w", err) + return false, fmt.Errorf("checking socket owner: %w", err) } stat, ok := fi.Sys().(*syscall.Stat_t) if !ok { @@ -89,11 +87,11 @@ func verifyRemoteOwnershipPosix(network, address string) (bool, error) { } user, err := user.Current() if err != nil { - return false, xerrors.Errorf("checking current user: %w", err) + return false, fmt.Errorf("checking current user: %w", err) } uid, err := strconv.ParseUint(user.Uid, 10, 32) if err != nil { - return false, xerrors.Errorf("parsing current UID: %w", err) + return false, fmt.Errorf("parsing current UID: %w", err) } return stat.Uid == uint32(uid), nil } diff --git a/internal/lsp/lsprpc/binder.go b/internal/lsp/lsprpc/binder.go index f3320e17a8d..aa2edb3309d 100644 --- a/internal/lsp/lsprpc/binder.go +++ b/internal/lsp/lsprpc/binder.go @@ -13,7 +13,6 @@ import ( jsonrpc2_v2 "golang.org/x/tools/internal/jsonrpc2_v2" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/xcontext" - errors "golang.org/x/xerrors" ) // The BinderFunc type adapts a bind function to implement the jsonrpc2.Binder @@ -69,7 +68,7 @@ func (c *canceler) Preempt(ctx context.Context, req *jsonrpc2_v2.Request) (inter } var params protocol.CancelParams if err := json.Unmarshal(req.Params, ¶ms); err != nil { - return nil, errors.Errorf("%w: %v", jsonrpc2_v2.ErrParse, err) + return nil, fmt.Errorf("%w: %v", jsonrpc2_v2.ErrParse, err) } var id jsonrpc2_v2.ID switch raw := params.ID.(type) { @@ -78,7 +77,7 @@ func (c *canceler) Preempt(ctx context.Context, req *jsonrpc2_v2.Request) (inter case string: id = jsonrpc2_v2.StringID(raw) default: - return nil, errors.Errorf("%w: invalid ID type %T", jsonrpc2_v2.ErrParse, params.ID) + return nil, fmt.Errorf("%w: invalid ID type %T", jsonrpc2_v2.ErrParse, params.ID) } c.conn.Cancel(id) return nil, nil diff --git a/internal/lsp/lsprpc/dialer.go b/internal/lsp/lsprpc/dialer.go index 713307ca04e..37e0c568031 100644 --- a/internal/lsp/lsprpc/dialer.go +++ b/internal/lsp/lsprpc/dialer.go @@ -14,7 +14,6 @@ import ( exec "golang.org/x/sys/execabs" "golang.org/x/tools/internal/event" - errors "golang.org/x/xerrors" ) // AutoNetwork is the pseudo network type used to signal that gopls should use @@ -39,7 +38,7 @@ func NewAutoDialer(rawAddr string, argFunc func(network, addr string) []string) d.isAuto = true bin, err := os.Executable() if err != nil { - return nil, errors.Errorf("getting executable: %w", err) + return nil, fmt.Errorf("getting executable: %w", err) } d.executable = bin d.network, d.addr = autoNetworkAddress(bin, d.addr) @@ -84,7 +83,7 @@ func (d *AutoDialer) dialNet(ctx context.Context) (net.Conn, error) { // instances are simultaneously starting up. if _, err := os.Stat(d.addr); err == nil { if err := os.Remove(d.addr); err != nil { - return nil, errors.Errorf("removing remote socket file: %w", err) + return nil, fmt.Errorf("removing remote socket file: %w", err) } } } @@ -111,5 +110,5 @@ func (d *AutoDialer) dialNet(ctx context.Context) (net.Conn, error) { time.Sleep(dialTimeout - time.Since(startDial)) } } - return nil, errors.Errorf("dialing remote: %w", err) + return nil, fmt.Errorf("dialing remote: %w", err) } diff --git a/internal/lsp/lsprpc/lsprpc.go b/internal/lsp/lsprpc/lsprpc.go index df2138348d7..a85e7914219 100644 --- a/internal/lsp/lsprpc/lsprpc.go +++ b/internal/lsp/lsprpc/lsprpc.go @@ -27,7 +27,6 @@ import ( "golang.org/x/tools/internal/lsp/debug" "golang.org/x/tools/internal/lsp/debug/tag" "golang.org/x/tools/internal/lsp/protocol" - errors "golang.org/x/xerrors" ) // Unique identifiers for client/server. @@ -140,7 +139,7 @@ func QueryServerState(ctx context.Context, addr string) (*ServerState, error) { } var state ServerState if err := protocol.Call(ctx, serverConn, sessionsMethod, nil, &state); err != nil { - return nil, errors.Errorf("querying server state: %w", err) + return nil, fmt.Errorf("querying server state: %w", err) } return &state, nil } @@ -153,13 +152,13 @@ func dialRemote(ctx context.Context, addr string) (jsonrpc2.Conn, error) { if network == AutoNetwork { gp, err := os.Executable() if err != nil { - return nil, errors.Errorf("getting gopls path: %w", err) + return nil, fmt.Errorf("getting gopls path: %w", err) } network, address = autoNetworkAddress(gp, address) } netConn, err := net.DialTimeout(network, address, 5*time.Second) if err != nil { - return nil, errors.Errorf("dialing remote: %w", err) + return nil, fmt.Errorf("dialing remote: %w", err) } serverConn := jsonrpc2.NewConn(jsonrpc2.NewHeaderStream(netConn)) serverConn.Go(ctx, jsonrpc2.MethodNotFound) @@ -189,7 +188,7 @@ func (f *Forwarder) ServeStream(ctx context.Context, clientConn jsonrpc2.Conn) e netConn, err := f.dialer.dialNet(ctx) if err != nil { - return errors.Errorf("forwarder: connecting to remote: %w", err) + return fmt.Errorf("forwarder: connecting to remote: %w", err) } serverConn := jsonrpc2.NewConn(jsonrpc2.NewHeaderStream(netConn)) server := protocol.ServerDispatcher(serverConn) @@ -225,9 +224,9 @@ func (f *Forwarder) ServeStream(ctx context.Context, clientConn jsonrpc2.Conn) e err = nil if serverConn.Err() != nil { - err = errors.Errorf("remote disconnected: %v", serverConn.Err()) + err = fmt.Errorf("remote disconnected: %v", serverConn.Err()) } else if clientConn.Err() != nil { - err = errors.Errorf("client disconnected: %v", clientConn.Err()) + err = fmt.Errorf("client disconnected: %v", clientConn.Err()) } event.Log(ctx, fmt.Sprintf("forwarder: exited with error: %v", err)) return err @@ -514,7 +513,7 @@ func handshaker(session *cache.Session, goplsPath string, logHandshakes bool, ha } func sendError(ctx context.Context, reply jsonrpc2.Replier, err error) { - err = errors.Errorf("%v: %w", err, jsonrpc2.ErrParse) + err = fmt.Errorf("%v: %w", err, jsonrpc2.ErrParse) if err := reply(ctx, nil, err); err != nil { event.Error(ctx, "", err) } diff --git a/internal/lsp/lsprpc/middleware.go b/internal/lsp/lsprpc/middleware.go index 2ee83a20301..f703217dd0b 100644 --- a/internal/lsp/lsprpc/middleware.go +++ b/internal/lsp/lsprpc/middleware.go @@ -7,11 +7,11 @@ package lsprpc import ( "context" "encoding/json" + "fmt" "sync" "golang.org/x/tools/internal/event" jsonrpc2_v2 "golang.org/x/tools/internal/jsonrpc2_v2" - "golang.org/x/xerrors" ) // Metadata holds arbitrary data transferred between jsonrpc2 peers. @@ -80,7 +80,7 @@ func (h *Handshaker) Middleware(inner jsonrpc2_v2.Binder) jsonrpc2_v2.Binder { if req.Method == handshakeMethod { var peerInfo PeerInfo if err := json.Unmarshal(req.Params, &peerInfo); err != nil { - return nil, xerrors.Errorf("%w: unmarshaling client info: %v", jsonrpc2_v2.ErrInvalidParams, err) + return nil, fmt.Errorf("%w: unmarshaling client info: %v", jsonrpc2_v2.ErrInvalidParams, err) } peerInfo.LocalID = localID peerInfo.IsClient = true diff --git a/internal/lsp/mod/hover.go b/internal/lsp/mod/hover.go index 0837e2aaa4c..6084ef93358 100644 --- a/internal/lsp/mod/hover.go +++ b/internal/lsp/mod/hover.go @@ -15,7 +15,6 @@ import ( "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/lsp/source" - errors "golang.org/x/xerrors" ) func Hover(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, position protocol.Position) (*protocol.Hover, error) { @@ -38,15 +37,15 @@ func Hover(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, // Get the position of the cursor. pm, err := snapshot.ParseMod(ctx, fh) if err != nil { - return nil, errors.Errorf("getting modfile handle: %w", err) + return nil, fmt.Errorf("getting modfile handle: %w", err) } spn, err := pm.Mapper.PointSpan(position) if err != nil { - return nil, errors.Errorf("computing cursor position: %w", err) + return nil, fmt.Errorf("computing cursor position: %w", err) } hoverRng, err := spn.Range(pm.Mapper.Converter) if err != nil { - return nil, errors.Errorf("computing hover range: %w", err) + return nil, fmt.Errorf("computing hover range: %w", err) } // Confirm that the cursor is at the position of a require statement. diff --git a/internal/lsp/progress/progress.go b/internal/lsp/progress/progress.go index ca3efc4de79..d9a01bdc091 100644 --- a/internal/lsp/progress/progress.go +++ b/internal/lsp/progress/progress.go @@ -6,6 +6,7 @@ package progress import ( "context" + "fmt" "math/rand" "strconv" "strings" @@ -15,7 +16,6 @@ import ( "golang.org/x/tools/internal/lsp/debug/tag" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/xcontext" - errors "golang.org/x/xerrors" ) type Tracker struct { @@ -128,10 +128,10 @@ func (t *Tracker) Cancel(ctx context.Context, token protocol.ProgressToken) erro defer t.mu.Unlock() wd, ok := t.inProgress[token] if !ok { - return errors.Errorf("token %q not found in progress", token) + return fmt.Errorf("token %q not found in progress", token) } if wd.cancel == nil { - return errors.Errorf("work %q is not cancellable", token) + return fmt.Errorf("work %q is not cancellable", token) } wd.doCancel() return nil diff --git a/internal/lsp/protocol/protocol.go b/internal/lsp/protocol/protocol.go index a7b156a5123..7ca8f2bc66a 100644 --- a/internal/lsp/protocol/protocol.go +++ b/internal/lsp/protocol/protocol.go @@ -14,7 +14,6 @@ import ( "golang.org/x/tools/internal/jsonrpc2" jsonrpc2_v2 "golang.org/x/tools/internal/jsonrpc2_v2" "golang.org/x/tools/internal/xcontext" - errors "golang.org/x/xerrors" ) var ( @@ -281,5 +280,5 @@ func cancelCall(ctx context.Context, sender connSender, id jsonrpc2.ID) { } func sendParseError(ctx context.Context, reply jsonrpc2.Replier, err error) error { - return reply(ctx, nil, errors.Errorf("%w: %s", jsonrpc2.ErrParse, err)) + return reply(ctx, nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err)) } diff --git a/internal/lsp/protocol/span.go b/internal/lsp/protocol/span.go index 381e5f500cc..39e0373f722 100644 --- a/internal/lsp/protocol/span.go +++ b/internal/lsp/protocol/span.go @@ -10,7 +10,6 @@ import ( "fmt" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) type ColumnMapper struct { @@ -41,7 +40,7 @@ func (m *ColumnMapper) Location(s span.Span) (Location, error) { func (m *ColumnMapper) Range(s span.Span) (Range, error) { if span.CompareURI(m.URI, s.URI()) != 0 { - return Range{}, errors.Errorf("column mapper is for file %q instead of %q", m.URI, s.URI()) + return Range{}, fmt.Errorf("column mapper is for file %q instead of %q", m.URI, s.URI()) } s, err := s.WithAll(m.Converter) if err != nil { diff --git a/internal/lsp/protocol/tsclient.go b/internal/lsp/protocol/tsclient.go index c80a4c9ec71..971a2df72b1 100644 --- a/internal/lsp/protocol/tsclient.go +++ b/internal/lsp/protocol/tsclient.go @@ -14,9 +14,9 @@ package protocol import ( "context" "encoding/json" + "fmt" "golang.org/x/tools/internal/jsonrpc2" - errors "golang.org/x/xerrors" ) type Client interface { @@ -74,7 +74,7 @@ func clientDispatch(ctx context.Context, client Client, reply jsonrpc2.Replier, return true, reply(ctx, nil, err) case "workspace/workspaceFolders": // req if len(r.Params()) > 0 { - return true, reply(ctx, nil, errors.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) + return true, reply(ctx, nil, fmt.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) } resp, err := client.WorkspaceFolders(ctx) if err != nil { diff --git a/internal/lsp/protocol/tsserver.go b/internal/lsp/protocol/tsserver.go index e0f83b76aed..a26e50cf4e5 100644 --- a/internal/lsp/protocol/tsserver.go +++ b/internal/lsp/protocol/tsserver.go @@ -14,9 +14,9 @@ package protocol import ( "context" "encoding/json" + "fmt" "golang.org/x/tools/internal/jsonrpc2" - errors "golang.org/x/xerrors" ) type Server interface { @@ -369,7 +369,7 @@ func serverDispatch(ctx context.Context, server Server, reply jsonrpc2.Replier, return true, reply(ctx, resp, nil) case "workspace/semanticTokens/refresh": // req if len(r.Params()) > 0 { - return true, reply(ctx, nil, errors.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) + return true, reply(ctx, nil, fmt.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) } err := server.SemanticTokensRefresh(ctx) return true, reply(ctx, nil, err) @@ -465,7 +465,7 @@ func serverDispatch(ctx context.Context, server Server, reply jsonrpc2.Replier, return true, reply(ctx, resp, nil) case "workspace/inlineValue/refresh": // req if len(r.Params()) > 0 { - return true, reply(ctx, nil, errors.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) + return true, reply(ctx, nil, fmt.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) } err := server.InlineValueRefresh(ctx) return true, reply(ctx, nil, err) @@ -491,7 +491,7 @@ func serverDispatch(ctx context.Context, server Server, reply jsonrpc2.Replier, return true, reply(ctx, resp, nil) case "workspace/inlayHint/refresh": // req if len(r.Params()) > 0 { - return true, reply(ctx, nil, errors.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) + return true, reply(ctx, nil, fmt.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) } err := server.InlayHintRefresh(ctx) return true, reply(ctx, nil, err) @@ -509,7 +509,7 @@ func serverDispatch(ctx context.Context, server Server, reply jsonrpc2.Replier, return true, reply(ctx, resp, nil) case "shutdown": // req if len(r.Params()) > 0 { - return true, reply(ctx, nil, errors.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) + return true, reply(ctx, nil, fmt.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) } err := server.Shutdown(ctx) return true, reply(ctx, nil, err) @@ -665,7 +665,7 @@ func serverDispatch(ctx context.Context, server Server, reply jsonrpc2.Replier, return true, reply(ctx, resp, nil) case "workspace/codeLens/refresh": // req if len(r.Params()) > 0 { - return true, reply(ctx, nil, errors.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) + return true, reply(ctx, nil, fmt.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) } err := server.CodeLensRefresh(ctx) return true, reply(ctx, nil, err) @@ -771,7 +771,7 @@ func serverDispatch(ctx context.Context, server Server, reply jsonrpc2.Replier, return true, reply(ctx, resp, nil) case "workspace/diagnostic/refresh": // req if len(r.Params()) > 0 { - return true, reply(ctx, nil, errors.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) + return true, reply(ctx, nil, fmt.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) } err := server.DiagnosticRefresh(ctx) return true, reply(ctx, nil, err) diff --git a/internal/lsp/protocol/typescript/code.ts b/internal/lsp/protocol/typescript/code.ts index 168a128eeeb..1eefa55903a 100644 --- a/internal/lsp/protocol/typescript/code.ts +++ b/internal/lsp/protocol/typescript/code.ts @@ -1189,7 +1189,7 @@ let server: side = { // commonly used output const notNil = `if len(r.Params()) > 0 { - return true, reply(ctx, nil, errors.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) + return true, reply(ctx, nil, fmt.Errorf("%w: expected no params", jsonrpc2.ErrInvalidParams)) }`; // Go code for notifications. Side is client or server, m is the request @@ -1364,7 +1364,6 @@ function output(side: side) { "encoding/json" "golang.org/x/tools/internal/jsonrpc2" - errors "golang.org/x/xerrors" ) `); const a = side.name[0].toUpperCase() + side.name.substring(1); diff --git a/internal/lsp/semantic.go b/internal/lsp/semantic.go index 4c9e5d31a7c..e01be7e56ee 100644 --- a/internal/lsp/semantic.go +++ b/internal/lsp/semantic.go @@ -7,6 +7,7 @@ package lsp import ( "bytes" "context" + "errors" "fmt" "go/ast" "go/token" @@ -22,7 +23,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/lsp/template" "golang.org/x/tools/internal/typeparams" - errors "golang.org/x/xerrors" ) // The LSP says that errors for the semantic token requests should only be returned @@ -42,7 +42,7 @@ func (s *Server) semanticTokensFull(ctx context.Context, p *protocol.SemanticTok } func (s *Server) semanticTokensFullDelta(ctx context.Context, p *protocol.SemanticTokensDeltaParams) (interface{}, error) { - return nil, errors.Errorf("implement SemanticTokensFullDelta") + return nil, fmt.Errorf("implement SemanticTokensFullDelta") } func (s *Server) semanticTokensRange(ctx context.Context, p *protocol.SemanticTokensRangeParams) (*protocol.SemanticTokens, error) { @@ -52,7 +52,7 @@ func (s *Server) semanticTokensRange(ctx context.Context, p *protocol.SemanticTo func (s *Server) semanticTokensRefresh(ctx context.Context) error { // in the code, but not in the protocol spec - return errors.Errorf("implement SemanticTokensRefresh") + return fmt.Errorf("implement SemanticTokensRefresh") } func (s *Server) computeSemanticTokens(ctx context.Context, td protocol.TextDocumentIdentifier, rng *protocol.Range) (*protocol.SemanticTokens, error) { @@ -68,7 +68,7 @@ func (s *Server) computeSemanticTokens(ctx context.Context, td protocol.TextDocu if !vv.Options().SemanticTokens { // return an error, so if the option changes // the client won't remember the wrong answer - return nil, errors.Errorf("semantictokens are disabled") + return nil, fmt.Errorf("semantictokens are disabled") } kind := snapshot.View().FileKind(fh) if kind == source.Tmpl { @@ -814,7 +814,7 @@ func (e *encoded) init() error { } span, err := e.pgf.Mapper.RangeSpan(*e.rng) if err != nil { - return errors.Errorf("range span (%w) error for %s", err, e.pgf.File.Name) + return fmt.Errorf("range span (%w) error for %s", err, e.pgf.File.Name) } e.end = e.start + token.Pos(span.End().Offset()) e.start += token.Pos(span.Start().Offset()) diff --git a/internal/lsp/server.go b/internal/lsp/server.go index becfc718e85..3b86f47a0be 100644 --- a/internal/lsp/server.go +++ b/internal/lsp/server.go @@ -15,7 +15,6 @@ import ( "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) const concurrentAnalyses = 1 @@ -162,7 +161,7 @@ func (s *Server) nonstandardRequest(ctx context.Context, method string, params i } func notImplemented(method string) error { - return errors.Errorf("%w: %q not yet implemented", jsonrpc2.ErrMethodNotFound, method) + return fmt.Errorf("%w: %q not yet implemented", jsonrpc2.ErrMethodNotFound, method) } //go:generate helper/helper -d protocol/tsserver.go -o server_gen.go -u . diff --git a/internal/lsp/source/call_hierarchy.go b/internal/lsp/source/call_hierarchy.go index 212e648e5f5..c2c8a1866d0 100644 --- a/internal/lsp/source/call_hierarchy.go +++ b/internal/lsp/source/call_hierarchy.go @@ -6,6 +6,7 @@ package source import ( "context" + "errors" "fmt" "go/ast" "go/token" @@ -17,7 +18,6 @@ import ( "golang.org/x/tools/internal/lsp/debug/tag" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // PrepareCallHierarchy returns an array of CallHierarchyItem for a file and the position within the file. diff --git a/internal/lsp/source/completion/completion.go b/internal/lsp/source/completion/completion.go index 45bb6db0c15..af2380a122b 100644 --- a/internal/lsp/source/completion/completion.go +++ b/internal/lsp/source/completion/completion.go @@ -30,7 +30,6 @@ import ( "golang.org/x/tools/internal/lsp/snippet" "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/typeparams" - errors "golang.org/x/xerrors" ) type CompletionItem struct { @@ -435,7 +434,7 @@ func Completion(ctx context.Context, snapshot source.Snapshot, fh source.FileHan items, surrounding, innerErr := packageClauseCompletions(ctx, snapshot, fh, protoPos) if innerErr != nil { // return the error for GetParsedFile since it's more relevant in this situation. - return nil, nil, errors.Errorf("getting file for Completion: %w (package completions: %v)", err, innerErr) + return nil, nil, fmt.Errorf("getting file for Completion: %w (package completions: %v)", err, innerErr) } return items, surrounding, nil } @@ -451,7 +450,7 @@ func Completion(ctx context.Context, snapshot source.Snapshot, fh source.FileHan // Find the path to the position before pos. path, _ := astutil.PathEnclosingInterval(pgf.File, rng.Start-1, rng.Start-1) if path == nil { - return nil, nil, errors.Errorf("cannot find node enclosing position") + return nil, nil, fmt.Errorf("cannot find node enclosing position") } pos := rng.Start diff --git a/internal/lsp/source/completion/format.go b/internal/lsp/source/completion/format.go index e67456911ff..72498cc6874 100644 --- a/internal/lsp/source/completion/format.go +++ b/internal/lsp/source/completion/format.go @@ -6,6 +6,7 @@ package completion import ( "context" + "errors" "fmt" "go/ast" "go/doc" @@ -20,7 +21,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/typeparams" - errors "golang.org/x/xerrors" ) var ( diff --git a/internal/lsp/source/completion/package.go b/internal/lsp/source/completion/package.go index c7e52d7186c..3ae830484a0 100644 --- a/internal/lsp/source/completion/package.go +++ b/internal/lsp/source/completion/package.go @@ -7,6 +7,7 @@ package completion import ( "bytes" "context" + "errors" "fmt" "go/ast" "go/parser" @@ -22,7 +23,6 @@ import ( "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // packageClauseCompletions offers completions for a package declaration when @@ -46,7 +46,7 @@ func packageClauseCompletions(ctx context.Context, snapshot source.Snapshot, fh surrounding, err := packageCompletionSurrounding(ctx, snapshot.FileSet(), pgf, rng.Start) if err != nil { - return nil, nil, errors.Errorf("invalid position for package completion: %w", err) + return nil, nil, fmt.Errorf("invalid position for package completion: %w", err) } packageSuggestions, err := packageSuggestions(ctx, snapshot, fh.URI(), "") diff --git a/internal/lsp/source/completion/postfix_snippets.go b/internal/lsp/source/completion/postfix_snippets.go index 7ea962118b2..d7f0d90da9e 100644 --- a/internal/lsp/source/completion/postfix_snippets.go +++ b/internal/lsp/source/completion/postfix_snippets.go @@ -21,7 +21,6 @@ import ( "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/lsp/snippet" "golang.org/x/tools/internal/lsp/source" - errors "golang.org/x/xerrors" ) // Postfix snippets are artificial methods that allow the user to @@ -200,7 +199,7 @@ func (a *postfixTmplArgs) Cursor() string { func (a *postfixTmplArgs) Import(path string) (string, error) { name, edits, err := a.importIfNeeded(path, a.scope) if err != nil { - return "", errors.Errorf("couldn't import %q: %w", path, err) + return "", fmt.Errorf("couldn't import %q: %w", path, err) } a.edits = append(a.edits, edits...) return name, nil diff --git a/internal/lsp/source/fix.go b/internal/lsp/source/fix.go index 2f921ad0caa..6a7f77dab36 100644 --- a/internal/lsp/source/fix.go +++ b/internal/lsp/source/fix.go @@ -16,7 +16,6 @@ import ( "golang.org/x/tools/internal/lsp/analysis/undeclaredname" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) type ( @@ -130,7 +129,7 @@ func ApplyFix(ctx context.Context, fix string, snapshot Snapshot, fh VersionedFi func getAllSuggestedFixInputs(ctx context.Context, snapshot Snapshot, fh FileHandle, pRng protocol.Range) (*token.FileSet, span.Range, []byte, *ast.File, *types.Package, *types.Info, error) { pkg, pgf, err := GetParsedFile(ctx, snapshot, fh, NarrowestPackage) if err != nil { - return nil, span.Range{}, nil, nil, nil, nil, errors.Errorf("getting file for Identifier: %w", err) + return nil, span.Range{}, nil, nil, nil, nil, fmt.Errorf("getting file for Identifier: %w", err) } rng, err := pgf.Mapper.RangeToSpanRange(pRng) if err != nil { diff --git a/internal/lsp/source/highlight.go b/internal/lsp/source/highlight.go index 66a8e9b627d..ea54b7ce862 100644 --- a/internal/lsp/source/highlight.go +++ b/internal/lsp/source/highlight.go @@ -15,7 +15,6 @@ import ( "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/lsp/protocol" - errors "golang.org/x/xerrors" ) func Highlight(ctx context.Context, snapshot Snapshot, fh FileHandle, pos protocol.Position) ([]protocol.Range, error) { @@ -27,11 +26,11 @@ func Highlight(ctx context.Context, snapshot Snapshot, fh FileHandle, pos protoc // the file belongs to a workspace package. pkg, err := snapshot.PackageForFile(ctx, fh.URI(), TypecheckFull, WidestPackage) if err != nil { - return nil, errors.Errorf("getting package for Highlight: %w", err) + return nil, fmt.Errorf("getting package for Highlight: %w", err) } pgf, err := pkg.File(fh.URI()) if err != nil { - return nil, errors.Errorf("getting file for Highlight: %w", err) + return nil, fmt.Errorf("getting file for Highlight: %w", err) } spn, err := pgf.Mapper.PointSpan(pos) @@ -443,7 +442,7 @@ func labelDecl(n *ast.Ident) *ast.Ident { func highlightImportUses(pkg Package, path []ast.Node, result map[posRange]struct{}) error { basicLit, ok := path[0].(*ast.BasicLit) if !ok { - return errors.Errorf("highlightImportUses called with an ast.Node of type %T", basicLit) + return fmt.Errorf("highlightImportUses called with an ast.Node of type %T", basicLit) } ast.Inspect(path[len(path)-1], func(node ast.Node) bool { if imp, ok := node.(*ast.ImportSpec); ok && imp.Path == basicLit { @@ -470,7 +469,7 @@ func highlightImportUses(pkg Package, path []ast.Node, result map[posRange]struc func highlightIdentifiers(pkg Package, path []ast.Node, result map[posRange]struct{}) error { id, ok := path[0].(*ast.Ident) if !ok { - return errors.Errorf("highlightIdentifiers called with an ast.Node of type %T", id) + return fmt.Errorf("highlightIdentifiers called with an ast.Node of type %T", id) } // Check if ident is inside return or func decl. highlightFuncControlFlow(path, result) diff --git a/internal/lsp/source/hover.go b/internal/lsp/source/hover.go index b6fd9acf907..71a159c3619 100644 --- a/internal/lsp/source/hover.go +++ b/internal/lsp/source/hover.go @@ -7,6 +7,7 @@ package source import ( "context" "encoding/json" + "errors" "fmt" "go/ast" "go/constant" @@ -23,7 +24,6 @@ import ( "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/typeparams" - errors "golang.org/x/xerrors" ) // HoverContext contains context extracted from the syntax and type information @@ -648,7 +648,7 @@ func isFunctionParam(obj types.Object, node *ast.FuncDecl) bool { // given nodes; fullPos is the position of obj in node's AST. func hoverGenDecl(node *ast.GenDecl, spec ast.Spec, fullPos token.Pos, obj types.Object) (*HoverContext, error) { if spec == nil { - return nil, errors.Errorf("no spec for node %v at position %v", node, fullPos) + return nil, fmt.Errorf("no spec for node %v at position %v", node, fullPos) } // If we have a field or method. @@ -665,7 +665,7 @@ func hoverGenDecl(node *ast.GenDecl, spec ast.Spec, fullPos token.Pos, obj types case *ast.ImportSpec: return &HoverContext{signatureSource: spec, Comment: spec.Doc}, nil } - return nil, errors.Errorf("unable to format spec %v (%T)", spec, spec) + return nil, fmt.Errorf("unable to format spec %v (%T)", spec, spec) } // TODO(rfindley): rename this function. diff --git a/internal/lsp/source/identifier.go b/internal/lsp/source/identifier.go index 09c8493ed9e..fe02f741369 100644 --- a/internal/lsp/source/identifier.go +++ b/internal/lsp/source/identifier.go @@ -6,6 +6,7 @@ package source import ( "context" + "errors" "fmt" "go/ast" "go/parser" @@ -19,7 +20,6 @@ import ( "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/typeparams" - errors "golang.org/x/xerrors" ) // IdentifierInfo holds information about an identifier in Go source. @@ -199,7 +199,7 @@ func findIdentifier(ctx context.Context, snapshot Snapshot, pkg Package, pgf *Pa result.Declaration.typeSwitchImplicit = typ } else { // Probably a type error. - return nil, errors.Errorf("%w for ident %v", errNoObjectFound, result.Name) + return nil, fmt.Errorf("%w for ident %v", errNoObjectFound, result.Name) } } @@ -215,7 +215,7 @@ func findIdentifier(ctx context.Context, snapshot Snapshot, pkg Package, pgf *Pa } decl, ok := builtinObj.Decl.(ast.Node) if !ok { - return nil, errors.Errorf("no declaration for %s", result.Name) + return nil, fmt.Errorf("no declaration for %s", result.Name) } result.Declaration.node = decl if typeSpec, ok := decl.(*ast.TypeSpec); ok { @@ -247,7 +247,7 @@ func findIdentifier(ctx context.Context, snapshot Snapshot, pkg Package, pgf *Pa } decl, ok := builtinObj.Decl.(ast.Node) if !ok { - return nil, errors.Errorf("no declaration for %s", errorName) + return nil, fmt.Errorf("no declaration for %s", errorName) } spec, ok := decl.(*ast.TypeSpec) if !ok { @@ -473,7 +473,7 @@ func importSpec(snapshot Snapshot, pkg Package, file *ast.File, pos token.Pos) ( } importPath, err := strconv.Unquote(imp.Path.Value) if err != nil { - return nil, errors.Errorf("import path not quoted: %s (%v)", imp.Path.Value, err) + return nil, fmt.Errorf("import path not quoted: %s (%v)", imp.Path.Value, err) } result := &IdentifierInfo{ Snapshot: snapshot, diff --git a/internal/lsp/source/implementation.go b/internal/lsp/source/implementation.go index b53d7c994e3..23344b04902 100644 --- a/internal/lsp/source/implementation.go +++ b/internal/lsp/source/implementation.go @@ -16,7 +16,6 @@ import ( "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" - "golang.org/x/xerrors" ) func Implementation(ctx context.Context, snapshot Snapshot, f FileHandle, pp protocol.Position) ([]protocol.Location, error) { @@ -296,7 +295,7 @@ func qualifiedObjsAtLocation(ctx context.Context, s Snapshot, key objSearchKey, } else { obj := searchpkg.GetTypesInfo().ObjectOf(leaf) if obj == nil { - return nil, xerrors.Errorf("%w for %q", errNoObjectFound, leaf.Name) + return nil, fmt.Errorf("%w for %q", errNoObjectFound, leaf.Name) } objs = append(objs, obj) } @@ -304,7 +303,7 @@ func qualifiedObjsAtLocation(ctx context.Context, s Snapshot, key objSearchKey, // Look up the implicit *types.PkgName. obj := searchpkg.GetTypesInfo().Implicits[leaf] if obj == nil { - return nil, xerrors.Errorf("%w for import %q", errNoObjectFound, ImportPath(leaf)) + return nil, fmt.Errorf("%w for import %q", errNoObjectFound, ImportPath(leaf)) } objs = append(objs, obj) } @@ -322,7 +321,7 @@ func qualifiedObjsAtLocation(ctx context.Context, s Snapshot, key objSearchKey, addPkg(searchpkg) for _, obj := range objs { if obj.Parent() == types.Universe { - return nil, xerrors.Errorf("%q: %w", obj.Name(), errBuiltin) + return nil, fmt.Errorf("%q: %w", obj.Name(), errBuiltin) } pkg, ok := pkgs[obj.Pkg()] if !ok { diff --git a/internal/lsp/source/known_packages.go b/internal/lsp/source/known_packages.go index fd83da002ad..d7f229ecc80 100644 --- a/internal/lsp/source/known_packages.go +++ b/internal/lsp/source/known_packages.go @@ -6,6 +6,7 @@ package source import ( "context" + "fmt" "sort" "strings" "sync" @@ -13,7 +14,6 @@ import ( "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/imports" - errors "golang.org/x/xerrors" ) // KnownPackages returns a list of all known packages @@ -22,7 +22,7 @@ import ( func KnownPackages(ctx context.Context, snapshot Snapshot, fh VersionedFileHandle) ([]string, error) { pkg, pgf, err := GetParsedFile(ctx, snapshot, fh, NarrowestPackage) if err != nil { - return nil, errors.Errorf("GetParsedFile: %w", err) + return nil, fmt.Errorf("GetParsedFile: %w", err) } alreadyImported := map[string]struct{}{} for _, imp := range pgf.File.Imports { diff --git a/internal/lsp/source/options.go b/internal/lsp/source/options.go index 592a09841f7..79628ee2637 100644 --- a/internal/lsp/source/options.go +++ b/internal/lsp/source/options.go @@ -65,7 +65,6 @@ import ( "golang.org/x/tools/internal/lsp/diff" "golang.org/x/tools/internal/lsp/diff/myers" "golang.org/x/tools/internal/lsp/protocol" - errors "golang.org/x/xerrors" ) var ( @@ -664,7 +663,7 @@ func SetOptions(options *Options, opts interface{}) OptionResults { default: results = append(results, OptionResult{ Value: opts, - Error: errors.Errorf("Invalid options type %T", opts), + Error: fmt.Errorf("Invalid options type %T", opts), }) } return results @@ -1050,7 +1049,7 @@ func (o *Options) set(name string, value interface{}, seen map[string]struct{}) func (r *OptionResult) errorf(msg string, values ...interface{}) { prefix := fmt.Sprintf("parsing setting %q: ", r.Name) - r.Error = errors.Errorf(prefix+msg, values...) + r.Error = fmt.Errorf(prefix+msg, values...) } // A SoftError is an error that does not affect the functionality of gopls. diff --git a/internal/lsp/source/references.go b/internal/lsp/source/references.go index 5d3eac33781..3541600b207 100644 --- a/internal/lsp/source/references.go +++ b/internal/lsp/source/references.go @@ -6,6 +6,7 @@ package source import ( "context" + "errors" "fmt" "go/ast" "go/token" @@ -15,7 +16,6 @@ import ( "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // ReferenceInfo holds information about reference to an identifier in Go source. diff --git a/internal/lsp/source/rename.go b/internal/lsp/source/rename.go index 7fce067cb88..641e463769f 100644 --- a/internal/lsp/source/rename.go +++ b/internal/lsp/source/rename.go @@ -7,6 +7,8 @@ package source import ( "bytes" "context" + "errors" + "fmt" "go/ast" "go/format" "go/token" @@ -20,7 +22,6 @@ import ( "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" "golang.org/x/tools/refactor/satisfy" - errors "golang.org/x/xerrors" ) type renamer struct { @@ -105,13 +106,13 @@ func Rename(ctx context.Context, s Snapshot, f FileHandle, pp protocol.Position, return nil, err } if obj.Name() == newName { - return nil, errors.Errorf("old and new names are the same: %s", newName) + return nil, fmt.Errorf("old and new names are the same: %s", newName) } if !isValidIdentifier(newName) { - return nil, errors.Errorf("invalid identifier to rename: %q", newName) + return nil, fmt.Errorf("invalid identifier to rename: %q", newName) } if pkg == nil || pkg.IsIllTyped() { - return nil, errors.Errorf("package for %s is ill typed", f.URI()) + return nil, fmt.Errorf("package for %s is ill typed", f.URI()) } refs, err := references(ctx, s, qos, true, false, true) if err != nil { @@ -151,7 +152,7 @@ func Rename(ctx context.Context, s Snapshot, f FileHandle, pp protocol.Position, } } if r.hadConflicts { - return nil, errors.Errorf(r.errors) + return nil, fmt.Errorf(r.errors) } changes, err := r.update() @@ -334,11 +335,11 @@ func (r *renamer) updatePkgName(pkgName *types.PkgName) (*diff.TextEdit, error) pkg := r.packages[pkgName.Pkg()] _, path, _ := pathEnclosingInterval(r.fset, pkg, pkgName.Pos(), pkgName.Pos()) if len(path) < 2 { - return nil, errors.Errorf("no path enclosing interval for %s", pkgName.Name()) + return nil, fmt.Errorf("no path enclosing interval for %s", pkgName.Name()) } spec, ok := path[1].(*ast.ImportSpec) if !ok { - return nil, errors.Errorf("failed to update PkgName for %s", pkgName.Name()) + return nil, fmt.Errorf("failed to update PkgName for %s", pkgName.Name()) } var astIdent *ast.Ident // will be nil if ident is removed diff --git a/internal/lsp/source/signature_help.go b/internal/lsp/source/signature_help.go index e7ed9cc8b7f..d5def0bcd45 100644 --- a/internal/lsp/source/signature_help.go +++ b/internal/lsp/source/signature_help.go @@ -6,6 +6,7 @@ package source import ( "context" + "fmt" "go/ast" "go/token" "go/types" @@ -13,7 +14,6 @@ import ( "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/lsp/protocol" - errors "golang.org/x/xerrors" ) func SignatureHelp(ctx context.Context, snapshot Snapshot, fh FileHandle, pos protocol.Position) (*protocol.SignatureInformation, int, error) { @@ -22,7 +22,7 @@ func SignatureHelp(ctx context.Context, snapshot Snapshot, fh FileHandle, pos pr pkg, pgf, err := GetParsedFile(ctx, snapshot, fh, NarrowestPackage) if err != nil { - return nil, 0, errors.Errorf("getting file for SignatureHelp: %w", err) + return nil, 0, fmt.Errorf("getting file for SignatureHelp: %w", err) } spn, err := pgf.Mapper.PointSpan(pos) if err != nil { @@ -36,7 +36,7 @@ func SignatureHelp(ctx context.Context, snapshot Snapshot, fh FileHandle, pos pr var callExpr *ast.CallExpr path, _ := astutil.PathEnclosingInterval(pgf.File, rng.Start, rng.Start) if path == nil { - return nil, 0, errors.Errorf("cannot find node enclosing position") + return nil, 0, fmt.Errorf("cannot find node enclosing position") } FindCall: for _, node := range path { @@ -50,16 +50,16 @@ FindCall: // The user is within an anonymous function, // which may be the parameter to the *ast.CallExpr. // Don't show signature help in this case. - return nil, 0, errors.Errorf("no signature help within a function declaration") + return nil, 0, fmt.Errorf("no signature help within a function declaration") case *ast.BasicLit: if node.Kind == token.STRING { - return nil, 0, errors.Errorf("no signature help within a string literal") + return nil, 0, fmt.Errorf("no signature help within a string literal") } } } if callExpr == nil || callExpr.Fun == nil { - return nil, 0, errors.Errorf("cannot find an enclosing function") + return nil, 0, fmt.Errorf("cannot find an enclosing function") } qf := Qualifier(pgf.File, pkg.GetTypes(), pkg.GetTypesInfo()) @@ -83,12 +83,12 @@ FindCall: // Get the type information for the function being called. sigType := pkg.GetTypesInfo().TypeOf(callExpr.Fun) if sigType == nil { - return nil, 0, errors.Errorf("cannot get type for Fun %[1]T (%[1]v)", callExpr.Fun) + return nil, 0, fmt.Errorf("cannot get type for Fun %[1]T (%[1]v)", callExpr.Fun) } sig, _ := sigType.Underlying().(*types.Signature) if sig == nil { - return nil, 0, errors.Errorf("cannot find signature for Fun %[1]T (%[1]v)", callExpr.Fun) + return nil, 0, fmt.Errorf("cannot find signature for Fun %[1]T (%[1]v)", callExpr.Fun) } activeParam := activeParameter(callExpr, sig.Params().Len(), sig.Variadic(), rng.Start) diff --git a/internal/lsp/source/source_test.go b/internal/lsp/source/source_test.go index dc5fe53b58d..405c35c3683 100644 --- a/internal/lsp/source/source_test.go +++ b/internal/lsp/source/source_test.go @@ -6,6 +6,7 @@ package source_test import ( "context" + "errors" "fmt" "os" "os/exec" @@ -24,7 +25,6 @@ import ( "golang.org/x/tools/internal/lsp/tests" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/testenv" - errors "golang.org/x/xerrors" ) func TestMain(m *testing.M) { diff --git a/internal/lsp/source/symbols.go b/internal/lsp/source/symbols.go index 16fb2223d28..074b24eba01 100644 --- a/internal/lsp/source/symbols.go +++ b/internal/lsp/source/symbols.go @@ -12,7 +12,6 @@ import ( "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/lsp/protocol" - errors "golang.org/x/xerrors" ) func DocumentSymbols(ctx context.Context, snapshot Snapshot, fh FileHandle) ([]protocol.DocumentSymbol, error) { @@ -21,7 +20,7 @@ func DocumentSymbols(ctx context.Context, snapshot Snapshot, fh FileHandle) ([]p pkg, pgf, err := GetParsedFile(ctx, snapshot, fh, NarrowestPackage) if err != nil { - return nil, errors.Errorf("getting file for DocumentSymbols: %w", err) + return nil, fmt.Errorf("getting file for DocumentSymbols: %w", err) } info := pkg.GetTypesInfo() diff --git a/internal/lsp/source/util.go b/internal/lsp/source/util.go index d371c2b4230..7874340ca12 100644 --- a/internal/lsp/source/util.go +++ b/internal/lsp/source/util.go @@ -20,7 +20,6 @@ import ( "golang.org/x/mod/modfile" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // MappedRange provides mapped protocol.Range for a span.Range, accounting for @@ -150,10 +149,10 @@ func posToMappedRange(snapshot Snapshot, pkg Package, pos, end token.Pos) (Mappe return MappedRange{}, err } if !pos.IsValid() { - return MappedRange{}, errors.Errorf("invalid position for %v", pos) + return MappedRange{}, fmt.Errorf("invalid position for %v", pos) } if !end.IsValid() { - return MappedRange{}, errors.Errorf("invalid position for %v", end) + return MappedRange{}, fmt.Errorf("invalid position for %v", end) } return NewMappedRange(snapshot.FileSet(), pgf.Mapper, pos, end), nil } @@ -278,7 +277,7 @@ func CompareDiagnostic(a, b *Diagnostic) int { func FindPackageFromPos(ctx context.Context, snapshot Snapshot, pos token.Pos) (Package, error) { tok := snapshot.FileSet().File(pos) if tok == nil { - return nil, errors.Errorf("no file for pos %v", pos) + return nil, fmt.Errorf("no file for pos %v", pos) } uri := span.URIFromPath(tok.Name()) pkgs, err := snapshot.PackagesForFile(ctx, uri, TypecheckAll, true) @@ -299,7 +298,7 @@ func FindPackageFromPos(ctx context.Context, snapshot Snapshot, pos token.Pos) ( } return pkg, nil } - return nil, errors.Errorf("no package for given file position") + return nil, fmt.Errorf("no package for given file position") } // findFileInDeps finds uri in pkg or its dependencies. @@ -321,7 +320,7 @@ func findFileInDeps(pkg Package, uri span.URI) (*ParsedGoFile, Package, error) { } } } - return nil, nil, errors.Errorf("no file for %s in package %s", uri, pkg.ID()) + return nil, nil, fmt.Errorf("no file for %s in package %s", uri, pkg.ID()) } // ImportPath returns the unquoted import path of s, diff --git a/internal/lsp/source/view.go b/internal/lsp/source/view.go index f698a07e3ef..94037f33fe3 100644 --- a/internal/lsp/source/view.go +++ b/internal/lsp/source/view.go @@ -7,6 +7,7 @@ package source import ( "bytes" "context" + "errors" "fmt" "go/ast" "go/scanner" @@ -24,7 +25,6 @@ import ( "golang.org/x/tools/internal/lsp/progress" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) // Snapshot represents the current state for the given view. diff --git a/internal/lsp/text_synchronization.go b/internal/lsp/text_synchronization.go index d9a69614074..59fc29c4e9c 100644 --- a/internal/lsp/text_synchronization.go +++ b/internal/lsp/text_synchronization.go @@ -7,6 +7,7 @@ package lsp import ( "bytes" "context" + "errors" "fmt" "path/filepath" "time" @@ -17,7 +18,6 @@ import ( "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/xcontext" - errors "golang.org/x/xerrors" ) // ModificationSource identifies the originating cause of a file modification. @@ -318,7 +318,7 @@ func DiagnosticWorkTitle(cause ModificationSource) string { func (s *Server) changedText(ctx context.Context, uri span.URI, changes []protocol.TextDocumentContentChangeEvent) ([]byte, error) { if len(changes) == 0 { - return nil, errors.Errorf("%w: no content changes provided", jsonrpc2.ErrInternal) + return nil, fmt.Errorf("%w: no content changes provided", jsonrpc2.ErrInternal) } // Check if the client sent the full content of the file. @@ -336,7 +336,7 @@ func (s *Server) applyIncrementalChanges(ctx context.Context, uri span.URI, chan } content, err := fh.Read() if err != nil { - return nil, errors.Errorf("%w: file not found (%v)", jsonrpc2.ErrInternal, err) + return nil, fmt.Errorf("%w: file not found (%v)", jsonrpc2.ErrInternal, err) } for _, change := range changes { // Make sure to update column mapper along with the content. @@ -347,18 +347,18 @@ func (s *Server) applyIncrementalChanges(ctx context.Context, uri span.URI, chan Content: content, } if change.Range == nil { - return nil, errors.Errorf("%w: unexpected nil range for change", jsonrpc2.ErrInternal) + return nil, fmt.Errorf("%w: unexpected nil range for change", jsonrpc2.ErrInternal) } spn, err := m.RangeSpan(*change.Range) if err != nil { return nil, err } if !spn.HasOffset() { - return nil, errors.Errorf("%w: invalid range for content change", jsonrpc2.ErrInternal) + return nil, fmt.Errorf("%w: invalid range for content change", jsonrpc2.ErrInternal) } start, end := spn.Start().Offset(), spn.End().Offset() if end < start { - return nil, errors.Errorf("%w: invalid range for content change", jsonrpc2.ErrInternal) + return nil, fmt.Errorf("%w: invalid range for content change", jsonrpc2.ErrInternal) } var buf bytes.Buffer buf.Write(content[:start]) diff --git a/internal/lsp/work/completion.go b/internal/lsp/work/completion.go index 60b69f12f5a..93b6e78c94b 100644 --- a/internal/lsp/work/completion.go +++ b/internal/lsp/work/completion.go @@ -6,6 +6,8 @@ package work import ( "context" + "errors" + "fmt" "go/token" "os" "path/filepath" @@ -15,7 +17,6 @@ import ( "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/lsp/source" - errors "golang.org/x/xerrors" ) func Completion(ctx context.Context, snapshot source.Snapshot, fh source.VersionedFileHandle, position protocol.Position) (*protocol.CompletionList, error) { @@ -25,15 +26,15 @@ func Completion(ctx context.Context, snapshot source.Snapshot, fh source.Version // Get the position of the cursor. pw, err := snapshot.ParseWork(ctx, fh) if err != nil { - return nil, errors.Errorf("getting go.work file handle: %w", err) + return nil, fmt.Errorf("getting go.work file handle: %w", err) } spn, err := pw.Mapper.PointSpan(position) if err != nil { - return nil, errors.Errorf("computing cursor position: %w", err) + return nil, fmt.Errorf("computing cursor position: %w", err) } rng, err := spn.Range(pw.Mapper.Converter) if err != nil { - return nil, errors.Errorf("computing range: %w", err) + return nil, fmt.Errorf("computing range: %w", err) } // Find the use statement the user is in. @@ -123,7 +124,7 @@ func Completion(ctx context.Context, snapshot source.Snapshot, fh source.Version return nil }) if err != nil && !errors.Is(err, stopWalking) { - return nil, errors.Errorf("walking to find completions: %w", err) + return nil, fmt.Errorf("walking to find completions: %w", err) } sort.Strings(completions) diff --git a/internal/lsp/work/hover.go b/internal/lsp/work/hover.go index 1699c5cbaeb..abb7055d064 100644 --- a/internal/lsp/work/hover.go +++ b/internal/lsp/work/hover.go @@ -7,13 +7,13 @@ package work import ( "bytes" "context" + "fmt" "go/token" "golang.org/x/mod/modfile" "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/lsp/source" - errors "golang.org/x/xerrors" ) func Hover(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, position protocol.Position) (*protocol.Hover, error) { @@ -28,15 +28,15 @@ func Hover(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, // Get the position of the cursor. pw, err := snapshot.ParseWork(ctx, fh) if err != nil { - return nil, errors.Errorf("getting go.work file handle: %w", err) + return nil, fmt.Errorf("getting go.work file handle: %w", err) } spn, err := pw.Mapper.PointSpan(position) if err != nil { - return nil, errors.Errorf("computing cursor position: %w", err) + return nil, fmt.Errorf("computing cursor position: %w", err) } hoverRng, err := spn.Range(pw.Mapper.Converter) if err != nil { - return nil, errors.Errorf("computing hover range: %w", err) + return nil, fmt.Errorf("computing hover range: %w", err) } // Confirm that the cursor is inside a use statement, and then find @@ -51,11 +51,11 @@ func Hover(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, // Get the mod file denoted by the use. modfh, err := snapshot.GetFile(ctx, modFileURI(pw, use)) if err != nil { - return nil, errors.Errorf("getting modfile handle: %w", err) + return nil, fmt.Errorf("getting modfile handle: %w", err) } pm, err := snapshot.ParseMod(ctx, modfh) if err != nil { - return nil, errors.Errorf("getting modfile handle: %w", err) + return nil, fmt.Errorf("getting modfile handle: %w", err) } mod := pm.File.Module.Mod diff --git a/internal/lsp/workspace.go b/internal/lsp/workspace.go index 1f01b3b3bef..a1f837e2309 100644 --- a/internal/lsp/workspace.go +++ b/internal/lsp/workspace.go @@ -6,11 +6,11 @@ package lsp import ( "context" + "fmt" "golang.org/x/tools/internal/lsp/protocol" "golang.org/x/tools/internal/lsp/source" "golang.org/x/tools/internal/span" - errors "golang.org/x/xerrors" ) func (s *Server) didChangeWorkspaceFolders(ctx context.Context, params *protocol.DidChangeWorkspaceFoldersParams) error { @@ -20,7 +20,7 @@ func (s *Server) didChangeWorkspaceFolders(ctx context.Context, params *protocol if view != nil { view.Shutdown(ctx) } else { - return errors.Errorf("view %s for %v not found", folder.Name, folder.URI) + return fmt.Errorf("view %s for %v not found", folder.Name, folder.URI) } } return s.addFolders(ctx, event.Added) @@ -31,7 +31,7 @@ func (s *Server) addView(ctx context.Context, name string, uri span.URI) (source state := s.state s.stateMu.Unlock() if state < serverInitialized { - return nil, func() {}, errors.Errorf("addView called before server initialized") + return nil, func() {}, fmt.Errorf("addView called before server initialized") } options := s.session.Options().Clone() if err := s.fetchConfig(ctx, name, uri, options); err != nil {