Skip to content

Commit

Permalink
replace_all
Browse files Browse the repository at this point in the history
  • Loading branch information
xzbdmw committed Nov 1, 2024
1 parent 386503d commit 30abec2
Show file tree
Hide file tree
Showing 16 changed files with 932 additions and 37 deletions.
Binary file added gopls/doc/assets/extract-expressions-after.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added gopls/doc/assets/extract-expressions-before.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified gopls/doc/assets/extract-var-after.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed gopls/doc/assets/extract-var-before.png
Binary file not shown.
12 changes: 10 additions & 2 deletions gopls/doc/features/transformation.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ Gopls supports the following code actions:
- [`refactor.extract.method`](#extract)
- [`refactor.extract.toNewFile`](#extract.toNewFile)
- [`refactor.extract.variable`](#extract)
- [`refactor.extract.variable.all`](#extract)
- [`refactor.inline.call`](#refactor.inline.call)
- [`refactor.rewrite.changeQuote`](#refactor.rewrite.changeQuote)
- [`refactor.rewrite.fillStruct`](#refactor.rewrite.fillStruct)
Expand Down Expand Up @@ -313,11 +314,18 @@ newly created declaration that contains the selected code:
will be a method of the same receiver type.

- **`refactor.extract.variable`** replaces an expression by a reference to a new
local variable named `x` initialized by the expression:
local variable named `newVar` initialized by the expression:

![Before extracting a var](../assets/extract-var-before.png)
![Before extracting a var](../assets/extract-expressions-before.png)
![After extracting a var](../assets/extract-var-after.png)

- **`refactor.extract.variable.all`** replaces all occurrences of the selected expression
within the function with a reference to a new local variable named `newVar`.
This extracts the expression once and reuses it wherever it appears in the function.

![Before extracting all expressions](../assets/extract-expressions-before.png)
![After extracting all expressions](../assets/extract-expressions-after.png)

If the default name for the new declaration is already in use, gopls
generates a fresh name.

Expand Down
5 changes: 5 additions & 0 deletions gopls/doc/release/v0.17.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,8 @@ Gopls now offers a new code action, “Declare missing method of T.f”,
where T is the concrete type and f is the undefined method.
The stub method's signature is inferred
from the context of the call.

## Replace all occurrences of expression within function with newVar
When you have multiple instances of the same expression in a function,
you can use this code action to extract it into a variable.
All occurrences of the expression will be replaced with a reference to the new variable.
22 changes: 22 additions & 0 deletions gopls/internal/golang/codeaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/protocol/command"
"golang.org/x/tools/gopls/internal/settings"
"golang.org/x/tools/gopls/internal/util/safetoken"
"golang.org/x/tools/gopls/internal/util/typesutil"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/imports"
Expand Down Expand Up @@ -236,6 +237,7 @@ var codeActionProducers = [...]codeActionProducer{
{kind: settings.RefactorExtractFunction, fn: refactorExtractFunction},
{kind: settings.RefactorExtractMethod, fn: refactorExtractMethod},
{kind: settings.RefactorExtractToNewFile, fn: refactorExtractToNewFile},
{kind: settings.RefactorExtractAllOccursOfExpr, fn: refactorExtractAllOccursOfExpr},
{kind: settings.RefactorExtractVariable, fn: refactorExtractVariable},
{kind: settings.RefactorInlineCall, fn: refactorInlineCall, needPkg: true},
{kind: settings.RefactorRewriteChangeQuote, fn: refactorRewriteChangeQuote},
Expand Down Expand Up @@ -458,6 +460,26 @@ func refactorExtractVariable(ctx context.Context, req *codeActionsRequest) error
return nil
}

// refactorExtractAllOccursOfExpr produces "Extract all occcurrances of expression" code action.
// See [extractAllOccursOfExpr] for command implementation.
func refactorExtractAllOccursOfExpr(ctx context.Context, req *codeActionsRequest) error {
// Don't suggest if only one expr is found,
// otherwise will duplicate with [refactorExtractVariable]
if exprs, ok, _ := canExtractExprs(req.start, req.end, req.pgf.File); ok && len(exprs) > 1 {
startOffset, err := safetoken.Offset(req.pgf.Tok, exprs[0].Pos())
if err != nil {
return nil
}
endOffset, err := safetoken.Offset(req.pgf.Tok, exprs[0].End())
if err != nil {
return nil
}
expr := req.pgf.Src[startOffset:endOffset]
req.addApplyFixAction(fmt.Sprintf("Extract %d occcurrances of %s", len(exprs), expr), fixExtractAllOccursOfExpr, req.loc)
}
return nil
}

// refactorExtractToNewFile produces "Extract declarations to new file" code actions.
// See [server.commandHandler.ExtractToNewFile] for command implementation.
func refactorExtractToNewFile(ctx context.Context, req *codeActionsRequest) error {
Expand Down
10 changes: 5 additions & 5 deletions gopls/internal/golang/extract.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,23 @@ func extractVariable(fset *token.FileSet, start, end token.Pos, src []byte, file
switch expr := expr.(type) {
// TODO: stricter rules for selectorExpr.
case *ast.BasicLit, *ast.CompositeLit, *ast.IndexExpr, *ast.SliceExpr,
*ast.UnaryExpr, *ast.BinaryExpr, *ast.SelectorExpr:
lhsName, _ := generateAvailableIdentifier(expr.Pos(), path, pkg, info, "x", 0)
*ast.UnaryExpr, *ast.BinaryExpr, *ast.SelectorExpr, *ast.FuncLit:
lhsName, _ := generateAvailableIdentifier(expr.Pos(), path, pkg, info, "newVar", 0)
lhsNames = append(lhsNames, lhsName)
case *ast.CallExpr:
tup, ok := info.TypeOf(expr).(*types.Tuple)
if !ok {
// If the call expression only has one return value, we can treat it the
// same as our standard extract variable case.
lhsName, _ := generateAvailableIdentifier(expr.Pos(), path, pkg, info, "x", 0)
lhsName, _ := generateAvailableIdentifier(expr.Pos(), path, pkg, info, "newVar", 0)
lhsNames = append(lhsNames, lhsName)
break
}
idx := 0
for i := 0; i < tup.Len(); i++ {
// Generate a unique variable for each return value.
var lhsName string
lhsName, idx = generateAvailableIdentifier(expr.Pos(), path, pkg, info, "x", idx)
lhsName, idx = generateAvailableIdentifier(expr.Pos(), path, pkg, info, "newVar", idx)
lhsNames = append(lhsNames, lhsName)
}
default:
Expand Down Expand Up @@ -130,7 +130,7 @@ func canExtractVariable(start, end token.Pos, file *ast.File) (ast.Expr, []ast.N
}
switch expr.(type) {
case *ast.BasicLit, *ast.CompositeLit, *ast.IndexExpr, *ast.CallExpr,
*ast.SliceExpr, *ast.UnaryExpr, *ast.BinaryExpr, *ast.SelectorExpr:
*ast.SliceExpr, *ast.UnaryExpr, *ast.BinaryExpr, *ast.SelectorExpr, *ast.FuncLit:
return expr, path, true, nil
}
return nil, nil, false, fmt.Errorf("cannot extract an %T to a variable", expr)
Expand Down
Loading

0 comments on commit 30abec2

Please sign in to comment.