From 74f147daacab40800ec9c82ef31586d72db27af6 Mon Sep 17 00:00:00 2001 From: darxnet Date: Thu, 12 Nov 2026 18:50:18 +0100 Subject: [PATCH 1/2] fix: generate Reset for generic structs The generator panicked on a generic struct (go/types cannot size a type parameter), and the template would have declared the receiver without its type parameters. Reset now names them (func (r *Pair[K, V]) Reset()), resets a type-parameter field to *new(T), and the cost model sizes each type parameter as a pointer. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +++ goreset.go | 73 ++++++++++++++++++++++++++++++++----- regression_test.go | 91 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 160 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 6304260..c0bc317 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ func (r *Request) Reset() { | `sync/atomic` types | `Store(0)` / `Store(false)` / `Store(nil)`; `atomic.Value` is set to its zero value | | `sync.*` (Mutex, WaitGroup, Pool...) | left alone | | `_` (padding) | left out: field by field it is not touched, bulk mode zeroes it | +| type parameter `T` | `*new(T)`, its zero value, whatever its constraint | Struct tags change the treatment of a field: @@ -145,6 +146,10 @@ for tools that want the source without the file. handled by hand, or released through `release=`. - A nested value's `Reset()` is called after the bulk assignment, so it sees its own state, not zeroes. +- A generic struct gets one `Reset` for all its instantiations + (`func (r *Pair[K, V]) Reset()`). The cost model sizes each type parameter + as one pointer, so the choice of mode is a guess for the instantiations + that are much larger. ## See also diff --git a/goreset.go b/goreset.go index 1943905..1f12e85 100644 --- a/goreset.go +++ b/goreset.go @@ -97,6 +97,11 @@ func (p *Package) Analyze(typeName string) (Result, error) { return res, fmt.Errorf("goreset: %s is not a struct", typeName) } + typeExpr, sized, err := p.generic(obj, structType) + if err != nil { + return res, err + } + var ( imports []string // tagImports come from `reset:"import=..."` tags. Field-wise code names @@ -166,7 +171,7 @@ func (p *Package) Analyze(typeName string) (Result, error) { }) default: - fields = append(fields, p.resetCode(f, opts.release, &names)) + fields = append(fields, p.resetCode(f, sized.Field(i).Type(), opts.release, &names)) } } @@ -188,7 +193,7 @@ func (p *Package) Analyze(typeName string) (Result, error) { kept int ) - structSize := p.sizes.Sizeof(obj.Type()) + structSize := p.sizes.Sizeof(sized) res.BulkCost = units(structSize) for i := range fields { @@ -232,6 +237,7 @@ func (p *Package) Analyze(typeName string) (Result, error) { data := struct { PackageName string TypeName string + TypeExpr string Fields []fieldInfo Imports []string Reasons []string @@ -239,6 +245,7 @@ func (p *Package) Analyze(typeName string) (Result, error) { }{ PackageName: p.pkg.Name(), TypeName: typeName, + TypeExpr: typeExpr, Fields: fields, Imports: imports, Reasons: reasons, @@ -246,7 +253,7 @@ func (p *Package) Analyze(typeName string) (Result, error) { } var buf bytes.Buffer - if err := tmpl.Execute(&buf, data); err != nil { + if err = tmpl.Execute(&buf, data); err != nil { return res, fmt.Errorf("goreset: template: %w", err) } @@ -292,7 +299,9 @@ func cut(part, prefix string, dst *string) bool { return ok } -func (p *Package) resetCode(f *types.Var, release string, names *importNames) fieldInfo { +// resetCode is the code that resets field f; sized is f's type with any type +// parameters replaced, whose size the model can take. +func (p *Package) resetCode(f *types.Var, sized types.Type, release string, names *importNames) fieldInfo { var ( info fieldInfo imports []string @@ -313,6 +322,15 @@ func (p *Package) resetCode(f *types.Var, release string, names *importNames) fi info.Weight = costStore // the common case: one statement, nothing to keep + // A type parameter has no zero literal of its own, whatever its + // constraint: *new(T) is its zero value. It is not reset through a Reset + // in its constraint either, as that would panic on a nil pointer. + if _, ok := types.Unalias(f.Type()).(*types.TypeParam); ok { + info.Code = fmt.Sprintf("r.%s = *new(%s)", info.Field, typeName) + + return info + } + // The sync/atomic types are stored to, but Value is zeroed by the // assignment below: its Store panics on nil and on a type other than // the one stored before, so it has no zero to store. @@ -369,7 +387,7 @@ func (p *Package) resetCode(f *types.Var, release string, names *importNames) fi info.Code = fmt.Sprintf("r.%s.Reset()", info.Field) info.Keep = fmt.Sprintf("keep%s := r.%s", info.Field, info.Field) info.Restore = fmt.Sprintf("r.%s = keep%s\n\tr.%s.Reset()", info.Field, info.Field, info.Field) - info.BulkExtra = costKeep + 2*units(p.sizes.Sizeof(f.Type())) + info.BulkExtra = costKeep + 2*units(p.sizes.Sizeof(sized)) p.forbidCopy(&info, f.Type()) return info @@ -415,11 +433,48 @@ func (p *Package) resetCode(f *types.Var, release string, names *importNames) fi // arrays and structs without Reset: assign the zero value, a memclr of the field info.Imports = imports info.Code = fmt.Sprintf("r.%s = %s{}", info.Field, typeName) - info.Weight = units(p.sizes.Sizeof(f.Type())) + info.Weight = units(p.sizes.Sizeof(sized)) return info } +// generic returns how the generated code spells the type named by obj, with +// its type parameters (Pair[K, V]), and the struct whose sizes the cost model +// takes: a generic type has none until instantiated, so each type parameter +// is replaced by a pointer-sized placeholder. +func (p *Package) generic(obj types.Object, st *types.Struct) (string, *types.Struct, error) { + named, ok := obj.Type().(*types.Named) + if !ok || named.TypeParams().Len() == 0 { + return obj.Name(), st, nil + } + + tparams := named.TypeParams() + names := make([]string, tparams.Len()) + placeholders := make([]types.Type, tparams.Len()) + + for i := range tparams.Len() { + names[i] = tparams.At(i).Obj().Name() + if names[i] == "r" || names[i] == "_" { + return "", nil, fmt.Errorf("goreset: %s has a type parameter named %s, "+ + "which the receiver of Reset cannot refer to; rename it", obj.Name(), names[i]) + } + + placeholders[i] = types.Typ[types.UnsafePointer] + } + + inst, err := types.Instantiate(nil, named, placeholders, false) + if err != nil { + return "", nil, fmt.Errorf("goreset: size %s: %w", obj.Name(), err) + } + + sized, ok := inst.Underlying().(*types.Struct) + if !ok { + return "", nil, fmt.Errorf("goreset: %s is not a struct", obj.Name()) + } + + return obj.Name() + "[" + strings.Join(names, ", ") + "]", sized, nil +} + // hasPointers reports whether a value of type t holds a pointer the garbage // collector follows: a string, a pointer, a slice, a map, a channel, a func, // an interface, or an array or struct with one of those. @@ -609,14 +664,14 @@ import ( {{- if .Bulk}} // Reset zeroes r in one assignment and gives the slices their arrays back. -func (r *{{.TypeName}}) Reset() { +func (r *{{.TypeExpr}}) Reset() { {{- range .Fields}} {{- if .Keep}} {{.Keep}} {{- end}} {{- end}} - *r = {{.TypeName}}{} + *r = {{.TypeExpr}}{} {{- range .Fields}} {{- if .Restore}} @@ -630,7 +685,7 @@ func (r *{{.TypeName}}) Reset() { {{- range .Reasons}} // - {{.}} {{- end}} -func (r *{{.TypeName}}) Reset() { +func (r *{{.TypeExpr}}) Reset() { {{- range .Fields}} {{.Code}} {{- end}} diff --git a/regression_test.go b/regression_test.go index d43c4fc..05538c0 100644 --- a/regression_test.go +++ b/regression_test.go @@ -466,3 +466,94 @@ func TestReset(t *testing.T) { t.Errorf("Bulk is not reset in one assignment:\n%s", srcs["Bulk"]) } } + +func TestGeneric(t *testing.T) { + t.Parallel() + + srcs := checkGenerated(t, "generic", map[string]string{ + "m.go": `package m + +import "sync" + +type Pair[K comparable, V any] struct { + Key K + Val V + Items []V + Index map[K]V + Next *Pair[K, V] +} + +type Guarded[T any, P interface { + *T + Reset() +}] struct { + Mu sync.Mutex + Val T + Ptr P + Inner Pair[string, T] + Nums [4]T + N int +} + +type Slicy[S ~[]E, E any] struct { + Items S + Last E +} +`, + "m_test.go": `package m + +import "testing" + +type item struct{ n int } + +func (i *item) Reset() { i.n = 0 } + +func TestReset(t *testing.T) { + next := &Pair[string, int]{} + p := Pair[string, int]{Key: "k", Val: 1, Items: []int{1, 2}, Index: map[string]int{"k": 1}, Next: next} + p.Reset() + + if p.Key != "" || p.Val != 0 || len(p.Items) != 0 || cap(p.Items) != 2 || p.Index != nil || p.Next != nil { + t.Fatalf("Pair = %+v, want zero with the array kept", p) + } + + g := Guarded[item, *item]{Val: item{1}, Ptr: &item{2}, Inner: Pair[string, item]{Key: "k"}, Nums: [4]item{{3}}, N: 4} + g.Mu.Lock() + g.Reset() + g.Mu.Unlock() + + if g.Val != (item{}) || g.Ptr != nil || g.Inner.Key != "" || g.Nums != [4]item{} || g.N != 0 { + t.Fatalf("Guarded = %+v %+v %+v %+v %d, want zero", g.Val, g.Ptr, g.Inner, g.Nums, g.N) + } + + s := Slicy[[]int, int]{Items: []int{1}, Last: 1} + s.Reset() + + if s.Items != nil || s.Last != 0 { + t.Fatalf("Slicy = %+v, want zero", s) + } +} +`, + }, "Pair", "Guarded", "Slicy") + + if !strings.Contains(srcs["Guarded"], "func (r *Guarded[T, P]) Reset()") { + t.Errorf("Guarded: receiver without its type parameters:\n%s", srcs["Guarded"]) + } +} + +func TestGenericReceiverName(t *testing.T) { + t.Parallel() + + dir := writeModule(t, "recvname", map[string]string{ + "m.go": "package m\n\ntype Box[r any] struct{ V r }\n", + }) + + pkg, err := goreset.Load(dir) + if err != nil { + t.Fatal(err) + } + + if _, err := pkg.Generate("Box"); err == nil { + t.Fatal("Generate(Box) succeeded with a type parameter named r, the receiver's name") + } +} From edc3922da355e10e9f07a36d755f86ac068e31b0 Mon Sep 17 00:00:00 2001 From: darxnet Date: Thu, 12 Nov 2026 19:12:49 +0100 Subject: [PATCH 2/2] fix: reset generic pointer fields through Reset, compile call= on type parameters A type-parameter field whose constraint lets only pointers in and has Reset (P interface{ *T; Reset() }) is now kept and reset when not nil, like any pointer with Reset. call= on a type parameter that is not only pointers generated r.F != nil, which does not compile; it now calls the method without the check. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 ++-- goreset.go | 71 ++++++++++++++++++++++++++++++++++++++++------ regression_test.go | 52 ++++++++++++++++++++++++++++----- 3 files changed, 110 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index c0bc317..b24b233 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,8 @@ func (r *Request) Reset() { | `sync/atomic` types | `Store(0)` / `Store(false)` / `Store(nil)`; `atomic.Value` is set to its zero value | | `sync.*` (Mutex, WaitGroup, Pool...) | left alone | | `_` (padding) | left out: field by field it is not touched, bulk mode zeroes it | -| type parameter `T` | `*new(T)`, its zero value, whatever its constraint | +| type parameter `T` | `*new(T)`, its zero value, even when its constraint has `Reset()`: the call could not be guarded against nil | +| type parameter `P` that only pointers satisfy and that has `Reset()` (`P interface{ *T; Reset() }`) | like a pointer with its own `Reset()`: kept; `r.F.Reset()` when not nil | Struct tags change the treatment of a field: @@ -57,7 +58,7 @@ Struct tags change the treatment of a field: | `reset:"-"` | the field is left as it is | | `reset:"value=EXPR"` | set to `EXPR` instead of zero, e.g. `value=^uint32(0)` | | `reset:"value=pkg.Const,import=example.com/pkg"` | the same with an import the expression needs | -| `reset:"call=Method"` | kept; `r.F.Method()` is called (`call=Stop` for a `*time.Timer`) | +| `reset:"call=Method"` | kept; `r.F.Method()` is called (`call=Stop` for a `*time.Timer`), when not nil if the field can be nil; a type parameter that is not only pointers cannot be checked for nil, so the method is called whatever the value | | `reset:"release=Func"` | pointer with `Reset()`: `Func(r.F)` is called and the field set to nil | ## Two modes diff --git a/goreset.go b/goreset.go index 1f12e85..0669250 100644 --- a/goreset.go +++ b/goreset.go @@ -322,10 +322,15 @@ func (p *Package) resetCode(f *types.Var, sized types.Type, release string, name info.Weight = costStore // the common case: one statement, nothing to keep - // A type parameter has no zero literal of its own, whatever its - // constraint: *new(T) is its zero value. It is not reset through a Reset - // in its constraint either, as that would panic on a nil pointer. - if _, ok := types.Unalias(f.Type()).(*types.TypeParam); ok { + // A pointer, or a type parameter whose constraint allows only pointers + // (P interface{ *T; Reset() }): either can be compared with nil. + ptr := isPointer(f.Type()) + + // A type parameter has no zero literal of its own: *new(T) is its zero + // value. One that is a pointer with Reset is kept and reset like any such + // pointer below; any other is zeroed even when its constraint has Reset, + // as the call could not be guarded against a nil pointer. + if _, ok := types.Unalias(f.Type()).(*types.TypeParam); ok && (!ptr || !hasResetMethod(f.Type())) { info.Code = fmt.Sprintf("r.%s = *new(%s)", info.Field, typeName) return info @@ -362,8 +367,8 @@ func (p *Package) resetCode(f *types.Var, sized types.Type, release string, name // An interface is set to nil even when its method set has Reset: the // call would panic on a nil value and keep a non-nil one. - if _, ok := f.Type().Underlying().(*types.Interface); !ok && hasResetMethod(f.Type()) { - if _, ok := f.Type().(*types.Pointer); ok { + if _, iface := f.Type().Underlying().(*types.Interface); (ptr || !iface) && hasResetMethod(f.Type()) { + if ptr { if release != "" { info.Code = fmt.Sprintf("if r.%s != nil { %s(r.%s); r.%s = nil }", info.Field, release, info.Field, info.Field) info.Keep = fmt.Sprintf("if r.%s != nil { %s(r.%s) }", info.Field, release, info.Field) @@ -551,10 +556,13 @@ func callCode(f *types.Var, method string) fieldInfo { info := fieldInfo{Field: f.Name(), Weight: costStore, BulkExtra: costKeep} info.Keep = fmt.Sprintf("keep%s := r.%s", info.Field, info.Field) - switch f.Type().Underlying().(type) { - case *types.Pointer, *types.Interface: + _, tparam := types.Unalias(f.Type()).(*types.TypeParam) + _, iface := f.Type().Underlying().(*types.Interface) + + // a type parameter cannot be compared with nil unless it is a pointer + if isPointer(f.Type()) || (iface && !tparam) { info.Code = fmt.Sprintf("if r.%s != nil { r.%s.%s() }", info.Field, info.Field, method) - default: + } else { info.Code = fmt.Sprintf("r.%s.%s()", info.Field, method) } @@ -563,6 +571,51 @@ func callCode(f *types.Var, method string) fieldInfo { return info } +// isPointer reports whether t is a pointer type, or a type parameter whose +// constraint lets only pointers in, like P in [T any, P interface{ *T }]. +func isPointer(t types.Type) bool { + switch t := types.Unalias(t).(type) { + case *types.Pointer: + return true + case *types.TypeParam: + return pointersOnly(t.Constraint()) + default: + return false + } +} + +// pointersOnly reports whether the type set of the constraint c holds only +// pointers: one of the terms it embeds (an interface's type set is the +// intersection of them) is a pointer, or a union of pointers. +func pointersOnly(c types.Type) bool { + iface, ok := c.Underlying().(*types.Interface) + if !ok { + return false + } + + for embedded := range iface.EmbeddedTypes() { + switch e := types.Unalias(embedded).(type) { + case *types.Union: + all := e.Len() > 0 + for term := range e.Terms() { + if _, ok := term.Type().Underlying().(*types.Pointer); !ok { + all = false + } + } + + if all { + return true + } + default: + if _, ok := e.Underlying().(*types.Pointer); ok || pointersOnly(e) { + return true + } + } + } + + return false +} + // isForbidden reports whether a field of this type must not be touched: the // sync types (Mutex, RWMutex, WaitGroup, Once, Pool...) cannot be copied and // are not meant to be reset. diff --git a/regression_test.go b/regression_test.go index 05538c0..01b2016 100644 --- a/regression_test.go +++ b/regression_test.go @@ -495,6 +495,34 @@ type Guarded[T any, P interface { N int } +type item struct{ n int } + +func (i *item) Reset() { i.n = 0 } + +type other struct{ n int } + +func (o *other) Reset() { o.n = 0 } + +type Resetter interface{ Reset() } + +type PtrTo[T any] interface { + *T + Resetter +} + +// Held has type parameters with Reset: only the ones that are pointers can +// be checked for nil, so only they are kept and reset without a tag. +type Held[T Resetter, P PtrTo[item], U interface { + *item | *other + Reset() +}] struct { + Zeroed T + Called T ` + "`" + `reset:"call=Reset"` + "`" + ` + Kept P + Union U + N int +} + type Slicy[S ~[]E, E any] struct { Items S Last E @@ -504,10 +532,6 @@ type Slicy[S ~[]E, E any] struct { import "testing" -type item struct{ n int } - -func (i *item) Reset() { i.n = 0 } - func TestReset(t *testing.T) { next := &Pair[string, int]{} p := Pair[string, int]{Key: "k", Val: 1, Items: []int{1, 2}, Index: map[string]int{"k": 1}, Next: next} @@ -517,15 +541,29 @@ func TestReset(t *testing.T) { t.Fatalf("Pair = %+v, want zero with the array kept", p) } - g := Guarded[item, *item]{Val: item{1}, Ptr: &item{2}, Inner: Pair[string, item]{Key: "k"}, Nums: [4]item{{3}}, N: 4} + ptr := &item{2} + g := Guarded[item, *item]{Val: item{1}, Ptr: ptr, Inner: Pair[string, item]{Key: "k"}, Nums: [4]item{{3}}, N: 4} g.Mu.Lock() g.Reset() g.Mu.Unlock() - if g.Val != (item{}) || g.Ptr != nil || g.Inner.Key != "" || g.Nums != [4]item{} || g.N != 0 { + if g.Val != (item{}) || g.Ptr != ptr || ptr.n != 0 || g.Inner.Key != "" || g.Nums != [4]item{} || g.N != 0 { t.Fatalf("Guarded = %+v %+v %+v %+v %d, want zero", g.Val, g.Ptr, g.Inner, g.Nums, g.N) } + called, kept, union := &item{2}, &item{3}, &other{4} + h := Held[*item, *item, *other]{Zeroed: &item{1}, Called: called, Kept: kept, Union: union, N: 5} + h.Reset() + + if h.Zeroed != nil || h.Called != called || h.Kept != kept || h.Union != union || h.N != 0 || + called.n != 0 || kept.n != 0 || union.n != 0 { + t.Fatalf("Held = %+v, want Zeroed nil, the others kept and reset", h) + } + + // nil pointers are not called, but call= is called whatever the value is + empty := Held[*item, *item, *other]{Called: &item{}} + empty.Reset() + s := Slicy[[]int, int]{Items: []int{1}, Last: 1} s.Reset() @@ -534,7 +572,7 @@ func TestReset(t *testing.T) { } } `, - }, "Pair", "Guarded", "Slicy") + }, "Pair", "Guarded", "Held", "Slicy") if !strings.Contains(srcs["Guarded"], "func (r *Guarded[T, P]) Reset()") { t.Errorf("Guarded: receiver without its type parameters:\n%s", srcs["Guarded"])