Debian Codegraph @

gopls/internal/golang/resolve.go

raw symbols SCIP
1 // Copyright 2026 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/token"
12 "slices"
13 "strings"
14 "unicode"
15
16 "golang.org/x/mod/module"
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/gopls/internal/util/morestrings"
21 )
22
23 // Ths file contains the code to mediate user dialogs in the client
24
25 // The logical flow is as follows:
26 // 1. Client sends 'textDocument/codeAction'
27 // gopls respond with one or more CodeActions, including one with kind either
28 // 'refactor.rewrite.addTags' or 'refactor.rewrite.removeTags'
29 // 2. Client sends 'codeAction/resolve' with the selected CodeActions
30 // gopls returns the same CodeAction
31 // 3. Client sends 'workspace/executeCommand' to get the dialog form
32 // gopls responds with the form to display to the user
33 // 4. Client sends 'command/resolve' with the filled out form
34 // gopls responds, with 'workspace/applyEdit' saying what to do
35 // 5. Client return ApplyWorkspaceEditResult with applied = true
36 // 6. Client sends a textDocument/didChange notification, with the edits applied (optional)
37
38 // In vscode-go, because it is a standard LSP client, cannot do step 4 as
39 // described. Instead it calls "workspace/executeCommand" with command
40 // 'gopls.lsp' and parameter.Method "command/resolve".
41 //
42 // ExecuteCommand() calls command.Dispatch() which calls LSP()
43 // which calls protocol.ServerDispatchCall("command/resolve")
44 // which calls ResolveCommand. command.Dispatch() switches on param.Command and LSP() passes param.Method
45 // to ServerDispatchCall
46
47 // The neovim flow is simpler, as 'command/resolve' can be invoked directly.
48
49 var addTagsForm = []protocol.FormField{
50 {
51 ID: "tags",
52 Description: `comma-separated list of tags to add; e.g.. "json,xml"`,
53 Type: protocol.FormFieldTypeString{Kind: "string"},
54 Required: true,
55 Default: "json",
56 },
57 {
58 ID: "transform",
59 Description: `transform rule for added tags, e.g., "camelcase' or 'snakecase"`,
60 Type: protocol.FormFieldTypeEnum{
61 Kind: "enum",
62 Entries: []protocol.FormEnumEntry{
63 {
64 Value: "camelcase",
65 Description: "camelCase",
66 },
67 {
68 Value: "lispcase",
69 Description: "lisp-case",
70 },
71 {
72 Value: "pascalcase",
73 Description: "PascalCase",
74 },
75 {
76 Value: "titlecase",
77 Description: "Title Case",
78 },
79 {
80 Value: "snakecase",
81 Description: "snake_case",
82 },
83 },
84 },
85 Required: true,
86 Default: "camelcase",
87 },
88 }
89
90 var removeTagsForm = []protocol.FormField{
91 {
92 ID: "tags",
93 Description: `comma-separated list of tags to remove; e.g., "json,xml"`,
94 Type: protocol.FormFieldTypeString{Kind: "string"},
95 Required: true,
96 Default: "json", // TODO(?): put the existing tags here?
97 },
98 }
99
100 // ResolveCommand implements the interactive resolution step for workspace commands.
101 // It inspects the command name within the provided [protocol.ExecuteCommandParams]
102 // and delegates to the appropriate command-specific resolver (e.g., modify_tags,
103 // implement_interface).
104 //
105 // For full details on the interactive protocol, the multi-step handshake, and the
106 // conditions under which the parameter is modified or returned as-is, see the
107 // official documentation on the protocol interface and [protocol.Server.ResolveCommand].
108 func ResolveCommand(ctx context.Context, params *protocol.ExecuteCommandParams, options settings.ClientOptions) (*protocol.ExecuteCommandParams, error) {
109 switch params.Command {
110 case "gopls.modify_tags":
111 if err := resolveModifyTags(options, params); err != nil {
112 return nil, err
113 }
114 case "gopls.implement_interface":
115 if err := resolveImplementInterface(options, params); err != nil {
116 return nil, err
117 }
118 }
119 return params, nil
120 }
121
122 func resolveModifyTags(options settings.ClientOptions, param *protocol.ExecuteCommandParams) error {
123 var a0 command.ModifyTagsArgs
124 if err := command.UnmarshalArgs(param.Arguments, &a0); err != nil {
125 return err
126 }
127 switch a0.Modification {
128 case "add":
129 if !supportsDialog(options, addTagsForm) {
130 return nil
131 }
132
133 // First call, return the form.
134 if len(param.FormAnswers) == 0 {
135 param.FormFields = addTagsForm
136 return nil
137 }
138
139 v0, err := FormAnswer[string](&param.InteractiveParams, "tags")
140 if err != nil {
141 return err
142 }
143 if _, err = SanitizeTags(v0); err != nil {
144 form := slices.Clone(addTagsForm)
145 form[0].Error = err.Error()
146 param.FormFields = form
147 return nil
148 }
149
150 _, err = FormAnswer[string](&param.InteractiveParams, "transform")
151 if err != nil {
152 return err
153 }
154 // PJW: what happens when the user enters a bad value? (i think the client handles it)
155
156 param.FormFields = nil
157 return nil
158 case "remove":
159 if !supportsDialog(options, removeTagsForm) {
160 return nil
161 }
162
163 // First call, return the form
164 if len(param.FormAnswers) == 0 {
165 // TODO? show the user the current list of tags?
166 param.FormFields = removeTagsForm
167 return nil
168 }
169
170 v, err := FormAnswer[string](&param.InteractiveParams, "tags")
171 if err != nil {
172 return err
173 }
174 if _, err := SanitizeTags(v); err != nil {
175 form := slices.Clone(addTagsForm)
176 form[0].Error = err.Error()
177 param.FormFields = form
178 return nil
179 }
180
181 param.FormFields = nil
182 return nil
183 default:
184 return fmt.Errorf("unsupported modify tags operation: %s", a0.Modification)
185 }
186 }
187
188 func mustMarshal(x any) json.RawMessage {
189 data, err := json.Marshal(x)
190 if err != nil {
191 panic(err)
192 }
193 return json.RawMessage(data)
194 }
195
196 var implementInterfaceFormLazyEnum = []protocol.FormField{
197 {
198 ID: "interface",
199 Description: `fully qualified interface identifier path/to/pkg.interface; e.g., "net.Error"`,
200 Type: protocol.FormFieldTypeLazyEnum{
201 Kind: "lazyEnum",
202 Source: "workspaceSymbol",
203 Config: mustMarshal(InteractiveWorkspaceSymbolEnumConfig{
204 Kinds: []protocol.SymbolKind{protocol.Interface},
205 }),
206 },
207 Required: true,
208 Default: "error",
209 },
210 }
211
212 var implementInterfaceFormString = []protocol.FormField{
213 {
214 ID: "interface",
215 Description: `fully qualified interface identifier path/to/pkg.interface; e.g., "net.Error"`,
216 Type: protocol.FormFieldTypeString{
217 Kind: "string",
218 },
219 Required: true,
220 Default: "error",
221 },
222 }
223
224 func resolveImplementInterface(options settings.ClientOptions, param *protocol.ExecuteCommandParams) error {
225 var a0 command.ImplementInterfaceArgs
226 if err := command.UnmarshalArgs(param.Arguments, &a0); err != nil {
227 return err
228 }
229
230 var form []protocol.FormField
231 if ok := options.SupportedInteractiveInputTypes[settings.InteractiveInputTypeLazyEnum]; ok {
232 form = implementInterfaceFormLazyEnum
233 } else if ok := options.SupportedInteractiveInputTypes[settings.InteractiveInputTypeString]; ok {
234 form = implementInterfaceFormString
235 } else {
236 // This should not happen, as the gopls should not offer such code
237 // action if the language client does not support any kind above.
238 return fmt.Errorf("internal error: unsupported interactive input types: %v", options.SupportedInteractiveInputTypes)
239 }
240
241 // First call, return the empty form.
242 if len(param.FormAnswers) == 0 {
243 param.FormFields = form
244 return nil
245 }
246
247 v, err := FormAnswer[string](&param.InteractiveParams, "interface")
248 if err != nil {
249 return err
250 }
251
252 // Gopls only validates the syntax of the string; it does not verify that
253 // the package or interface actually exists in the workspace.
254 validInterface := func(ifaceStr string) error {
255 if ifaceStr == "error" {
256 return nil
257 }
258 pkgPath, ifaceName, ok := morestrings.CutLast(ifaceStr, ".")
259 if !ok {
260 return fmt.Errorf(`invalid interface type name: want string of form "example.com/pkg.Type", got %q`, ifaceStr)
261 }
262
263 if err := module.CheckImportPath(pkgPath); err != nil {
264 return fmt.Errorf("invalid package path %w", err)
265 }
266
267 if !token.IsIdentifier(ifaceName) {
268 return fmt.Errorf("invalid type name: %q", ifaceName)
269 }
270
271 return nil
272 }
273
274 if err := validInterface(v); err != nil {
275 // The client only sends back answers, not the original form fields.
276 // Clone the static form template so we can attach the validation
277 // error and send the complete form back for the client to re-render.
278 form := slices.Clone(form)
279 form[0].Error = err.Error()
280 param.FormFields = form
281 return nil
282 }
283
284 param.FormFields = nil
285 return nil
286 }
287
288 // FormAnswer finds, validates, and returns the unique answer for id.
289 //
290 // It uses a linear scan since the number of answers is small (usually < 5).
291 func FormAnswer[T any](params *protocol.InteractiveParams, id string) (v T, err error) {
292 matches := 0
293 for _, ans := range params.FormAnswers {
294 if ans.ID == id {
295 matches++
296 val, ok := ans.Value.(T)
297 if !ok {
298 return v, fmt.Errorf("form answer %q has unexpected type %T, want %T", id, ans.Value, v)
299 }
300 v = val
301 }
302 }
303 if matches == 0 {
304 return v, fmt.Errorf("form lacks answer %q", id)
305 } else if matches > 1 {
306 return v, fmt.Errorf("form contains duplicate answer %q", id)
307 }
308 return v, nil
309 }
310
311 // SanitizeTags cleans up comma-separated tags and ensures they are valid.
312 func SanitizeTags(tags string) (string, error) {
313 parts := strings.Split(tags, ",")
314 var clean []string
315
316 for _, p := range parts {
317 p = strings.TrimSpace(p)
318 if p == "" {
319 continue
320 }
321
322 // Use strings.ContainsFunc instead of a manual byte loop.
323 // It returns true if any rune in the string matches the condition.
324 if strings.ContainsFunc(p, func(r rune) bool {
325 // Space, colon, quote, or any non-printable character (like control chars)
326 return r == ' ' || r == ':' || r == '"' || !unicode.IsPrint(r)
327 }) {
328 return "", fmt.Errorf("illegal tag %q: cannot contain spaces, quotes, colons, or control characters", p)
329 }
330
331 clean = append(clean, p)
332 }
333
334 return strings.Join(clean, ","), nil
335 }