Debian Codegraph @

gopls/internal/server/code_action.go

raw symbols SCIP
1 // Copyright 2018 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 server
6
7 import (
8 "context"
9 "fmt"
10 "slices"
11 "strings"
12
13 "golang.org/x/tools/gopls/internal/cache"
14 "golang.org/x/tools/gopls/internal/file"
15 "golang.org/x/tools/gopls/internal/golang"
16 "golang.org/x/tools/gopls/internal/mod"
17 "golang.org/x/tools/gopls/internal/protocol"
18 "golang.org/x/tools/gopls/internal/protocol/command"
19 "golang.org/x/tools/gopls/internal/settings"
20 "golang.org/x/tools/internal/event"
21 )
22
23 func (s *server) CodeAction(ctx context.Context, params *protocol.CodeActionParams) ([]protocol.CodeAction, error) {
24 ctx, done := event.Start(ctx, "server.CodeAction")
25 defer done()
26
27 fh, snapshot, release, err := s.session.FileOf(ctx, params.TextDocument.URI)
28 if err != nil {
29 return nil, err
30 }
31 defer release()
32 uri := fh.URI()
33 kind := snapshot.FileKind(fh)
34
35 // Determine the supported code action kinds for this file.
36 //
37 // We interpret CodeActionKinds hierarchically, so refactor.rewrite
38 // subsumes refactor.rewrite.change_quote, for example,
39 // and "" (protocol.Empty) subsumes all kinds.
40 // See ../protocol/codeactionkind.go for some code action theory.
41 //
42 // The Context.Only field specifies which code actions
43 // the client wants. According to LSP 3.18 textDocument_codeAction,
44 // an Only=[] should be interpreted as Only=["quickfix"]:
45 //
46 // "In version 1.0 of the protocol, there weren’t any
47 // source or refactoring code actions. Code actions
48 // were solely used to (quick) fix code, not to
49 // write/rewrite code. So if a client asks for code
50 // actions without any kind, the standard quick fix
51 // code actions should be returned."
52 //
53 // However, this would deny clients (e.g. Vim+coc.nvim,
54 // Emacs+eglot, and possibly others) the easiest and most
55 // natural way of querying the server for the entire set of
56 // available code actions. But reporting all available code
57 // actions would be a nuisance for VS Code, since mere cursor
58 // motion into a region with a code action (~anywhere) would
59 // trigger a lightbulb usually associated with quickfixes.
60 //
61 // As a compromise, we use the trigger kind as a heuristic: if
62 // the query was triggered by cursor motion (Automatic), we
63 // respond with only quick fixes; if the query was invoked
64 // explicitly (Invoked), we respond with all available
65 // actions.
66 codeActionKinds := make(map[protocol.CodeActionKind]bool)
67 if len(params.Context.Only) > 0 {
68 for _, kind := range params.Context.Only { // kind may be "" (=> all)
69 codeActionKinds[kind] = true
70 }
71 } else {
72 // No explicit kind specified.
73 // Heuristic: decide based on trigger.
74 if triggerKind(params) == protocol.CodeActionAutomatic {
75 // e.g. cursor motion: show only quick fixes
76 codeActionKinds[protocol.QuickFix] = true
77 } else {
78 // e.g. a menu selection (or unknown trigger kind,
79 // as in our tests): show all available code actions.
80 codeActionKinds[protocol.Empty] = true
81 }
82 }
83
84 // enabled reports whether the specified kind of code action is required.
85 enabled := func(kind protocol.CodeActionKind) bool {
86 // Given "refactor.rewrite.foo", check for it,
87 // then "refactor.rewrite", "refactor", then "".
88 // A false map entry prunes the search for ancestors.
89 //
90 // If codeActionKinds contains protocol.Empty (""),
91 // all kinds are enabled.
92 for {
93 if v, ok := codeActionKinds[kind]; ok {
94 return v
95 }
96 if kind == "" {
97 return false
98 }
99
100 // The "source.test" code action shouldn't be
101 // returned to the client unless requested by
102 // an exact match in Only.
103 //
104 // This mechanism exists to avoid a distracting
105 // lightbulb (code action) on each Test function.
106 // These actions are unwanted in VS Code because it
107 // has Test Explorer, and in other editors because
108 // the UX of executeCommand is unsatisfactory for tests:
109 // it doesn't show the complete streaming output.
110 // See https://github.com/joaotavora/eglot/discussions/1402
111 // for a better solution. See also
112 // https://github.com/golang/go/issues/67400.
113 //
114 // TODO(adonovan): consider instead switching on
115 // codeActionTriggerKind. Perhaps other noisy Source
116 // Actions should be guarded in the same way.
117 if kind == settings.GoTest {
118 return false // don't search ancestors
119 }
120
121 // Try the parent.
122 if dot := strings.LastIndexByte(string(kind), '.'); dot >= 0 {
123 kind = kind[:dot] // "refactor.foo" -> "refactor"
124 } else {
125 kind = "" // "refactor" -> ""
126 }
127 }
128 }
129
130 switch kind {
131 case file.Mod:
132 var actions []protocol.CodeAction
133
134 fixes, err := s.codeActionsMatchingDiagnostics(ctx, fh.URI(), snapshot, params.Context.Diagnostics, enabled)
135 if err != nil {
136 return nil, err
137 }
138
139 // Group vulnerability fixes by their range, and select only the most
140 // appropriate upgrades.
141 //
142 // TODO(rfindley): can this instead be accomplished on the diagnosis side,
143 // so that code action handling remains uniform?
144 vulnFixes := make(map[protocol.Range][]protocol.CodeAction)
145 searchFixes:
146 for _, fix := range fixes {
147 for _, diag := range fix.Diagnostics {
148 if diag.Source == string(cache.Govulncheck) || diag.Source == string(cache.Vulncheck) {
149 vulnFixes[diag.Range] = append(vulnFixes[diag.Range], fix)
150 continue searchFixes
151 }
152 }
153 actions = append(actions, fix)
154 }
155
156 for _, fixes := range vulnFixes {
157 fixes = mod.SelectUpgradeCodeActions(fixes)
158 actions = append(actions, fixes...)
159 }
160
161 return actions, nil
162
163 case file.Go:
164 // diagnostic-bundled code actions
165 //
166 // The diagnostics already have a UI presence (e.g. squiggly underline);
167 // the associated action may additionally show (in VS Code) as a lightbulb.
168 // Note s.codeActionsMatchingDiagnostics returns only fixes
169 // detected during the analysis phase. golang.CodeActions computes
170 // extra changes that can address some diagnostics.
171 actions, err := s.codeActionsMatchingDiagnostics(ctx, uri, snapshot, params.Context.Diagnostics, enabled)
172 if err != nil {
173 return nil, err
174 }
175
176 // computed code actions (may include quickfixes from diagnostics)
177 moreActions, err := golang.CodeActions(ctx, snapshot, fh, params.Range, params.Context.Diagnostics, enabled, triggerKind(params))
178 if err != nil {
179 return nil, err
180 }
181 actions = append(actions, moreActions...)
182
183 // Don't suggest most fixes for generated files, since they are generally
184 // not useful and some editors may apply them automatically on save.
185 // (Unfortunately there's no reliable way to distinguish fixes from
186 // queries, so we must list all kinds of queries here.)
187 //
188 // We make an exception for OrganizeImports, because
189 // (a) it is needed when making temporary experimental
190 // changes (e.g. adding logging) in generated files, and
191 // (b) it doesn't report diagnostics on well-formed code, and
192 // unedited generated files must be well formed.
193 if golang.IsGenerated(ctx, snapshot, uri) {
194 actions = slices.DeleteFunc(actions, func(a protocol.CodeAction) bool {
195 switch a.Kind {
196 case settings.GoTest,
197 settings.GoDoc,
198 settings.GoFreeSymbols,
199 settings.GoSplitPackage,
200 settings.GoAssembly,
201 settings.GoplsDocFeatures,
202 settings.GoToggleCompilerOptDetails:
203 return false // read-only query
204 case settings.OrganizeImports:
205 return false // fix allowed in generated files (see #73959)
206 }
207 return true // potential write operation
208 })
209 }
210
211 return actions, nil
212
213 default:
214 // Unsupported file kind for a code action.
215 return nil, nil
216 }
217 }
218
219 func triggerKind(params *protocol.CodeActionParams) protocol.CodeActionTriggerKind {
220 if kind := params.Context.TriggerKind; kind != nil { // (some clients omit it)
221 return *kind
222 }
223 return protocol.CodeActionUnknownTrigger
224 }
225
226 // ResolveCodeAction resolves missing Edit information (that is, computes the
227 // details of the necessary patch) in the given code action using the provided
228 // Data field of the CodeAction, which should contain the raw json of a protocol.Command.
229 //
230 // This should be called by the client before applying code actions, when the
231 // client has code action resolve support.
232 //
233 // This feature allows capable clients to preview and selectively apply the diff
234 // instead of applying the whole thing unconditionally through workspace/applyEdit.
235 func (s *server) ResolveCodeAction(ctx context.Context, ca *protocol.CodeAction) (*protocol.CodeAction, error) {
236 ctx, done := event.Start(ctx, "server.ResolveCodeAction")
237 defer done()
238
239 // Only resolve the code action if there is Data provided.
240 var cmd protocol.Command
241 if ca.Data != nil {
242 if err := protocol.UnmarshalJSON(*ca.Data, &cmd); err != nil {
243 return nil, err
244 }
245 }
246 ca.Data = nil
247 if cmd.Command != "" {
248 // Try to resolve codeaction edits by running the command.
249 //
250 // Unfortunately, we can't simply report failure to execute the command, as
251 // some clients (namely, VS Code with the Live Share extension) eagerly
252 // resolve *all* code actions, and returning an error leads to spammy
253 // popups. Instead, we simply set the command on the code action, and let
254 // it fail if/when invoked (golang/go#75442).
255 //
256 // This is arguably a client-side bug, but we work around it as it causes
257 // significant problems for our users.
258 // https://github.com/microsoft/live-share/issues/5293
259 params := &protocol.ExecuteCommandParams{
260 Command: cmd.Command,
261 Arguments: cmd.Arguments,
262 }
263 handler := &commandHandler{
264 s: s,
265 params: params,
266 }
267 edit, err := command.Dispatch(ctx, params, handler)
268 if err != nil {
269 // Resolving edits failed, so just resolve the command.
270 ca.Command = &cmd
271 return ca, nil
272 }
273 var ok bool
274 if ca.Edit, ok = edit.(*protocol.WorkspaceEdit); !ok {
275 return nil, fmt.Errorf("unable to resolve code action %q", ca.Title)
276 }
277 }
278 return ca, nil
279 }
280
281 // codeActionsMatchingDiagnostics creates code actions for the
282 // provided diagnostics, by unmarshalling actions bundled in the
283 // protocol.Diagnostic.Data field or, if there were none, by creating
284 // actions from edits associated with a matching Diagnostic from the
285 // set of stored diagnostics for this file.
286 func (s *server) codeActionsMatchingDiagnostics(ctx context.Context, uri protocol.DocumentURI, snapshot *cache.Snapshot, pds []protocol.Diagnostic, enabled func(protocol.CodeActionKind) bool) ([]protocol.CodeAction, error) {
287 var actions []protocol.CodeAction
288 var unbundled []protocol.Diagnostic // diagnostics without bundled code actions in their Data field
289 for _, pd := range pds {
290 bundled, err := cache.BundledLazyFixes(pd)
291 if err != nil {
292 return nil, err
293 }
294 if len(bundled) > 0 {
295 for _, fix := range bundled {
296 if enabled(fix.Kind) {
297 actions = append(actions, fix)
298 }
299 }
300 } else {
301 // No bundled actions: keep searching for a match.
302 unbundled = append(unbundled, pd)
303 }
304 }
305
306 for _, pd := range unbundled {
307 for _, sd := range s.findMatchingDiagnostics(uri, pd) {
308 diagActions, err := codeActionsForDiagnostic(ctx, snapshot, sd, &pd, enabled)
309 if err != nil {
310 return nil, err
311 }
312 actions = append(actions, diagActions...)
313 }
314 }
315 return actions, nil
316 }
317
318 func codeActionsForDiagnostic(ctx context.Context, snapshot *cache.Snapshot, sd *cache.Diagnostic, pd *protocol.Diagnostic, enabled func(protocol.CodeActionKind) bool) ([]protocol.CodeAction, error) {
319 var actions []protocol.CodeAction
320 for _, fix := range sd.SuggestedFixes {
321 if !enabled(fix.ActionKind) {
322 continue
323 }
324 var changes []protocol.DocumentChange
325 for uri, edits := range fix.Edits {
326 fh, err := snapshot.ReadFile(ctx, uri)
327 if err != nil {
328 return nil, err
329 }
330 change := protocol.DocumentChangeEdit(fh, edits)
331 changes = append(changes, change)
332 }
333 actions = append(actions, protocol.CodeAction{
334 Title: fix.Title,
335 Kind: fix.ActionKind,
336 Edit: protocol.NewWorkspaceEdit(changes...),
337 Command: fix.Command,
338 Diagnostics: []protocol.Diagnostic{*pd},
339 })
340 }
341 return actions, nil
342 }
343
344 func (s *server) findMatchingDiagnostics(uri protocol.DocumentURI, pd protocol.Diagnostic) []*cache.Diagnostic {
345 s.diagnosticsMu.Lock()
346 defer s.diagnosticsMu.Unlock()
347
348 var sds []*cache.Diagnostic
349 if fileDiags := s.diagnostics[uri]; fileDiags != nil {
350 for _, viewDiags := range fileDiags.byView {
351 for _, sd := range viewDiags.diagnostics {
352 // extra space may have been trimmed when
353 // converting to protocol.Diagnostic
354 sameDiagnostic := pd.Message == strings.TrimSpace(sd.Message) &&
355 protocol.CompareRange(pd.Range, sd.Range) == 0 &&
356 pd.Source == string(sd.Source)
357
358 if sameDiagnostic {
359 sds = append(sds, sd)
360 }
361 }
362 }
363 }
364 return sds
365 }
366
367 func (s *server) getSupportedCodeActions() []protocol.CodeActionKind {
368 allCodeActionKinds := make(map[protocol.CodeActionKind]struct{})
369 for _, kinds := range s.Options().SupportedCodeActions {
370 for kind := range kinds {
371 allCodeActionKinds[kind] = struct{}{}
372 }
373 }
374 var result []protocol.CodeActionKind
375 for kind := range allCodeActionKinds {
376 result = append(result, kind)
377 }
378 slices.Sort(result)
379 return result
380 }
381
382 type unit = struct{}