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.
13 "golang.org/x/tools/go/analysis"
14 "golang.org/x/tools/internal/event"
15 "golang.org/x/tools/internal/imports"
16 "golang.org/x/tools/internal/lsp/debug/tag"
17 "golang.org/x/tools/internal/lsp/mod"
18 "golang.org/x/tools/internal/lsp/protocol"
19 "golang.org/x/tools/internal/lsp/source"
20 "golang.org/x/tools/internal/span"
23 func (s *Server) codeAction(ctx context.Context, params *protocol.CodeActionParams) ([]protocol.CodeAction, error) {
24 snapshot, fh, ok, release, err := s.beginFileRequest(ctx, params.TextDocument.URI, source.UnknownKind)
31 // Determine the supported actions for this file kind.
32 supportedCodeActions, ok := snapshot.View().Options().SupportedCodeActions[fh.Kind()]
34 return nil, fmt.Errorf("no supported code actions for %v file kind", fh.Kind())
37 // The Only field of the context specifies which code actions the client wants.
38 // If Only is empty, assume that the client wants all of the non-explicit code actions.
39 var wanted map[protocol.CodeActionKind]bool
41 // Explicit Code Actions are opt-in and shouldn't be returned to the client unless
42 // requested using Only.
43 // TODO: Add other CodeLenses such as GoGenerate, RegenerateCgo, etc..
44 explicit := map[protocol.CodeActionKind]bool{
45 protocol.GoTest: true,
48 if len(params.Context.Only) == 0 {
49 wanted = supportedCodeActions
51 wanted = make(map[protocol.CodeActionKind]bool)
52 for _, only := range params.Context.Only {
53 wanted[only] = supportedCodeActions[only] || explicit[only]
57 return nil, fmt.Errorf("no supported code action to execute for %s, wanted %v", uri, params.Context.Only)
60 var codeActions []protocol.CodeAction
63 if diagnostics := params.Context.Diagnostics; len(diagnostics) > 0 {
64 modQuickFixes, err := moduleQuickFixes(ctx, snapshot, fh, diagnostics)
65 if source.IsNonFatalGoModError(err) {
71 codeActions = append(codeActions, modQuickFixes...)
74 // Don't suggest fixes for generated files, since they are generally
75 // not useful and some editors may apply them automatically on save.
76 if source.IsGenerated(ctx, snapshot, uri) {
79 diagnostics := params.Context.Diagnostics
81 // First, process any missing imports and pair them with the
82 // diagnostics they fix.
83 if wantQuickFixes := wanted[protocol.QuickFix] && len(diagnostics) > 0; wantQuickFixes || wanted[protocol.SourceOrganizeImports] {
84 importEdits, importEditsPerFix, err := source.AllImportsFixes(ctx, snapshot, fh)
86 event.Error(ctx, "imports fixes", err, tag.File.Of(fh.URI().Filename()))
88 // Separate this into a set of codeActions per diagnostic, where
89 // each action is the addition, removal, or renaming of one import.
91 for _, importFix := range importEditsPerFix {
92 fixes := importDiagnostics(importFix.Fix, diagnostics)
96 codeActions = append(codeActions, protocol.CodeAction{
97 Title: importFixTitle(importFix.Fix),
98 Kind: protocol.QuickFix,
99 Edit: protocol.WorkspaceEdit{
100 DocumentChanges: documentChanges(fh, importFix.Edits),
106 // Send all of the import edits as one code action if the file is
108 if wanted[protocol.SourceOrganizeImports] && len(importEdits) > 0 {
109 codeActions = append(codeActions, protocol.CodeAction{
110 Title: "Organize Imports",
111 Kind: protocol.SourceOrganizeImports,
112 Edit: protocol.WorkspaceEdit{
113 DocumentChanges: documentChanges(fh, importEdits),
118 if ctx.Err() != nil {
119 return nil, ctx.Err()
121 pkg, err := snapshot.PackageForFile(ctx, fh.URI(), source.TypecheckFull, source.WidestPackage)
125 if (wanted[protocol.QuickFix] || wanted[protocol.SourceFixAll]) && len(diagnostics) > 0 {
126 analysisQuickFixes, highConfidenceEdits, err := analysisFixes(ctx, snapshot, pkg, diagnostics)
130 if wanted[protocol.QuickFix] {
131 // Add the quick fixes reported by go/analysis.
132 codeActions = append(codeActions, analysisQuickFixes...)
134 // If there are any diagnostics relating to the go.mod file,
135 // add their corresponding quick fixes.
136 modQuickFixes, err := moduleQuickFixes(ctx, snapshot, fh, diagnostics)
137 if source.IsNonFatalGoModError(err) {
138 // Not a fatal error.
139 event.Error(ctx, "module suggested fixes failed", err, tag.Directory.Of(snapshot.View().Folder()))
141 codeActions = append(codeActions, modQuickFixes...)
143 if wanted[protocol.SourceFixAll] && len(highConfidenceEdits) > 0 {
144 codeActions = append(codeActions, protocol.CodeAction{
145 Title: "Simplifications",
146 Kind: protocol.SourceFixAll,
147 Edit: protocol.WorkspaceEdit{
148 DocumentChanges: highConfidenceEdits,
153 if ctx.Err() != nil {
154 return nil, ctx.Err()
156 // Add any suggestions that do not necessarily fix any diagnostics.
157 if wanted[protocol.RefactorRewrite] {
158 fixes, err := convenienceFixes(ctx, snapshot, pkg, uri, params.Range)
162 codeActions = append(codeActions, fixes...)
164 if wanted[protocol.RefactorExtract] {
165 fixes, err := extractionFixes(ctx, snapshot, pkg, uri, params.Range)
169 codeActions = append(codeActions, fixes...)
172 if wanted[protocol.GoTest] {
173 fixes, err := goTest(ctx, snapshot, uri, params.Range)
177 codeActions = append(codeActions, fixes...)
181 // Unsupported file kind for a code action.
184 return codeActions, nil
187 func (s *Server) getSupportedCodeActions() []protocol.CodeActionKind {
188 allCodeActionKinds := make(map[protocol.CodeActionKind]struct{})
189 for _, kinds := range s.session.Options().SupportedCodeActions {
190 for kind := range kinds {
191 allCodeActionKinds[kind] = struct{}{}
194 var result []protocol.CodeActionKind
195 for kind := range allCodeActionKinds {
196 result = append(result, kind)
198 sort.Slice(result, func(i, j int) bool {
199 return result[i] < result[j]
204 func importFixTitle(fix *imports.ImportFix) string {
207 case imports.AddImport:
208 str = fmt.Sprintf("Add import: %s %q", fix.StmtInfo.Name, fix.StmtInfo.ImportPath)
209 case imports.DeleteImport:
210 str = fmt.Sprintf("Delete import: %s %q", fix.StmtInfo.Name, fix.StmtInfo.ImportPath)
211 case imports.SetImportName:
212 str = fmt.Sprintf("Rename import: %s %q", fix.StmtInfo.Name, fix.StmtInfo.ImportPath)
217 func importDiagnostics(fix *imports.ImportFix, diagnostics []protocol.Diagnostic) (results []protocol.Diagnostic) {
218 for _, diagnostic := range diagnostics {
220 // "undeclared name: X" may be an unresolved import.
221 case strings.HasPrefix(diagnostic.Message, "undeclared name: "):
222 ident := strings.TrimPrefix(diagnostic.Message, "undeclared name: ")
223 if ident == fix.IdentName {
224 results = append(results, diagnostic)
226 // "could not import: X" may be an invalid import.
227 case strings.HasPrefix(diagnostic.Message, "could not import: "):
228 ident := strings.TrimPrefix(diagnostic.Message, "could not import: ")
229 if ident == fix.IdentName {
230 results = append(results, diagnostic)
232 // "X imported but not used" is an unused import.
233 // "X imported but not used as Y" is an unused import.
234 case strings.Contains(diagnostic.Message, " imported but not used"):
235 idx := strings.Index(diagnostic.Message, " imported but not used")
236 importPath := diagnostic.Message[:idx]
237 if importPath == fmt.Sprintf("%q", fix.StmtInfo.ImportPath) {
238 results = append(results, diagnostic)
245 func analysisFixes(ctx context.Context, snapshot source.Snapshot, pkg source.Package, diagnostics []protocol.Diagnostic) ([]protocol.CodeAction, []protocol.TextDocumentEdit, error) {
246 if len(diagnostics) == 0 {
250 codeActions []protocol.CodeAction
251 sourceFixAllEdits []protocol.TextDocumentEdit
253 for _, diag := range diagnostics {
254 srcErr, analyzer, ok := findSourceError(ctx, snapshot, pkg.ID(), diag)
258 // If the suggested fix for the diagnostic is expected to be separate,
259 // see if there are any supported commands available.
260 if analyzer.Command != nil {
261 action, err := diagnosticToCommandCodeAction(ctx, snapshot, srcErr, &diag, protocol.QuickFix)
265 codeActions = append(codeActions, *action)
268 for _, fix := range srcErr.SuggestedFixes {
269 action := protocol.CodeAction{
271 Kind: protocol.QuickFix,
272 Diagnostics: []protocol.Diagnostic{diag},
273 Edit: protocol.WorkspaceEdit{},
275 for uri, edits := range fix.Edits {
276 fh, err := snapshot.GetVersionedFile(ctx, uri)
280 docChanges := documentChanges(fh, edits)
281 if analyzer.HighConfidence {
282 sourceFixAllEdits = append(sourceFixAllEdits, docChanges...)
284 action.Edit.DocumentChanges = append(action.Edit.DocumentChanges, docChanges...)
286 codeActions = append(codeActions, action)
289 return codeActions, sourceFixAllEdits, nil
292 func findSourceError(ctx context.Context, snapshot source.Snapshot, pkgID string, diag protocol.Diagnostic) (*source.Error, source.Analyzer, bool) {
293 analyzer := diagnosticToAnalyzer(snapshot, diag.Source, diag.Message)
295 return nil, source.Analyzer{}, false
297 analysisErrors, err := snapshot.Analyze(ctx, pkgID, analyzer.Analyzer)
299 return nil, source.Analyzer{}, false
301 for _, err := range analysisErrors {
302 if err.Message != diag.Message {
305 if protocol.CompareRange(err.Range, diag.Range) != 0 {
308 if err.Category != analyzer.Analyzer.Name {
311 // The error matches.
312 return err, *analyzer, true
314 return nil, source.Analyzer{}, false
317 // diagnosticToAnalyzer return the analyzer associated with a given diagnostic.
318 // It assumes that the diagnostic's source will be the name of the analyzer.
319 // If this changes, this approach will need to be reworked.
320 func diagnosticToAnalyzer(snapshot source.Snapshot, src, msg string) (analyzer *source.Analyzer) {
321 // Make sure that the analyzer we found is enabled.
323 if analyzer != nil && !analyzer.IsEnabled(snapshot.View()) {
327 if a, ok := snapshot.View().Options().DefaultAnalyzers[src]; ok {
330 if a, ok := snapshot.View().Options().StaticcheckAnalyzers[src]; ok {
333 if a, ok := snapshot.View().Options().ConvenienceAnalyzers[src]; ok {
336 // Hack: We publish diagnostics with the source "compiler" for type errors,
337 // but these analyzers have different names. Try both possibilities.
338 if a, ok := snapshot.View().Options().TypeErrorAnalyzers[src]; ok {
341 if src != "compiler" {
344 for _, a := range snapshot.View().Options().TypeErrorAnalyzers {
345 if a.FixesError(msg) {
352 func convenienceFixes(ctx context.Context, snapshot source.Snapshot, pkg source.Package, uri span.URI, rng protocol.Range) ([]protocol.CodeAction, error) {
353 var analyzers []*analysis.Analyzer
354 for _, a := range snapshot.View().Options().ConvenienceAnalyzers {
355 if !a.IsEnabled(snapshot.View()) {
358 if a.Command == nil {
359 event.Error(ctx, "convenienceFixes", fmt.Errorf("no suggested fixes for convenience analyzer %s", a.Analyzer.Name))
362 analyzers = append(analyzers, a.Analyzer)
364 diagnostics, err := snapshot.Analyze(ctx, pkg.ID(), analyzers...)
368 var codeActions []protocol.CodeAction
369 for _, d := range diagnostics {
370 // For now, only show diagnostics for matching lines. Maybe we should
371 // alter this behavior in the future, depending on the user experience.
376 if !protocol.Intersect(d.Range, rng) {
379 action, err := diagnosticToCommandCodeAction(ctx, snapshot, d, nil, protocol.RefactorRewrite)
383 codeActions = append(codeActions, *action)
385 return codeActions, nil
388 func diagnosticToCommandCodeAction(ctx context.Context, snapshot source.Snapshot, e *source.Error, d *protocol.Diagnostic, kind protocol.CodeActionKind) (*protocol.CodeAction, error) {
389 // The fix depends on the category of the analyzer. The diagnostic may be
390 // nil, so use the error's category.
391 analyzer := diagnosticToAnalyzer(snapshot, e.Category, e.Message)
393 return nil, fmt.Errorf("no convenience analyzer for category %s", e.Category)
395 if analyzer.Command == nil {
396 return nil, fmt.Errorf("no command for convenience analyzer %s", analyzer.Analyzer.Name)
398 jsonArgs, err := source.MarshalArgs(e.URI, e.Range)
402 var diagnostics []protocol.Diagnostic
404 diagnostics = append(diagnostics, *d)
406 return &protocol.CodeAction{
409 Diagnostics: diagnostics,
410 Command: &protocol.Command{
411 Command: analyzer.Command.ID(),
418 func extractionFixes(ctx context.Context, snapshot source.Snapshot, pkg source.Package, uri span.URI, rng protocol.Range) ([]protocol.CodeAction, error) {
419 if rng.Start == rng.End {
422 fh, err := snapshot.GetFile(ctx, uri)
426 jsonArgs, err := source.MarshalArgs(uri, rng)
430 var actions []protocol.CodeAction
431 for _, command := range []*source.Command{
432 source.CommandExtractFunction,
433 source.CommandExtractVariable,
435 if !command.Applies(ctx, snapshot, fh, rng) {
438 actions = append(actions, protocol.CodeAction{
439 Title: command.Title,
440 Kind: protocol.RefactorExtract,
441 Command: &protocol.Command{
442 Command: command.ID(),
450 func documentChanges(fh source.VersionedFileHandle, edits []protocol.TextEdit) []protocol.TextDocumentEdit {
451 return []protocol.TextDocumentEdit{
453 TextDocument: protocol.VersionedTextDocumentIdentifier{
454 Version: fh.Version(),
455 TextDocumentIdentifier: protocol.TextDocumentIdentifier{
456 URI: protocol.URIFromSpanURI(fh.URI()),
464 func moduleQuickFixes(ctx context.Context, snapshot source.Snapshot, fh source.VersionedFileHandle, diagnostics []protocol.Diagnostic) ([]protocol.CodeAction, error) {
465 var modFH source.VersionedFileHandle
470 modURI := snapshot.GoModForFile(ctx, fh.URI())
475 modFH, err = snapshot.GetVersionedFile(ctx, modURI)
480 errors, err := mod.ErrorsForMod(ctx, snapshot, modFH)
484 var quickFixes []protocol.CodeAction
485 for _, e := range errors {
486 var diag *protocol.Diagnostic
487 for _, d := range diagnostics {
488 if sameDiagnostic(d, e) {
496 for _, fix := range e.SuggestedFixes {
497 action := protocol.CodeAction{
499 Kind: protocol.QuickFix,
500 Diagnostics: []protocol.Diagnostic{*diag},
501 Edit: protocol.WorkspaceEdit{},
502 Command: fix.Command,
504 for uri, edits := range fix.Edits {
505 if uri != modFH.URI() {
508 action.Edit.DocumentChanges = append(action.Edit.DocumentChanges, protocol.TextDocumentEdit{
509 TextDocument: protocol.VersionedTextDocumentIdentifier{
510 Version: modFH.Version(),
511 TextDocumentIdentifier: protocol.TextDocumentIdentifier{
512 URI: protocol.URIFromSpanURI(modFH.URI()),
518 if fix.Command != nil {
519 action.Command = &protocol.Command{
520 Command: fix.Command.Command,
521 Title: fix.Command.Title,
522 Arguments: fix.Command.Arguments,
525 quickFixes = append(quickFixes, action)
528 return quickFixes, nil
531 func sameDiagnostic(d protocol.Diagnostic, e source.Error) bool {
532 return d.Message == e.Message && protocol.CompareRange(d.Range, e.Range) == 0 && d.Source == e.Category
535 func goTest(ctx context.Context, snapshot source.Snapshot, uri span.URI, rng protocol.Range) ([]protocol.CodeAction, error) {
536 fh, err := snapshot.GetFile(ctx, uri)
540 fns, err := source.TestsAndBenchmarks(ctx, snapshot, fh)
545 var tests, benchmarks []string
546 for _, fn := range fns.Tests {
547 if !protocol.Intersect(fn.Rng, rng) {
550 tests = append(tests, fn.Name)
552 for _, fn := range fns.Benchmarks {
553 if !protocol.Intersect(fn.Rng, rng) {
556 benchmarks = append(benchmarks, fn.Name)
559 if len(tests) == 0 && len(benchmarks) == 0 {
563 jsonArgs, err := source.MarshalArgs(uri, tests, benchmarks)
567 return []protocol.CodeAction{{
568 Title: source.CommandTest.Name,
569 Kind: protocol.GoTest,
570 Command: &protocol.Command{
571 Title: source.CommandTest.Title,
572 Command: source.CommandTest.ID(),