Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gopls/internal: CodeAction: quickfix to generate missing method #528

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion gopls/doc/features/diagnostics.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ Client support:
<!-- Below we list any quick fixes (by their internal fix name)
that aren't analyzers. -->

### `stubMethods`: Declare missing methods of type
### `stubMissingInterfaceMethods`: Declare missing methods to implement an interface of type

When a value of a concrete type is assigned to a variable of an
interface type, but the concrete type does not possess all the
Expand Down Expand Up @@ -162,6 +162,37 @@ func (NegativeErr) Error() string {
}
```

### `StubMissingCalledFunction`: Generate missing method from function calls

When you attempt to call a method on a type that does not have that method,
the compiler will report an error like “type X has no field or method Y”.
In this scenario, gopls now offers a quick fix to generate a stub declaration of
the missing method on that concrete type. The the stub method's signature is inferred
from the method call.

Consider the following code where `Foo` does not have a method `bar`:

```go
type Foo struct{}

func main() {
var s string
f := Foo{}
s = f.bar("str", 42)
}
```

This code will not compile and produces the error:
`f.bar undefined (type Foo has no field or method bar`.

Gopls will offer a quick fix to declare this method:

```go
func (f Foo) bar(s string, i int) string {
panic("unimplemented")
}
```

Beware that the new declarations appear alongside the concrete type,
which may be in a different file or even package from the cursor
position.
Expand Down
8 changes: 8 additions & 0 deletions gopls/doc/release/v0.17.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,11 @@ function's Go `func` declaration. If the function is implemented in C
or assembly, the function has no body. Executing a second Definition
query (while already at the Go declaration) will navigate you to the
assembly implementation.

## Generate missing method from function call
When you attempt to call a method on a type that does not have that method,
the compiler will report an error like “type X has no field or method Y”.
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.
In this scenario, the stub method's signature is inferred
from the method call.
25 changes: 18 additions & 7 deletions gopls/internal/golang/codeaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,20 +301,31 @@ func quickFix(ctx context.Context, req *codeActionsRequest) error {
continue
}

msg := typeError.Error()
switch {
// "Missing method" error? (stubmethods)
// Offer a "Declare missing methods of INTERFACE" code action.
// See [stubMethodsFixer] for command implementation.
msg := typeError.Error()
if strings.Contains(msg, "missing method") ||
strings.HasPrefix(msg, "cannot convert") ||
strings.Contains(msg, "not implement") {
// See [stubMissingInterfaceMethodsFixer] for command implementation.
case strings.Contains(msg, "missing method"),
strings.HasPrefix(msg, "cannot convert"),
strings.Contains(msg, "not implement"):
path, _ := astutil.PathEnclosingInterval(req.pgf.File, start, end)
si := stubmethods.GetStubInfo(req.pkg.FileSet(), info, path, start)
si := stubmethods.GetIfaceStubInfo(req.pkg.FileSet(), info, path, start)
if si != nil {
qf := typesutil.FileQualifier(req.pgf.File, si.Concrete.Obj().Pkg(), info)
iface := types.TypeString(si.Interface.Type(), qf)
msg := fmt.Sprintf("Declare missing methods of %s", iface)
req.addApplyFixAction(msg, fixStubMethods, req.loc)
req.addApplyFixAction(msg, fixMissingInterfaceMethods, req.loc)
}
// "type X has no field or method Y" compiler error.
// Offer a "Declare missing method of T.f" code action.
// See [stubMissingCalledFunctionFixer] for command implementation.
case strings.Contains(msg, "has no field or method"):
path, _ := astutil.PathEnclosingInterval(req.pgf.File, start, end)
si := stubmethods.GetCallStubInfo(req.pkg.FileSet(), info, path, start)
if si != nil {
msg := fmt.Sprintf("Declare missing method of %s.%s", si.Receiver.Obj().Name(), si.MethodName)
req.addApplyFixAction(msg, fixMissingCalledFunction, req.loc)
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion gopls/internal/golang/completion/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"golang.org/x/tools/gopls/internal/golang/completion/snippet"
"golang.org/x/tools/gopls/internal/protocol"
"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"
"golang.org/x/tools/internal/typesinternal"
Expand Down Expand Up @@ -62,7 +63,7 @@ func (c *completer) item(ctx context.Context, cand candidate) (CompletionItem, e
if isTypeName(obj) && c.wantTypeParams() {
// obj is a *types.TypeName, so its type must be Alias|Named.
tparams := typesinternal.TypeParams(obj.Type().(typesinternal.NamedOrAlias))
label += golang.FormatTypeParams(tparams)
label += typesutil.FormatTypeParams(tparams)
insert = label // maintain invariant above (label == insert)
}

Expand Down
34 changes: 18 additions & 16 deletions gopls/internal/golang/fix.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,15 @@ func singleFile(fixer1 singleFileFixer) fixer {

// Names of ApplyFix.Fix created directly by the CodeAction handler.
const (
fixExtractVariable = "extract_variable"
fixExtractFunction = "extract_function"
fixExtractMethod = "extract_method"
fixInlineCall = "inline_call"
fixInvertIfCondition = "invert_if_condition"
fixSplitLines = "split_lines"
fixJoinLines = "join_lines"
fixStubMethods = "stub_methods"
fixExtractVariable = "extract_variable"
fixExtractFunction = "extract_function"
fixExtractMethod = "extract_method"
fixInlineCall = "inline_call"
fixInvertIfCondition = "invert_if_condition"
fixSplitLines = "split_lines"
fixJoinLines = "join_lines"
fixMissingInterfaceMethods = "stub_missing_interface_method"
fixMissingCalledFunction = "stub_missing_called_function"
)

// ApplyFix applies the specified kind of suggested fix to the given
Expand Down Expand Up @@ -102,14 +103,15 @@ func ApplyFix(ctx context.Context, fix string, snapshot *cache.Snapshot, fh file

// Ad-hoc fixers: these are used when the command is
// constructed directly by logic in server/code_action.
fixExtractFunction: singleFile(extractFunction),
fixExtractMethod: singleFile(extractMethod),
fixExtractVariable: singleFile(extractVariable),
fixInlineCall: inlineCall,
fixInvertIfCondition: singleFile(invertIfCondition),
fixSplitLines: singleFile(splitLines),
fixJoinLines: singleFile(joinLines),
fixStubMethods: stubMethodsFixer,
fixExtractFunction: singleFile(extractFunction),
fixExtractMethod: singleFile(extractMethod),
fixExtractVariable: singleFile(extractVariable),
fixInlineCall: inlineCall,
fixInvertIfCondition: singleFile(invertIfCondition),
fixSplitLines: singleFile(splitLines),
fixJoinLines: singleFile(joinLines),
fixMissingInterfaceMethods: stubMissingInterfaceMethodsFixer,
fixMissingCalledFunction: stubMissingCalledFunctionFixer,
}
fixer, ok := fixers[fix]
if !ok {
Expand Down
Loading