Debian Codegraph @

gopls/internal/golang/codeaction.go

raw symbols SCIP
1 // Copyright 2024 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
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 // CodeActions returns all enabled code actions (edits and other
39 // commands) available for the selected range.
40 //
41 // Depending on how the request was triggered, fewer actions may be
42 // offered, e.g. to avoid UI distractions after mere cursor motion.
43 //
44 // See ../protocol/codeactionkind.go for some code action theory.
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 // Scan to see if any enabled producer needs type information.
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 // Compute type information if needed.
70 // Also update pgf, start, end to be consistent with pkg.
71 // They may differ in case of parse cache miss.
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 // Execute each enabled producer function.
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 // An error in one code action producer
111 // should not affect the others.
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 // Return code actions in the order their providers are listed.
121 return actions, nil
122 }
123
124 // A codeActionsRequest is passed to each function
125 // that produces code actions.
126 type codeActionsRequest struct {
127 // internal fields for use only by [CodeActions].
128 actions *[]protocol.CodeAction // pointer to output slice; call addAction to populate
129 lazy map[reflect.Type]any // lazy construction
130
131 // inputs to the producer function:
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 // set only if producer.needPkg
141 }
142
143 // addApplyFixAction adds an ApplyFix command-based CodeAction to the result.
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 // addCommandAction adds a CodeAction to the result based on the provided command.
154 //
155 // If allowResolveEdits (and the client supports codeAction/resolve)
156 // then the command is embedded into the code action data field so
157 // that the client can later ask the server to "resolve" a command
158 // into an edit that they can preview and apply selectively.
159 // IMPORTANT: set allowResolveEdits only for actions that are 'edit aware',
160 // meaning they can detect when they are being executed in the context of a
161 // codeAction/resolve request, and return edits rather than applying them using
162 // workspace/applyEdit. In golang/go#71405, edits were being apply during the
163 // codeAction/resolve request handler.
164 // TODO(rfindley): refactor the command and code lens registration APIs so that
165 // resolve edit support is inferred from the command signature, not dependent
166 // on coordination between codeAction and command logic.
167 //
168 // Otherwise, the command is set as the code action operation.
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 // addEditAction adds an edit-based CodeAction to the result.
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 // addAction adds a code action to the response.
198 func (req *codeActionsRequest) addAction(act protocol.CodeAction) {
199 *req.actions = append(*req.actions, act)
200 }
201
202 // resolveEdits reports whether the client can resolve edits lazily.
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 // lazyInit[*T](ctx, req) returns a pointer to an instance of T,
210 // calling new(T).init(ctx.req) on the first request.
211 //
212 // It is conceptually a (generic) method of req.
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 // -- producers --
228
229 // A codeActionProducer describes a function that produces CodeActions
230 // of a particular kind.
231 // The function is only called if that kind is enabled.
232 type codeActionProducer struct {
233 kind protocol.CodeActionKind
234 fn func(ctx context.Context, req *codeActionsRequest) error
235 needPkg bool // fn needs type information (req.pkg)
236 }
237
238 // Code Actions are returned in the order their producers are listed below.
239 // Depending on the client, this may influence the order they appear in the UI.
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 // {kind: settings.RefactorMoveType, fn: refactorMoveType, needPkg: true},
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}, // offer this one last (#72742)
274
275 // Note: don't forget to update the allow-list in Server.CodeAction
276 // when adding new query operations like GoTest and GoDoc that
277 // are permitted even in generated source files.
278 }
279
280 // sourceOrganizeImports produces "Organize Imports" code actions.
281 func sourceOrganizeImports(ctx context.Context, req *codeActionsRequest) error {
282 res := lazyInit[*allImportsFixesResult](ctx, req)
283
284 // Send all of the import edits as one code action
285 // if the file is being organized.
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 // quickFix produces code actions that fix errors,
294 // for example by adding/deleting/renaming imports,
295 // or declaring the missing methods of a type.
296 func quickFix(ctx context.Context, req *codeActionsRequest) error {
297 // Only compute quick fixes if there are any diagnostics to fix.
298 if len(req.diagnostics) == 0 {
299 return nil
300 }
301
302 // Process any missing imports and pair them with the diagnostics they fix.
303 res := lazyInit[*allImportsFixesResult](ctx, req)
304 if res.err != nil {
305 return nil
306 }
307
308 // Separate this into a set of codeActions per diagnostic, where
309 // each action is the addition, removal, or renaming of one import.
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 // Quick fixes for type errors.
319 info := req.pkg.TypesInfo()
320 for _, typeError := range req.pkg.TypeErrors() {
321 // Does type error overlap with CodeAction range?
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 // "Missing method" error? (stubmethods)
334 // Offer a "Declare missing methods of INTERFACE" code action.
335 // See [stubMissingInterfaceMethodsFixer] for command implementation.
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 // "type X has no field or method Y" compiler error.
348 // Offer a "Declare missing method T.f" code action.
349 // See [stubMissingCalledFunctionFixer] for command implementation.
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 // "undeclared name: X" or "undefined: X" compiler error.
358 // Offer a "Create variable/function X" code action.
359 // See [createUndeclared] for command implementation.
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 // allImportsFixesResult is the result of a lazy call to allImportsFixes.
374 // It implements the codeActionsRequest lazyInit interface.
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 // fixedByImportFix filters the provided slice of diagnostics to those that
402 // would be fixed by the provided imports fix.
403 func fixedByImportFix(fix *imports.ImportFix, diagnostics []protocol.Diagnostic) []protocol.Diagnostic {
404 var results []protocol.Diagnostic
405 for _, diagnostic := range diagnostics {
406 switch {
407 // "undeclared name: X" may be an unresolved import.
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 // "undefined: X" may be an unresolved import at Go 1.20+.
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 // "could not import: X" may be an invalid import.
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 // "X imported but not used" is an unused import.
426 // "X imported but not used as Y" is an unused import.
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 // goFreeSymbols produces "Browse free symbols" code actions.
439 // See [server.commandHandler.FreeSymbols] for command implementation.
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 // goSplitPackage produces "Split package p" code actions.
449 // See [server.commandHandler.SplitPackage] for command implementation.
450 func goSplitPackage(ctx context.Context, req *codeActionsRequest) error {
451 // TODO(adonovan): ideally we would key by the package path,
452 // or the ID of the widest package for the current file,
453 // so that we don't see different results when toggling
454 // between p.go and p_test.go.
455 //
456 // TODO(adonovan): opt: req should always provide metadata so
457 // that we don't have to request type checking (needPkg=true).
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 // goplsDocFeatures produces "Browse gopls feature documentation" code actions.
466 // See [server.commandHandler.ClientOpenURL] for command implementation.
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 // goDoc produces "Browse documentation for X" code actions.
476 // See [server.commandHandler.Doc] for command implementation.
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 // refactorExtractFunction produces "Extract function" code actions.
487 // See [extractFunction] for command implementation.
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 // refactorExtractMethod produces "Extract method" code actions.
496 // See [extractMethod] for command implementation.
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 // refactorExtractVariable produces "Extract variable|constant" code actions.
505 // See [extractVariable] for command implementation.
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 // Offer one of refactor.extract.{constant,variable}
510 // based on the constness of the expression; this is a
511 // limitation of the codeActionProducers mechanism.
512 // Beware that future evolutions of the refactorings
513 // may make them diverge to become non-complementary,
514 // for example because "if const x = ...; y {" is illegal.
515 // Same as [refactorExtractVariableAll].
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 // refactorExtractVariableAll produces "Extract N occurrences of EXPR" code action.
530 // See [extractVariable] for implementation.
531 func refactorExtractVariableAll(ctx context.Context, req *codeActionsRequest) error {
532 info := req.pkg.TypesInfo()
533 // Don't suggest if only one expr is found,
534 // otherwise it will duplicate with [refactorExtractVariable]
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 // refactorExtractToNewFile produces "Extract declarations to new file" code actions.
560 // See [server.commandHandler.ExtractToNewFile] for command implementation.
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 // addTest produces "Add test for FUNC" code actions.
570 // See [server.commandHandler.AddTest] for command implementation.
571 func addTest(ctx context.Context, req *codeActionsRequest) error {
572 // Reject test package.
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 // Don't offer to create tests of "init" or "_".
588 if decl.Name.Name == "_" || decl.Name.Name == "init" {
589 return nil
590 }
591
592 // TODO(hxjiang): support functions with type parameter.
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 // TODO(hxjiang): add code action for generate test for package/file.
601 return nil
602 }
603
604 // identityTransform returns a change signature transformation that leaves the
605 // given fieldlist unmodified.
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 // refactorRewriteRemoveUnusedParam produces "Remove unused parameter" code actions.
615 // See [server.commandHandler.ChangeSignature] for command implementation.
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 // ^^ we can't currently handle moving a variadic param.
641 // TODO(rfindley): implement.
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 { // not the last param
663 if info.paramIndex == nparams-2 && is[*ast.Ellipsis](params.List[len(params.List)-1].Type) {
664 // We can't currently handle moving a variadic param.
665 // TODO(rfindley): implement.
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 // refactorRewriteChangeQuote produces "Convert to {raw,interpreted} string literal" code actions.
685 func refactorRewriteChangeQuote(ctx context.Context, req *codeActionsRequest) error {
686 convertStringLiteral(req)
687 return nil
688 }
689
690 // refactorRewriteInvertIf produces "Invert 'if' condition" code actions.
691 // See [invertIfCondition] for command implementation.
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 // refactorRewriteSplitLines produces "Split ITEMS into separate lines" code actions.
700 // See [splitLines] for command implementation.
701 func refactorRewriteSplitLines(ctx context.Context, req *codeActionsRequest) error {
702 // TODO(adonovan): opt: don't set needPkg just for FileSet.
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 // Figure out if the request is placed over a dot import.
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 // dotImported package path and its imported name after removing the dot.
726 pkgname := req.pkg.TypesInfo().PkgNameOf(importSpec)
727 if pkgname == nil {
728 return nil // e.g. import . "C"
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 // Delete the '.' part of the import.
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 // Go through each use of the dot imported package, checking its scope for
748 // shadowing and calculating an edit to qualify the identifier.
749 for curId := range req.pgf.Cursor().Preorder((*ast.Ident)(nil)) {
750 ident := curId.Node().(*ast.Ident)
751
752 // Only keep identifiers that use a symbol from the
753 // dot imported package.
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 // Only qualify unqualified identifiers (due to dot imports)
763 // that reference package-level symbols.
764 // All other references to a symbol imported from another package
765 // are nested within a select expression (pkg.Foo, v.Method, v.Field).
766 if curId.ParentEdgeKind() == edge.SelectorExpr_Sel {
767 continue // qualified identifier (pkg.X) or selector (T.X or e.X)
768 }
769 if !typesinternal.IsPackageLevel(use) {
770 continue // unqualified field reference T{X: ...}
771 }
772
773 // Make sure that the package name will not be shadowed by something else in scope.
774 // If it is then we cannot offer this particular code action.
775 //
776 // TODO: If the object found in scope is the package imported without a
777 // dot, or some builtin not used in the file, the code action could be
778 // allowed to go through.
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()) // sic, zero-width range before ident
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 // refactorRewriteJoinLines produces "Join ITEMS into one line" code actions.
806 // See [joinLines] for command implementation.
807 func refactorRewriteJoinLines(ctx context.Context, req *codeActionsRequest) error {
808 // TODO(adonovan): opt: don't set needPkg just for FileSet.
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 // refactorRewriteFillStruct produces "Fill STRUCT" code actions.
816 // See [fillstruct.SuggestedFix] for command implementation.
817 func refactorRewriteFillStruct(ctx context.Context, req *codeActionsRequest) error {
818 // [fillstruct.Diagnose] is a lazy analyzer: all it gives us is the
819 // (start, end, message) of each SuggestedFix; the actual edit is
820 // computed only later by ApplyFix, which calls [fillstruct.SuggestedFix].
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 // refactorRewriteFillSwitch produces "Add cases for TYPE/ENUM" code actions.
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 // selectionContainsStructField returns true if the given struct contains a
848 // field between start and end pos. If needsTag is true, it only returns true if
849 // the struct field found contains a struct tag.
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 // selectionContainsStruct returns true if there exists a struct containing
862 // fields within start and end positions. If removeTags is true, it means the
863 // current command is for remove tags rather than add tags, so we only return
864 // true if the struct field found contains a struct tag to remove.
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 // Handles case where selection is within struct.
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 // Handles case where selection contains struct but may contain other nodes, including other structs.
882 for c := range cur.Preorder((*ast.StructType)(nil)) {
883 node := c.Node().(*ast.StructType)
884 // Check that at least one field is located within the selection. If we are removing tags, that field
885 // must also have a struct tag, otherwise we do not provide the code action.
886 if selectionContainsStructField(node, start, end, removeTags) {
887 return true
888 }
889 }
890 return false
891 }
892
893 // supportsDialog reports whether the client supports interactive UI dialogs.
894 //
895 // If more than one form is provided, they are treated as a prioritized list of
896 // alternatives, typically ordered with decreasing demands for client protocol
897 // support. The function returns true if the client explicitly supports all
898 // field input types required by at least one of these alternative forms.
899 //
900 // If no forms are provided, the function panics.
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 // Ensure that at least one form does not depend on unsupported types.
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 // form is free of unsupported types
912 }
913 }
914
915 return false
916 }
917
918 // formFieldInputType extracts the interactive input type from a
919 // protocol.FormFieldType*.
920 //
921 // It panics if the type is unknown, as forms are generated internally by gopls.
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 // A form field type was added to gopls without updating this function.
940 panic(fmt.Sprintf("gopls bug: unhandled FormFieldType %T", typ))
941 }
942 }
943
944 // refactorRewriteAddStructTags produces "Add struct tags" code actions.
945 // See [server.commandHandler.ModifyTags] for command implementation.
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" // default choice
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 // refactorRewriteRemoveStructTags produces "Remove struct tags" code actions.
964 // See [server.commandHandler.ModifyTags] for command implementation.
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) // clear the entry if there is no dialog
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 // refactorRewriteImplementInterface produces "Add methods to implement an
980 // interface." code actions.
981 // See [server.commandHandler.ImplementInterface] for command implementation.
982 func refactorRewriteImplementInterface(_ context.Context, req *codeActionsRequest) error {
983 // The "Implement Interface" interaction requires either lazy enum support
984 // (for rich workspace symbol search) or at least string support (as a fallback
985 // text prompt). We disable the action if the client supports neither.
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) // can't fail
996
997 spec, curSpec := cursorutil.FirstEnclosing[*ast.TypeSpec](cur)
998 if spec == nil {
999 return nil
1000 }
1001
1002 // Only offer code action for package level type spec.
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 // Have: concrete defined type
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 // Interface will be provided by the user through dialog.
1022 },
1023 )
1024 req.addCommandAction(cmdAdd, false)
1025 return nil
1026 }
1027
1028 // removableParameter returns paramInfo about a removable parameter indicated
1029 // by the given [start, end) range, or nil if no such removal is available.
1030 //
1031 // Removing a parameter is possible if
1032 // - there are no parse or type errors, and
1033 // - [start, end) is contained within an unused field or parameter name
1034 // - ... of a non-method function declaration.
1035 //
1036 // (Note that the unusedparam analyzer also computes this property, but
1037 // much more precisely, allowing it to report its findings as diagnostics.)
1038 //
1039 // TODO(adonovan): inline into refactorRewriteRemoveUnusedParam.
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 // can't remove parameters from packages with errors
1043 }
1044 info := findParam(pgf, rng)
1045 if info == nil || info.field == nil {
1046 return nil // range does not span a parameter
1047 }
1048 if info.decl.Body == nil {
1049 return nil // external function
1050 }
1051 if len(info.field.Names) == 0 {
1052 return info // no names => field is unused
1053 }
1054 if info.name == nil {
1055 return nil // no name is indicated
1056 }
1057 if info.name.Name == "_" {
1058 return info // trivially unused
1059 }
1060
1061 obj := pkg.TypesInfo().Defs[info.name]
1062 if obj == nil {
1063 return nil // something went wrong
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 // keep going until we find a use
1072 })
1073 if used {
1074 return nil
1075 }
1076 return info
1077 }
1078
1079 // refactorInlineCall produces "Inline call to FUNC" code actions.
1080 // See [inlineCall] for command implementation.
1081 func refactorInlineCall(ctx context.Context, req *codeActionsRequest) error {
1082 // To avoid distraction (e.g. VS Code lightbulb), offer "inline"
1083 // only after a selection or explicit menu operation.
1084 // TODO(adonovan): remove this (and req.trigger); see comment at TestVSCodeIssue65167.
1085 if req.trigger == protocol.CodeActionAutomatic && req.loc.Empty() {
1086 return nil
1087 }
1088
1089 // If range is within call expression, offer to inline the call.
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 // refactorInlineVariable produces the "Inline variable 'v'" code action.
1097 // See [inlineVariableOne] for command implementation.
1098 func refactorInlineVariable(ctx context.Context, req *codeActionsRequest) error {
1099 // TODO(adonovan): offer "inline all" variant that eliminates the var (see #70085).
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 // goTest produces "Run tests and benchmarks" code actions.
1108 // See [server.commandHandler.runTests] for command implementation.
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 // goAssembly produces "Browse ARCH assembly for FUNC" code actions.
1141 // See [server.commandHandler.Assembly] for command implementation.
1142 func goAssembly(ctx context.Context, req *codeActionsRequest) error {
1143 view := req.snapshot.View()
1144
1145 // Find the enclosing toplevel function or method,
1146 // and compute its symbol name (e.g. "pkgpath.(T).method").
1147 // The report will show this method and all its nested
1148 // functions (FuncLit, defers, etc).
1149 //
1150 // TODO(adonovan): this is no good for generics, since they
1151 // will always be uninstantiated when they enclose the cursor.
1152 // Instead, we need to query the func symbol under the cursor,
1153 // rather than the enclosing function. It may be an explicitly
1154 // or implicitly instantiated generic, and it may be defined
1155 // in another package, though we would still need to compile
1156 // the current package to see its assembly. The challenge,
1157 // however, is that computing the linker name for a generic
1158 // symbol is quite tricky. Talk with the compiler team for
1159 // ideas.
1160 //
1161 // TODO(adonovan): think about a smoother UX for jumping
1162 // directly to (say) a lambda of interest.
1163 // Perhaps we could scroll to STEXT for the innermost
1164 // enclosing nested function?
1165
1166 // Compute the linker symbol of the enclosing function or var initializer.
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 // in command title
1178 switch node := cur.Node().(type) {
1179 case *ast.FuncDecl:
1180 // package-level func or method
1181 if fn, ok := req.pkg.TypesInfo().Defs[node.Name].(*types.Func); ok &&
1182 fn.Name() != "_" { // blank functions are not compiled
1183
1184 // Source-level init functions are compiled (along with
1185 // package-level var initializers) in into a single pkg.init
1186 // function, so this falls out of the logic below.
1187
1188 if sig := fn.Signature(); sig.TypeParams() == nil && sig.RecvTypeParams() == nil { // generic => no assembly
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 // success
1202 }
1203 }
1204
1205 case *ast.ValueSpec:
1206 // package-level var initializer?
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" // success
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 // toggleCompilerOptDetails produces "{Show,Hide} compiler optimization details" code action.
1230 // See [server.commandHandler.GCDetails] for command implementation.
1231 func toggleCompilerOptDetails(ctx context.Context, req *codeActionsRequest) error {
1232 // TODO(adonovan): errors from code action providers should probably be
1233 // logged, even if they aren't visible to the client; see https://go.dev/issue/71275.
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 // (this function is unused)
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 }