diff --git a/README.md b/README.md index 99fb11e..74c5315 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,9 @@ func (dst *Request) CopyFrom(src *Request) { *dst = *src dst.Data = append(keepData, src.Data...) + if dst.Data == nil && src.Data != nil { + dst.Data = make([]byte, 0) + } dst.Inner = keepInner dst.Inner.CopyFrom(&src.Inner) } @@ -44,12 +47,29 @@ A `CopyFrom` into a pooled, already-sized `dst` allocates nothing. | Field | Copy | |---|---| -| slice | `append(dst.F[:0], src.F...)` — into dst's own array | +| slice | `append(dst.F[:0], src.F...)` — into dst's own array (nil only when src is nil and dst was: see below) | | map | entry by entry into dst's own map (`clear` first; a nil dst map is made, a nil src leaves dst empty) | | struct with `CopyFrom(*T)` | `dst.F.CopyFrom(&src.F)` | | pointer to struct with `CopyFrom(*T)` | into dst's own object; a nil dst gets a new one, a nil src gives nil | -| array of slices / of structs with `CopyFrom` | element by element | +| array | element by element, when the elements need a copy of their own | +| slice of slices, maps, structs with `CopyFrom` or pointers to them | element by element into dst's own elements, up to its capacity (a larger src gets a new array) | +| map of slices, maps, structs with `CopyFrom` or pointers to them | each value a new copy (dst's old values are dropped with `clear`) | | everything else (numbers, strings, pointers, interfaces, chans, funcs, plain structs) | assigned as it is | +| a type parameter `T` of a generic struct | assigned as it is, whatever the type argument (`Box[[]byte]` shares it) | + +A non-nil src slice or map gives a non-nil dst one, even when empty, so +`[]` stays `[]` in JSON. A nil src slice or map empties dst's but leaves it +non-nil when it was — dst keeps its memory for the next copy — so after +`CopyFrom` a nil and an empty one are not told apart; `Copy` starts from a +zero dst and keeps them apart. + +The rules apply at any depth: `[][]byte`, `map[string][]Inner` and +`[2][3][]byte` share nothing with src. A type that contains itself through +slices or maps (`type Tree []Tree`) has no end to copy: such a field needs a +tag. Map keys are assigned. + +A generic struct gets `func (dst *Box[T]) CopyFrom(src *Box[T])`; a +`[]T` or `map[K]V` field is still copied as a slice or a map. Struct tags change the treatment of a field: @@ -58,8 +78,12 @@ Struct tags change the treatment of a field: | `copy:"-"` | dst keeps its own value | | `copy:"shallow"` | assigned as it is, even if it is a slice or a map — on purpose, and visibly | -A field holding a `sync` or `sync/atomic` type (also inside a nested struct -or array, by value) **must** carry one of the two tags; an array of maps too. +A field holding a lock **must** carry one of the two tags. A lock is what +`go vet` copylocks calls one — a type whose pointer is a `sync.Locker` while +the value is not, so a custom `noCopy` counts — and any other `sync` or +`sync/atomic` type except an interface (`sync.Locker` itself is assigned), +also inside a nested struct or array, by value. Blank (`_`) fields are never +copied: dst keeps its own. ## Two modes @@ -99,8 +123,9 @@ type Request struct { This writes `request_copy.gen.go` and `response_copy.gen.go` in the same package. `-dir` points the generator at another package. -The generator is also a library — [`gocopy.Load`](https://pkg.go.dev/github.com/darxnet/gocopy#Load) -and [`Package.Generate`](https://pkg.go.dev/github.com/darxnet/gocopy#Package.Generate) — +The generator is also a library — [`gocopy.Load`](https://pkg.go.dev/github.com/darxnet/gocopy#Load), +[`Package.Generate`](https://pkg.go.dev/github.com/darxnet/gocopy#Package.Generate) and +[`Package.GenerateAll`](https://pkg.go.dev/github.com/darxnet/gocopy#Package.GenerateAll) — for tools that want the source without the file. ## Rules of the generated CopyFrom @@ -108,7 +133,14 @@ for tools that want the source without the file. - `src` and `dst` must not be the same value or share slices: `dst`'s arrays are overwritten. - A nested type's `CopyFrom` is found by its method set when the generator - runs: generate (or write) the inner type's first. + runs, or because the same run generates it: name all the types of a package + in one `-type` list (one `go:generate` line), and the output does not depend + on their order or on the files already there. A type generated by another + directive is seen only once its file exists, so the first `go generate` + and the second could differ. +- A pointer to the type itself (`Next *Node`) is copied recursively, from + the first run: a long chain costs as much stack, and cyclic data (a ring) + never ends — tag such a field `copy:"shallow"` to share it instead. - Pointers other than "pointer to a struct with CopyFrom" are shared with `src`. That is usually right for references to long-lived objects; for an owned object, give its type a `CopyFrom`. diff --git a/cmd/gocopy/main.go b/cmd/gocopy/main.go index 0654f23..3f7bd93 100644 --- a/cmd/gocopy/main.go +++ b/cmd/gocopy/main.go @@ -49,22 +49,26 @@ func run(args []string, stderr io.Writer) int { return 1 } + var typeNames []string + for typeName := range strings.SplitSeq(*typeFlag, ",") { - typeName = strings.TrimSpace(typeName) - if typeName == "" { - continue + if typeName = strings.TrimSpace(typeName); typeName != "" { + typeNames = append(typeNames, typeName) } + } - src, err := pkg.Generate(typeName) - if err != nil { - say("%v", err) + // one run: the types see each other's CopyFrom before it is written + srcs, err := pkg.GenerateAll(typeNames...) + if err != nil { + say("%v", err) - return 1 - } + return 1 + } + for i, typeName := range typeNames { name := filepath.Join(*dirFlag, gocopy.FileName(typeName)) - if err := os.WriteFile(name, src, 0o600); err != nil { + if err := os.WriteFile(name, srcs[i], 0o600); err != nil { say("gocopy: write %s: %v", name, err) return 1 diff --git a/cmd/gocopy/main_test.go b/cmd/gocopy/main_test.go index 16f5fe4..a4334b5 100644 --- a/cmd/gocopy/main_test.go +++ b/cmd/gocopy/main_test.go @@ -3,7 +3,9 @@ package main import ( "bytes" "os" + "os/exec" "path/filepath" + "slices" "strings" "testing" ) @@ -120,3 +122,88 @@ func TestRunWriteError(t *testing.T) { t.Fatalf("exit code %d, stderr %q, want a write error", code, stderr.String()) } } + +// TestRunIdempotent checks that a second run writes what the first did: a +// type sees the CopyFrom of a type generated in the same run (even listed +// after it), and of itself. +func TestRunIdempotent(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + + for name, content := range map[string]string{ + "go.mod": "module example.com/c\n\ngo 1.24\n", + "c.go": `package c + +type Request struct { + In Inner + Ptr *Inner +} + +type Inner struct{ B []byte } + +type Node struct { + Next *Node + Data []byte +} +`, + "c_test.go": `package c + +import "testing" + +func TestCopy(t *testing.T) { + src := Request{In: Inner{B: []byte("a")}, Ptr: &Inner{B: []byte("b")}} + dst := src.Copy() + src.In.B[0], src.Ptr.B[0] = 'X', 'X' + + if string(dst.In.B) != "a" || string(dst.Ptr.B) != "b" { + t.Fatalf("dst = %+v", dst) + } + + list := Node{Next: &Node{Data: []byte("n")}} + cp := list.Copy() + list.Next.Data[0] = 'X' + + if cp.Next == list.Next || string(cp.Next.Data) != "n" { + t.Fatal("Next must be copied") + } +} +`, + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + + files := []string{"request_copy.gen.go", "inner_copy.gen.go", "node_copy.gen.go"} + runs := make([][]string, 2) + + for i := range runs { + var stderr bytes.Buffer + + if code := run([]string{"-dir", dir, "-type", "Request,Inner,Node"}, &stderr); code != 0 { + t.Fatalf("run %d: exit code %d: %s", i, code, stderr.String()) + } + + for _, name := range files { + src, err := os.ReadFile(filepath.Join(dir, name)) //nolint:gosec // a path under t.TempDir() + if err != nil { + t.Fatal(err) + } + + runs[i] = append(runs[i], string(src)) + } + } + + if !slices.Equal(runs[0], runs[1]) { + t.Fatalf("the second run differs:\n%s\n--- first run ---\n%s", + strings.Join(runs[1], "\n"), strings.Join(runs[0], "\n")) + } + + cmd := exec.Command("go", "test", "-count=1", ".") + cmd.Dir = dir + + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("go test: %v\n%s\n%s", err, out, strings.Join(runs[0], "\n")) + } +} diff --git a/doc.go b/doc.go index 8bd5645..72dbc65 100644 --- a/doc.go +++ b/doc.go @@ -5,21 +5,27 @@ // A generated CopyFrom(src) is one bulk assignment (*dst = *src) followed by // fixes for the fields that would otherwise share memory: slices are copied // into dst's own backing arrays (reusing their capacity), maps entry by entry -// into dst's own map, nested values with a CopyFrom through it. Pointers, -// interfaces, channels and funcs are assigned as they are. Struct tags choose -// a different treatment per field: +// into dst's own map, nested values with a CopyFrom through it — at any depth: +// the elements of a [][]byte or the values of a map[string][]byte get their +// own copies too. Pointers, interfaces, channels and funcs are assigned as +// they are. Struct tags choose a different treatment per field: // // Buf []byte `copy:"-"` // dst keeps its own value // Table []byte `copy:"shallow"` // assigned as it is, on purpose // // A struct holding a lock or an atomic (also nested, by value) cannot be // assigned as a whole: such fields must be tagged, the type is copied field -// by field, and it gets no Copy method. +// by field, and it gets no Copy method. A lock is what go vet copylocks calls +// one (a type whose pointer is a sync.Locker and value is not, so a custom +// noCopy too) and any other sync or sync/atomic type except an interface. // // The usual way to run it is a go:generate directive next to the type: // // //go:generate go tool gocopy -type=Request // -// which writes request_copy.gen.go in the same package. [Load] and -// [Package.Generate] expose the generator to other tools. +// which writes request_copy.gen.go in the same package. Name all the types of +// a package in one -type list: a type sees the CopyFrom of another (or of +// itself) generated in the same run, so the output does not depend on their +// order or on the files already generated. [Load], [Package.Generate] and +// [Package.GenerateAll] expose the generator to other tools. package gocopy diff --git a/export_test.go b/export_test.go new file mode 100644 index 0000000..804c158 --- /dev/null +++ b/export_test.go @@ -0,0 +1,3 @@ +package gocopy + +var IsLocalName = isLocalName diff --git a/gocopy.go b/gocopy.go index 037dd2e..05f90d9 100644 --- a/gocopy.go +++ b/gocopy.go @@ -2,10 +2,11 @@ package gocopy import ( "bytes" - "errors" "fmt" "go/format" + "go/token" "go/types" + "maps" "reflect" "slices" "strings" @@ -21,7 +22,6 @@ func FileName(typeName string) string { // Keep saves dst's own value before the bulk copy, Copy fills it from src after. type deepField struct { Field string - Import string Keep string // bulk mode: save dst's own value before `*dst = *src` Copy string // bulk mode: fill from src after, using the kept value Direct string // field-wise mode: the same, straight on dst @@ -29,8 +29,47 @@ type deepField struct { // Generate returns the gofmt-ed source of a file declaring // `func (dst *T) CopyFrom(src *T)` — and `func (src *T) Copy() T` when T holds -// no lock — for the struct type named typeName. +// no lock — for the struct type named typeName. It is GenerateAll for the one +// type. func (p *Package) Generate(typeName string) ([]byte, error) { + srcs, err := p.GenerateAll(typeName) + if err != nil { + return nil, err + } + + return srcs[0], nil +} + +// GenerateAll returns what Generate does for each of typeNames, as one run: +// a field of one of these types (or of a pointer to one) is copied through +// the CopyFrom being generated for it, whether or not a file of an earlier +// run declares it yet. The output thus does not depend on the order of the +// types or on the files already generated, and a type that refers to itself +// (Next *Node) copies the pointed-to value recursively from the first run. +func (p *Package) GenerateAll(typeNames ...string) ([][]byte, error) { + pending := make(map[*types.TypeName]bool, len(typeNames)) + + for _, typeName := range typeNames { + if obj, ok := p.pkg.Scope().Lookup(typeName).(*types.TypeName); ok { + pending[obj] = true + } + } + + srcs := make([][]byte, len(typeNames)) + + for i, typeName := range typeNames { + src, err := p.generate(typeName, pending) + if err != nil { + return nil, err + } + + srcs[i] = src + } + + return srcs, nil +} + +func (p *Package) generate(typeName string, pending map[*types.TypeName]bool) ([]byte, error) { obj := p.pkg.Scope().Lookup(typeName) if obj == nil { return nil, fmt.Errorf("gocopy: type %s not found in package %s", typeName, p.pkg.Name()) @@ -42,25 +81,54 @@ func (p *Package) Generate(typeName string) ([]byte, error) { } var ( - imports []string - fields []deepField - plain []deepField // field-wise mode: every field that is simply assigned + fields []deepField + plain []deepField // field-wise mode: every field that is simply assigned ) + g := &generator{ + p: p, + pending: pending, + copying: make(map[string]bool), + imports: make(map[string]goImport), + names: make(map[string]bool), + } + + // a generic type's methods name its type parameters in the receiver + recv, lockCheck := typeName, obj.Type() + + if named, ok := obj.Type().(*types.Named); ok && named.TypeParams().Len() > 0 { + params := make([]string, named.TypeParams().Len()) + for i := range params { + params[i] = named.TypeParams().At(i).Obj().Name() + if params[i] == "_" { // src's type must name it + params[i] = fmt.Sprintf("_%d", i) + } + + g.names[params[i]] = true // an import must not be shadowed by one + } + + recv += "[" + strings.Join(params, ", ") + "]" + lockCheck = structType // Implements is unspecified for an uninstantiated type + } + // A struct with a lock or an atomic inside (even nested) cannot be copied // with `*dst = *src` (go vet copylocks): then every field is copied on its own. - bulk := !containsLock(structType) + bulk := !isLockType(lockCheck) for i := range structType.NumFields() { f := structType.Field(i) tag := reflect.StructTag(structType.Tag(i)).Get("copy") + if f.Name() == "_" { + continue // a blank field cannot be referred to: dst keeps its own + } + if tag == "" && isLockType(f.Type()) { return nil, fmt.Errorf("gocopy: field %s.%s holds a lock or an atomic: "+ "tag it copy:\"-\" (keep dst's) or copy:\"shallow\" (copy anyway)", typeName, f.Name()) } - d, deep, err := p.deepCode(f, tag) + d, deep, err := g.deepCode(f, tag) if err != nil { return nil, fmt.Errorf("gocopy: field %s.%s: %w", typeName, f.Name(), err) } @@ -76,27 +144,19 @@ func (p *Package) Generate(typeName string) ([]byte, error) { } } - for _, f := range fields { - if f.Import != "" { - imports = append(imports, f.Import) - } - } - - imports = slices.Compact(slices.Sorted(slices.Values(imports))) - data := struct { PackageName string - TypeName string + Recv string Fields []deepField Plain []deepField - Imports []string + Imports []goImport Bulk bool }{ PackageName: p.pkg.Name(), - TypeName: typeName, + Recv: recv, Fields: fields, Plain: plain, - Imports: imports, + Imports: g.importList(), Bulk: bulk, } @@ -113,11 +173,18 @@ func (p *Package) Generate(typeName string) ([]byte, error) { return src, nil } -var errArrayOfMaps = errors.New("an array of maps: tag it copy:\"-\" or copy:\"shallow\"") +// generator holds the state of one generated file: the imports its code needs. +type generator struct { + p *Package + pending map[*types.TypeName]bool // the types generated in this run + copying map[string]bool // the slice and map types being copied, against recursion + imports map[string]goImport // by path + names map[string]bool // the names the imports take +} // deepCode describes how f is copied; deep is false for a field the bulk // assignment copies correctly on its own. -func (p *Package) deepCode(f *types.Var, tag string) (d deepField, deep bool, err error) { +func (g *generator) deepCode(f *types.Var, tag string) (d deepField, deep bool, err error) { name := f.Name() d = deepField{Field: name} @@ -134,143 +201,290 @@ func (p *Package) deepCode(f *types.Var, tag string) (d deepField, deep bool, er return d, false, nil } - switch ut := f.Type().Underlying().(type) { - case *types.Slice: - // nil src with nil dst stays nil + code, err := g.copyCode("dst."+name, "src."+name, f.Type(), 0) + if err != nil || code == "" { + return d, false, err + } + + d.Keep = fmt.Sprintf("keep%s := dst.%s", name, name) + d.Copy = fmt.Sprintf("dst.%s = keep%s\n%s", name, name, code) + d.Direct = code + + if s, ok := f.Type().Underlying().(*types.Slice); ok && g.plain(s.Elem()) { + // the slice is all there is to copy: keep its emptied array d.Keep = fmt.Sprintf("keep%s := dst.%s[:0]", name, name) - d.Copy = fmt.Sprintf("dst.%s = append(keep%s, src.%s...)", name, name, name) - d.Direct = fmt.Sprintf("dst.%s = append(dst.%s[:0], src.%s...)", name, name, name) + d.Copy = fmt.Sprintf("dst.%[1]s = append(keep%[1]s, src.%[1]s...)\n%[2]s", + name, nonNil("dst."+name, "src."+name, g.typeName(f.Type()))) + } - return d, true, nil + return d, true, nil +} + +// plain reports whether a value of type t is copied by assignment. +func (g *generator) plain(t types.Type) bool { + code, _ := g.copyCode("dst", "src", t, 0) + + return code == "" +} + +// copyCode returns the statements that make dst an independent copy of src, +// two addressable expressions of type t, reusing the memory dst owns; "" +// when `dst = src` is one already. depth names the loop variables. +func (g *generator) copyCode(dst, src string, t types.Type, depth int) (string, error) { + switch ut := t.Underlying().(type) { + case *types.Slice: + return g.nested(t, func() (string, error) { return g.sliceCode(dst, src, t, ut, depth) }) case *types.Map: - typeName := p.typeName(f.Type(), &d.Import) - d.Keep = fmt.Sprintf("keep%s := dst.%s", name, name) - d.Direct = fmt.Sprintf(`clear(dst.%[1]s) - if src.%[1]s != nil { - if dst.%[1]s == nil { - dst.%[1]s = make(%[2]s, len(src.%[1]s)) - } - for k, v := range src.%[1]s { - dst.%[1]s[k] = v + return g.nested(t, func() (string, error) { return g.mapCode(dst, src, t, ut, depth) }) + + case *types.Array: + i := loopVar("i", depth) + + code, err := g.copyCode(dst+"["+i+"]", src+"["+i+"]", ut.Elem(), depth+1) + if err != nil || code == "" { + return "", err } - }`, name, typeName) - d.Copy = fmt.Sprintf("dst.%[1]s = keep%[1]s\n\t%[2]s", name, d.Direct) - return d, true, nil + return fmt.Sprintf("for %s := range %s {\n%s\n}", i, src, code), nil case *types.Struct: - if hasCopyFrom(f.Type()) { - d.Keep = fmt.Sprintf("keep%s := dst.%s", name, name) - d.Copy = fmt.Sprintf("dst.%s = keep%s\n\tdst.%s.CopyFrom(&src.%s)", name, name, name, name) - d.Direct = fmt.Sprintf("dst.%s.CopyFrom(&src.%s)", name, name) - - return d, true, nil + if g.hasCopyFrom(t) { + return fmt.Sprintf("%s.CopyFrom(&%s)", dst, src), nil } - case *types.Array: - return arrayCode(name, ut) - case *types.Pointer: - if _, ok := ut.Elem().Underlying().(*types.Struct); ok && hasCopyFrom(ut.Elem()) { + if _, ok := ut.Elem().Underlying().(*types.Struct); ok && g.hasCopyFrom(ut.Elem()) { // dst keeps its own object and copies into it; a nil dst gets a new one - d.Keep = fmt.Sprintf("keep%s := dst.%s", name, name) - d.Direct = fmt.Sprintf(`if src.%[1]s == nil { - dst.%[1]s = nil - } else { - if dst.%[1]s == nil { - dst.%[1]s = new(%[2]s) + return fmt.Sprintf(`if %[2]s == nil { + %[1]s = nil +} else { + if %[1]s == nil { + %[1]s = new(%[3]s) + } + %[1]s.CopyFrom(%[2]s) +}`, dst, src, g.typeName(ut.Elem())), nil } - dst.%[1]s.CopyFrom(src.%[1]s) - }`, name, p.typeName(ut.Elem(), &d.Import)) - d.Copy = fmt.Sprintf("dst.%[1]s = keep%[1]s\n\t%[2]s", name, d.Direct) + } - return d, true, nil - } + return "", nil +} + +// nested runs code for the slice or map type t, failing when t contains +// itself (type L []L): its copy would never end. +func (g *generator) nested(t types.Type, code func() (string, error)) (string, error) { + key := t.String() + if g.copying[key] { + return "", fmt.Errorf("type %s contains itself: tag the field copy:\"-\" or copy:\"shallow\"", + types.TypeString(t, types.RelativeTo(g.p.pkg))) } - return d, false, nil + g.copying[key] = true + defer delete(g.copying, key) + + return code() } -func arrayCode(name string, ut *types.Array) (deepField, bool, error) { - d := deepField{Field: name} +func (g *generator) sliceCode(dst, src string, t types.Type, ut *types.Slice, depth int) (string, error) { + i := loopVar("i", depth) - switch ut.Elem().Underlying().(type) { - case *types.Slice: - // an array of slices would share every element's memory; copy element-wise - d.Keep = fmt.Sprintf("keep%s := dst.%s", name, name) - d.Direct = fmt.Sprintf(`for i := range src.%[1]s { - dst.%[1]s[i] = append(dst.%[1]s[i][:0], src.%[1]s[i]...) - }`, name) - d.Copy = fmt.Sprintf("dst.%[1]s = keep%[1]s\n\t%[2]s", name, d.Direct) + code, err := g.copyCode(dst+"["+i+"]", src+"["+i+"]", ut.Elem(), depth+1) + if err != nil { + return "", err + } - return d, true, nil + if code == "" { + return fmt.Sprintf("%[1]s = append(%[1]s[:0], %[2]s...)\n%[3]s", dst, src, nonNil(dst, src, g.typeName(t))), nil + } - case *types.Struct: - if !hasCopyFrom(ut.Elem()) { - return d, false, nil - } + // dst's elements, up to its capacity, are its own: copy into them + return fmt.Sprintf(`if cap(%[1]s) < len(%[2]s) || %[1]s == nil && %[2]s != nil { + %[1]s = make(%[3]s, len(%[2]s)) +} else { + %[1]s = %[1]s[:len(%[2]s)] +} +for %[4]s := range %[2]s { +%[5]s +}`, dst, src, g.typeName(t), i, code), nil +} - d.Keep = fmt.Sprintf("keep%s := dst.%s", name, name) - d.Direct = fmt.Sprintf(`for i := range src.%[1]s { - dst.%[1]s[i].CopyFrom(&src.%[1]s[i]) - }`, name) - d.Copy = fmt.Sprintf("dst.%[1]s = keep%[1]s\n\t%[2]s", name, d.Direct) +func (g *generator) mapCode(dst, src string, t types.Type, ut *types.Map, depth int) (string, error) { + k, v, w := loopVar("k", depth), loopVar("v", depth), loopVar("w", depth) - return d, true, nil + code, err := g.copyCode(w, v, ut.Elem(), depth+1) + if err != nil { + return "", err + } - case *types.Map: - return d, false, errArrayOfMaps + put := fmt.Sprintf("%s[%s] = %s", dst, k, v) + if code != "" { + // a value is a fresh copy: dst's old values are gone with clear + put = fmt.Sprintf("var %[1]s %[2]s\n%[3]s\n%[4]s[%[5]s] = %[1]s", w, g.typeName(ut.Elem()), code, dst, k) + } - default: - return d, false, nil + return fmt.Sprintf(`clear(%[1]s) +if %[2]s != nil { + if %[1]s == nil { + %[1]s = make(%[3]s, len(%[2]s)) } + for %[4]s, %[5]s := range %[2]s { + %[6]s + } +}`, dst, src, g.typeName(t), k, v, put), nil } -// typeName returns the name of t as seen from the package, recording the import it needs. -func (p *Package) typeName(t types.Type, importPath *string) string { - return types.TypeString(t, func(other *types.Package) string { - if p.pkg == other { - return "" - } +// nonNil returns the statement that makes the slice dst, after an append of +// src's elements, non-nil when src is: an empty src must not come out nil. +func nonNil(dst, src, typeName string) string { + return fmt.Sprintf(`if %[1]s == nil && %[2]s != nil { + %[1]s = make(%[3]s, 0) +}`, dst, src, typeName) +} + +// loopVar is the name of a variable of the generated code at depth: i, i_1, i_2... +func loopVar(name string, depth int) string { + if depth == 0 { + return name + } - *importPath = other.Path() + return fmt.Sprintf("%s_%d", name, depth) +} + +// goImport is one import of the generated file; Name is set when it differs +// from the package's own name. +type goImport struct { + Name, Path string +} + +// typeName returns the name of t as seen from the generated file, importing +// every package it refers to. +func (g *generator) typeName(t types.Type) string { + return types.TypeString(t, g.qualifier) +} + +// qualifier is the types.Qualifier of the generated file: a package gets its +// own name unless that is taken by another import, a declaration of the +// package, a predeclared identifier or a local variable of the generated code. +func (g *generator) qualifier(other *types.Package) string { + if other == g.p.pkg { + return "" + } + + if imp, ok := g.imports[other.Path()]; ok { + if imp.Name != "" { + return imp.Name + } return other.Name() - }) + } + + name := other.Name() + for n := 2; g.taken(name); n++ { + name = fmt.Sprintf("%s_%d", other.Name(), n) + } + + imp := goImport{Path: other.Path()} + if name != other.Name() { + imp.Name = name + } + + g.imports[other.Path()] = imp + g.names[name] = true + + return name } -// isLockType reports whether t is a sync or atomic type, or a struct holding one. +func (g *generator) taken(name string) bool { + return g.names[name] || g.p.pkg.Scope().Lookup(name) != nil || types.Universe.Lookup(name) != nil || + isLocalName(name) +} + +// isLocalName reports whether name may be a variable of the generated code: +// dst, src, keep, or a loop variable i, k, v, w (with a _ suffix +// when nested). +func isLocalName(name string) bool { + if name == "dst" || name == "src" || strings.HasPrefix(name, "keep") { + return true + } + + if !strings.ContainsAny(name[:1], "ikvw") { + return false + } + + rest, ok := strings.CutPrefix(name[1:], "_") + if !ok { + return rest == "" + } + + return rest != "" && strings.Trim(rest, "0123456789") == "" +} + +// importList returns the imports of the generated file, sorted by path. +func (g *generator) importList() []goImport { + list := make([]goImport, 0, len(g.imports)) + for _, path := range slices.Sorted(maps.Keys(g.imports)) { + list = append(list, g.imports[path]) + } + + return list +} + +// locker is sync.Locker, built here: the package being generated need not import sync. +var locker = func() *types.Interface { + sig := types.NewSignatureType(nil, nil, nil, nil, nil, false) + + return types.NewInterfaceType([]*types.Func{ + types.NewFunc(token.NoPos, nil, "Lock", sig), + types.NewFunc(token.NoPos, nil, "Unlock", sig), + }, nil).Complete() +}() + +// isLockType reports whether a value of type t must not be copied: a sync or +// sync/atomic type other than an interface, a struct whose pointer is a +// sync.Locker while the value is not (the rule of go vet copylocks, which +// catches a custom noCopy), or a struct or array holding one by value. func isLockType(t types.Type) bool { - if named, ok := t.(*types.Named); ok { - if p := named.Obj().Pkg(); p != nil && (p.Path() == "sync" || p.Path() == "sync/atomic") { + return lockType(t, make(map[types.Type]bool)) +} + +func lockType(t types.Type, seen map[types.Type]bool) bool { + if seen[t] { + return false + } + + seen[t] = true + + if named, ok := types.Unalias(t).(*types.Named); ok { + if p := named.Obj().Pkg(); p != nil && (p.Path() == "sync" || p.Path() == "sync/atomic") && !types.IsInterface(t) { return true } } switch ut := t.Underlying().(type) { case *types.Struct: - return containsLock(ut) + if types.Implements(types.NewPointer(t), locker) && !types.Implements(t, locker) { + return true + } + + for f := range ut.Fields() { + if lockType(f.Type(), seen) { + return true + } + } case *types.Array: - return isLockType(ut.Elem()) + return lockType(ut.Elem(), seen) } return false } -// containsLock reports whether any field of st, nested by value, is a lock type. -func containsLock(st *types.Struct) bool { - for f := range st.Fields() { - if isLockType(f.Type()) { - return true - } +// hasCopyFrom reports whether *T has a method CopyFrom(*T), or will have +// once this run is over. +func (g *generator) hasCopyFrom(t types.Type) bool { + if named, ok := types.Unalias(t).(*types.Named); ok && g.pending[named.Origin().Obj()] { + return true } - return false -} - -// hasCopyFrom reports whether *T has a method CopyFrom(*T). -func hasCopyFrom(t types.Type) bool { meth, _, _ := types.LookupFieldOrMethod(types.NewPointer(t), true, nil, "CopyFrom") if meth == nil { return false @@ -278,7 +492,8 @@ func hasCopyFrom(t types.Type) bool { sig, ok := meth.Type().(*types.Signature) - return ok && sig.Params().Len() == 1 && sig.Results().Len() == 0 + return ok && sig.Params().Len() == 1 && sig.Results().Len() == 0 && + types.Identical(sig.Params().At(0).Type(), types.NewPointer(t)) } var tmpl = template.Must(template.New("copy").Parse(`// Code generated by gocopy; DO NOT EDIT. @@ -289,7 +504,7 @@ package {{.PackageName}} import ( {{- range .Imports}} - "{{.}}" + {{with .Name}}{{.}} {{end}}"{{.Path}}" {{- end}} ) {{- end}} @@ -298,7 +513,7 @@ import ( // CopyFrom makes dst an independent copy of src: one bulk copy, then the // fields that would share memory get dst's own, reusing its capacity. -func (dst *{{.TypeName}}) CopyFrom(src *{{.TypeName}}) { +func (dst *{{.Recv}}) CopyFrom(src *{{.Recv}}) { {{- range .Fields}} {{.Keep}} {{- end}} @@ -311,7 +526,7 @@ func (dst *{{.TypeName}}) CopyFrom(src *{{.TypeName}}) { } // Copy returns a new independent copy of src. -func (src *{{.TypeName}}) Copy() (dst {{.TypeName}}) { +func (src *{{.Recv}}) Copy() (dst {{.Recv}}) { dst.CopyFrom(src) return dst } @@ -320,7 +535,7 @@ func (src *{{.TypeName}}) Copy() (dst {{.TypeName}}) { // CopyFrom makes dst an independent copy of src, field by field: the type // holds a lock or an atomic, so it cannot be assigned or returned as a whole // (there is no Copy method for it). Fields tagged copy:"-" keep dst's value. -func (dst *{{.TypeName}}) CopyFrom(src *{{.TypeName}}) { +func (dst *{{.Recv}}) CopyFrom(src *{{.Recv}}) { {{- range .Plain}} {{.Copy}} {{- end}} diff --git a/gocopy_test.go b/gocopy_test.go index afd6c19..2891a84 100644 --- a/gocopy_test.go +++ b/gocopy_test.go @@ -2,8 +2,11 @@ package gocopy_test import ( "bytes" + "maps" "os" + "os/exec" "path/filepath" + "slices" "strings" "testing" @@ -137,7 +140,8 @@ func TestGenerateErrors(t *testing.T) { {pkg: bulk, typeName: "Missing", want: "not found"}, {pkg: bulk, typeName: "NotAStruct", want: "not a struct"}, {pkg: fieldwise, typeName: "Untagged", want: "holds a lock"}, - {pkg: fieldwise, typeName: "ArrayOfMaps", want: "array of maps"}, + {pkg: fieldwise, typeName: "Recursive", want: "type Tree contains itself"}, + {pkg: fieldwise, typeName: "RecursiveMap", want: "type Index contains itself"}, } for _, tt := range tests { @@ -226,3 +230,503 @@ func TestFileName(t *testing.T) { t.Fatalf("FileName = %q", got) } } + +// checkGenerated writes a throwaway module, generates the CopyFrom of each +// type in typeNames in its root package and runs go vet and go test on the +// result: the generated code must compile, pass vet and the module's own +// tests. It returns the generated sources by type name. +func checkGenerated(t *testing.T, name string, files map[string]string, typeNames ...string) map[string]string { + t.Helper() + + dir := writeModule(t, name, files) + + pkg, err := gocopy.Load(dir) + if err != nil { + t.Fatal(err) + } + + srcs, err := pkg.GenerateAll(typeNames...) + if err != nil { + t.Fatalf("GenerateAll(%v): %v", typeNames, err) + } + + gen := make(map[string]string, len(typeNames)) + + for i, typeName := range typeNames { + gen[typeName] = string(srcs[i]) + + if err := os.WriteFile(filepath.Join(dir, gocopy.FileName(typeName)), srcs[i], 0o600); err != nil { + t.Fatal(err) + } + } + + for _, args := range [][]string{{"vet", "./..."}, {"test", "-count=1", "./..."}} { + cmd := exec.Command("go", args...) //nolint:gosec // fixed arguments + cmd.Dir = dir + + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("go %s: %v\n%s\n%s", strings.Join(args, " "), err, out, + strings.Join(slices.Collect(maps.Values(gen)), "\n")) + } + } + + return gen +} + +// TestGenerateImports checks that every package a field's type names is +// imported, and that two packages with the same name get distinct names. +func TestGenerateImports(t *testing.T) { + t.Parallel() + + gen := checkGenerated(t, "imports", map[string]string{ + "a/a.go": "package a\n\ntype K string\n", + "b/b.go": "package b\n\ntype V int\n", + "x/v1/v1.go": "package v1\n\ntype T int\n", + "y/v1/v1.go": "package v1\n\ntype U int\n", + "box/box.go": "package box\n\ntype Box[T any] struct{ X T }\n\n" + + "func (dst *Box[T]) CopyFrom(src *Box[T]) { *dst = *src }\n", + "root.go": `package root + +import ( + "example.com/imports/a" + "example.com/imports/b" + "example.com/imports/box" + xv1 "example.com/imports/x/v1" + yv1 "example.com/imports/y/v1" +) + +// v1 takes the name, so neither package may be imported as v1 +var v1 = 1 + +type T struct { + AB map[a.K]b.V + V1 map[xv1.T]yv1.U + V1s []map[xv1.T]bool + Box *box.Box[a.K] +} +`, + "root_test.go": `package root + +import ( + "testing" + + "example.com/imports/a" + "example.com/imports/b" + "example.com/imports/box" +) + +func TestCopy(t *testing.T) { + src := T{AB: map[a.K]b.V{"k": 1}, Box: &box.Box[a.K]{X: "x"}} + dst := src.Copy() + + if dst.AB["k"] != 1 || dst.Box == src.Box || dst.Box.X != "x" || v1 != 1 { + t.Fatalf("dst = %+v", dst) + } +} +`, + }, "T") + + for _, want := range []string{ + `v1_2 "example.com/imports/x/v1"`, + `v1_3 "example.com/imports/y/v1"`, + "make(map[v1_2.T]v1_3.U, len(src.V1))", + "new(box.Box[a.K])", + } { + if !strings.Contains(gen["T"], want) { + t.Errorf("generated code lacks %q:\n%s", want, gen["T"]) + } + } +} + +func TestIsLocalName(t *testing.T) { + t.Parallel() + + for name, want := range map[string]bool{ + "dst": true, "src": true, "keepData": true, "i": true, "k": true, "v_2": true, "w_10": true, + "v1": false, "v_": false, "v_x": false, "vv": false, "a": false, "kv": false, + } { + if got := gocopy.IsLocalName(name); got != want { + t.Errorf("isLocalName(%q) = %v, want %v", name, got, want) + } + } +} + +// TestGenerateCopyFromSignature checks that only CopyFrom(*T) counts as T's +// CopyFrom: one promoted from an embedded type, or taking another type, is +// not called. +func TestGenerateCopyFromSignature(t *testing.T) { + t.Parallel() + + gen := checkGenerated(t, "signature", map[string]string{ + "root.go": `package root + +type Inner struct{ B []byte } + +func (dst *Inner) CopyFrom(src *Inner) { dst.B = append(dst.B[:0], src.B...) } + +// Outer gets Inner's CopyFrom(*Inner) by embedding +type Outer struct { + Inner + N int +} + +type Other struct{ N int } + +func (dst *Other) CopyFrom(src *Inner) { dst.N = len(src.B) } + +type Value struct{ N int } + +func (dst *Value) CopyFrom(src Value) { dst.N = src.N } + +type T struct { + O Outer + OP *Outer + Ot Other + V Value + In Inner +} +`, + }, "T") + + for _, field := range []string{"O", "OP", "Ot", "V"} { + if strings.Contains(gen["T"], "dst."+field+".CopyFrom") { + t.Errorf("field %s has no CopyFrom of its own type:\n%s", field, gen["T"]) + } + } + + if !strings.Contains(gen["T"], "dst.In.CopyFrom(&src.In)") { + t.Errorf("Inner's CopyFrom is not called:\n%s", gen["T"]) + } +} + +// TestGenerateLocks checks lock detection against go vet copylocks: a type +// whose pointer is a sync.Locker and value is not (a custom noCopy) is a lock, +// a sync.Locker interface is not, and a blank field is never referred to. +func TestGenerateLocks(t *testing.T) { + t.Parallel() + + const locks = `package root + +import "sync" + +type noCopy struct{} + +func (*noCopy) Lock() {} +func (*noCopy) Unlock() {} + +type NoCopy struct { + nc noCopy ` + "`copy:\"-\"`" + ` + Data []byte +} + +type Blank struct { + _ noCopy + _ []byte + Data []byte +} + +type Locker struct { + L sync.Locker + Data []byte +} + +type Untagged struct { + nc [2]noCopy +} +` + + gen := checkGenerated(t, "locks", map[string]string{ + "root.go": locks, + "root_test.go": `package root + +import ( + "sync" + "testing" +) + +func TestCopy(t *testing.T) { + var mu sync.Mutex + + src := Locker{L: &mu, Data: []byte("x")} + dst := src.Copy() + + if dst.L != &mu || string(dst.Data) != "x" { + t.Fatalf("dst = %+v", dst) + } + + var b Blank + b.CopyFrom(&Blank{Data: []byte("b")}) + + if string(b.Data) != "b" { + t.Fatalf("b.Data = %q", b.Data) + } +} +`, + }, "NoCopy", "Blank", "Locker") + + for typeName, bulk := range map[string]bool{"NoCopy": false, "Blank": false, "Locker": true} { + if got := strings.Contains(gen[typeName], "Copy() (dst"); got != bulk { + t.Errorf("%s: Copy method generated = %v, want %v:\n%s", typeName, got, bulk, gen[typeName]) + } + } + + pkg, err := gocopy.Load(writeModule(t, "untagged", map[string]string{"root.go": locks})) + if err != nil { + t.Fatal(err) + } + + if _, err := pkg.Generate("Untagged"); err == nil || !strings.Contains(err.Error(), "holds a lock") { + t.Fatalf("Generate(Untagged) error = %v, want a lock error", err) + } +} + +// TestGenerateGeneric checks the methods of generic structs: the receiver +// lists the type parameters. +func TestGenerateGeneric(t *testing.T) { + t.Parallel() + + gen := checkGenerated(t, "generic", map[string]string{ + "root.go": `package root + +import "sync" + +type Box[T any] struct { + Items []T + M map[string]T + X T +} + +type Pair[K comparable, V any] struct { + M map[K]V + Box Box[V] +} + +type Locked[_ any] struct { + Mu sync.Mutex ` + "`copy:\"-\"`" + ` + Data []byte +} +`, + "root_test.go": `package root + +import "testing" + +func TestCopy(t *testing.T) { + src := Box[string]{Items: []string{"a"}, M: map[string]string{"k": "v"}, X: "x"} + dst := src.Copy() + src.Items[0], src.M["k"] = "A", "V" + + if dst.Items[0] != "a" || dst.M["k"] != "v" || dst.X != "x" { + t.Fatalf("dst = %+v", dst) + } + + var p Pair[int, []byte] + p.CopyFrom(&Pair[int, []byte]{M: map[int][]byte{1: nil}}) + + if len(p.M) != 1 { + t.Fatalf("p = %+v", p) + } + + var l Locked[int] + l.CopyFrom(&Locked[int]{Data: []byte("d")}) + + if string(l.Data) != "d" { + t.Fatalf("l.Data = %q", l.Data) + } +} +`, + }, "Box", "Pair", "Locked") + + for typeName, want := range map[string]string{ + "Box": "func (src *Box[T]) Copy() (dst Box[T])", + "Pair": "func (dst *Pair[K, V]) CopyFrom(src *Pair[K, V])", + "Locked": "func (dst *Locked[_0]) CopyFrom(src *Locked[_0])", + } { + if !strings.Contains(gen[typeName], want) { + t.Errorf("%s lacks %q:\n%s", typeName, want, gen[typeName]) + } + } +} + +// TestGenerateNested checks that nested collections share nothing with src: +// slices of slices or of structs with CopyFrom, maps of slices or of maps, +// arrays of arrays of slices, and so on. +func TestGenerateNested(t *testing.T) { + t.Parallel() + + gen := checkGenerated(t, "nested", map[string]string{ + "root.go": `package root + +import "sync" + +type Inner struct{ B []byte } + +func (dst *Inner) CopyFrom(src *Inner) { dst.B = append(dst.B[:0], src.B...) } + +type Matrix [][]float64 + +type T struct { + BB [][]byte + Inners []Inner + Ptrs []*Inner + MB map[string][]byte + MI map[string]Inner + AAB [2][2][]byte + ASB [2][][]byte + AM [2]map[string]int + SM []map[string]int + MM map[string]map[string]int + Mx Matrix + Plain [2][2]int +} + +type Locked struct { + Mu sync.Mutex ` + "`copy:\"-\"`" + ` + BB [][]byte +} +`, + "root_test.go": `package root + +import ( + "reflect" + "testing" +) + +func source() *T { + return &T{ + BB: [][]byte{[]byte("bb")}, + Inners: []Inner{{B: []byte("in")}}, + Ptrs: []*Inner{{B: []byte("p")}, nil}, + MB: map[string][]byte{"k": []byte("mb")}, + MI: map[string]Inner{"k": {B: []byte("mi")}}, + AAB: [2][2][]byte{{[]byte("aab")}}, + ASB: [2][][]byte{{[]byte("asb")}}, + AM: [2]map[string]int{{"k": 1}}, + SM: []map[string]int{{"k": 1}}, + MM: map[string]map[string]int{"k": {"k": 1}}, + Mx: Matrix{{1}}, + Plain: [2][2]int{{1}}, + } +} + +func mutate(t *T) { + t.BB[0][0] = 'X' + t.Inners[0].B[0] = 'X' + t.Ptrs[0].B[0] = 'X' + t.MB["k"][0] = 'X' + t.MI["k"].B[0] = 'X' + t.AAB[0][0][0] = 'X' + t.ASB[0][0][0] = 'X' + t.AM[0]["k"] = 9 + t.SM[0]["k"] = 9 + t.MM["k"]["k"] = 9 + t.Mx[0][0] = 9 +} + +func TestCopy(t *testing.T) { + src := source() + + // dst's own memory, some of it larger than src's + dst := T{BB: [][]byte{make([]byte, 0, 8), make([]byte, 0, 8)}, Inners: make([]Inner, 0, 4)} + bb := &dst.BB[:1][0][:1][0] + + dst.CopyFrom(src) + + if !reflect.DeepEqual(&dst, source()) { + t.Fatalf("dst = %+v", dst) + } + + if &dst.BB[0][0] != bb || cap(dst.Inners) != 4 { + t.Fatal("dst's own memory must be reused") + } + + mutate(src) + + if !reflect.DeepEqual(&dst, source()) { + t.Fatalf("dst changed with src: %+v", dst) + } + + cp := source().Copy() + mutate(&cp) + + var l Locked + l.CopyFrom(&Locked{BB: [][]byte{[]byte("l")}}) + + if string(l.BB[0]) != "l" { + t.Fatalf("l.BB = %q", l.BB) + } +} +`, + }, "T", "Locked") + + if strings.Contains(gen["T"], "keepPlain") { + t.Errorf("an array of numbers needs no code:\n%s", gen["T"]) + } +} + +// TestGenerateNilSlices checks the nil-ness of copied slices: a non-nil src +// gives a non-nil dst, even when empty; a nil src empties dst, which keeps its +// array; so Copy, starting from a zero dst, keeps nil and empty apart. +func TestGenerateNilSlices(t *testing.T) { + t.Parallel() + + checkGenerated(t, "nilslices", map[string]string{ + "root.go": `package root + +import "sync" + +type T struct { + B []byte + BB [][]byte + A [1][]byte + M map[string][]int +} + +type Locked struct { + Mu sync.Mutex ` + "`copy:\"-\"`" + ` + B []byte +} +`, + "root_test.go": `package root + +import ( + "encoding/json" + "testing" +) + +func TestNil(t *testing.T) { + empty := T{B: []byte{}, BB: [][]byte{{}}, A: [1][]byte{{}}, M: map[string][]int{"k": {}}} + cp := empty.Copy() + + if cp.B == nil || cp.BB == nil || cp.BB[0] == nil || cp.A[0] == nil || cp.M["k"] == nil { + t.Fatalf("an empty src gave nil: %#v", cp) + } + + got, _ := json.Marshal(&cp) + want, _ := json.Marshal(&empty) + + if string(got) != string(want) { + t.Fatalf("Copy marshals to %s, want %s", got, want) + } + + var zero T + if cp := zero.Copy(); cp.B != nil || cp.BB != nil || cp.A[0] != nil { + t.Fatalf("a nil src gave non-nil: %#v", cp) + } + + dst := T{B: make([]byte, 1, 8), BB: make([][]byte, 1, 8)} + dst.CopyFrom(&zero) + + if len(dst.B) != 0 || cap(dst.B) != 8 || len(dst.BB) != 0 || cap(dst.BB) != 8 { + t.Fatalf("a nil src must empty dst and keep its arrays: %#v", dst) + } + + var l Locked + l.CopyFrom(&Locked{B: []byte{}}) + + if l.B == nil { + t.Fatal("an empty src gave nil") + } +} +`, + }, "T", "Locked") +} diff --git a/internal/cases/bulk/bulk_test.go b/internal/cases/bulk/bulk_test.go index 4797ba5..233b5f9 100644 --- a/internal/cases/bulk/bulk_test.go +++ b/internal/cases/bulk/bulk_test.go @@ -115,6 +115,17 @@ func TestRequestCopyFromNil(t *testing.T) { } } +func TestRequestCopyEmpty(t *testing.T) { + t.Parallel() + + src := &bulk.Request{Data: []byte{}, Names: []string{}, Arr: [2][]byte{{}, {}}} + dst := src.Copy() + + if dst.Data == nil || dst.Names == nil || dst.Arr[0] == nil || dst.Arr[1] == nil { + t.Fatalf("dst = %#v: an empty src slice must not come out nil", dst) + } +} + func TestRequestCopy(t *testing.T) { t.Parallel() diff --git a/internal/cases/bulk/request_copy.gen.go b/internal/cases/bulk/request_copy.gen.go index 745765a..ba9ec5a 100644 --- a/internal/cases/bulk/request_copy.gen.go +++ b/internal/cases/bulk/request_copy.gen.go @@ -21,7 +21,13 @@ func (dst *Request) CopyFrom(src *Request) { *dst = *src dst.Data = append(keepData, src.Data...) + if dst.Data == nil && src.Data != nil { + dst.Data = make([]byte, 0) + } dst.Names = append(keepNames, src.Names...) + if dst.Names == nil && src.Names != nil { + dst.Names = make([]string, 0) + } dst.M = keepM clear(dst.M) if src.M != nil { @@ -56,6 +62,9 @@ func (dst *Request) CopyFrom(src *Request) { dst.Arr = keepArr for i := range src.Arr { dst.Arr[i] = append(dst.Arr[i][:0], src.Arr[i]...) + if dst.Arr[i] == nil && src.Arr[i] != nil { + dst.Arr[i] = make([]byte, 0) + } } dst.Inners = keepInners for i := range src.Inners { diff --git a/internal/cases/fieldwise/fieldwise.go b/internal/cases/fieldwise/fieldwise.go index 946593b..a6cc099 100644 --- a/internal/cases/fieldwise/fieldwise.go +++ b/internal/cases/fieldwise/fieldwise.go @@ -44,7 +44,17 @@ type Untagged struct { Mu sync.Mutex } -// ArrayOfMaps is here for the error path of Generate. -type ArrayOfMaps struct { - M [2]map[string]int +// Tree contains itself: its copy would never end. +type Tree []Tree + +// Index contains itself too, as a map value. +type Index map[string][]Index + +// Recursive and RecursiveMap are here for the error path of Generate. +type Recursive struct { + T Tree +} + +type RecursiveMap struct { + I Index } diff --git a/internal/cases/fieldwise/fieldwise_test.go b/internal/cases/fieldwise/fieldwise_test.go index ff4a896..facb1db 100644 --- a/internal/cases/fieldwise/fieldwise_test.go +++ b/internal/cases/fieldwise/fieldwise_test.go @@ -64,6 +64,13 @@ func TestStateCopyFrom(t *testing.T) { t.Fatal("dst changed with src") } + var empty fieldwise.State + empty.CopyFrom(&fieldwise.State{Data: []byte{}, Arr: [2][]byte{{}, {}}}) + + if empty.Data == nil || empty.Arr[0] == nil { + t.Fatal("an empty src slice must not come out nil") + } + dst.CopyFrom(&fieldwise.State{}) if len(dst.M) != 0 || dst.InnerPtr != nil || len(dst.Data) != 0 { diff --git a/internal/cases/fieldwise/state_copy.gen.go b/internal/cases/fieldwise/state_copy.gen.go index 69292dc..0b255bc 100644 --- a/internal/cases/fieldwise/state_copy.gen.go +++ b/internal/cases/fieldwise/state_copy.gen.go @@ -12,6 +12,9 @@ func (dst *State) CopyFrom(src *State) { // dst.Count kept via tag // dst.Stats kept via tag dst.Data = append(dst.Data[:0], src.Data...) + if dst.Data == nil && src.Data != nil { + dst.Data = make([]byte, 0) + } clear(dst.M) if src.M != nil { if dst.M == nil { @@ -32,6 +35,9 @@ func (dst *State) CopyFrom(src *State) { } for i := range src.Arr { dst.Arr[i] = append(dst.Arr[i][:0], src.Arr[i]...) + if dst.Arr[i] == nil && src.Arr[i] != nil { + dst.Arr[i] = make([]byte, 0) + } } for i := range src.Inners { dst.Inners[i].CopyFrom(&src.Inners[i])