1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
import (
"context"
"encoding/json"
"fmt"
"go/ast"
"go/types"
"strings"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/gopls/internal/analysis/fillstruct"
"golang.org/x/tools/gopls/internal/analysis/fillswitch"
"golang.org/x/tools/gopls/internal/cache"
"golang.org/x/tools/gopls/internal/cache/parsego"
"golang.org/x/tools/gopls/internal/file"
"golang.org/x/tools/gopls/internal/label"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/protocol/command"
"golang.org/x/tools/gopls/internal/settings"
"golang.org/x/tools/gopls/internal/util/bug"
"golang.org/x/tools/gopls/internal/util/slices"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/imports"
"golang.org/x/tools/internal/typesinternal"
)
// CodeActions returns all wanted code actions (edits and other
// commands) available for the selected range.
//
// Depending on how the request was triggered, fewer actions may be
// offered, e.g. to avoid UI distractions after mere cursor motion.
//
// See ../protocol/codeactionkind.go for some code action theory.
func CodeActions(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range, diagnostics []protocol.Diagnostic, want map[protocol.CodeActionKind]bool, trigger protocol.CodeActionTriggerKind) (actions []protocol.CodeAction, _ error) {
// Only compute quick fixes if there are any diagnostics to fix.
wantQuickFixes := want[protocol.QuickFix] && len(diagnostics) > 0
// Note: don't forget to update the allow-list in Server.CodeAction
// when adding new query operations like GoTest and GoDoc that
// are permitted even in generated source files
// Code actions that can be offered based on syntax information alone.
if wantQuickFixes ||
want[protocol.SourceOrganizeImports] ||
want[protocol.RefactorExtract] ||
want[settings.GoFreeSymbols] ||
want[settings.GoplsDocFeatures] {
pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full)
if err != nil {
return nil, err
}
// Process any missing imports and pair them with the diagnostics they fix.
if wantQuickFixes || want[protocol.SourceOrganizeImports] {
importEdits, importEditsPerFix, err := allImportsFixes(ctx, snapshot, pgf)
if err != nil {
event.Error(ctx, "imports fixes", err, label.File.Of(fh.URI().Path()))
importEdits = nil
importEditsPerFix = nil
}
// Separate this into a set of codeActions per diagnostic, where
// each action is the addition, removal, or renaming of one import.
if wantQuickFixes {
for _, importFix := range importEditsPerFix {
fixed := fixedByImportFix(importFix.fix, diagnostics)
if len(fixed) == 0 {
continue
}
actions = append(actions, protocol.CodeAction{
Title: importFixTitle(importFix.fix),
Kind: protocol.QuickFix,
Edit: protocol.NewWorkspaceEdit(
protocol.DocumentChangeEdit(fh, importFix.edits)),
Diagnostics: fixed,
})
}
}
// Send all of the import edits as one code action if the file is
// being organized.
if want[protocol.SourceOrganizeImports] && len(importEdits) > 0 {
actions = append(actions, protocol.CodeAction{
Title: "Organize Imports",
Kind: protocol.SourceOrganizeImports,
Edit: protocol.NewWorkspaceEdit(
protocol.DocumentChangeEdit(fh, importEdits)),
})
}
}
if want[protocol.RefactorExtract] {
extractions, err := getExtractCodeActions(pgf, rng, snapshot.Options())
if err != nil {
return nil, err
}
actions = append(actions, extractions...)
}
if want[settings.GoFreeSymbols] && rng.End != rng.Start {
loc := protocol.Location{URI: pgf.URI, Range: rng}
cmd, err := command.NewFreeSymbolsCommand("Browse free symbols", snapshot.View().ID(), loc)
if err != nil {
return nil, err
}
// For implementation, see commandHandler.FreeSymbols.
actions = append(actions, protocol.CodeAction{
Title: cmd.Title,
Kind: settings.GoFreeSymbols,
Command: &cmd,
})
}
if want[settings.GoplsDocFeatures] {
// TODO(adonovan): after the docs are published in gopls/v0.17.0,
// use the gopls release tag instead of master.
cmd, err := command.NewClientOpenURLCommand(
"Browse gopls feature documentation",
"https://github.com/golang/tools/blob/master/gopls/doc/features/README.md")
if err != nil {
return nil, err
}
actions = append(actions, protocol.CodeAction{
Title: cmd.Title,
Kind: settings.GoplsDocFeatures,
Command: &cmd,
})
}
}
// Code actions requiring type information.
if want[protocol.RefactorRewrite] ||
want[protocol.RefactorInline] ||
want[settings.GoAssembly] ||
want[settings.GoDoc] ||
want[settings.GoTest] {
pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
if err != nil {
return nil, err
}
start, end, err := pgf.RangePos(rng)
if err != nil {
return nil, err
}
if want[protocol.RefactorRewrite] {
rewrites, err := getRewriteCodeActions(ctx, pkg, snapshot, pgf, fh, rng, snapshot.Options())
if err != nil {
return nil, err
}
actions = append(actions, rewrites...)
}
// To avoid distraction (e.g. VS Code lightbulb), offer "inline"
// only after a selection or explicit menu operation.
if want[protocol.RefactorInline] && (trigger != protocol.CodeActionAutomatic || rng.Start != rng.End) {
rewrites, err := getInlineCodeActions(pkg, pgf, rng, snapshot.Options())
if err != nil {
return nil, err
}
actions = append(actions, rewrites...)
}
if want[settings.GoTest] {
fixes, err := getGoTestCodeActions(pkg, pgf, rng)
if err != nil {
return nil, err
}
actions = append(actions, fixes...)
}
if want[settings.GoDoc] {
// "Browse documentation for ..."
_, _, title := DocFragment(pkg, pgf, start, end)
loc := protocol.Location{URI: pgf.URI, Range: rng}
cmd, err := command.NewDocCommand(title, loc)
if err != nil {
return nil, err
}
actions = append(actions, protocol.CodeAction{
Title: cmd.Title,
Kind: settings.GoDoc,
Command: &cmd,
})
}
if want[settings.GoAssembly] {
fixes, err := getGoAssemblyAction(snapshot.View(), pkg, pgf, rng)
if err != nil {
return nil, err
}
actions = append(actions, fixes...)
}
}
return actions, nil
}
func supportsResolveEdits(options *settings.Options) bool {
return options.CodeActionResolveOptions != nil && slices.Contains(options.CodeActionResolveOptions, "edit")
}
func importFixTitle(fix *imports.ImportFix) string {
var str string
switch fix.FixType {
case imports.AddImport:
str = fmt.Sprintf("Add import: %s %q", fix.StmtInfo.Name, fix.StmtInfo.ImportPath)
case imports.DeleteImport:
str = fmt.Sprintf("Delete import: %s %q", fix.StmtInfo.Name, fix.StmtInfo.ImportPath)
case imports.SetImportName:
str = fmt.Sprintf("Rename import: %s %q", fix.StmtInfo.Name, fix.StmtInfo.ImportPath)
}
return str
}
// fixedByImportFix filters the provided slice of diagnostics to those that
// would be fixed by the provided imports fix.
func fixedByImportFix(fix *imports.ImportFix, diagnostics []protocol.Diagnostic) []protocol.Diagnostic {
var results []protocol.Diagnostic
for _, diagnostic := range diagnostics {
switch {
// "undeclared name: X" may be an unresolved import.
case strings.HasPrefix(diagnostic.Message, "undeclared name: "):
ident := strings.TrimPrefix(diagnostic.Message, "undeclared name: ")
if ident == fix.IdentName {
results = append(results, diagnostic)
}
// "undefined: X" may be an unresolved import at Go 1.20+.
case strings.HasPrefix(diagnostic.Message, "undefined: "):
ident := strings.TrimPrefix(diagnostic.Message, "undefined: ")
if ident == fix.IdentName {
results = append(results, diagnostic)
}
// "could not import: X" may be an invalid import.
case strings.HasPrefix(diagnostic.Message, "could not import: "):
ident := strings.TrimPrefix(diagnostic.Message, "could not import: ")
if ident == fix.IdentName {
results = append(results, diagnostic)
}
// "X imported but not used" is an unused import.
// "X imported but not used as Y" is an unused import.
case strings.Contains(diagnostic.Message, " imported but not used"):
idx := strings.Index(diagnostic.Message, " imported but not used")
importPath := diagnostic.Message[:idx]
if importPath == fmt.Sprintf("%q", fix.StmtInfo.ImportPath) {
results = append(results, diagnostic)
}
}
}
return results
}
// getExtractCodeActions returns any refactor.extract code actions for the selection.
func getExtractCodeActions(pgf *parsego.File, rng protocol.Range, options *settings.Options) ([]protocol.CodeAction, error) {
start, end, err := pgf.RangePos(rng)
if err != nil {
return nil, err
}
puri := pgf.URI
var commands []protocol.Command
if _, ok, methodOk, _ := canExtractFunction(pgf.Tok, start, end, pgf.Src, pgf.File); ok {
cmd, err := command.NewApplyFixCommand("Extract function", command.ApplyFixArgs{
Fix: fixExtractFunction,
URI: puri,
Range: rng,
ResolveEdits: supportsResolveEdits(options),
})
if err != nil {
return nil, err
}
commands = append(commands, cmd)
if methodOk {
cmd, err := command.NewApplyFixCommand("Extract method", command.ApplyFixArgs{
Fix: fixExtractMethod,
URI: puri,
Range: rng,
ResolveEdits: supportsResolveEdits(options),
})
if err != nil {
return nil, err
}
commands = append(commands, cmd)
}
}
if _, _, ok, _ := canExtractVariable(start, end, pgf.File); ok {
cmd, err := command.NewApplyFixCommand("Extract variable", command.ApplyFixArgs{
Fix: fixExtractVariable,
URI: puri,
Range: rng,
ResolveEdits: supportsResolveEdits(options),
})
if err != nil {
return nil, err
}
commands = append(commands, cmd)
}
if canExtractToNewFile(pgf, start, end) {
cmd, err := command.NewExtractToNewFileCommand(
"Extract declarations to new file",
protocol.Location{URI: pgf.URI, Range: rng},
)
if err != nil {
return nil, err
}
commands = append(commands, cmd)
}
var actions []protocol.CodeAction
for i := range commands {
actions = append(actions, newCodeAction(commands[i].Title, protocol.RefactorExtract, &commands[i], nil, options))
}
return actions, nil
}
func newCodeAction(title string, kind protocol.CodeActionKind, cmd *protocol.Command, diagnostics []protocol.Diagnostic, options *settings.Options) protocol.CodeAction {
action := protocol.CodeAction{
Title: title,
Kind: kind,
Diagnostics: diagnostics,
}
if !supportsResolveEdits(options) {
action.Command = cmd
} else {
data, err := json.Marshal(cmd)
if err != nil {
panic("unable to marshal")
}
msg := json.RawMessage(data)
action.Data = &msg
}
return action
}
func getRewriteCodeActions(ctx context.Context, pkg *cache.Package, snapshot *cache.Snapshot, pgf *parsego.File, fh file.Handle, rng protocol.Range, options *settings.Options) (_ []protocol.CodeAction, rerr error) {
// golang/go#61693: code actions were refactored to run outside of the
// analysis framework, but as a result they lost their panic recovery.
//
// These code actions should never fail, but put back the panic recovery as a
// defensive measure.
defer func() {
if r := recover(); r != nil {
rerr = bug.Errorf("refactor.rewrite code actions panicked: %v", r)
}
}()
var actions []protocol.CodeAction
if canRemoveParameter(pkg, pgf, rng) {
cmd, err := command.NewChangeSignatureCommand("remove unused parameter", command.ChangeSignatureArgs{
RemoveParameter: protocol.Location{
URI: pgf.URI,
Range: rng,
},
ResolveEdits: supportsResolveEdits(options),
})
if err != nil {
return nil, err
}
actions = append(actions, newCodeAction("Refactor: remove unused parameter", protocol.RefactorRewrite, &cmd, nil, options))
}
start, end, err := pgf.RangePos(rng)
if err != nil {
return nil, err
}
if action, ok := convertStringLiteral(pgf, fh, start, end); ok {
actions = append(actions, action)
}
var commands []protocol.Command
if _, ok, _ := canInvertIfCondition(pgf.File, start, end); ok {
cmd, err := command.NewApplyFixCommand("Invert 'if' condition", command.ApplyFixArgs{
Fix: fixInvertIfCondition,
URI: pgf.URI,
Range: rng,
ResolveEdits: supportsResolveEdits(options),
})
if err != nil {
return nil, err
}
commands = append(commands, cmd)
}
if msg, ok, _ := canSplitLines(pgf.File, pkg.FileSet(), start, end); ok {
cmd, err := command.NewApplyFixCommand(msg, command.ApplyFixArgs{
Fix: fixSplitLines,
URI: pgf.URI,
Range: rng,
ResolveEdits: supportsResolveEdits(options),
})
if err != nil {
return nil, err
}
commands = append(commands, cmd)
}
if msg, ok, _ := canJoinLines(pgf.File, pkg.FileSet(), start, end); ok {
cmd, err := command.NewApplyFixCommand(msg, command.ApplyFixArgs{
Fix: fixJoinLines,
URI: pgf.URI,
Range: rng,
ResolveEdits: supportsResolveEdits(options),
})
if err != nil {
return nil, err
}
commands = append(commands, cmd)
}
// fillstruct.Diagnose is a lazy analyzer: all it gives us is
// the (start, end, message) of each SuggestedFix; the actual
// edit is computed only later by ApplyFix, which calls fillstruct.SuggestedFix.
for _, diag := range fillstruct.Diagnose(pgf.File, start, end, pkg.Types(), pkg.TypesInfo()) {
rng, err := pgf.Mapper.PosRange(pgf.Tok, diag.Pos, diag.End)
if err != nil {
return nil, err
}
for _, fix := range diag.SuggestedFixes {
cmd, err := command.NewApplyFixCommand(fix.Message, command.ApplyFixArgs{
Fix: diag.Category,
URI: pgf.URI,
Range: rng,
ResolveEdits: supportsResolveEdits(options),
})
if err != nil {
return nil, err
}
commands = append(commands, cmd)
}
}
for _, diag := range fillswitch.Diagnose(pgf.File, start, end, pkg.Types(), pkg.TypesInfo()) {
changes, err := suggestedFixToDocumentChange(ctx, snapshot, pkg.FileSet(), &diag.SuggestedFixes[0])
if err != nil {
return nil, err
}
actions = append(actions, protocol.CodeAction{
Title: diag.Message,
Kind: protocol.RefactorRewrite,
Edit: protocol.NewWorkspaceEdit(changes...),
})
}
for i := range commands {
actions = append(actions, newCodeAction(commands[i].Title, protocol.RefactorRewrite, &commands[i], nil, options))
}
return actions, nil
}
// canRemoveParameter reports whether we can remove the function parameter
// indicated by the given [start, end) range.
//
// This is true if:
// - there are no parse or type errors, and
// - [start, end) is contained within an unused field or parameter name
// - ... of a non-method function declaration.
//
// (Note that the unusedparam analyzer also computes this property, but
// much more precisely, allowing it to report its findings as diagnostics.)
func canRemoveParameter(pkg *cache.Package, pgf *parsego.File, rng protocol.Range) bool {
if perrors, terrors := pkg.ParseErrors(), pkg.TypeErrors(); len(perrors) > 0 || len(terrors) > 0 {
return false // can't remove parameters from packages with errors
}
info, err := findParam(pgf, rng)
if err != nil {
return false // e.g. invalid range
}
if info.field == nil {
return false // range does not span a parameter
}
if info.decl.Body == nil {
return false // external function
}
if len(info.field.Names) == 0 {
return true // no names => field is unused
}
if info.name == nil {
return false // no name is indicated
}
if info.name.Name == "_" {
return true // trivially unused
}
obj := pkg.TypesInfo().Defs[info.name]
if obj == nil {
return false // something went wrong
}
used := false
ast.Inspect(info.decl.Body, func(node ast.Node) bool {
if n, ok := node.(*ast.Ident); ok && pkg.TypesInfo().Uses[n] == obj {
used = true
}
return !used // keep going until we find a use
})
return !used
}
// getInlineCodeActions returns refactor.inline actions available at the specified range.
func getInlineCodeActions(pkg *cache.Package, pgf *parsego.File, rng protocol.Range, options *settings.Options) ([]protocol.CodeAction, error) {
start, end, err := pgf.RangePos(rng)
if err != nil {
return nil, err
}
// If range is within call expression, offer to inline the call.
var commands []protocol.Command
if _, fn, err := enclosingStaticCall(pkg, pgf, start, end); err == nil {
cmd, err := command.NewApplyFixCommand(fmt.Sprintf("Inline call to %s", fn.Name()), command.ApplyFixArgs{
Fix: fixInlineCall,
URI: pgf.URI,
Range: rng,
ResolveEdits: supportsResolveEdits(options),
})
if err != nil {
return nil, err
}
commands = append(commands, cmd)
}
// Convert commands to actions.
var actions []protocol.CodeAction
for i := range commands {
actions = append(actions, newCodeAction(commands[i].Title, protocol.RefactorInline, &commands[i], nil, options))
}
return actions, nil
}
// getGoTestCodeActions returns any "run this test/benchmark" code actions for the selection.
func getGoTestCodeActions(pkg *cache.Package, pgf *parsego.File, rng protocol.Range) ([]protocol.CodeAction, error) {
testFuncs, benchFuncs, err := testsAndBenchmarks(pkg.TypesInfo(), pgf)
if err != nil {
return nil, err
}
var tests, benchmarks []string
for _, fn := range testFuncs {
if protocol.Intersect(fn.rng, rng) {
tests = append(tests, fn.name)
}
}
for _, fn := range benchFuncs {
if protocol.Intersect(fn.rng, rng) {
benchmarks = append(benchmarks, fn.name)
}
}
if len(tests) == 0 && len(benchmarks) == 0 {
return nil, nil
}
cmd, err := command.NewTestCommand("Run tests and benchmarks", pgf.URI, tests, benchmarks)
if err != nil {
return nil, err
}
return []protocol.CodeAction{{
Title: cmd.Title,
Kind: settings.GoTest,
Command: &cmd,
}}, nil
}
// getGoAssemblyAction returns any "Browse assembly for f" code actions for the selection.
func getGoAssemblyAction(view *cache.View, pkg *cache.Package, pgf *parsego.File, rng protocol.Range) ([]protocol.CodeAction, error) {
start, end, err := pgf.RangePos(rng)
if err != nil {
return nil, err
}
// Find the enclosing toplevel function or method,
// and compute its symbol name (e.g. "pkgpath.(T).method").
// The report will show this method and all its nested
// functions (FuncLit, defers, etc).
//
// TODO(adonovan): this is no good for generics, since they
// will always be uninstantiated when they enclose the cursor.
// Instead, we need to query the func symbol under the cursor,
// rather than the enclosing function. It may be an explicitly
// or implicitly instantiated generic, and it may be defined
// in another package, though we would still need to compile
// the current package to see its assembly. The challenge,
// however, is that computing the linker name for a generic
// symbol is quite tricky. Talk with the compiler team for
// ideas.
//
// TODO(adonovan): think about a smoother UX for jumping
// directly to (say) a lambda of interest.
// Perhaps we could scroll to STEXT for the innermost
// enclosing nested function?
var actions []protocol.CodeAction
path, _ := astutil.PathEnclosingInterval(pgf.File, start, end)
if len(path) >= 2 { // [... FuncDecl File]
if decl, ok := path[len(path)-2].(*ast.FuncDecl); ok {
if fn, ok := pkg.TypesInfo().Defs[decl.Name].(*types.Func); ok {
sig := fn.Type().(*types.Signature)
// Compute the linker symbol of the enclosing function.
var sym strings.Builder
if fn.Pkg().Name() == "main" {
sym.WriteString("main")
} else {
sym.WriteString(fn.Pkg().Path())
}
sym.WriteString(".")
if sig.Recv() != nil {
if isPtr, named := typesinternal.ReceiverNamed(sig.Recv()); named != nil {
sym.WriteString("(")
if isPtr {
sym.WriteString("*")
}
sym.WriteString(named.Obj().Name())
sym.WriteString(").")
}
}
sym.WriteString(fn.Name())
if fn.Name() != "_" && // blank functions are not compiled
(fn.Name() != "init" || sig.Recv() != nil) && // init functions aren't linker functions
sig.TypeParams() == nil && sig.RecvTypeParams() == nil { // generic => no assembly
cmd, err := command.NewAssemblyCommand(
fmt.Sprintf("Browse %s assembly for %s", view.GOARCH(), decl.Name),
view.ID(),
string(pkg.Metadata().ID),
sym.String())
if err != nil {
return nil, err
}
// For handler, see commandHandler.Assembly.
actions = append(actions, protocol.CodeAction{
Title: cmd.Title,
Kind: settings.GoAssembly,
Command: &cmd,
})
}
}
}
}
return actions, nil
}
|