| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package golang |
| 6 |
|
| 7 |
import ( |
| 8 |
"context" |
| 9 |
"encoding/json" |
| 10 |
"fmt" |
| 11 |
"go/ast" |
| 12 |
"go/token" |
| 13 |
"go/types" |
| 14 |
"reflect" |
| 15 |
"slices" |
| 16 |
"strings" |
| 17 |
|
| 18 |
goastutil "golang.org/x/tools/go/ast/astutil" |
| 19 |
"golang.org/x/tools/go/ast/edge" |
| 20 |
"golang.org/x/tools/go/ast/inspector" |
| 21 |
"golang.org/x/tools/gopls/internal/analysis/fillstruct" |
| 22 |
"golang.org/x/tools/gopls/internal/analysis/fillswitch" |
| 23 |
"golang.org/x/tools/gopls/internal/cache" |
| 24 |
"golang.org/x/tools/gopls/internal/cache/parsego" |
| 25 |
"golang.org/x/tools/gopls/internal/file" |
| 26 |
"golang.org/x/tools/gopls/internal/golang/stubmethods" |
| 27 |
"golang.org/x/tools/gopls/internal/label" |
| 28 |
"golang.org/x/tools/gopls/internal/protocol" |
| 29 |
"golang.org/x/tools/gopls/internal/protocol/command" |
| 30 |
"golang.org/x/tools/gopls/internal/settings" |
| 31 |
"golang.org/x/tools/gopls/internal/util/cursorutil" |
| 32 |
"golang.org/x/tools/internal/astutil" |
| 33 |
"golang.org/x/tools/internal/event" |
| 34 |
"golang.org/x/tools/internal/imports" |
| 35 |
"golang.org/x/tools/internal/typesinternal" |
| 36 |
) |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
func CodeActions(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range, diagnostics []protocol.Diagnostic, enabled func(protocol.CodeActionKind) bool, trigger protocol.CodeActionTriggerKind) (actions []protocol.CodeAction, _ error) { |
| 46 |
loc := fh.URI().Location(rng) |
| 47 |
|
| 48 |
pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full) |
| 49 |
if err != nil { |
| 50 |
return nil, err |
| 51 |
} |
| 52 |
start, end, err := pgf.RangePos(rng) |
| 53 |
if err != nil { |
| 54 |
return nil, err |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
var enabledMemo [len(codeActionProducers)]bool |
| 59 |
needTypes := false |
| 60 |
for i, p := range codeActionProducers { |
| 61 |
if enabled(p.kind) { |
| 62 |
enabledMemo[i] = true |
| 63 |
if p.needPkg { |
| 64 |
needTypes = true |
| 65 |
} |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
var pkg *cache.Package |
| 73 |
if needTypes { |
| 74 |
var err error |
| 75 |
pkg, pgf, err = NarrowestPackageForFile(ctx, snapshot, loc.URI) |
| 76 |
if err != nil { |
| 77 |
return nil, err |
| 78 |
} |
| 79 |
start, end, err = pgf.RangePos(loc.Range) |
| 80 |
if err != nil { |
| 81 |
return nil, err |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
|
| 86 |
req := &codeActionsRequest{ |
| 87 |
actions: &actions, |
| 88 |
lazy: make(map[reflect.Type]any), |
| 89 |
snapshot: snapshot, |
| 90 |
fh: fh, |
| 91 |
pgf: pgf, |
| 92 |
loc: loc, |
| 93 |
start: start, |
| 94 |
end: end, |
| 95 |
diagnostics: diagnostics, |
| 96 |
trigger: trigger, |
| 97 |
pkg: pkg, |
| 98 |
} |
| 99 |
for i, p := range codeActionProducers { |
| 100 |
if !enabledMemo[i] { |
| 101 |
continue |
| 102 |
} |
| 103 |
req.kind = p.kind |
| 104 |
if p.needPkg { |
| 105 |
req.pkg = pkg |
| 106 |
} else { |
| 107 |
req.pkg = nil |
| 108 |
} |
| 109 |
if err := p.fn(ctx, req); err != nil { |
| 110 |
|
| 111 |
|
| 112 |
if ctx.Err() != nil { |
| 113 |
return nil, err |
| 114 |
} |
| 115 |
event.Error(ctx, fmt.Sprintf("CodeAction producer %s failed", p.kind), err) |
| 116 |
continue |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
|
| 121 |
return actions, nil |
| 122 |
} |
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
type codeActionsRequest struct { |
| 127 |
|
| 128 |
actions *[]protocol.CodeAction |
| 129 |
lazy map[reflect.Type]any |
| 130 |
|
| 131 |
|
| 132 |
kind protocol.CodeActionKind |
| 133 |
snapshot *cache.Snapshot |
| 134 |
fh file.Handle |
| 135 |
pgf *parsego.File |
| 136 |
loc protocol.Location |
| 137 |
start, end token.Pos |
| 138 |
diagnostics []protocol.Diagnostic |
| 139 |
trigger protocol.CodeActionTriggerKind |
| 140 |
pkg *cache.Package |
| 141 |
} |
| 142 |
|
| 143 |
|
| 144 |
func (req *codeActionsRequest) addApplyFixAction(title, fix string, loc protocol.Location) { |
| 145 |
cmd := command.NewApplyFixCommand(title, command.ApplyFixArgs{ |
| 146 |
Fix: fix, |
| 147 |
Location: loc, |
| 148 |
ResolveEdits: req.resolveEdits(), |
| 149 |
}) |
| 150 |
req.addCommandAction(cmd, true) |
| 151 |
} |
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
func (req *codeActionsRequest) addCommandAction(cmd *protocol.Command, allowResolveEdits bool) { |
| 170 |
act := protocol.CodeAction{ |
| 171 |
Title: cmd.Title, |
| 172 |
Kind: req.kind, |
| 173 |
} |
| 174 |
if allowResolveEdits && req.resolveEdits() { |
| 175 |
data, err := json.Marshal(cmd) |
| 176 |
if err != nil { |
| 177 |
panic("unable to marshal") |
| 178 |
} |
| 179 |
msg := json.RawMessage(data) |
| 180 |
act.Data = &msg |
| 181 |
} else { |
| 182 |
act.Command = cmd |
| 183 |
} |
| 184 |
req.addAction(act) |
| 185 |
} |
| 186 |
|
| 187 |
|
| 188 |
func (req *codeActionsRequest) addEditAction(title string, fixedDiagnostics []protocol.Diagnostic, changes ...protocol.DocumentChange) { |
| 189 |
req.addAction(protocol.CodeAction{ |
| 190 |
Title: title, |
| 191 |
Kind: req.kind, |
| 192 |
Diagnostics: fixedDiagnostics, |
| 193 |
Edit: protocol.NewWorkspaceEdit(changes...), |
| 194 |
}) |
| 195 |
} |
| 196 |
|
| 197 |
|
| 198 |
func (req *codeActionsRequest) addAction(act protocol.CodeAction) { |
| 199 |
*req.actions = append(*req.actions, act) |
| 200 |
} |
| 201 |
|
| 202 |
|
| 203 |
func (req *codeActionsRequest) resolveEdits() bool { |
| 204 |
opts := req.snapshot.Options() |
| 205 |
return opts.CodeActionResolveOptions != nil && |
| 206 |
slices.Contains(opts.CodeActionResolveOptions, "edit") |
| 207 |
} |
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
func lazyInit[P interface { |
| 214 |
init(ctx context.Context, req *codeActionsRequest) |
| 215 |
*T |
| 216 |
}, T any](ctx context.Context, req *codeActionsRequest) P { |
| 217 |
t := reflect.TypeFor[T]() |
| 218 |
v, ok := req.lazy[t].(P) |
| 219 |
if !ok { |
| 220 |
v = new(T) |
| 221 |
v.init(ctx, req) |
| 222 |
req.lazy[t] = v |
| 223 |
} |
| 224 |
return v |
| 225 |
} |
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
type codeActionProducer struct { |
| 233 |
kind protocol.CodeActionKind |
| 234 |
fn func(ctx context.Context, req *codeActionsRequest) error |
| 235 |
needPkg bool |
| 236 |
} |
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
var codeActionProducers = [...]codeActionProducer{ |
| 241 |
{kind: protocol.QuickFix, fn: quickFix, needPkg: true}, |
| 242 |
{kind: protocol.SourceOrganizeImports, fn: sourceOrganizeImports}, |
| 243 |
{kind: settings.AddTest, fn: addTest, needPkg: true}, |
| 244 |
{kind: settings.GoAssembly, fn: goAssembly, needPkg: true}, |
| 245 |
{kind: settings.GoDoc, fn: goDoc, needPkg: true}, |
| 246 |
{kind: settings.GoFreeSymbols, fn: goFreeSymbols}, |
| 247 |
{kind: settings.GoSplitPackage, fn: goSplitPackage, needPkg: true}, |
| 248 |
{kind: settings.GoTest, fn: goTest, needPkg: true}, |
| 249 |
{kind: settings.GoToggleCompilerOptDetails, fn: toggleCompilerOptDetails}, |
| 250 |
{kind: settings.RefactorExtractFunction, fn: refactorExtractFunction}, |
| 251 |
{kind: settings.RefactorExtractMethod, fn: refactorExtractMethod}, |
| 252 |
{kind: settings.RefactorExtractToNewFile, fn: refactorExtractToNewFile}, |
| 253 |
{kind: settings.RefactorExtractConstant, fn: refactorExtractVariable, needPkg: true}, |
| 254 |
{kind: settings.RefactorExtractVariable, fn: refactorExtractVariable, needPkg: true}, |
| 255 |
{kind: settings.RefactorExtractConstantAll, fn: refactorExtractVariableAll, needPkg: true}, |
| 256 |
{kind: settings.RefactorExtractVariableAll, fn: refactorExtractVariableAll, needPkg: true}, |
| 257 |
{kind: settings.RefactorInlineCall, fn: refactorInlineCall, needPkg: true}, |
| 258 |
{kind: settings.RefactorInlineVariable, fn: refactorInlineVariable, needPkg: true}, |
| 259 |
|
| 260 |
{kind: settings.RefactorRewriteChangeQuote, fn: refactorRewriteChangeQuote}, |
| 261 |
{kind: settings.RefactorRewriteFillStruct, fn: refactorRewriteFillStruct, needPkg: true}, |
| 262 |
{kind: settings.RefactorRewriteFillSwitch, fn: refactorRewriteFillSwitch, needPkg: true}, |
| 263 |
{kind: settings.RefactorRewriteImplementInterface, fn: refactorRewriteImplementInterface, needPkg: true}, |
| 264 |
{kind: settings.RefactorRewriteInvertIf, fn: refactorRewriteInvertIf}, |
| 265 |
{kind: settings.RefactorRewriteJoinLines, fn: refactorRewriteJoinLines, needPkg: true}, |
| 266 |
{kind: settings.RefactorRewriteRemoveUnusedParam, fn: refactorRewriteRemoveUnusedParam, needPkg: true}, |
| 267 |
{kind: settings.RefactorRewriteMoveParamLeft, fn: refactorRewriteMoveParamLeft, needPkg: true}, |
| 268 |
{kind: settings.RefactorRewriteMoveParamRight, fn: refactorRewriteMoveParamRight, needPkg: true}, |
| 269 |
{kind: settings.RefactorRewriteSplitLines, fn: refactorRewriteSplitLines, needPkg: true}, |
| 270 |
{kind: settings.RefactorRewriteEliminateDotImport, fn: refactorRewriteEliminateDotImport, needPkg: true}, |
| 271 |
{kind: settings.RefactorRewriteAddTags, fn: refactorRewriteAddStructTags, needPkg: true}, |
| 272 |
{kind: settings.RefactorRewriteRemoveTags, fn: refactorRewriteRemoveStructTags, needPkg: true}, |
| 273 |
{kind: settings.GoplsDocFeatures, fn: goplsDocFeatures}, |
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
|
| 278 |
} |
| 279 |
|
| 280 |
|
| 281 |
func sourceOrganizeImports(ctx context.Context, req *codeActionsRequest) error { |
| 282 |
res := lazyInit[*allImportsFixesResult](ctx, req) |
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
if len(res.allFixEdits) > 0 { |
| 287 |
req.addEditAction("Organize Imports", nil, protocol.DocumentChangeEdit(req.fh, res.allFixEdits)) |
| 288 |
} |
| 289 |
|
| 290 |
return nil |
| 291 |
} |
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
func quickFix(ctx context.Context, req *codeActionsRequest) error { |
| 297 |
|
| 298 |
if len(req.diagnostics) == 0 { |
| 299 |
return nil |
| 300 |
} |
| 301 |
|
| 302 |
|
| 303 |
res := lazyInit[*allImportsFixesResult](ctx, req) |
| 304 |
if res.err != nil { |
| 305 |
return nil |
| 306 |
} |
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
for _, importFix := range res.editsPerFix { |
| 311 |
fixedDiags := fixedByImportFix(importFix.fix, req.diagnostics) |
| 312 |
if len(fixedDiags) == 0 { |
| 313 |
continue |
| 314 |
} |
| 315 |
req.addEditAction(importFixTitle(importFix.fix), fixedDiags, protocol.DocumentChangeEdit(req.fh, importFix.edits)) |
| 316 |
} |
| 317 |
|
| 318 |
|
| 319 |
info := req.pkg.TypesInfo() |
| 320 |
for _, typeError := range req.pkg.TypeErrors() { |
| 321 |
|
| 322 |
start, end := typeError.Pos, typeError.Pos |
| 323 |
if _, _, endPos, ok := typesinternal.ErrorCodeStartEnd(typeError); ok { |
| 324 |
end = endPos |
| 325 |
} |
| 326 |
typeErrorRange, err := req.pgf.PosRange(start, end) |
| 327 |
if err != nil || !protocol.Intersect(typeErrorRange, req.loc.Range) { |
| 328 |
continue |
| 329 |
} |
| 330 |
|
| 331 |
msg := typeError.Msg |
| 332 |
switch { |
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
case strings.Contains(msg, "missing method"), |
| 337 |
strings.HasPrefix(msg, "cannot convert"), |
| 338 |
strings.Contains(msg, "not implement"): |
| 339 |
si := stubmethods.GetIfaceStubInfo(req.pkg.FileSet(), info, req.pgf, start, end) |
| 340 |
if si != nil { |
| 341 |
qual := typesinternal.FileQualifier(req.pgf.File, si.Concrete.Obj().Pkg()) |
| 342 |
iface := types.TypeString(si.Interface, qual) |
| 343 |
msg := fmt.Sprintf("Declare missing methods of %s", iface) |
| 344 |
req.addApplyFixAction(msg, fixMissingInterfaceMethods, req.loc) |
| 345 |
} |
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
case strings.Contains(msg, "has no field or method"): |
| 351 |
si := stubmethods.GetCallStubInfo(req.pkg.FileSet(), info, req.pgf, start, end) |
| 352 |
if si != nil { |
| 353 |
msg := fmt.Sprintf("Declare missing method %s.%s", si.Receiver.Obj().Name(), si.MethodName) |
| 354 |
req.addApplyFixAction(msg, fixMissingCalledFunction, req.loc) |
| 355 |
} |
| 356 |
|
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
case strings.HasPrefix(msg, "undeclared name: "), |
| 361 |
strings.HasPrefix(msg, "undefined: "): |
| 362 |
cur, _ := req.pgf.Cursor().FindByPos(start, end) |
| 363 |
title := undeclaredFixTitle(cur, msg) |
| 364 |
if title != "" { |
| 365 |
req.addApplyFixAction(title, fixCreateUndeclared, req.loc) |
| 366 |
} |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
return nil |
| 371 |
} |
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
type allImportsFixesResult struct { |
| 376 |
allFixEdits []protocol.TextEdit |
| 377 |
editsPerFix []*importFix |
| 378 |
err error |
| 379 |
} |
| 380 |
|
| 381 |
func (res *allImportsFixesResult) init(ctx context.Context, req *codeActionsRequest) { |
| 382 |
res.allFixEdits, res.editsPerFix, res.err = allImportsFixes(ctx, req.snapshot, req.pgf) |
| 383 |
if res.err != nil { |
| 384 |
event.Error(ctx, "imports fixes", res.err, label.File.Of(req.loc.URI.Path())) |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
func importFixTitle(fix *imports.ImportFix) string { |
| 389 |
var str string |
| 390 |
switch fix.FixType { |
| 391 |
case imports.AddImport: |
| 392 |
str = fmt.Sprintf("Add import: %s %q", fix.StmtInfo.Name, fix.StmtInfo.ImportPath) |
| 393 |
case imports.DeleteImport: |
| 394 |
str = fmt.Sprintf("Delete import: %s %q", fix.StmtInfo.Name, fix.StmtInfo.ImportPath) |
| 395 |
case imports.SetImportName: |
| 396 |
str = fmt.Sprintf("Rename import: %s %q", fix.StmtInfo.Name, fix.StmtInfo.ImportPath) |
| 397 |
} |
| 398 |
return str |
| 399 |
} |
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
func fixedByImportFix(fix *imports.ImportFix, diagnostics []protocol.Diagnostic) []protocol.Diagnostic { |
| 404 |
var results []protocol.Diagnostic |
| 405 |
for _, diagnostic := range diagnostics { |
| 406 |
switch { |
| 407 |
|
| 408 |
case strings.HasPrefix(diagnostic.Message, "undeclared name: "): |
| 409 |
ident := strings.TrimPrefix(diagnostic.Message, "undeclared name: ") |
| 410 |
if ident == fix.IdentName { |
| 411 |
results = append(results, diagnostic) |
| 412 |
} |
| 413 |
|
| 414 |
case strings.HasPrefix(diagnostic.Message, "undefined: "): |
| 415 |
ident := strings.TrimPrefix(diagnostic.Message, "undefined: ") |
| 416 |
if ident == fix.IdentName { |
| 417 |
results = append(results, diagnostic) |
| 418 |
} |
| 419 |
|
| 420 |
case strings.HasPrefix(diagnostic.Message, "could not import: "): |
| 421 |
ident := strings.TrimPrefix(diagnostic.Message, "could not import: ") |
| 422 |
if ident == fix.IdentName { |
| 423 |
results = append(results, diagnostic) |
| 424 |
} |
| 425 |
|
| 426 |
|
| 427 |
case strings.Contains(diagnostic.Message, " imported but not used"): |
| 428 |
idx := strings.Index(diagnostic.Message, " imported but not used") |
| 429 |
importPath := diagnostic.Message[:idx] |
| 430 |
if importPath == fmt.Sprintf("%q", fix.StmtInfo.ImportPath) { |
| 431 |
results = append(results, diagnostic) |
| 432 |
} |
| 433 |
} |
| 434 |
} |
| 435 |
return results |
| 436 |
} |
| 437 |
|
| 438 |
|
| 439 |
|
| 440 |
func goFreeSymbols(ctx context.Context, req *codeActionsRequest) error { |
| 441 |
if !req.loc.Empty() { |
| 442 |
cmd := command.NewFreeSymbolsCommand("Browse free symbols", req.snapshot.View().ID(), req.loc) |
| 443 |
req.addCommandAction(cmd, false) |
| 444 |
} |
| 445 |
return nil |
| 446 |
} |
| 447 |
|
| 448 |
|
| 449 |
|
| 450 |
func goSplitPackage(ctx context.Context, req *codeActionsRequest) error { |
| 451 |
|
| 452 |
|
| 453 |
|
| 454 |
|
| 455 |
|
| 456 |
|
| 457 |
|
| 458 |
meta := req.pkg.Metadata() |
| 459 |
title := fmt.Sprintf("Split package %q", meta.Name) |
| 460 |
cmd := command.NewSplitPackageCommand(title, req.snapshot.View().ID(), string(meta.ID)) |
| 461 |
req.addCommandAction(cmd, false) |
| 462 |
return nil |
| 463 |
} |
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
func goplsDocFeatures(ctx context.Context, req *codeActionsRequest) error { |
| 468 |
cmd := command.NewClientOpenURLCommand( |
| 469 |
"Browse gopls feature documentation", |
| 470 |
"https://go.dev/gopls/features") |
| 471 |
req.addCommandAction(cmd, false) |
| 472 |
return nil |
| 473 |
} |
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
func goDoc(ctx context.Context, req *codeActionsRequest) error { |
| 478 |
_, _, title := DocFragment(req.pkg, req.pgf, req.start, req.end) |
| 479 |
if title != "" { |
| 480 |
cmd := command.NewDocCommand(title, command.DocArgs{Location: req.loc, ShowDocument: true}) |
| 481 |
req.addCommandAction(cmd, false) |
| 482 |
} |
| 483 |
return nil |
| 484 |
} |
| 485 |
|
| 486 |
|
| 487 |
|
| 488 |
func refactorExtractFunction(ctx context.Context, req *codeActionsRequest) error { |
| 489 |
if _, ok, _, _ := canExtractFunction(req.pgf.Cursor(), req.start, req.end); ok { |
| 490 |
req.addApplyFixAction("Extract function", fixExtractFunction, req.loc) |
| 491 |
} |
| 492 |
return nil |
| 493 |
} |
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
func refactorExtractMethod(ctx context.Context, req *codeActionsRequest) error { |
| 498 |
if _, ok, methodOK, _ := canExtractFunction(req.pgf.Cursor(), req.start, req.end); ok && methodOK { |
| 499 |
req.addApplyFixAction("Extract method", fixExtractMethod, req.loc) |
| 500 |
} |
| 501 |
return nil |
| 502 |
} |
| 503 |
|
| 504 |
|
| 505 |
|
| 506 |
func refactorExtractVariable(ctx context.Context, req *codeActionsRequest) error { |
| 507 |
info := req.pkg.TypesInfo() |
| 508 |
if curExprs, err := canExtractVariable(info, req.pgf.Cursor(), req.start, req.end, false); err == nil && len(curExprs) > 0 { |
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
expr0 := curExprs[0].Node().(ast.Expr) |
| 517 |
constant := info.Types[expr0].Value != nil |
| 518 |
if (req.kind == settings.RefactorExtractConstant) == constant { |
| 519 |
title := "Extract variable" |
| 520 |
if constant { |
| 521 |
title = "Extract constant" |
| 522 |
} |
| 523 |
req.addApplyFixAction(title, fixExtractVariable, req.loc) |
| 524 |
} |
| 525 |
} |
| 526 |
return nil |
| 527 |
} |
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
func refactorExtractVariableAll(ctx context.Context, req *codeActionsRequest) error { |
| 532 |
info := req.pkg.TypesInfo() |
| 533 |
|
| 534 |
|
| 535 |
if curExprs, err := canExtractVariable(info, req.pgf.Cursor(), req.start, req.end, true); err == nil && len(curExprs) > 1 { |
| 536 |
expr0 := curExprs[0].Node().(ast.Expr) |
| 537 |
text, err := req.pgf.NodeText(expr0) |
| 538 |
if err != nil { |
| 539 |
return err |
| 540 |
} |
| 541 |
desc := string(text) |
| 542 |
if len(desc) >= 40 || strings.Contains(desc, "\n") { |
| 543 |
desc = goastutil.NodeDescription(expr0) |
| 544 |
} |
| 545 |
constant := info.Types[expr0].Value != nil |
| 546 |
if (req.kind == settings.RefactorExtractConstantAll) == constant { |
| 547 |
var title string |
| 548 |
if constant { |
| 549 |
title = fmt.Sprintf("Extract %d occurrences of const expression: %s", len(curExprs), desc) |
| 550 |
} else { |
| 551 |
title = fmt.Sprintf("Extract %d occurrences of %s", len(curExprs), desc) |
| 552 |
} |
| 553 |
req.addApplyFixAction(title, fixExtractVariableAll, req.loc) |
| 554 |
} |
| 555 |
} |
| 556 |
return nil |
| 557 |
} |
| 558 |
|
| 559 |
|
| 560 |
|
| 561 |
func refactorExtractToNewFile(ctx context.Context, req *codeActionsRequest) error { |
| 562 |
if canExtractToNewFile(req.pgf, req.start, req.end) { |
| 563 |
cmd := command.NewExtractToNewFileCommand("Extract declarations to new file", req.loc) |
| 564 |
req.addCommandAction(cmd, false) |
| 565 |
} |
| 566 |
return nil |
| 567 |
} |
| 568 |
|
| 569 |
|
| 570 |
|
| 571 |
func addTest(ctx context.Context, req *codeActionsRequest) error { |
| 572 |
|
| 573 |
if req.pkg.Metadata().ForTest != "" { |
| 574 |
return nil |
| 575 |
} |
| 576 |
|
| 577 |
path, _ := goastutil.PathEnclosingInterval(req.pgf.File, req.start, req.end) |
| 578 |
if len(path) < 2 { |
| 579 |
return nil |
| 580 |
} |
| 581 |
|
| 582 |
decl, ok := path[len(path)-2].(*ast.FuncDecl) |
| 583 |
if !ok { |
| 584 |
return nil |
| 585 |
} |
| 586 |
|
| 587 |
|
| 588 |
if decl.Name.Name == "_" || decl.Name.Name == "init" { |
| 589 |
return nil |
| 590 |
} |
| 591 |
|
| 592 |
|
| 593 |
if decl.Type.TypeParams != nil { |
| 594 |
return nil |
| 595 |
} |
| 596 |
|
| 597 |
cmd := command.NewAddTestCommand("Add test for "+decl.Name.String(), req.loc) |
| 598 |
req.addCommandAction(cmd, false) |
| 599 |
|
| 600 |
|
| 601 |
return nil |
| 602 |
} |
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
func identityTransform(fields *ast.FieldList) []command.ChangeSignatureParam { |
| 607 |
var id []command.ChangeSignatureParam |
| 608 |
for i := 0; i < fields.NumFields(); i++ { |
| 609 |
id = append(id, command.ChangeSignatureParam{OldIndex: i}) |
| 610 |
} |
| 611 |
return id |
| 612 |
} |
| 613 |
|
| 614 |
|
| 615 |
|
| 616 |
func refactorRewriteRemoveUnusedParam(ctx context.Context, req *codeActionsRequest) error { |
| 617 |
if info := removableParameter(req.pkg, req.pgf, req.loc.Range); info != nil { |
| 618 |
var transform []command.ChangeSignatureParam |
| 619 |
for i := 0; i < info.decl.Type.Params.NumFields(); i++ { |
| 620 |
if i != info.paramIndex { |
| 621 |
transform = append(transform, command.ChangeSignatureParam{OldIndex: i}) |
| 622 |
} |
| 623 |
} |
| 624 |
cmd := command.NewChangeSignatureCommand("Remove unused parameter", command.ChangeSignatureArgs{ |
| 625 |
Location: req.loc, |
| 626 |
NewParams: transform, |
| 627 |
NewResults: identityTransform(info.decl.Type.Results), |
| 628 |
ResolveEdits: req.resolveEdits(), |
| 629 |
}) |
| 630 |
req.addCommandAction(cmd, true) |
| 631 |
} |
| 632 |
return nil |
| 633 |
} |
| 634 |
|
| 635 |
func refactorRewriteMoveParamLeft(ctx context.Context, req *codeActionsRequest) error { |
| 636 |
if info := findParam(req.pgf, req.loc.Range); info != nil && |
| 637 |
info.paramIndex > 0 && |
| 638 |
!is[*ast.Ellipsis](info.field.Type) { |
| 639 |
|
| 640 |
|
| 641 |
|
| 642 |
|
| 643 |
transform := identityTransform(info.decl.Type.Params) |
| 644 |
transform[info.paramIndex] = command.ChangeSignatureParam{OldIndex: info.paramIndex - 1} |
| 645 |
transform[info.paramIndex-1] = command.ChangeSignatureParam{OldIndex: info.paramIndex} |
| 646 |
cmd := command.NewChangeSignatureCommand("Move parameter left", command.ChangeSignatureArgs{ |
| 647 |
Location: req.loc, |
| 648 |
NewParams: transform, |
| 649 |
NewResults: identityTransform(info.decl.Type.Results), |
| 650 |
ResolveEdits: req.resolveEdits(), |
| 651 |
}) |
| 652 |
|
| 653 |
req.addCommandAction(cmd, true) |
| 654 |
} |
| 655 |
return nil |
| 656 |
} |
| 657 |
|
| 658 |
func refactorRewriteMoveParamRight(ctx context.Context, req *codeActionsRequest) error { |
| 659 |
if info := findParam(req.pgf, req.loc.Range); info != nil && info.paramIndex >= 0 { |
| 660 |
params := info.decl.Type.Params |
| 661 |
nparams := params.NumFields() |
| 662 |
if info.paramIndex < nparams-1 { |
| 663 |
if info.paramIndex == nparams-2 && is[*ast.Ellipsis](params.List[len(params.List)-1].Type) { |
| 664 |
|
| 665 |
|
| 666 |
return nil |
| 667 |
} |
| 668 |
|
| 669 |
transform := identityTransform(info.decl.Type.Params) |
| 670 |
transform[info.paramIndex] = command.ChangeSignatureParam{OldIndex: info.paramIndex + 1} |
| 671 |
transform[info.paramIndex+1] = command.ChangeSignatureParam{OldIndex: info.paramIndex} |
| 672 |
cmd := command.NewChangeSignatureCommand("Move parameter right", command.ChangeSignatureArgs{ |
| 673 |
Location: req.loc, |
| 674 |
NewParams: transform, |
| 675 |
NewResults: identityTransform(info.decl.Type.Results), |
| 676 |
ResolveEdits: req.resolveEdits(), |
| 677 |
}) |
| 678 |
req.addCommandAction(cmd, true) |
| 679 |
} |
| 680 |
} |
| 681 |
return nil |
| 682 |
} |
| 683 |
|
| 684 |
|
| 685 |
func refactorRewriteChangeQuote(ctx context.Context, req *codeActionsRequest) error { |
| 686 |
convertStringLiteral(req) |
| 687 |
return nil |
| 688 |
} |
| 689 |
|
| 690 |
|
| 691 |
|
| 692 |
func refactorRewriteInvertIf(ctx context.Context, req *codeActionsRequest) error { |
| 693 |
if _, ok, _ := canInvertIfCondition(req.pgf.Cursor(), req.start, req.end); ok { |
| 694 |
req.addApplyFixAction("Invert 'if' condition", fixInvertIfCondition, req.loc) |
| 695 |
} |
| 696 |
return nil |
| 697 |
} |
| 698 |
|
| 699 |
|
| 700 |
|
| 701 |
func refactorRewriteSplitLines(ctx context.Context, req *codeActionsRequest) error { |
| 702 |
|
| 703 |
if msg, ok, _ := canSplitLines(req.pgf.Cursor(), req.pkg.FileSet(), req.start, req.end); ok { |
| 704 |
req.addApplyFixAction(msg, fixSplitLines, req.loc) |
| 705 |
} |
| 706 |
return nil |
| 707 |
} |
| 708 |
|
| 709 |
func refactorRewriteEliminateDotImport(ctx context.Context, req *codeActionsRequest) error { |
| 710 |
|
| 711 |
var importSpec *ast.ImportSpec |
| 712 |
for _, imp := range req.pgf.File.Imports { |
| 713 |
if posRangeContains(imp.Pos(), imp.End(), req.start, req.end) { |
| 714 |
importSpec = imp |
| 715 |
break |
| 716 |
} |
| 717 |
} |
| 718 |
if importSpec == nil { |
| 719 |
return nil |
| 720 |
} |
| 721 |
if importSpec.Name == nil || importSpec.Name.Name != "." { |
| 722 |
return nil |
| 723 |
} |
| 724 |
|
| 725 |
|
| 726 |
pkgname := req.pkg.TypesInfo().PkgNameOf(importSpec) |
| 727 |
if pkgname == nil { |
| 728 |
return nil |
| 729 |
} |
| 730 |
imported := pkgname.Imported() |
| 731 |
newName := imported.Name() |
| 732 |
|
| 733 |
rng, err := req.pgf.PosRange(importSpec.Name.Pos(), importSpec.Path.Pos()) |
| 734 |
if err != nil { |
| 735 |
return err |
| 736 |
} |
| 737 |
|
| 738 |
edits := []protocol.TextEdit{{ |
| 739 |
Range: rng, |
| 740 |
}} |
| 741 |
|
| 742 |
fileScope, ok := req.pkg.TypesInfo().Scopes[req.pgf.File] |
| 743 |
if !ok { |
| 744 |
return nil |
| 745 |
} |
| 746 |
|
| 747 |
|
| 748 |
|
| 749 |
for curId := range req.pgf.Cursor().Preorder((*ast.Ident)(nil)) { |
| 750 |
ident := curId.Node().(*ast.Ident) |
| 751 |
|
| 752 |
|
| 753 |
|
| 754 |
use := req.pkg.TypesInfo().Uses[ident] |
| 755 |
if use == nil || use.Pkg() == nil { |
| 756 |
continue |
| 757 |
} |
| 758 |
if use.Pkg() != imported { |
| 759 |
continue |
| 760 |
} |
| 761 |
|
| 762 |
|
| 763 |
|
| 764 |
|
| 765 |
|
| 766 |
if curId.ParentEdgeKind() == edge.SelectorExpr_Sel { |
| 767 |
continue |
| 768 |
} |
| 769 |
if !typesinternal.IsPackageLevel(use) { |
| 770 |
continue |
| 771 |
} |
| 772 |
|
| 773 |
|
| 774 |
|
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
|
| 779 |
sc := fileScope.Innermost(ident.Pos()) |
| 780 |
if sc == nil { |
| 781 |
continue |
| 782 |
} |
| 783 |
_, obj := sc.LookupParent(newName, ident.Pos()) |
| 784 |
if obj != nil { |
| 785 |
continue |
| 786 |
} |
| 787 |
|
| 788 |
rng, err := req.pgf.PosRange(ident.Pos(), ident.Pos()) |
| 789 |
if err != nil { |
| 790 |
continue |
| 791 |
} |
| 792 |
edits = append(edits, protocol.TextEdit{ |
| 793 |
Range: rng, |
| 794 |
NewText: newName + ".", |
| 795 |
}) |
| 796 |
} |
| 797 |
|
| 798 |
req.addEditAction("Eliminate dot import", nil, protocol.DocumentChangeEdit( |
| 799 |
req.fh, |
| 800 |
edits, |
| 801 |
)) |
| 802 |
return nil |
| 803 |
} |
| 804 |
|
| 805 |
|
| 806 |
|
| 807 |
func refactorRewriteJoinLines(ctx context.Context, req *codeActionsRequest) error { |
| 808 |
|
| 809 |
if msg, ok, _ := canJoinLines(req.pgf.Cursor(), req.pkg.FileSet(), req.start, req.end); ok { |
| 810 |
req.addApplyFixAction(msg, fixJoinLines, req.loc) |
| 811 |
} |
| 812 |
return nil |
| 813 |
} |
| 814 |
|
| 815 |
|
| 816 |
|
| 817 |
func refactorRewriteFillStruct(ctx context.Context, req *codeActionsRequest) error { |
| 818 |
|
| 819 |
|
| 820 |
|
| 821 |
for _, diag := range fillstruct.Diagnose(req.pgf.Cursor(), req.start, req.end, req.pkg.Types(), req.pkg.TypesInfo()) { |
| 822 |
loc, err := req.pgf.Mapper.PosLocation(req.pgf.Tok, diag.Pos, diag.End) |
| 823 |
if err != nil { |
| 824 |
return err |
| 825 |
} |
| 826 |
for _, fix := range diag.SuggestedFixes { |
| 827 |
req.addApplyFixAction(fix.Message, diag.Category, loc) |
| 828 |
} |
| 829 |
} |
| 830 |
|
| 831 |
return nil |
| 832 |
} |
| 833 |
|
| 834 |
|
| 835 |
func refactorRewriteFillSwitch(ctx context.Context, req *codeActionsRequest) error { |
| 836 |
for _, diag := range fillswitch.Diagnose(req.pgf.File, req.start, req.end, req.pkg.Types(), req.pkg.TypesInfo()) { |
| 837 |
changes, err := suggestedFixToDocumentChange(ctx, req.snapshot, req.pkg.FileSet(), &diag.SuggestedFixes[0]) |
| 838 |
if err != nil { |
| 839 |
return err |
| 840 |
} |
| 841 |
req.addEditAction(diag.Message, nil, changes...) |
| 842 |
} |
| 843 |
|
| 844 |
return nil |
| 845 |
} |
| 846 |
|
| 847 |
|
| 848 |
|
| 849 |
|
| 850 |
func selectionContainsStructField(node *ast.StructType, start, end token.Pos, needsTag bool) bool { |
| 851 |
for _, field := range node.Fields.List { |
| 852 |
if start <= field.End() && end >= field.Pos() { |
| 853 |
if !needsTag || field.Tag != nil { |
| 854 |
return true |
| 855 |
} |
| 856 |
} |
| 857 |
} |
| 858 |
return false |
| 859 |
} |
| 860 |
|
| 861 |
|
| 862 |
|
| 863 |
|
| 864 |
|
| 865 |
func selectionContainsStruct(cursor inspector.Cursor, start, end token.Pos, removeTags bool) bool { |
| 866 |
cur, ok := cursor.FindByPos(start, end) |
| 867 |
if !ok { |
| 868 |
return false |
| 869 |
} |
| 870 |
if _, ok := cur.Node().(*ast.StructType); ok { |
| 871 |
return true |
| 872 |
} |
| 873 |
|
| 874 |
|
| 875 |
for c := range cur.Enclosing((*ast.StructType)(nil)) { |
| 876 |
if selectionContainsStructField(c.Node().(*ast.StructType), start, end, removeTags) { |
| 877 |
return true |
| 878 |
} |
| 879 |
} |
| 880 |
|
| 881 |
|
| 882 |
for c := range cur.Preorder((*ast.StructType)(nil)) { |
| 883 |
node := c.Node().(*ast.StructType) |
| 884 |
|
| 885 |
|
| 886 |
if selectionContainsStructField(node, start, end, removeTags) { |
| 887 |
return true |
| 888 |
} |
| 889 |
} |
| 890 |
return false |
| 891 |
} |
| 892 |
|
| 893 |
|
| 894 |
|
| 895 |
|
| 896 |
|
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
func supportsDialog(options settings.ClientOptions, forms ...[]protocol.FormField) bool { |
| 902 |
if len(forms) == 0 { |
| 903 |
panic("supportsDialog called with empty forms") |
| 904 |
} |
| 905 |
|
| 906 |
|
| 907 |
for _, form := range forms { |
| 908 |
if !slices.ContainsFunc(form, func(field protocol.FormField) bool { |
| 909 |
return !options.SupportedInteractiveInputTypes[formFieldInputType(field.Type)] |
| 910 |
}) { |
| 911 |
return true |
| 912 |
} |
| 913 |
} |
| 914 |
|
| 915 |
return false |
| 916 |
} |
| 917 |
|
| 918 |
|
| 919 |
|
| 920 |
|
| 921 |
|
| 922 |
func formFieldInputType(typ any) settings.InteractiveInputType { |
| 923 |
switch t := typ.(type) { |
| 924 |
case protocol.FormFieldTypeString: |
| 925 |
return settings.InteractiveInputType(t.Kind) |
| 926 |
case protocol.FormFieldTypeFile: |
| 927 |
return settings.InteractiveInputType(t.Kind) |
| 928 |
case protocol.FormFieldTypeBool: |
| 929 |
return settings.InteractiveInputType(t.Kind) |
| 930 |
case protocol.FormFieldTypeNumber: |
| 931 |
return settings.InteractiveInputType(t.Kind) |
| 932 |
case protocol.FormFieldTypeEnum: |
| 933 |
return settings.InteractiveInputType(t.Kind) |
| 934 |
case protocol.FormFieldTypeLazyEnum: |
| 935 |
return settings.InteractiveInputType(t.Kind) |
| 936 |
case protocol.FormFieldTypeList: |
| 937 |
return settings.InteractiveInputType(t.Kind) |
| 938 |
default: |
| 939 |
|
| 940 |
panic(fmt.Sprintf("gopls bug: unhandled FormFieldType %T", typ)) |
| 941 |
} |
| 942 |
} |
| 943 |
|
| 944 |
|
| 945 |
|
| 946 |
func refactorRewriteAddStructTags(ctx context.Context, req *codeActionsRequest) error { |
| 947 |
if selectionContainsStruct(req.pgf.Cursor(), req.start, req.end, false) { |
| 948 |
add := "" |
| 949 |
if !supportsDialog(req.snapshot.Options().ClientOptions, addTagsForm) { |
| 950 |
add = "json" |
| 951 |
} |
| 952 |
cmdAdd := command.NewModifyTagsCommand("Add struct tags", command.ModifyTagsArgs{ |
| 953 |
Modification: "add", |
| 954 |
URI: req.loc.URI, |
| 955 |
Range: req.loc.Range, |
| 956 |
Add: add, |
| 957 |
}) |
| 958 |
req.addCommandAction(cmdAdd, false) |
| 959 |
} |
| 960 |
return nil |
| 961 |
} |
| 962 |
|
| 963 |
|
| 964 |
|
| 965 |
func refactorRewriteRemoveStructTags(ctx context.Context, req *codeActionsRequest) error { |
| 966 |
if selectionContainsStruct(req.pgf.Cursor(), req.start, req.end, true) { |
| 967 |
clear := !supportsDialog(req.snapshot.Options().ClientOptions, removeTagsForm) |
| 968 |
cmdRemove := command.NewModifyTagsCommand("Remove struct tags", command.ModifyTagsArgs{ |
| 969 |
Modification: "remove", |
| 970 |
URI: req.loc.URI, |
| 971 |
Range: req.loc.Range, |
| 972 |
Clear: clear, |
| 973 |
}) |
| 974 |
req.addCommandAction(cmdRemove, false) |
| 975 |
} |
| 976 |
return nil |
| 977 |
} |
| 978 |
|
| 979 |
|
| 980 |
|
| 981 |
|
| 982 |
func refactorRewriteImplementInterface(_ context.Context, req *codeActionsRequest) error { |
| 983 |
|
| 984 |
|
| 985 |
|
| 986 |
if !supportsDialog(req.snapshot.Options().ClientOptions, implementInterfaceFormLazyEnum, implementInterfaceFormString) { |
| 987 |
return nil |
| 988 |
} |
| 989 |
|
| 990 |
start, end, err := req.pgf.RangePos(req.loc.Range) |
| 991 |
if err != nil { |
| 992 |
return err |
| 993 |
} |
| 994 |
|
| 995 |
cur, _, _, _ := astutil.Select(req.pgf.Cursor(), start, end) |
| 996 |
|
| 997 |
spec, curSpec := cursorutil.FirstEnclosing[*ast.TypeSpec](cur) |
| 998 |
if spec == nil { |
| 999 |
return nil |
| 1000 |
} |
| 1001 |
|
| 1002 |
|
| 1003 |
if curSpec.Parent().Parent().Node() != req.pgf.File { |
| 1004 |
return nil |
| 1005 |
} |
| 1006 |
|
| 1007 |
named, ok := types.Unalias(req.pkg.TypesInfo().TypeOf(spec.Name)).(*types.Named) |
| 1008 |
if !ok { |
| 1009 |
return nil |
| 1010 |
} |
| 1011 |
|
| 1012 |
if is[*types.Pointer](named.Underlying()) || types.IsInterface(named) { |
| 1013 |
return nil |
| 1014 |
} |
| 1015 |
|
| 1016 |
|
| 1017 |
cmdAdd := command.NewImplementInterfaceCommand( |
| 1018 |
fmt.Sprintf("Add methods to %s to implement an interface...", spec.Name.Name), |
| 1019 |
command.ImplementInterfaceArgs{ |
| 1020 |
Location: req.loc, |
| 1021 |
|
| 1022 |
}, |
| 1023 |
) |
| 1024 |
req.addCommandAction(cmdAdd, false) |
| 1025 |
return nil |
| 1026 |
} |
| 1027 |
|
| 1028 |
|
| 1029 |
|
| 1030 |
|
| 1031 |
|
| 1032 |
|
| 1033 |
|
| 1034 |
|
| 1035 |
|
| 1036 |
|
| 1037 |
|
| 1038 |
|
| 1039 |
|
| 1040 |
func removableParameter(pkg *cache.Package, pgf *parsego.File, rng protocol.Range) *paramInfo { |
| 1041 |
if perrors, terrors := pkg.ParseErrors(), pkg.TypeErrors(); len(perrors) > 0 || len(terrors) > 0 { |
| 1042 |
return nil |
| 1043 |
} |
| 1044 |
info := findParam(pgf, rng) |
| 1045 |
if info == nil || info.field == nil { |
| 1046 |
return nil |
| 1047 |
} |
| 1048 |
if info.decl.Body == nil { |
| 1049 |
return nil |
| 1050 |
} |
| 1051 |
if len(info.field.Names) == 0 { |
| 1052 |
return info |
| 1053 |
} |
| 1054 |
if info.name == nil { |
| 1055 |
return nil |
| 1056 |
} |
| 1057 |
if info.name.Name == "_" { |
| 1058 |
return info |
| 1059 |
} |
| 1060 |
|
| 1061 |
obj := pkg.TypesInfo().Defs[info.name] |
| 1062 |
if obj == nil { |
| 1063 |
return nil |
| 1064 |
} |
| 1065 |
|
| 1066 |
used := false |
| 1067 |
ast.Inspect(info.decl.Body, func(node ast.Node) bool { |
| 1068 |
if n, ok := node.(*ast.Ident); ok && pkg.TypesInfo().Uses[n] == obj { |
| 1069 |
used = true |
| 1070 |
} |
| 1071 |
return !used |
| 1072 |
}) |
| 1073 |
if used { |
| 1074 |
return nil |
| 1075 |
} |
| 1076 |
return info |
| 1077 |
} |
| 1078 |
|
| 1079 |
|
| 1080 |
|
| 1081 |
func refactorInlineCall(ctx context.Context, req *codeActionsRequest) error { |
| 1082 |
|
| 1083 |
|
| 1084 |
|
| 1085 |
if req.trigger == protocol.CodeActionAutomatic && req.loc.Empty() { |
| 1086 |
return nil |
| 1087 |
} |
| 1088 |
|
| 1089 |
|
| 1090 |
if _, fn, err := enclosingStaticCall(req.pkg, req.pgf, req.start, req.end); err == nil { |
| 1091 |
req.addApplyFixAction("Inline call to "+fn.Name(), fixInlineCall, req.loc) |
| 1092 |
} |
| 1093 |
return nil |
| 1094 |
} |
| 1095 |
|
| 1096 |
|
| 1097 |
|
| 1098 |
func refactorInlineVariable(ctx context.Context, req *codeActionsRequest) error { |
| 1099 |
|
| 1100 |
if curUse, _, ok := canInlineVariable(req.pkg.TypesInfo(), req.pgf.Cursor(), req.start, req.end); ok { |
| 1101 |
title := fmt.Sprintf("Inline variable %q", curUse.Node().(*ast.Ident).Name) |
| 1102 |
req.addApplyFixAction(title, fixInlineVariable, req.loc) |
| 1103 |
} |
| 1104 |
return nil |
| 1105 |
} |
| 1106 |
|
| 1107 |
|
| 1108 |
|
| 1109 |
func goTest(ctx context.Context, req *codeActionsRequest) error { |
| 1110 |
testFuncs, benchFuncs, err := testsAndBenchmarks(req.pkg.TypesInfo(), req.pgf) |
| 1111 |
if err != nil { |
| 1112 |
return err |
| 1113 |
} |
| 1114 |
|
| 1115 |
var tests, benchmarks []string |
| 1116 |
for _, fn := range testFuncs { |
| 1117 |
if protocol.Intersect(fn.rng, req.loc.Range) { |
| 1118 |
tests = append(tests, fn.name) |
| 1119 |
} |
| 1120 |
} |
| 1121 |
for _, fn := range benchFuncs { |
| 1122 |
if protocol.Intersect(fn.rng, req.loc.Range) { |
| 1123 |
benchmarks = append(benchmarks, fn.name) |
| 1124 |
} |
| 1125 |
} |
| 1126 |
|
| 1127 |
if len(tests) == 0 && len(benchmarks) == 0 { |
| 1128 |
return nil |
| 1129 |
} |
| 1130 |
|
| 1131 |
cmd := command.NewRunTestsCommand("Run tests and benchmarks", command.RunTestsArgs{ |
| 1132 |
URI: req.loc.URI, |
| 1133 |
Tests: tests, |
| 1134 |
Benchmarks: benchmarks, |
| 1135 |
}) |
| 1136 |
req.addCommandAction(cmd, false) |
| 1137 |
return nil |
| 1138 |
} |
| 1139 |
|
| 1140 |
|
| 1141 |
|
| 1142 |
func goAssembly(ctx context.Context, req *codeActionsRequest) error { |
| 1143 |
view := req.snapshot.View() |
| 1144 |
|
| 1145 |
|
| 1146 |
|
| 1147 |
|
| 1148 |
|
| 1149 |
|
| 1150 |
|
| 1151 |
|
| 1152 |
|
| 1153 |
|
| 1154 |
|
| 1155 |
|
| 1156 |
|
| 1157 |
|
| 1158 |
|
| 1159 |
|
| 1160 |
|
| 1161 |
|
| 1162 |
|
| 1163 |
|
| 1164 |
|
| 1165 |
|
| 1166 |
|
| 1167 |
var sym strings.Builder |
| 1168 |
if pkg := req.pkg.Types(); pkg.Name() == "main" { |
| 1169 |
sym.WriteString("main") |
| 1170 |
} else { |
| 1171 |
sym.WriteString(pkg.Path()) |
| 1172 |
} |
| 1173 |
sym.WriteString(".") |
| 1174 |
|
| 1175 |
curSel, _ := req.pgf.Cursor().FindByPos(req.start, req.end) |
| 1176 |
for cur := range curSel.Enclosing((*ast.FuncDecl)(nil), (*ast.ValueSpec)(nil)) { |
| 1177 |
var name string |
| 1178 |
switch node := cur.Node().(type) { |
| 1179 |
case *ast.FuncDecl: |
| 1180 |
|
| 1181 |
if fn, ok := req.pkg.TypesInfo().Defs[node.Name].(*types.Func); ok && |
| 1182 |
fn.Name() != "_" { |
| 1183 |
|
| 1184 |
|
| 1185 |
|
| 1186 |
|
| 1187 |
|
| 1188 |
if sig := fn.Signature(); sig.TypeParams() == nil && sig.RecvTypeParams() == nil { |
| 1189 |
if sig.Recv() != nil { |
| 1190 |
if isPtr, named := typesinternal.ReceiverNamed(sig.Recv()); named != nil { |
| 1191 |
if isPtr { |
| 1192 |
fmt.Fprintf(&sym, "(*%s)", named.Obj().Name()) |
| 1193 |
} else { |
| 1194 |
sym.WriteString(named.Obj().Name()) |
| 1195 |
} |
| 1196 |
sym.WriteByte('.') |
| 1197 |
} |
| 1198 |
} |
| 1199 |
sym.WriteString(fn.Name()) |
| 1200 |
|
| 1201 |
name = node.Name.Name |
| 1202 |
} |
| 1203 |
} |
| 1204 |
|
| 1205 |
case *ast.ValueSpec: |
| 1206 |
|
| 1207 |
if len(node.Names) > 0 && len(node.Values) > 0 { |
| 1208 |
v := req.pkg.TypesInfo().Defs[node.Names[0]] |
| 1209 |
if v != nil && typesinternal.IsPackageLevel(v) { |
| 1210 |
sym.WriteString("init") |
| 1211 |
name = "package initializer" |
| 1212 |
} |
| 1213 |
} |
| 1214 |
} |
| 1215 |
|
| 1216 |
if name != "" { |
| 1217 |
cmd := command.NewAssemblyCommand( |
| 1218 |
fmt.Sprintf("Browse %s assembly for %s", view.GOARCH(), name), |
| 1219 |
view.ID(), |
| 1220 |
string(req.pkg.Metadata().ID), |
| 1221 |
sym.String()) |
| 1222 |
req.addCommandAction(cmd, false) |
| 1223 |
break |
| 1224 |
} |
| 1225 |
} |
| 1226 |
return nil |
| 1227 |
} |
| 1228 |
|
| 1229 |
|
| 1230 |
|
| 1231 |
func toggleCompilerOptDetails(ctx context.Context, req *codeActionsRequest) error { |
| 1232 |
|
| 1233 |
|
| 1234 |
if meta, err := req.snapshot.NarrowestMetadataForFile(ctx, req.fh.URI()); err == nil { |
| 1235 |
if len(meta.CompiledGoFiles) == 0 { |
| 1236 |
return fmt.Errorf("package %q does not compile file %q", meta.ID, req.fh.URI()) |
| 1237 |
} |
| 1238 |
dir := meta.CompiledGoFiles[0].Dir() |
| 1239 |
|
| 1240 |
title := fmt.Sprintf("%s compiler optimization details for %q", |
| 1241 |
cond(req.snapshot.WantCompilerOptDetails(dir), "Hide", "Show"), |
| 1242 |
dir.Base()) |
| 1243 |
cmd := command.NewGCDetailsCommand(title, req.fh.URI()) |
| 1244 |
req.addCommandAction(cmd, false) |
| 1245 |
} |
| 1246 |
return nil |
| 1247 |
} |
| 1248 |
|
| 1249 |
|
| 1250 |
func refactorMoveType(_ context.Context, req *codeActionsRequest) error { |
| 1251 |
curSel, _ := req.pgf.Cursor().FindByPos(req.start, req.end) |
| 1252 |
if _, _, _, typeName, ok := selectionContainsType(curSel); ok { |
| 1253 |
cmd := command.NewMoveTypeCommand(fmt.Sprintf("Move type %s", typeName), command.MoveTypeArgs{Location: req.loc}) |
| 1254 |
req.addCommandAction(cmd, false) |
| 1255 |
} |
| 1256 |
return nil |
| 1257 |
} |