Skip to content

Commit

Permalink
gopls/internal/analysis/fillstruct: don't panic with invalid fields
Browse files Browse the repository at this point in the history
Fixes golang/go#63921

Change-Id: Ic7c310f39cd92c93b9fd6cc78a35ab88ba6b3f7b
Reviewed-on: https://go-review.googlesource.com/c/tools/+/549116
Reviewed-by: Alan Donovan <adonovan@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
  • Loading branch information
findleyr committed Dec 12, 2023
1 parent 8bd7553 commit e46688f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
10 changes: 9 additions & 1 deletion gopls/internal/analysis/fillstruct/fillstruct.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,8 @@ func indent(str, ind []byte) []byte {
//
// The reasoning here is that users will call fillstruct with the intention of
// initializing the struct, in which case setting these fields to nil has no effect.
//
// populateValue returns nil if the value cannot be filled.
func populateValue(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr {
switch u := typ.Underlying().(type) {
case *types.Basic:
Expand All @@ -357,6 +359,8 @@ func populateValue(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr {
return &ast.BasicLit{Kind: token.STRING, Value: `""`}
case u.Kind() == types.UnsafePointer:
return ast.NewIdent("nil")
case u.Kind() == types.Invalid:
return nil
default:
panic(fmt.Sprintf("unknown basic type %v", u))
}
Expand Down Expand Up @@ -478,9 +482,13 @@ func populateValue(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr {
},
}
default:
x := populateValue(f, pkg, u.Elem())
if x == nil {
return nil
}
return &ast.UnaryExpr{
Op: token.AND,
X: populateValue(f, pkg, u.Elem()),
X: x,
}
}

Expand Down
14 changes: 14 additions & 0 deletions gopls/internal/test/marker/testdata/codeaction/fill_struct.txt
Original file line number Diff line number Diff line change
Expand Up @@ -558,3 +558,17 @@ func _[T any]() {
+ _ = S{
+ t: *new(T),
+ } //@codeactionedit("}", "refactor.rewrite", typeparams5)
-- issue63921.go --
package fillstruct

// Test for golang/go#63921: fillstruct panicked with invalid fields.
type invalidStruct struct {
F int
Undefined
}

func _() {
// Note: the golden content for issue63921 is empty: fillstruct produces no
// edits, but does not panic.
invalidStruct{} //@codeactionedit("}", "refactor.rewrite", issue63921)
}

0 comments on commit e46688f

Please sign in to comment.