Skip to content

Commit e46688f

Browse files
committed
gopls/internal/analysis/fillstruct: don't panic with invalid fields
Fixes golang/go#63921 Change-Id: Ic7c310f39cd92c93b9fd6cc78a35ab88ba6b3f7b Reviewed-on: https://go-review.googlesource.com/c/tools/+/549116 Reviewed-by: Alan Donovan <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]>
1 parent 8bd7553 commit e46688f

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

gopls/internal/analysis/fillstruct/fillstruct.go

+9-1
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,8 @@ func indent(str, ind []byte) []byte {
345345
//
346346
// The reasoning here is that users will call fillstruct with the intention of
347347
// initializing the struct, in which case setting these fields to nil has no effect.
348+
//
349+
// populateValue returns nil if the value cannot be filled.
348350
func populateValue(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr {
349351
switch u := typ.Underlying().(type) {
350352
case *types.Basic:
@@ -357,6 +359,8 @@ func populateValue(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr {
357359
return &ast.BasicLit{Kind: token.STRING, Value: `""`}
358360
case u.Kind() == types.UnsafePointer:
359361
return ast.NewIdent("nil")
362+
case u.Kind() == types.Invalid:
363+
return nil
360364
default:
361365
panic(fmt.Sprintf("unknown basic type %v", u))
362366
}
@@ -478,9 +482,13 @@ func populateValue(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr {
478482
},
479483
}
480484
default:
485+
x := populateValue(f, pkg, u.Elem())
486+
if x == nil {
487+
return nil
488+
}
481489
return &ast.UnaryExpr{
482490
Op: token.AND,
483-
X: populateValue(f, pkg, u.Elem()),
491+
X: x,
484492
}
485493
}
486494

gopls/internal/test/marker/testdata/codeaction/fill_struct.txt

+14
Original file line numberDiff line numberDiff line change
@@ -558,3 +558,17 @@ func _[T any]() {
558558
+ _ = S{
559559
+ t: *new(T),
560560
+ } //@codeactionedit("}", "refactor.rewrite", typeparams5)
561+
-- issue63921.go --
562+
package fillstruct
563+
564+
// Test for golang/go#63921: fillstruct panicked with invalid fields.
565+
type invalidStruct struct {
566+
F int
567+
Undefined
568+
}
569+
570+
func _() {
571+
// Note: the golden content for issue63921 is empty: fillstruct produces no
572+
// edits, but does not panic.
573+
invalidStruct{} //@codeactionedit("}", "refactor.rewrite", issue63921)
574+
}

0 commit comments

Comments
 (0)