From 5f30384a38fbaf470202e33139000174892ad371 Mon Sep 17 00:00:00 2001 From: Denis Date: Tue, 3 Dec 2024 22:04:24 +0100 Subject: [PATCH] x/tools/gopls: implement struct field generation quickfix --- gopls/doc/features/diagnostics.md | 29 +++ gopls/doc/release/v0.17.0.md | 10 +- gopls/internal/golang/codeaction.go | 83 ++++++++- gopls/internal/golang/fix.go | 2 + gopls/internal/golang/stub.go | 76 ++++++++ .../marker/testdata/quickfix/struct_field.txt | 132 ++++++++++++++ gopls/internal/util/typesutil/typesutil.go | 167 ++++++++++++++++++ 7 files changed, 496 insertions(+), 3 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 21015bcaa35..4391a85f72a 100644 --- a/gopls/doc/features/diagnostics.md +++ b/gopls/doc/features/diagnostics.md @@ -248,6 +248,35 @@ func doSomething(i int) string { panic("unimplemented") } ``` + +### `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 +} +``` +