Debian Codegraph @

gopls/doc/features/transformation.md

raw symbols SCIP
1 ---
2 title: "Gopls: Code transformation features"
3 ---
4
5 This document describes gopls' features for code transformation, which
6 include a range of behavior-preserving changes (refactorings,
7 formatting, simplifications), code repair (fixes), and editing support
8 (filling in struct literals and switch statements).
9
10 Code transformations are not a single category in the LSP:
11
12 - A few, such as Formatting and Rename, are primary operations in the
13 protocol.
14 - Some transformations are exposed through [Code Lenses](../codelenses.md),
15 which return _commands_, arbitrary server
16 operations invoked for their side effects through a
17 [`workspace/executeCommand`](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_executeCommand) request;
18 however, no current code lenses are transformations of Go syntax.
19 <!-- Generate, RegenerateCgo (Go); Tidy, UpgradeDependency, Vendor (go.mod) -->
20 - Most transformations are defined as *code actions*.
21
22 ## Code Actions
23
24 A **code action** is an action associated with a portion of the file.
25 Each time the selection changes, a typical client makes a
26 [`textDocument/codeAction`](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_codeAction)
27 request for the set of available actions, then updates its UI
28 elements (menus, icons, tooltips) to reflect them.
29 The VS Code manual describes code actions as
30 "[Quick fixes + Refactorings](https://code.visualstudio.com/docs/editor/refactoring#_code-actions-quick-fixes-and-refactorings)".
31
32 A `codeAction` request delivers the menu, so to speak, but it does
33 not order the meal. Once the user chooses an action, one of two things happens.
34 In trivial cases, the action itself contains an edit that the
35 client can directly apply to the file.
36 But in most cases the action contains a command,
37 similar to the command associated with a code lens.
38 This allows the work of computing the patch to be done lazily, only
39 when actually needed. (Most aren't.)
40 The server may then compute the edit and send the client a
41 [`workspace/applyEdit`](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_applyEdit)
42 request to patch the files.
43 Not all code actions' commands have an `applyEdit` side effect: some
44 may change the state of the server, for example to toggle a variable
45 or to cause the server to send other requests to the client,
46 such as a `showDocument` request to open a report in a web browser.
47
48 The main difference between code lenses and code actions is this:
49
50 - a `codeLens` request obtains commands for the entire file.
51 Each command specifies its applicable source range,
52 and typically appears as an annotation on that source range.
53 - a `codeAction` request obtains commands only for a particular range: the current selection.
54 All the commands are presented together in a menu at that location.
55
56 Each action has a _kind_,
57 which is a hierarchical identifier such as `refactor.inline.call`.
58 Clients may filter actions based on their kind.
59 For example, VS Code has:
60 two menus, "Refactor..." and "Source action...", each populated by
61 different kinds of code actions (`refactor` and `source`);
62 a lightbulb icon that triggers a menu of "quick fixes" (of kind `quickfix`);
63 and a "Fix All" command that executes all code actions of
64 kind `source.fixAll`, which are those deemed unambiguously safe to apply.
65
66 Gopls supports the following code actions:
67
68 - `quickfix`, which applies unambiguously safe fixes <!-- TODO: document -->
69 - [`source.organizeImports`](#source.organizeImports)
70 - [`source.assembly`](web.md#assembly)
71 - [`source.doc`](web.md#doc)
72 - [`source.freesymbols`](web.md#freesymbols)
73 - `source.test` (undocumented) <!-- TODO: fix that -->
74 - [`source.addTest`](#source.addTest)
75 - [`source.toggleCompilerOptDetails`](diagnostics.md#toggleCompilerOptDetails)
76 - [`gopls.doc.features`](README.md), which opens gopls' index of features in a browser
77 - [`refactor.extract.constant`](#extract)
78 - [`refactor.extract.function`](#extract)
79 - [`refactor.extract.method`](#extract)
80 - [`refactor.extract.toNewFile`](#extract.toNewFile)
81 - [`refactor.extract.variable`](#extract)
82 - [`refactor.extract.variable-all`](#extract)
83 - [`refactor.inline.call`](#refactor.inline.call)
84 - [`refactor.inline.variable`](#refactor.inline.variable)
85 - [`refactor.rewrite.addTags`](#refactor.rewrite.addTags)
86 - [`refactor.rewrite.changeQuote`](#refactor.rewrite.changeQuote)
87 - [`refactor.rewrite.fillStruct`](#refactor.rewrite.fillStruct)
88 - [`refactor.rewrite.fillSwitch`](#refactor.rewrite.fillSwitch)
89 - [`refactor.rewrite.implementInterface`](#refactor.rewrite.implementInterface)
90 - [`refactor.rewrite.invertIf`](#refactor.rewrite.invertIf)
91 - [`refactor.rewrite.joinLines`](#refactor.rewrite.joinLines)
92 - [`refactor.rewrite.moveParamLeft`](#refactor.rewrite.moveParamLeft)
93 - [`refactor.rewrite.moveParamRight`](#refactor.rewrite.moveParamRight)
94 - [`refactor.rewrite.removeTags`](#refactor.rewrite.removeTags)
95 - [`refactor.rewrite.removeUnusedParam`](#refactor.rewrite.removeUnusedParam)
96 - [`refactor.rewrite.splitLines`](#refactor.rewrite.splitLines)
97
98 Gopls reports some code actions twice, with two different kinds, so
99 that they appear in multiple UI elements: simplifications,
100 for example from `for _ = range m` to `for range m`,
101 have kinds `quickfix` and `source.fixAll`,
102 so they appear in the "Quick Fix" menu and
103 are activated by the "Fix All" command.
104
105 <!-- In principle the filter may include the trigger event
106 e.g. auto (cursor motion) vs. invoked (open a menu)
107 but gopls currently ignores it. -->
108
109 Many transformations are computed by [analyzers](../analyzers.md)
110 that, in the course of reporting a diagnostic about a problem,
111 also suggest a fix.
112 A `codeActions` request will return any fixes accompanying diagnostics
113 for the current selection.
114
115 <!-- Some gopls-internal analyzers compute fixes lazily by
116 reporting an empty list of TextEdits and a Diagnostic.Category
117 recognized by gopls that enables corresponding logic in the
118 server's ApplyFix command handler. -->
119
120 <!-- The source.test ("Run this test") code action (not a
121 transformation) runs the selected test. However, it is not
122 offered by default because:
123 (a) VS Code has a richer test UX (with richer ones to come--see
124 https://github.com/golang/vscode-go/issues/1641) and
125 (b) LSP has no good way to display the streaming output of a test
126 in the client's natural UX (see last paragraph of first note
127 of https://github.com/golang/go/issues/67400).
128 It is only offered when the "only" field includes kind source.test.
129 Should it be documented? If so, where?
130 -->
131
132 Caveats:
133
134 - Many of gopls code transformations are limited by Go's syntax tree
135 representation, which currently records comments not in the tree
136 but in a side table; consequently, transformations such as Extract
137 and Inline are prone to losing comments. This is issue
138 https://go.dev/issue/20744, and it is a priority for us to fix in 2024.
139
140 - Generated files, as identified by the conventional
141 [DO NOT EDIT](https://go.dev/s/generatedcode) comment,
142 are not offered code actions for transformations.
143 <!-- TODO: this is frankly a nuisance. It is often convenient to modify generated files -->
144
145 Client support for code actions:
146
147 - **VS Code**: Depending on their kind, code actions are found in
148 the "Refactor..." menu (`^⇧R`),
149 the "Source action..." menu,
150 the 💡 (light bulb) icon's menu, or
151 the "Quick fix" (`⌘.`) menu.
152 The "Fix All" command applies all actions of kind `source.fixAll`.
153 - **Emacs + eglot**: Code actions are invisible.
154 Use `M-x eglot-code-actions` to select one from those that are
155 available (if there are multiple) and execute it.
156 Some action kinds have filtering shortcuts,
157 e.g. [`M-x eglot-code-action-{inline,extract,rewrite}`](https://joaotavora.github.io/eglot/#index-M_002dx-eglot_002dcode_002daction_002dinline).
158 - **CLI**: `gopls codeaction -exec -kind k,... -diff file.go:#123-#456` executes code actions of the specified
159 kinds (e.g. `refactor.inline`) on the selected range, specified using zero-based byte offsets, and displays the diff.
160
161 ### Interactive Code Actions
162
163 Some code actions are **interactive**, meaning they require user input to complete. Unlike standard code actions, which can be applied immediately, these operations prompt the user for one or more additional pieces of information before proceeding.
164 In effect, the server asks the client to fill in a form. Each form element may be a number, string, file path, or a selection from a set of options, and so on.
165
166 When you invoke one of these actions, you will be prompted for the necessary parameters. If the provided input is invalid, the server returns the partially completed form along with error information about any invalid fields. A client may simply report the error, or offer the user a chance to amend the form. After valid input is received, the code action's command is executed as usual, which may involve updating your workspace or performing other actions.
167
168 This allows for more sophisticated transformations and analyses that require specific inputs or choices from the user.
169
170 For example, gopls's `refactor.rewrite.addTags` refactoring prompts the user to specify the set of struct field tags (`json`, `xml`, ...) to add, and its `refactor.rewrite.implementInterface` refactoring prompts for the name of an interface type.
171
172 Caveats:
173
174 Dialog support is a non-standard feature of LSP. It is currently supported only by gopls, but we plan to work with the broader LSP community toward a standard specification for dialogs and client support in a range of editors.
175
176 Client support for interactive code actions:
177
178 - **VS Code**: Interactive code actions integrate directly into the standard code action workflow.
179 <!-- TODO(hxjiang): add neovim once PR ready -->
180 <!-- TODO(adonovan): add emacs once PR ready -->
181
182 <a name='formatting'></a>
183 ## Formatting
184
185 The LSP
186 [`textDocument/formatting`](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_formatting)
187 request returns edits that format a file.
188 Gopls applies Go's canonical formatting algorithm,
189 [`go fmt`](https://pkg.go.dev/cmd/gofmt).
190 LSP formatting options are ignored.
191
192 Most clients are configured to format files and organize imports
193 whenever a file is saved.
194
195 Settings:
196
197 - The [`gofumpt`](../settings.md#gofumpt) setting causes gopls to use an
198 alternative formatter, [`github.com/mvdan/gofumpt`](https://pkg.go.dev/mvdan.cc/gofumpt).
199
200 Client support:
201
202 - **VS Code**: Formats on save by default. Use `Format document` menu item (`⌥⇧F`) to invoke manually.
203 - **Emacs + eglot**: Use `M-x eglot-format-buffer` to format. Attach it to `before-save-hook` to format on save. For formatting combined with organize-imports, many users take the legacy approach of setting `"goimports"` as their `gofmt-command` using [go-mode](https://github.com/dominikh/go-mode.el), and adding `gofmt-before-save` to `before-save-hook`. An LSP-based solution requires code such as https://github.com/joaotavora/eglot/discussions/1409.
204 - **CLI**: `gopls format file.go`
205
206 <a name='source.organizeImports'></a>
207 ## `source.organizeImports`: Organize imports
208
209 A `codeActions` request in a file whose imports are not organized will
210 return an action of the standard kind `source.organizeImports`.
211 Its command has the effect of organizing the imports:
212 deleting existing imports that are duplicate or unused,
213 adding new ones for undefined symbols,
214 and sorting them into the conventional order.
215
216 The addition of new imports is based on heuristics that depend on
217 your workspace and the contents of your GOMODCACHE directory; they may
218 sometimes make surprising choices.
219
220 Many editors automatically organize imports and format the code before
221 saving any edited file.
222
223 Some users dislike the automatic removal of imports that are
224 unreferenced because, for example, the sole line that refers to the
225 import is temporarily commented out for debugging; see https://go.dev/issue/54362.
226
227 Settings:
228
229 - The [`local`](../settings.md#local) setting is a comma-separated list of
230 prefixes of import paths that are "local" to the current file and
231 should appear after standard and third-party packages in the sort order.
232
233 Client support:
234
235 - **VS Code**: automatically invokes `source.organizeImports` before save.
236 To disable it, use the snippet below, and invoke the "Organize Imports" command manually as needed.
237 ```
238 "[go]": {
239 "editor.codeActionsOnSave": { "source.organizeImports": false }
240 }
241 ```
242 - **Emacs + eglot**: Use `M-x eglot-code-action-organize-imports` to invoke manually.
243 Many users of [go-mode](https://github.com/dominikh/go-mode.el) use these lines to
244 organize imports and reformat each modified file before saving it, but this
245 approach is based on the legacy
246 [`goimports`](https://pkg.go.dev/golang.org/x/tools/cmd/goimports) tool, not gopls:
247 ```lisp
248 (setq gofmt-command "goimports")
249 (add-hook 'before-save-hook 'gofmt-before-save)
250 ```
251 - **CLI**: `gopls fix -a file.go:#offset source.organizeImports`
252
253 <a name='source.addTest'></a>
254 ## `source.addTest`: Add test for function or method
255
256 If the selected chunk of code is part of a function or method declaration F,
257 gopls will offer the "Add test for F" code action, which adds a new test for the
258 selected function in the corresponding `_test.go` file. The generated test takes
259 into account its signature, including input parameters and results.
260
261 **Test file**: if the `_test.go` file does not exist, gopls creates it, based on
262 the name of the current file (`a.go` -> `a_test.go`), copying any copyright and
263 build constraint comments from the original file.
264
265 **Test package**: for new files that test code in package `p`, the test file
266 uses `p_test` package name whenever possible, to encourage testing only exported
267 functions. (If the test file already exists, the new test is added to that file.)
268
269 **Parameters**: each of the function's non-blank parameters becomes an item in
270 the struct used for the table-driven test. (For each blank `_` parameter, the
271 value has no effect, so the test provides a zero-valued argument.)
272
273 **Contexts**: If the first parameter is `context.Context`, the test passes
274 `t.Context()` when the module's Go version is 1.24 or later, and
275 `context.Background()` otherwise.
276
277 **Results**: the function's results are assigned to variables (`got`, `got2`,
278 and so on) and compared with expected values (`want`, `want2`, etc.`) defined in
279 the test case struct. The user should edit the logic to perform the appropriate
280 comparison. If the final result is an `error`, the test case defines a `wantErr`
281 boolean.
282
283 **Method receivers**: When testing a method `T.F` or `(*T).F`, the test must
284 construct an instance of T to pass as the receiver. Gopls searches the package
285 for a suitable function that constructs a value of type T or \*T, optionally with
286 an error, preferring a function named `NewT`.
287
288 **Imports**: Gopls adds missing imports to the test file, using the last
289 corresponding import specifier from the original file. It avoids duplicate
290 imports, preserving any existing imports in the test file.
291
292 <img title="Add test for func" src="../assets/add-test-for-func.png" width='80%'>
293
294 <a name='rename'></a>
295 ## Rename
296
297 The LSP
298 [`textDocument/rename`](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_rename)
299 request renames a symbol.
300
301 Renaming is a two-stage process. The first step, a
302 [`prepareRename`](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_prepareRename) query, returns the current
303 name of the identifier under the cursor (if indeed there is one).
304 The client then displays a dialog prompting the user to choose a new
305 name by editing the old one. The second step, `rename` proper, applies
306 the changes. (This simple dialog support is unique among LSP
307 refactoring operations; see microsoft/language-server-protocol#1164.)
308
309 Gopls' renaming algorithm takes great care to detect situations in
310 which renaming might introduce a compilation error.
311 For example, changing a name may cause a symbol to become "shadowed",
312 so that some existing references are no longer in scope. Gopls will
313 report an error, stating the pair of symbols and the shadowed reference:
314
315 <img title="Renamed failed due to a shadowing conflict" src="../assets/rename-conflict.png">
316
317 As another example, consider renaming a method of a concrete type.
318 Renaming may cause the type to no longer satisfy the same interfaces
319 as before, which could cause the program to fail to compile.
320 To avoid this, gopls inspects each conversion (explicit or implicit)
321 from the affected type to an interface type, and checks whether it
322 would remain valid after the renaming. If not, it aborts the renaming
323 with an error.
324
325 If you intend to rename both the original method and the corresponding
326 methods of any matching interface types (as well as any methods of
327 types matching them in turn), you can indicate this by invoking the
328 rename operation on the interface method.
329
330 Similarly, gopls will report an error if you rename a field of a
331 struct that happens to be an "anonymous" field that embeds a type,
332 since that would require a larger renaming involving the type as well.
333 If that is what you intend, you can again indicate this by
334 invoking the rename operation on the type.
335
336 Renaming should never introduce a compilation error, but it may
337 introduce dynamic errors. For example, in a method renaming, if there
338 is no direct conversion of the affected type to the interface type,
339 but there is an intermediate conversion to a broader type (such as `any`) followed by a
340 type assertion to the interface type, then gopls may proceed to rename
341 the method, causing the type assertion to fail at run time.
342 Similar problems may arise with packages that use reflection, such as
343 `encoding/json` or `text/template`. There is no substitute for good
344 judgment and testing.
345
346 Special cases:
347
348 - When renaming the declaration of a method receiver, the tool also
349 attempts to rename the receivers of all other methods associated
350 with the same named type. Each other receiver that cannot be fully
351 renamed is quietly skipped. Renaming any _use_ of a receiver affects
352 only that variable.
353
354 ```go
355 type Counter struct { x int }
356
357 Rename here to affect only this method
358 ↓
359 func (c *Counter) Inc() { c.x++ }
360 func (c *Counter) Dec() { c.x++ }
361 ↑
362 Rename here to affect all methods
363 ```
364
365 Using Rename to move a package:
366 To rename a package, execute the Rename operation over the `p` in a
367 `package p` declaration at the start of a file.
368 You will be prompted to edit the package's path and choose its new location.
369 The Rename operation will move all the package's files to the resulting directory,
370 creating it if necessary.
371 By default, subpackages will remain where they are. To include subpackages
372 in the renaming, set [renameMovesSubpackages](../settings.md#renamemovessubpackages-bool) to true.
373 Existing imports of the package will be updated to reflect its new path.
374
375 Package moves are rejected if they would break the build. For example:
376 - Packages cannot move across a module boundary.
377 - Packages cannot be moved into existing packages; gopls does not support package merging.
378 - Packages cannot be moved to internal directories that would make them inaccessible to any of their current importers.
379
380 Renaming package main is not supported, because the main package has special meaning to the linker.
381 Renaming x_test packages is currently not supported.
382
383 Some tips for best results:
384
385 - The safety checks performed by the Rename algorithm require type
386 information. If the program is grossly malformed, there may be
387 insufficient information for it to run (https://go.dev/issue/41870),
388 and renaming cannot generally be used to fix a type error (https://go.dev/issue/41851).
389 When refactoring, we recommend working in small steps, repairing any
390 problems as you go, so that as much as possible of the program
391 compiles at each step.
392 - Sometimes it may be desirable for a renaming operation to change the
393 reference structure of the program, for example to intentionally
394 combine two variables x and y by renaming y to x.
395 The renaming tool is too strict to help in this case (https://go.dev/issue/41852).
396
397 <!-- known issue: when renaming an interface method, gopls doesn't properly
398 traverse W-shaped import graphs looking for matching types; see https://go.dev/issue/58461. -->
399
400 For the gory details of gopls' rename algorithm, you may be interested
401 in the latter half of this 2015 GothamGo talk:
402 [Using go/types for Code Comprehension and Refactoring Tools](https://www.youtube.com/watch?v=p_cz7AxVdfg).
403
404 Client support:
405
406 - **VS Code**: Use "[Rename symbol](https://code.visualstudio.com/docs/editor/editingevolved#_rename-symbol)" menu item (`F2`).
407 - **Emacs + eglot**: Use `M-x eglot-rename`, or `M-x go-rename` from [go-mode](https://github.com/dominikh/go-mode.el).
408 - **Vim + coc.nvim**: Use the `coc-rename` command.
409 - **CLI**: `gopls rename file.go:#offset newname`
410
411 <a name='refactor.extract'></a>
412 ## `refactor.extract`: Extract function/method/variable
413
414 The `refactor.extract` family of code actions all return commands that
415 replace the selected expression or statements with a reference to a
416 newly created declaration that contains the selected code:
417
418 - **`refactor.extract.function`** replaces one or more complete statements by a
419 call to a new function named `newFunction` whose body contains the
420 statements. The selection must enclose fewer statements than the
421 entire body of the existing function.
422
423 ![Before extracting a function](../assets/extract-function-before.png)
424 ![After extracting a function](../assets/extract-function-after.png)
425
426 - **`refactor.extract.method`** is a variant of "Extract function" offered when
427 the selected statements belong to a method. The newly created function
428 will be a method of the same receiver type.
429
430 - **`refactor.extract.variable`** replaces an expression by a reference to a new
431 local variable named `newVar` initialized by the expression:
432
433 ![Before extracting a var](../assets/extract-var-before.png)
434 ![After extracting a var](../assets/extract-var-after.png)
435
436 - **`refactor.extract.constant** does the same thing for a constant
437 expression, introducing a local const declaration.
438 - **`refactor.extract.variable-all`** replaces all occurrences of the selected expression
439 within the function with a reference to a new local variable named `newVar`.
440 This extracts the expression once and reuses it wherever it appears in the function.
441
442 ![Before extracting all occurrences of EXPR](../assets/extract-var-all-before.png)
443 ![After extracting all occurrences of EXPR](../assets/extract-var-all-after.png)
444
445 - **`refactor.extract.constant-all** does the same thing for a constant
446 expression, introducing a local const declaration.
447 If the default name for the new declaration is already in use, gopls
448 generates a fresh name.
449
450 Extraction is a challenging problem requiring consideration of
451 identifier scope and shadowing, control
452 flow such as `break`/`continue` in a loop or `return` in a
453 function, cardinality of variables, and even subtle issues of style.
454 In each case, the tool will try to update the extracted statements
455 as needed to avoid build breakage or behavior changes.
456 Unfortunately, gopls' Extract algorithms are considerably less
457 rigorous than the Rename and Inline operations, and we are aware of a
458 number of cases where it falls short, including:
459
460 - https://github.com/golang/go/issues/66289
461 - https://github.com/golang/go/issues/65944
462 - https://github.com/golang/go/issues/63394
463 - https://github.com/golang/go/issues/61496
464
465 The following Extract features are planned for 2024 but not yet supported:
466
467 - **Extract parameter struct** will replace two or more parameters of a
468 function by a struct type with one field per parameter; see https://go.dev/issue/65552.
469 <!-- TODO(adonovan): review and land https://go.dev/cl/620995. -->
470 <!-- Should this operation update all callers? That's more of a Change Signature. -->
471 - **Extract interface for type** will create a declaration of an
472 interface type with all the methods of the selected concrete type;
473 see https://go.dev/issue/65721 and https://go.dev/issue/46665.
474
475 <a name='refactor.extract.toNewFile'></a>
476 ## `refactor.extract.toNewFile`: Extract declarations to new file
477
478 (Available from gopls/v0.17.0)
479
480 If you select one or more top-level declarations, gopls will offer an
481 "Extract declarations to new file" code action that moves the selected
482 declarations into a new file whose name is based on the first declared
483 symbol.
484 Import declarations are created as needed.
485 Gopls also offers this code action when the selection is just the
486 first token of the declaration, such as `func` or `type`.
487
488 ![Before: select the declarations to move](../assets/extract-to-new-file-before.png)
489 ![After: the new file is based on the first symbol name](../assets/extract-to-new-file-after.png)
490
491 <a name='refactor.inline.call'></a>
492
493 ## `refactor.inline.call`: Inline call to function
494
495 For a `codeActions` request where the selection is (or is within) a
496 call of a function or method, gopls will return a command of kind
497 `refactor.inline.call`, whose effect is to inline the function call.
498
499 The screenshots below show a call to `sum` before and after inlining:
500
501 <!-- source code used for images:
502
503 func six() int {
504 return sum(1, 2, 3)
505 }
506
507 func sum(values ...int) int {
508 total := 0
509 for _, v := range values {
510 total += v
511 }
512 return total
513 }
514 -->
515
516 ![Before: select Refactor... Inline call to sum](../assets/inline-before.png)
517 ![After: the call has been replaced by the sum logic](../assets/inline-after.png)
518
519 Inlining replaces the call expression by a copy of the function body,
520 with parameters replaced by arguments.
521 Inlining is useful for a number of reasons.
522 Perhaps you want to eliminate a call to a deprecated
523 function such as `ioutil.ReadFile` by replacing it with a call to the
524 newer `os.ReadFile`; inlining will do that for you.
525 Or perhaps you want to copy and modify an existing function in some
526 way; inlining can provide a starting point.
527 The inlining logic also provides a building block for
528 other refactorings, such as "change signature".
529
530 Not every call can be inlined.
531 Of course, the tool needs to know which function is being called, so
532 you can't inline a dynamic call through a function value or interface
533 method; but static calls to methods are fine.
534 Nor can you inline a call if the callee is declared in another package
535 and refers to non-exported parts of that package, or to [internal
536 packages](https://go.dev/doc/go1.4#internalpackages) that are
537 inaccessible to the caller.
538 Calls to generic functions are not yet supported
539 (https://go.dev/issue/63352), though we plan to fix that.
540
541 When inlining is possible, it's critical that the tool preserve
542 the original behavior of the program.
543 We don't want refactoring to break the build, or, worse, to introduce
544 subtle latent bugs.
545 This is especially important when inlining tools are used to perform
546 automated clean-ups in large code bases;
547 we must be able to trust the tool.
548 Our inliner is very careful not to make guesses or unsound
549 assumptions about the behavior of the code.
550 However, that does mean it sometimes produces a change that differs
551 from what someone with expert knowledge of the same code might have
552 written by hand.
553
554 In the most difficult cases, especially with complex control flow, it
555 may not be safe to eliminate the function call at all.
556 For example, the behavior of a `defer` statement is intimately tied to
557 its enclosing function call, and `defer` is the only control
558 construct that can be used to handle panics, so it cannot be reduced
559 into simpler constructs.
560 So, for example, given a function f defined as:
561
562 ```go
563 func f(s string) {
564 defer fmt.Println("goodbye")
565 fmt.Println(s)
566 }
567 ```
568
569 a call `f("hello")` will be inlined to:
570
571 ```go
572 func() {
573 defer fmt.Println("goodbye")
574 fmt.Println("hello")
575 }()
576 ```
577
578 Although the parameter was eliminated, the function call remains.
579
580 An inliner is a bit like an optimizing compiler.
581 A compiler is considered "correct" if it doesn't change the meaning of
582 the program in translation from source language to target language.
583 An _optimizing_ compiler exploits the particulars of the input to
584 generate better code, where "better" usually means more efficient.
585 As users report inputs that cause the compiler to emit suboptimal
586 code, the compiler is improved to recognize more cases, or more rules,
587 and more exceptions to rules---but this process has no end.
588 Inlining is similar, except that "better" code means tidier code.
589 The most conservative translation provides a simple but (hopefully)
590 correct foundation, on top of which endless rules, and exceptions to
591 rules, can embellish and improve the quality of the output.
592
593 Here are some of the technical challenges involved in sound inlining:
594
595 - **Effects:** When replacing a parameter by its argument expression,
596 we must be careful not to change the effects of the call. For
597 example, if we call a function `func twice(x int) int { return x + x }`
598 with `twice(g())`, we do not want to see `g() + g()`, which would
599 cause g's effects to occur twice, and potentially each call might
600 return a different value. All effects must occur the same number of
601 times, and in the same order. This requires analyzing both the
602 arguments and the callee function to determine whether they are
603 "pure", whether they read variables, or whether (and when) they
604 update them too. The inliner will introduce a declaration such as
605 `var x int = g()` when it cannot prove that it is safe to substitute
606 the argument throughout.
607
608 - **Constants:** If inlining always replaced a parameter by its argument
609 when the value is constant, some programs would no longer build
610 because checks previously done at run time would happen at compile time.
611 For example `func index(s string, i int) byte { return s[i] }`
612 is a valid function, but if inlining were to replace the call `index("abc", 3)`
613 by the expression `"abc"[3]`, the compiler will report that the
614 index `3` is out of bounds for the string `"abc"`.
615 The inliner will prevent substitution of parameters by problematic
616 constant arguments, again introducing a `var` declaration instead.
617
618 - **Referential integrity:** When a parameter variable is replaced by
619 its argument expression, we must ensure that any names in the
620 argument expression continue to refer to the same thing---not to a
621 different declaration in the callee function body that happens to
622 use the same name. The inliner must replace local references such as
623 `Printf` by qualified references such as `fmt.Printf`, and add an
624 import of package `fmt` as needed.
625
626 - **Implicit conversions:** When passing an argument to a function, it is
627 implicitly converted to the parameter type. If we eliminate the parameter
628 variable, we don't want to lose the conversion as it may be important. For
629 example, in `func f(x any) { y := x; fmt.Printf("%T", &y) }` the type of
630 variable y is `any`, so the program prints `"*interface{}"`. But if inlining
631 the call `f(1)` were to produce the statement `y := 1`, then the type of y
632 would have changed to `int`, which could cause a compile error or, as in this
633 case, a bug, as the program now prints `"*int"`. When the inliner substitutes
634 a parameter variable by its argument value, it may need to introduce explicit
635 conversions of each value to the original parameter type, such as `y :=
636 any(1)`.
637
638 - **Last reference:** When an argument expression has no effects
639 and its corresponding parameter is never used, the expression
640 may be eliminated. However, if the expression contains the last
641 reference to a local variable at the caller, this may cause a compile
642 error because the variable is now unused. So the inliner must be
643 cautious about eliminating references to local variables.
644
645 This is just a taste of the problem domain. If you're curious, the
646 documentation for [golang.org/x/tools/internal/refactor/inline](https://pkg.go.dev/golang.org/x/tools/internal/refactor/inline) has
647 more detail. All of this is to say, it's a complex problem, and we aim
648 for correctness first of all. We've already implemented a number of
649 important "tidiness optimizations" and we expect more to follow.
650
651 <a name='refactor.inline.variable'></a>
652
653 ## `refactor.inline.variable`: Inline local variable
654
655 For a `codeActions` request where the selection is (or is within) an
656 identifier that is a use of a local variable whose declaration has an
657 initializer expression, gopls will return a code action of kind
658 `refactor.inline.variable`, whose effect is to inline the variable:
659 that is, to replace the reference by the variable's initializer
660 expression.
661
662 For example, if invoked on the identifier `s` in the call `println(s)`:
663 ```go
664 func f(x int) {
665 s := fmt.Sprintf("+%d", x)
666 println(s)
667 }
668 ```
669 the code action transforms the code to:
670
671 ```go
672 func f(x int) {
673 s := fmt.Sprintf("+%d", x)
674 println(fmt.Sprintf("+%d", x))
675 }
676 ```
677
678 (In this instance, `s` becomes an unreferenced variable which you will
679 need to remove.)
680
681 The code action always replaces the reference by the initializer
682 expression, even if there are later assignments to the variable (such
683 as `s = ""`).
684
685 The code action reports an error if it is not possible to make the
686 transformation because one of the identifiers within the initializer
687 expression (e.g. `x` in the example above) is shadowed by an
688 intervening declaration, as in this example:
689
690 ```go
691 func f(x int) {
692 s := fmt.Sprintf("+%d", x)
693 {
694 x := 123
695 println(s, x) // error: cannot replace s with fmt.Sprintf(...) since x is shadowed
696 }
697 }
698 ```
699
700 <a name='refactor.rewrite'></a>
701 ## `refactor.rewrite`: Miscellaneous rewrites
702
703 This section covers a number of transformations that are accessible as
704 code actions whose kinds are children of `refactor.rewrite`.
705
706 <a name='refactor.rewrite.removeUnusedParam'></a>
707 ### `refactor.rewrite.removeUnusedParam`: Remove unused parameter
708
709 The [`unusedparams` analyzer](../analyzers.md#unusedparams) reports a
710 diagnostic for each parameter that is not used within the function body.
711 For example:
712
713 ```go
714 func f(x, y int) { // "unused parameter: x"
715 fmt.Println(y)
716 }
717 ```
718
719 It does _not_ report diagnostics for address-taken functions, which
720 may need all their parameters, even unused ones, in order to conform
721 to a particular function signature.
722 Nor does it report diagnostics for exported functions,
723 which may be address-taken by another package.
724 (A function is _address-taken_ if it is used other than in call position, `f(...)`.)
725
726 In addition to the diagnostic, it suggests two possible fixes:
727
728 1. rename the parameter to `_` to emphasize that it is unreferenced (an immediate edit); or
729 2. delete the parameter altogether, using a `ChangeSignature` command, updating all callers.
730
731 Fix \#2 uses the same machinery as "Inline function call" (see above)
732 to ensure that the behavior of all existing calls is preserved, even
733 when the argument expression for the deleted parameter has side
734 effects, as in the example below.
735
736 ![The parameter x is unused](../assets/remove-unusedparam-before.png)
737 ![The parameter x has been deleted](../assets/remove-unusedparam-after.png)
738
739 Observe that in the first call, the argument `chargeCreditCard()` was
740 not deleted because of potential side effects, whereas in the second
741 call, the argument 2, a constant, was safely deleted.
742
743 <a name='refactor.rewrite.moveParamLeft'></a>
744 <a name='refactor.rewrite.moveParamRight'></a>
745 ### `refactor.rewrite.moveParam{Left,Right}`: Move function parameters
746
747 When the selection is a parameter in a function or method signature, gopls
748 offers a code action to move the parameter left or right (if feasible),
749 updating all callers accordingly.
750
751 For example:
752
753 ```go
754 func Foo(x, y int) int {
755 return x + y
756 }
757
758 func _() {
759 _ = Foo(0, 1)
760 }
761 ```
762
763 becomes
764
765 ```go
766 func Foo(y, x int) int {
767 return x + y
768 }
769
770 func _() {
771 _ = Foo(1, 0)
772 }
773 ```
774
775 following a request to move `x` right, or `y` left.
776
777 This is a primitive building block of more general "Change signature"
778 operations. We plan to generalize this to arbitrary signature rewriting, but
779 the language server protocol does not currently offer good support for user
780 input into refactoring operations (see
781 [microsoft/language-server-protocol#1164](https://github.com/microsoft/language-server-protocol/issues/1164)).
782 Therefore, any such refactoring will require custom client-side logic. (As a
783 very hacky workaround, you can express arbitrary parameter movement by invoking
784 Rename on the `func` keyword of a function declaration, but this interface is
785 just a temporary stopgap.)
786
787 <a name='refactor.rewrite.changeQuote'></a>
788 ### `refactor.rewrite.changeQuote`: Convert string literal between raw and interpreted
789
790 When the selection is a string literal, gopls offers a code action
791 to convert the string between raw form (`` `abc` ``) and interpreted
792 form (`"abc"`) where this is possible:
793
794 ![Convert to interpreted](../assets/convert-string-interpreted.png)
795 ![Convert to raw](../assets/convert-string-raw.png)
796
797 Applying the code action a second time reverts back to the original
798 form.
799
800 <a name='refactor.rewrite.invertIf'></a>
801 ### `refactor.rewrite.invertIf`: Invert 'if' condition
802
803 When the selection is within an `if`/`else` statement that is not
804 followed by `else if`, gopls offers a code action to invert the
805 statement, negating the condition and swapping the `if` and `else`
806 blocks.
807
808 ![Before "Invert if condition"](../assets/invert-if-before.png)
809 ![After "Invert if condition"](../assets/invert-if-after.png)
810
811 <!-- The output of this transformation is often stylistically poor.
812 For example, it will drop the "else" and outdent an if/else
813 if the else block ends with a return statement; and thus applying
814 the operation twice does not get you back to where you started. -->
815
816 <a name='refactor.rewrite.splitLines'></a>
817 <a name='refactor.rewrite.joinLines'></a>
818 ### `refactor.rewrite.{split,join}Lines`: Split elements into separate lines
819
820 When the selection is within a bracketed list of items such as:
821
822 - the **elements** of a composite literal, `[]T{a, b, c}`,
823 - the **arguments** of a function call, `f(a, b, c)`,
824 - the **groups of parameters** of a function signature, `func(a, b, c int, d, e bool)`, or
825 - its **groups of results**, `func() (x, y string, z rune)`,
826
827 gopls will offer the "Split [items] into separate lines" code
828 action, which would transform the forms above into these forms:
829
830 ```go
831 []T{
832 a,
833 b,
834 c,
835 }
836
837 f(
838 a,
839 b,
840 c,
841 )
842
843 func(
844 a, b, c int,
845 d, e bool,
846 )
847
848 func() (
849 x, y string,
850 z rune,
851 )
852 ```
853
854 Observe that in the last two cases, each
855 [group](https://pkg.go.dev/go/ast#Field) of parameters or results is
856 treated as a single item.
857
858 The opposite code action, "Join [items] into one line", undoes the operation.
859 Neither action is offered if the list is already full split or joined,
860 respectively, or trivial (fewer than two items).
861
862 These code actions are not offered for lists containing `//`-style
863 comments, which run to the end of the line.
864
865 <!-- Strictly, line comments make only "join" (but not "split") infeasible. -->
866
867 <a name='refactor.rewrite.fillStruct'></a>
868 ### `refactor.rewrite.fillStruct`: Fill struct literal
869
870 When the cursor is within a struct literal `S{}`, gopls offers the
871 "Fill S" code action, which populates each missing field of the
872 literal that is accessible.
873
874 It uses the following heuristic to choose the value assigned to each
875 field: it finds candidate variables, constants, and functions that are
876 assignable to the field, and picks the one whose name is the closest
877 match to the field name.
878 If there are none, it uses the zero value (such as `0`, `""`, or
879 `nil`) of the field's type.
880
881 In the example below, a
882 [`slog.HandlerOptions`](https://pkg.go.dev/golang.org/x/exp/slog#HandlerOptions)
883 struct literal is filled in using two local variables (`level` and
884 `add`) and a function (`replace`):
885
886 ![Before "Fill slog.HandlerOptions"](../assets/fill-struct-before.png)
887 ![After "Fill slog.HandlerOptions"](../assets/fill-struct-after.png)
888
889 Caveats:
890
891 - This code action requires type information for the struct type, so
892 if it is defined in another package that is not yet imported, you
893 may need to "organize imports" first, for example by saving the
894 file.
895 - Candidate declarations are sought only in the current file, and only
896 above the current point. Symbols declared beneath the current point,
897 or in other files in the package, are not considered; see
898 https://go.dev/issue/68224.
899
900 <a name='refactor.rewrite.fillSwitch'></a>
901 ### `refactor.rewrite.fillSwitch`: Fill switch
902
903 When the cursor is within a switch statement whose operand type is an
904 _enum_ (a finite set of named constants), or within a type switch,
905 gopls offers the "Add cases for T" code action, which populates the
906 switch statement by adding a case for each accessible named constant
907 of the enum type, or, for a type switch, by adding a case for each
908 accessible named non-interface type that implements the interface.
909 Only missing cases are added.
910
911 The screenshots below show a type switch whose operand has the
912 [`net.Addr`](https://pkg.go.dev/net#Addr) interface type. The code
913 action adds one case per concrete network address type, plus a default
914 case that panics with an informative message if an unexpected operand
915 is encountered.
916
917 ![Before "Add cases for Addr"](../assets/fill-switch-before.png)
918 ![After "Add cases for Addr"](../assets/fill-switch-after.png)
919
920 And these screenshots illustrate the code action adding cases for each
921 value of the
922 [`html.TokenType`](https://pkg.go.dev/golang.org/x/net/html#TokenType)
923 enum type, which represents the various types of token from
924 which HTML documents are composed:
925
926 ![Before "Add cases for Addr"](../assets/fill-switch-enum-before.png)
927 ![After "Add cases for Addr"](../assets/fill-switch-enum-after.png)
928
929
930 <a name='refactor.rewrite.eliminateDotImport'></a>
931 ### `refactor.rewrite.eliminateDotImport`: Eliminate dot import
932
933 When the cursor is on a dot import gopls can offer the "Eliminate dot import"
934 code action, which removes the dot from the import and qualifies uses of the
935 package throughout the file. This code action is offered only if
936 each use of the package can be qualified without collisions with existing names.
937
938 <a name='refactor.rewrite.addTags'></a>
939 ### `refactor.rewrite.addTags`: Add struct tags
940
941 When the cursor is within a struct, this code action adds to each field a `json`
942 struct tag that specifies its JSON name, using lower case with underscores
943 (e.g. LinkTarget becomes link_target). For a highlighted selection, it only
944 adds tags on selected fields.
945
946 In editors that support interactive code actions, you can customize the operation:
947 - Tags: The struct tags to add.
948 - Transform rule: The casing rule for the generated tag values. Supported options are `camelCase` (default), `snake_case`, `lisp-case`, `PascalCase` and `Title Case`.
949
950 <a name='refactor.rewrite.removeTags'></a>
951 ### `refactor.rewrite.removeTags`: Remove struct tags
952
953 When the cursor is within a struct, this code action removes all struct tags on
954 all struct fields. For a highlighted selection, it removes tags from only
955 the selected fields.
956
957 In editors that support interactive code actions, you can specify which struct tags to remove.
958
959 <a name='refactor.rewrite.implementInterface'></a>
960 ### `refactor.rewrite.implementInterface`: Add methods to type T to implement an interface
961
962 This code action adds method declarations to a named type so that it implements a specified interface. The method bodies are placeholders to be filled in by the user. Gopls offers this code action when the cursor is on a package-level type declaration on which methods can be declared.
963
964 This code action is offered only in editors that support interactive code actions, a non-standard LSP protocol feature currently supported only by gopls. The server prompts the client to choose the interface. Defaults to `error`. Depending on your editor's support for dialog, it may provide a searchable list of interfaces types found in your workspace, or simply prompt the user to type it out.
965
966 The screenshots below show the seqence of steps in an editor that supports interactive code actions with a searchable list:
967
968 ![Before "Implement interface"](../assets/implement-interface-before.png)
969 ![Selecting the interface](../assets/implement-interface-select-enum.png)
970 ![After "Implement interface"](../assets/implement-interface-after.png)