Skip to content

Commit 0ccdb5c

Browse files
committed
unused: don't crash on generic composite literals
(cherry picked from commit 1cd2556)
1 parent 90a3456 commit 0ccdb5c

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

unused/testdata/src/typeparams/typeparams.go

+5
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,8 @@ type foo struct{} // used
8484
type Bar *Node[foo] // used
8585

8686
func (n Node[T]) anyMethod() {} // unused
87+
88+
func fn11[T ~struct{ Field int }]() { // unused
89+
// don't crash because of the composite literal
90+
_ = T{Field: 42}
91+
}

unused/unused.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -1630,12 +1630,17 @@ func (g *graph) instructions(fn *ir.Function) {
16301630
}
16311631
switch instr := instr.(type) {
16321632
case *ir.Field:
1633+
// Can't access fields via generics, for now.
1634+
16331635
st := instr.X.Type().Underlying().(*types.Struct)
16341636
field := st.Field(instr.Field)
16351637
// (4.7) functions use fields they access
16361638
g.seeAndUse(field, fnObj, edgeFieldAccess)
16371639
case *ir.FieldAddr:
1638-
st := typeutil.Dereference(instr.X.Type()).Underlying().(*types.Struct)
1640+
// User code can't access fields on type parameters, but composite literals are still possible, which
1641+
// compile to FieldAddr + Store.
1642+
1643+
st := typeutil.CoreType(typeutil.Dereference(instr.X.Type())).(*types.Struct)
16391644
field := st.Field(instr.Field)
16401645
// (4.7) functions use fields they access
16411646
g.seeAndUse(field, fnObj, edgeFieldAccess)

0 commit comments

Comments
 (0)