Skip to content

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

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

Closed
wants to merge 8 commits into from
Closed
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
30 changes: 29 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 of I

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 @@ -169,6 +169,34 @@ position.
client there, or a progress notification indicating that something
happened.)

### `StubMissingCalledFunction`: Declare missing method T.f

When you attempt to call a method on a type that does not have that method,
the compiler will report an error such as "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, inferring its type from the 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) // error: f.bar undefined (type Foo has no field or method bar)
}
```

Gopls will offer a quick fix, "Declare missing method Foo.bar".
When invoked, it creates the following declaration:

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

<!--

dorky details and deletia:
Expand Down
9 changes: 9 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,12 @@ 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.
The stub method's signature is inferred
from the context of the call.
26 changes: 19 additions & 7 deletions gopls/internal/golang/codeaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,20 +301,32 @@ 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 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 %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