gopls: remove unused parameters

Interestingly, this turned up one false positive of the form
  var hook = func(err error) {}
where other build-tagged files not visible to the analysis
assigned other values to hook that actually used the
parameter.

Change-Id: I7d230160fd7e5ad67ade7b6e57db150bf68fa1c3
Reviewed-on: https://go-review.googlesource.com/c/tools/+/560716
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Robert Findley <rfindley@google.com>
This commit is contained in:
Alan Donovan 2024-02-02 16:54:39 -05:00
Родитель d6bd2d74f6
Коммит 51e3724fe0
16 изменённых файлов: 74 добавлений и 81 удалений

Просмотреть файл

@ -9,7 +9,6 @@ package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
@ -50,8 +49,7 @@ func main() {
}
func diffAPI(oldVer, newVer string) (string, error) {
ctx := context.Background()
previousAPI, err := loadAPI(ctx, oldVer)
previousAPI, err := loadAPI(oldVer)
if err != nil {
return "", fmt.Errorf("loading %s: %v", oldVer, err)
}
@ -60,7 +58,7 @@ func diffAPI(oldVer, newVer string) (string, error) {
currentAPI = settings.GeneratedAPIJSON
} else {
var err error
currentAPI, err = loadAPI(ctx, newVer)
currentAPI, err = loadAPI(newVer)
if err != nil {
return "", fmt.Errorf("loading %s: %v", newVer, err)
}
@ -69,7 +67,7 @@ func diffAPI(oldVer, newVer string) (string, error) {
return cmp.Diff(previousAPI, currentAPI), nil
}
func loadAPI(ctx context.Context, version string) (*settings.APIJSON, error) {
func loadAPI(version string) (*settings.APIJSON, error) {
ver := fmt.Sprintf("golang.org/x/tools/gopls@%s", version)
cmd := exec.Command("go", "run", ver, "api-json")

Просмотреть файл

@ -114,7 +114,7 @@ func loadAPI() (*settings.APIJSON, error) {
Analyzers: loadAnalyzers(defaults.DefaultAnalyzers), // no staticcheck analyzers
}
api.Commands, err = loadCommands(pkg)
api.Commands, err = loadCommands()
if err != nil {
return nil, err
}
@ -403,7 +403,7 @@ func valueDoc(name, value, doc string) string {
return fmt.Sprintf("`%s`: %s", value, doc)
}
func loadCommands(pkg *packages.Package) ([]*settings.CommandJSON, error) {
func loadCommands() ([]*settings.CommandJSON, error) {
var commands []*settings.CommandJSON
_, cmds, err := commandmeta.Load()

Просмотреть файл

@ -104,7 +104,7 @@ func runForError(pass *analysis.Pass, err types.Error, name string) error {
continue
}
fixes := removeVariableFromAssignment(pass, path, stmt, ident)
fixes := removeVariableFromAssignment(path, stmt, ident)
// fixes may be nil
if len(fixes) > 0 {
diag.SuggestedFixes = fixes
@ -185,7 +185,7 @@ func removeVariableFromSpec(pass *analysis.Pass, path []ast.Node, stmt *ast.Valu
}
}
func removeVariableFromAssignment(pass *analysis.Pass, path []ast.Node, stmt *ast.AssignStmt, ident *ast.Ident) []analysis.SuggestedFix {
func removeVariableFromAssignment(path []ast.Node, stmt *ast.AssignStmt, ident *ast.Ident) []analysis.SuggestedFix {
// The only variable in the assignment is unused
if len(stmt.Lhs) == 1 {
// If LHS has only one expression to be valid it has to have 1 expression

4
gopls/internal/cache/session.go поставляемый
Просмотреть файл

@ -655,7 +655,7 @@ func bestView[V viewDefiner](ctx context.Context, fs file.Source, fh file.Handle
//
// If the resulting error is non-nil, the view may or may not have already been
// dropped from the session.
func (s *Session) updateViewLocked(ctx context.Context, view *View, def *viewDefinition, folder *Folder) (*View, error) {
func (s *Session) updateViewLocked(ctx context.Context, view *View, def *viewDefinition) (*View, error) {
i := s.dropView(view)
if i == -1 {
return nil, fmt.Errorf("view %q not found", view.id)
@ -707,7 +707,7 @@ func (s *Session) ResetView(ctx context.Context, uri protocol.DocumentURI) (*Vie
if err != nil {
return nil, err
}
return s.updateViewLocked(ctx, v, v.viewDefinition, v.folder)
return s.updateViewLocked(ctx, v, v.viewDefinition)
}
// DidModifyFiles reports a file modification to the session. It returns

Просмотреть файл

@ -180,7 +180,7 @@ func (s *stats) Run(ctx context.Context, args ...string) error {
if _, err := do("Collecting directory info", func() error {
var err error
stats.DirStats, err = findDirStats(ctx)
stats.DirStats, err = findDirStats()
if err != nil {
return err
}
@ -248,7 +248,7 @@ type dirStats struct {
// findDirStats collects information about the current directory and its
// subdirectories.
func findDirStats(ctx context.Context) (dirStats, error) {
func findDirStats() (dirStats, error) {
var ds dirStats
filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error {
if err != nil {

Просмотреть файл

@ -84,19 +84,19 @@ func (r *Rpcs) ProcessEvent(ctx context.Context, ev core.Event, lm label.Map) co
defer r.mu.Unlock()
switch {
case event.IsStart(ev):
if _, stats := r.getRPCSpan(ctx, ev); stats != nil {
if _, stats := r.getRPCSpan(ctx); stats != nil {
stats.Started++
}
case event.IsEnd(ev):
span, stats := r.getRPCSpan(ctx, ev)
span, stats := r.getRPCSpan(ctx)
if stats != nil {
endRPC(ctx, ev, span, stats)
endRPC(span, stats)
}
case event.IsMetric(ev):
sent := byteUnits(tag.SentBytes.Get(lm))
rec := byteUnits(tag.ReceivedBytes.Get(lm))
if sent != 0 || rec != 0 {
if _, stats := r.getRPCSpan(ctx, ev); stats != nil {
if _, stats := r.getRPCSpan(ctx); stats != nil {
stats.Sent += sent
stats.Received += rec
}
@ -105,7 +105,7 @@ func (r *Rpcs) ProcessEvent(ctx context.Context, ev core.Event, lm label.Map) co
return ctx
}
func endRPC(ctx context.Context, ev core.Event, span *export.Span, stats *rpcStats) {
func endRPC(span *export.Span, stats *rpcStats) {
// update the basic counts
stats.Completed++
@ -152,7 +152,7 @@ func endRPC(ctx context.Context, ev core.Event, span *export.Span, stats *rpcSta
}
}
func (r *Rpcs) getRPCSpan(ctx context.Context, ev core.Event) (*export.Span, *rpcStats) {
func (r *Rpcs) getRPCSpan(ctx context.Context) (*export.Span, *rpcStats) {
// get the span
span := export.GetSpan(ctx)
if span == nil {

Просмотреть файл

@ -150,14 +150,14 @@ func StdTrace(exporter event.Exporter) event.Exporter {
ctx = context.WithValue(ctx, traceKey, task)
}
// Log the start event as it may contain useful labels.
msg := formatEvent(ctx, ev, lm)
msg := formatEvent(ev, lm)
trace.Log(ctx, "start", msg)
case event.IsLog(ev):
category := ""
if event.IsError(ev) {
category = "error"
}
msg := formatEvent(ctx, ev, lm)
msg := formatEvent(ev, lm)
trace.Log(ctx, category, msg)
case event.IsEnd(ev):
if v := ctx.Value(traceKey); v != nil {
@ -168,7 +168,7 @@ func StdTrace(exporter event.Exporter) event.Exporter {
}
}
func formatEvent(ctx context.Context, ev core.Event, lm label.Map) string {
func formatEvent(ev core.Event, lm label.Map) string {
buf := &bytes.Buffer{}
p := export.Printer{}
p.WriteEvent(buf, ev, lm)

Просмотреть файл

@ -647,7 +647,7 @@ func (c *completer) collectCompletions(ctx context.Context) error {
// Inside comments, offer completions for the name of the relevant symbol.
for _, comment := range c.file.Comments {
if comment.Pos() < c.pos && c.pos <= comment.End() {
c.populateCommentCompletions(ctx, comment)
c.populateCommentCompletions(comment)
return nil
}
}
@ -922,7 +922,7 @@ func (c *completer) populateImportCompletions(searchImport *ast.ImportSpec) erro
}
// populateCommentCompletions yields completions for comments preceding or in declarations.
func (c *completer) populateCommentCompletions(ctx context.Context, comment *ast.CommentGroup) {
func (c *completer) populateCommentCompletions(comment *ast.CommentGroup) {
// If the completion was triggered by a period, ignore it. These types of
// completions will not be useful in comments.
if c.completionContext.triggerCharacter == "." {
@ -974,12 +974,12 @@ func (c *completer) populateCommentCompletions(ctx context.Context, comment *ast
// add TypeSpec fields to completion
switch typeNode := spec.Type.(type) {
case *ast.StructType:
c.addFieldItems(ctx, typeNode.Fields)
c.addFieldItems(typeNode.Fields)
case *ast.FuncType:
c.addFieldItems(ctx, typeNode.Params)
c.addFieldItems(ctx, typeNode.Results)
c.addFieldItems(typeNode.Params)
c.addFieldItems(typeNode.Results)
case *ast.InterfaceType:
c.addFieldItems(ctx, typeNode.Methods)
c.addFieldItems(typeNode.Methods)
}
if spec.Name.String() == "_" {
@ -1000,9 +1000,9 @@ func (c *completer) populateCommentCompletions(ctx context.Context, comment *ast
}
// handle functions
case *ast.FuncDecl:
c.addFieldItems(ctx, node.Recv)
c.addFieldItems(ctx, node.Type.Params)
c.addFieldItems(ctx, node.Type.Results)
c.addFieldItems(node.Recv)
c.addFieldItems(node.Type.Params)
c.addFieldItems(node.Type.Results)
// collect receiver struct fields
if node.Recv != nil {
@ -1086,7 +1086,7 @@ func isValidIdentifierChar(char byte) bool {
}
// adds struct fields, interface methods, function declaration fields to completion
func (c *completer) addFieldItems(ctx context.Context, fields *ast.FieldList) {
func (c *completer) addFieldItems(fields *ast.FieldList) {
if fields == nil {
return
}
@ -1466,7 +1466,7 @@ func (c *completer) methodsAndFields(typ types.Type, addressable bool, imp *impo
if isStarTestingDotF(typ) && addressable {
// is that a sufficient test? (or is more care needed?)
if c.fuzz(typ, mset, imp, cb, c.pkg.FileSet()) {
if c.fuzz(mset, imp, cb) {
return
}
}

Просмотреть файл

@ -7,7 +7,6 @@ package completion
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"strings"
@ -21,7 +20,7 @@ import (
// PJW: are there other packages where we can deduce usage constraints?
// if we find fuzz completions, then return true, as those are the only completions to offer
func (c *completer) fuzz(typ types.Type, mset *types.MethodSet, imp *importInfo, cb func(candidate), fset *token.FileSet) bool {
func (c *completer) fuzz(mset *types.MethodSet, imp *importInfo, cb func(candidate)) bool {
// 1. inside f.Fuzz? (only f.Failed and f.Name)
// 2. possible completing f.Fuzz?
// [Ident,SelectorExpr,Callexpr,ExprStmt,BlockiStmt,FuncDecl(Fuzz...)]

Просмотреть файл

@ -63,7 +63,7 @@ func (c *fakeClient) ShowMessage(context.Context, *protocol.ShowMessageParams) e
return nil
}
func setup(token protocol.ProgressToken) (context.Context, *Tracker, *fakeClient) {
func setup() (context.Context, *Tracker, *fakeClient) {
c := &fakeClient{}
tracker := NewTracker(c)
tracker.SetSupportsWorkDoneProgress(true)
@ -109,7 +109,7 @@ func TestProgressTracker_Reporting(t *testing.T) {
} {
test := test
t.Run(test.name, func(t *testing.T) {
ctx, tracker, client := setup(test.token)
ctx, tracker, client := setup()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
tracker.supportsWorkDoneProgress = test.supported
@ -147,7 +147,7 @@ func TestProgressTracker_Reporting(t *testing.T) {
func TestProgressTracker_Cancellation(t *testing.T) {
for _, token := range []protocol.ProgressToken{nil, 1, "a"} {
ctx, tracker, _ := setup(token)
ctx, tracker, _ := setup()
var canceled bool
cancel := func() { canceled = true }
work := tracker.Start(ctx, "work", "message", token, cancel)

Просмотреть файл

@ -117,7 +117,7 @@ func init() {
namesTextDocumentSaveReason[int(FocusOut)] = "FocusOut"
}
func formatEnum(f fmt.State, c rune, i int, names []string, unknown string) {
func formatEnum(f fmt.State, i int, names []string, unknown string) {
s := ""
if i >= 0 && i < len(names) {
s = names[i]
@ -130,45 +130,45 @@ func formatEnum(f fmt.State, c rune, i int, names []string, unknown string) {
}
func (e TextDocumentSyncKind) Format(f fmt.State, c rune) {
formatEnum(f, c, int(e), namesTextDocumentSyncKind[:], "TextDocumentSyncKind")
formatEnum(f, int(e), namesTextDocumentSyncKind[:], "TextDocumentSyncKind")
}
func (e MessageType) Format(f fmt.State, c rune) {
formatEnum(f, c, int(e), namesMessageType[:], "MessageType")
formatEnum(f, int(e), namesMessageType[:], "MessageType")
}
func (e FileChangeType) Format(f fmt.State, c rune) {
formatEnum(f, c, int(e), namesFileChangeType[:], "FileChangeType")
formatEnum(f, int(e), namesFileChangeType[:], "FileChangeType")
}
func (e CompletionTriggerKind) Format(f fmt.State, c rune) {
formatEnum(f, c, int(e), namesCompletionTriggerKind[:], "CompletionTriggerKind")
formatEnum(f, int(e), namesCompletionTriggerKind[:], "CompletionTriggerKind")
}
func (e DiagnosticSeverity) Format(f fmt.State, c rune) {
formatEnum(f, c, int(e), namesDiagnosticSeverity[:], "DiagnosticSeverity")
formatEnum(f, int(e), namesDiagnosticSeverity[:], "DiagnosticSeverity")
}
func (e DiagnosticTag) Format(f fmt.State, c rune) {
formatEnum(f, c, int(e), namesDiagnosticTag[:], "DiagnosticTag")
formatEnum(f, int(e), namesDiagnosticTag[:], "DiagnosticTag")
}
func (e CompletionItemKind) Format(f fmt.State, c rune) {
formatEnum(f, c, int(e), namesCompletionItemKind[:], "CompletionItemKind")
formatEnum(f, int(e), namesCompletionItemKind[:], "CompletionItemKind")
}
func (e InsertTextFormat) Format(f fmt.State, c rune) {
formatEnum(f, c, int(e), namesInsertTextFormat[:], "InsertTextFormat")
formatEnum(f, int(e), namesInsertTextFormat[:], "InsertTextFormat")
}
func (e DocumentHighlightKind) Format(f fmt.State, c rune) {
formatEnum(f, c, int(e), namesDocumentHighlightKind[:], "DocumentHighlightKind")
formatEnum(f, int(e), namesDocumentHighlightKind[:], "DocumentHighlightKind")
}
func (e SymbolKind) Format(f fmt.State, c rune) {
formatEnum(f, c, int(e), namesSymbolKind[:], "SymbolKind")
formatEnum(f, int(e), namesSymbolKind[:], "SymbolKind")
}
func (e TextDocumentSaveReason) Format(f fmt.State, c rune) {
formatEnum(f, c, int(e), namesTextDocumentSaveReason[:], "TextDocumentSaveReason")
formatEnum(f, int(e), namesTextDocumentSaveReason[:], "TextDocumentSaveReason")
}

Просмотреть файл

@ -364,7 +364,7 @@ func (s *server) diagnose(ctx context.Context, snapshot *cache.Snapshot) (diagMa
store("diagnosing vulnerabilities", vulnReports, vulnErr)
workspacePkgs, err := snapshot.WorkspaceMetadata(ctx)
if s.shouldIgnoreError(ctx, snapshot, err) {
if s.shouldIgnoreError(snapshot, err) {
return diagnostics, ctx.Err()
}
@ -893,7 +893,7 @@ func toProtocolDiagnostics(diagnostics []*cache.Diagnostic) []protocol.Diagnosti
return reports
}
func (s *server) shouldIgnoreError(ctx context.Context, snapshot *cache.Snapshot, err error) bool {
func (s *server) shouldIgnoreError(snapshot *cache.Snapshot, err error) bool {
if err == nil { // if there is no error at all
return false
}

Просмотреть файл

@ -156,7 +156,7 @@ func (e *encoded) semantics() {
e.token(c.Pos(), len(c.Text), tokComment, nil)
continue
}
e.multiline(c.Pos(), c.End(), c.Text, tokComment)
e.multiline(c.Pos(), c.End(), tokComment)
}
}
}
@ -290,7 +290,7 @@ func (e *encoded) inspector(n ast.Node) bool {
case *ast.BasicLit:
if strings.Contains(x.Value, "\n") {
// has to be a string.
e.multiline(x.Pos(), x.End(), x.Value, tokString)
e.multiline(x.Pos(), x.End(), tokString)
break
}
ln := len(x.Value)
@ -802,7 +802,7 @@ func isTypeParam(x *ast.Ident, y *ast.FuncType) bool {
return false
}
func (e *encoded) multiline(start, end token.Pos, val string, tok tokenType) {
func (e *encoded) multiline(start, end token.Pos, tok tokenType) {
f := e.fset.File(start)
// the hard part is finding the lengths of lines. include the \n
leng := func(line int) int {

Просмотреть файл

@ -16,24 +16,20 @@ import (
// BenchmarkInitialWorkspaceLoad benchmarks the initial workspace load time for
// a new editing session.
func BenchmarkInitialWorkspaceLoad(b *testing.B) {
tests := []struct {
repo string
file string
}{
{"google-cloud-go", "httpreplay/httpreplay.go"},
{"istio", "pkg/fuzz/util.go"},
{"kubernetes", "pkg/controller/lookup_cache.go"},
{"kuma", "api/generic/insights.go"},
{"oracle", "dataintegration/data_type.go"},
{"pkgsite", "internal/frontend/server.go"},
{"starlark", "starlark/eval.go"},
{"tools", "internal/lsp/cache/snapshot.go"},
{"hashiform", "internal/provider/provider.go"},
repoNames := []string{
"google-cloud-go",
"istio",
"kubernetes",
"kuma",
"oracle",
"pkgsite",
"starlark",
"tools",
"hashiform",
}
for _, test := range tests {
b.Run(test.repo, func(b *testing.B) {
repo := getRepo(b, test.repo)
for _, repoName := range repoNames {
b.Run(repoName, func(b *testing.B) {
repo := getRepo(b, repoName)
// get the (initialized) shared env to ensure the cache is warm.
// Reuse its GOPATH so that we get cache hits for things in the module
// cache.
@ -41,13 +37,13 @@ func BenchmarkInitialWorkspaceLoad(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
doIWL(b, sharedEnv.Sandbox.GOPATH(), repo, test.file)
doIWL(b, sharedEnv.Sandbox.GOPATH(), repo)
}
})
}
}
func doIWL(b *testing.B, gopath string, repo *repo, file string) {
func doIWL(b *testing.B, gopath string, repo *repo) {
// Exclude the time to set up the env from the benchmark time, as this may
// involve installing gopls and/or checking out the repo dir.
b.StopTimer()

Просмотреть файл

@ -1291,7 +1291,7 @@ func (e *Editor) SignatureHelp(ctx context.Context, loc protocol.Location) (*pro
}
func (e *Editor) RenameFile(ctx context.Context, oldPath, newPath string) error {
closed, opened, err := e.renameBuffers(ctx, oldPath, newPath)
closed, opened, err := e.renameBuffers(oldPath, newPath)
if err != nil {
return err
}
@ -1317,7 +1317,7 @@ func (e *Editor) RenameFile(ctx context.Context, oldPath, newPath string) error
// renameBuffers renames in-memory buffers affected by the renaming of
// oldPath->newPath, returning the resulting text documents that must be closed
// and opened over the LSP.
func (e *Editor) renameBuffers(ctx context.Context, oldPath, newPath string) (closed []protocol.TextDocumentIdentifier, opened []protocol.TextDocumentItem, _ error) {
func (e *Editor) renameBuffers(oldPath, newPath string) (closed []protocol.TextDocumentIdentifier, opened []protocol.TextDocumentItem, _ error) {
e.mu.Lock()
defer e.mu.Unlock()

Просмотреть файл

@ -434,7 +434,7 @@ func (v VulnData) Vuln1() {}
func (v VulnData) Vuln2() {}
`
func vulnTestEnv(vulnsDB, proxyData string) (*vulntest.DB, []RunOption, error) {
func vulnTestEnv(proxyData string) (*vulntest.DB, []RunOption, error) {
db, err := vulntest.NewDatabase(context.Background(), []byte(vulnsData))
if err != nil {
return nil, nil, nil
@ -458,7 +458,7 @@ func vulnTestEnv(vulnsDB, proxyData string) (*vulntest.DB, []RunOption, error) {
}
func TestRunVulncheckPackageDiagnostics(t *testing.T) {
db, opts0, err := vulnTestEnv(vulnsData, proxy1)
db, opts0, err := vulnTestEnv(proxy1)
if err != nil {
t.Fatal(err)
}
@ -606,7 +606,7 @@ func TestRunGovulncheck_Expiry(t *testing.T) {
}(cache.MaxGovulncheckResultAge)
cache.MaxGovulncheckResultAge = 99 * time.Millisecond
db, opts0, err := vulnTestEnv(vulnsData, proxy1)
db, opts0, err := vulnTestEnv(proxy1)
if err != nil {
t.Fatal(err)
}
@ -638,7 +638,7 @@ func stringify(a interface{}) string {
}
func TestRunVulncheckWarning(t *testing.T) {
db, opts, err := vulnTestEnv(vulnsData, proxy1)
db, opts, err := vulnTestEnv(proxy1)
if err != nil {
t.Fatal(err)
}
@ -793,7 +793,7 @@ func OK() {} // ok.
`
func TestGovulncheckInfo(t *testing.T) {
db, opts, err := vulnTestEnv(vulnsData, proxy2)
db, opts, err := vulnTestEnv(proxy2)
if err != nil {
t.Fatal(err)
}