From 9a6d22aa31189abc4368f8093175f1b2e8fbbc41 Mon Sep 17 00:00:00 2001 From: Denis Date: Sun, 17 Nov 2024 21:40:57 +0100 Subject: [PATCH] x/tools/gopls: Implement struct field generation quickfix --- gopls/doc/features/diagnostics.md | 28 +++ gopls/doc/release/v0.17.0.md | 8 + gopls/internal/golang/codeaction.go | 83 ++++++- gopls/internal/golang/fix.go | 2 + gopls/internal/golang/stub.go | 76 ++++++ .../golang/stubmethods/stubcalledfunc.go | 223 +++++++++++++++++- gopls/internal/golang/type_definition.go | 1 + .../marker/testdata/quickfix/struct_field.txt | 132 +++++++++++ 8 files changed, 549 insertions(+), 4 deletions(-) create mode 100644 gopls/internal/test/marker/testdata/quickfix/struct_field.txt diff --git a/gopls/doc/features/diagnostics.md b/gopls/doc/features/diagnostics.md index 5955a55d8b3..505015328b3 100644 --- a/gopls/doc/features/diagnostics.md +++ b/gopls/doc/features/diagnostics.md @@ -197,6 +197,34 @@ func (f Foo) bar(s string, i int) string { } ``` +### `StubMissingStructField`: Declare missing field T.f + +When you attempt to access a field on a type that does not have the field, +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 field, inferring its type from the accessing type or assigning a designated value. + +Consider the following code where `Foo` does not have a field `bar`: + +```go +type Foo struct{} + +func main() { + var s string + f := Foo{} + s = f.bar // error: f.bar undefined (type Foo has no field or method bar) +} +``` + +Gopls will offer a quick fix, "Declare missing field Foo.bar". +When invoked, it creates the following declaration: + +```go +type Foo struct{ + bar string +} +``` +