Debian Codegraph @

gopls/internal/golang/fix.go

raw symbols SCIP
1 // Copyright 2020 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 "fmt"
10 "go/token"
11
12 "golang.org/x/tools/go/analysis"
13 "golang.org/x/tools/gopls/internal/analysis/fillstruct"
14 "golang.org/x/tools/gopls/internal/analysis/unusedparams"
15 "golang.org/x/tools/gopls/internal/cache"
16 "golang.org/x/tools/gopls/internal/cache/parsego"
17 "golang.org/x/tools/gopls/internal/file"
18 "golang.org/x/tools/gopls/internal/protocol"
19 "golang.org/x/tools/gopls/internal/util/bug"
20 )
21
22 // A fixer is a function that suggests a fix for a diagnostic produced
23 // by the analysis framework. This is done outside of the analyzer Run
24 // function so that the construction of expensive fixes can be
25 // deferred until they are requested by the user.
26 //
27 // The actual diagnostic is not provided; only its position, as the
28 // triple (pgf, start, end); the resulting SuggestedFix implicitly
29 // relates to that file.
30 //
31 // The supplied token positions (start, end) must belong to
32 // pkg.FileSet(), and the returned positions
33 // (SuggestedFix.TextEdits[*].{Pos,End}) must belong to the returned
34 // FileSet, which is not necessarily the same.
35 // (See [insertDeclsAfter] for explanation.)
36 //
37 // A fixer may return (nil, nil) if no fix is available.
38 type fixer func(ctx context.Context, s *cache.Snapshot, pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error)
39
40 // A singleFileFixer is a [fixer] that inspects only a single file.
41 type singleFileFixer func(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error)
42
43 // singleFile adapts a [singleFileFixer] to a [fixer]
44 // by discarding the snapshot and the context it needs.
45 func singleFile(fixer1 singleFileFixer) fixer {
46 return func(_ context.Context, _ *cache.Snapshot, pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) {
47 return fixer1(pkg, pgf, start, end)
48 }
49 }
50
51 // Names of ApplyFix.Fix created directly by the CodeAction handler.
52 const (
53 fixExtractVariable = "extract_variable" // (or constant)
54 fixExtractVariableAll = "extract_variable_all"
55 fixExtractFunction = "extract_function"
56 fixExtractMethod = "extract_method"
57 fixInlineCall = "inline_call" // keep consistent with go/analysis/passes/inline Diagnostic.Category
58 fixInlineVariable = "inline_variable"
59 fixInvertIfCondition = "invert_if_condition"
60 fixSplitLines = "split_lines"
61 fixJoinLines = "join_lines"
62 fixCreateUndeclared = "create_undeclared"
63 fixMissingInterfaceMethods = "stub_missing_interface_method"
64 fixMissingCalledFunction = "stub_missing_called_function"
65 )
66
67 // ApplyFix applies the specified kind of suggested fix to the given
68 // file and range, returning the resulting changes.
69 //
70 // A fix kind is either the Category of an analysis.Diagnostic that
71 // had a SuggestedFix with no edits; or the name of a fix agreed upon
72 // by [CodeActions] and this function.
73 // Fix kinds identify fixes in the command protocol.
74 //
75 // TODO(adonovan): come up with a better mechanism for registering the
76 // connection between analyzers, code actions, and fixers. A flaw of
77 // the current approach is that the same Category could in theory
78 // apply to a Diagnostic with several lazy fixes, making them
79 // impossible to distinguish. It would more precise if there was a
80 // SuggestedFix.Category field, or some other way to squirrel metadata
81 // in the fix.
82 func ApplyFix(ctx context.Context, fix string, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) ([]protocol.DocumentChange, error) {
83 // This can't be expressed as an entry in the fixer table below
84 // because it operates in the protocol (not go/{token,ast}) domain.
85 // (Sigh; perhaps it was a mistake to factor out the
86 // NarrowestPackageForFile/RangePos/suggestedFixToEdits
87 // steps.)
88 if fix == unusedparams.FixCategory {
89 return removeParam(ctx, snapshot, fh, rng)
90 }
91
92 fixers := map[string]fixer{
93 // Fixes for analyzer-provided diagnostics.
94 // These match the Diagnostic.Category.
95 fillstruct.FixCategory: singleFile(fillstruct.SuggestedFix),
96
97 // Ad-hoc fixers: these are used when the command is
98 // constructed directly by logic in server/code_action.
99 fixExtractFunction: singleFile(extractFunction),
100 fixExtractMethod: singleFile(extractMethod),
101 fixExtractVariable: singleFile(extractVariableOne),
102 fixExtractVariableAll: singleFile(extractVariableAll),
103 fixInlineCall: inlineCall,
104 fixInlineVariable: singleFile(inlineVariableOne),
105 fixInvertIfCondition: singleFile(invertIfCondition),
106 fixSplitLines: singleFile(splitLines),
107 fixJoinLines: singleFile(joinLines),
108 fixCreateUndeclared: singleFile(createUndeclared),
109 fixMissingInterfaceMethods: stubMissingInterfaceMethodsFixer,
110 fixMissingCalledFunction: stubMissingCalledFunctionFixer,
111 }
112 fixer, ok := fixers[fix]
113 if !ok {
114 return nil, fmt.Errorf("no suggested fix function for %s", fix)
115 }
116 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
117 if err != nil {
118 return nil, err
119 }
120 start, end, err := pgf.RangePos(rng)
121 if err != nil {
122 return nil, err
123 }
124 fixFset, suggestion, err := fixer(ctx, snapshot, pkg, pgf, start, end)
125 if err != nil {
126 return nil, err
127 }
128 if suggestion == nil {
129 return nil, nil
130 }
131
132 // Refine #68818 so we learn which values of 'fix'
133 // break the assertion in suggestedFixToDocumentChange.
134 for _, edit := range suggestion.TextEdits {
135 if fixFset.File(edit.Pos) == nil {
136 switch fix {
137 case fillstruct.FixCategory:
138 bug.Report("no token.File for TextEdit.Pos (#68818)")
139 case fixExtractFunction:
140 bug.Report("no token.File for TextEdit.Pos (#68818)")
141 case fixExtractMethod:
142 bug.Report("no token.File for TextEdit.Pos (#68818)")
143 case fixExtractVariable:
144 bug.Report("no token.File for TextEdit.Pos (#68818)")
145 case fixExtractVariableAll:
146 bug.Report("no token.File for TextEdit.Pos (#68818)")
147 case fixInlineCall:
148 bug.Report("no token.File for TextEdit.Pos (#68818)")
149 case fixInlineVariable:
150 bug.Report("no token.File for TextEdit.Pos (#68818)")
151 case fixInvertIfCondition:
152 bug.Report("no token.File for TextEdit.Pos (#68818)")
153 case fixSplitLines:
154 bug.Report("no token.File for TextEdit.Pos (#68818)")
155 case fixJoinLines:
156 bug.Report("no token.File for TextEdit.Pos (#68818)")
157 case fixCreateUndeclared:
158 bug.Report("no token.File for TextEdit.Pos (#68818)")
159 case fixMissingInterfaceMethods:
160 bug.Report("no token.File for TextEdit.Pos (#68818)")
161 case fixMissingCalledFunction:
162 bug.Report("no token.File for TextEdit.Pos (#68818)")
163 }
164 break
165 }
166 }
167
168 return suggestedFixToDocumentChange(ctx, snapshot, fixFset, suggestion)
169 }
170
171 // suggestedFixToDocumentChange converts the suggestion's edits from analysis form into protocol form.
172 func suggestedFixToDocumentChange(ctx context.Context, snapshot *cache.Snapshot, fset *token.FileSet, suggestion *analysis.SuggestedFix) ([]protocol.DocumentChange, error) {
173 type fileInfo struct {
174 fh file.Handle
175 mapper *protocol.Mapper
176 edits []protocol.TextEdit
177 }
178 files := make(map[protocol.DocumentURI]*fileInfo)
179 for _, edit := range suggestion.TextEdits {
180 tokFile := fset.File(edit.Pos)
181 if tokFile == nil {
182 return nil, bug.Errorf("no file for edit position (#68818)")
183 }
184 end := edit.End
185 if !end.IsValid() {
186 end = edit.Pos
187 }
188 uri := protocol.URIFromPath(tokFile.Name())
189 info, ok := files[uri]
190 if !ok {
191 // First edit: create a mapper.
192 fh, err := snapshot.ReadFile(ctx, uri)
193 if err != nil {
194 return nil, err
195 }
196 content, err := fh.Content()
197 if err != nil {
198 return nil, err
199 }
200 mapper := protocol.NewMapper(uri, content)
201 info = &fileInfo{fh, mapper, nil}
202 files[uri] = info
203 }
204 rng, err := info.mapper.PosRange(tokFile, edit.Pos, end)
205 if err != nil {
206 return nil, err
207 }
208 info.edits = append(info.edits, protocol.TextEdit{
209 Range: rng,
210 NewText: string(edit.NewText),
211 })
212 }
213 var changes []protocol.DocumentChange
214 for _, info := range files {
215 change := protocol.DocumentChangeEdit(info.fh, info.edits)
216 changes = append(changes, change)
217 }
218 return changes, nil
219 }