Debian Codegraph @

examples/deepcopy-gen/generators/deepcopy.go

raw
1 /*
2 Copyright 2015 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package generators
18
19 import (
20 "fmt"
21 "io"
22 "path/filepath"
23 "sort"
24 "strings"
25
26 "k8s.io/gengo/args"
27 "k8s.io/gengo/generator"
28 "k8s.io/gengo/namer"
29 "k8s.io/gengo/types"
30
31 "k8s.io/klog/v2"
32 )
33
34 // CustomArgs is used tby the go2idl framework to pass args specific to this
35 // generator.
36 type CustomArgs struct {
37 BoundingDirs []string // Only deal with types rooted under these dirs.
38 }
39
40 // This is the comment tag that carries parameters for deep-copy generation.
41 const (
42 tagEnabledName = "k8s:deepcopy-gen"
43 interfacesTagName = tagEnabledName + ":interfaces"
44 interfacesNonPointerTagName = tagEnabledName + ":nonpointer-interfaces" // attach the DeepCopy<Interface> methods to the
45 )
46
47 // Known values for the comment tag.
48 const tagValuePackage = "package"
49
50 // enabledTagValue holds parameters from a tagName tag.
51 type enabledTagValue struct {
52 value string
53 register bool
54 }
55
56 func extractEnabledTypeTag(t *types.Type) *enabledTagValue {
57 comments := append(append([]string{}, t.SecondClosestCommentLines...), t.CommentLines...)
58 return extractEnabledTag(comments)
59 }
60
61 func extractEnabledTag(comments []string) *enabledTagValue {
62 tagVals := types.ExtractCommentTags("+", comments)[tagEnabledName]
63 if tagVals == nil {
64 // No match for the tag.
65 return nil
66 }
67 // If there are multiple values, abort.
68 if len(tagVals) > 1 {
69 klog.Fatalf("Found %d %s tags: %q", len(tagVals), tagEnabledName, tagVals)
70 }
71
72 // If we got here we are returning something.
73 tag := &enabledTagValue{}
74
75 // Get the primary value.
76 parts := strings.Split(tagVals[0], ",")
77 if len(parts) >= 1 {
78 tag.value = parts[0]
79 }
80
81 // Parse extra arguments.
82 parts = parts[1:]
83 for i := range parts {
84 kv := strings.SplitN(parts[i], "=", 2)
85 k := kv[0]
86 v := ""
87 if len(kv) == 2 {
88 v = kv[1]
89 }
90 switch k {
91 case "register":
92 if v != "false" {
93 tag.register = true
94 }
95 default:
96 klog.Fatalf("Unsupported %s param: %q", tagEnabledName, parts[i])
97 }
98 }
99 return tag
100 }
101
102 // TODO: This is created only to reduce number of changes in a single PR.
103 // Remove it and use PublicNamer instead.
104 func deepCopyNamer() *namer.NameStrategy {
105 return &namer.NameStrategy{
106 Join: func(pre string, in []string, post string) string {
107 return strings.Join(in, "_")
108 },
109 PrependPackageNames: 1,
110 }
111 }
112
113 // NameSystems returns the name system used by the generators in this package.
114 func NameSystems() namer.NameSystems {
115 return namer.NameSystems{
116 "public": deepCopyNamer(),
117 "raw": namer.NewRawNamer("", nil),
118 }
119 }
120
121 // DefaultNameSystem returns the default name system for ordering the types to be
122 // processed by the generators in this package.
123 func DefaultNameSystem() string {
124 return "public"
125 }
126
127 func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {
128 boilerplate, err := arguments.LoadGoBoilerplate()
129 if err != nil {
130 klog.Fatalf("Failed loading boilerplate: %v", err)
131 }
132
133 packages := generator.Packages{}
134 header := append([]byte(fmt.Sprintf("//go:build !%s\n// +build !%s\n\n", arguments.GeneratedBuildTag, arguments.GeneratedBuildTag)), boilerplate...)
135
136 boundingDirs := []string{}
137 if customArgs, ok := arguments.CustomArgs.(*CustomArgs); ok {
138 if customArgs.BoundingDirs == nil {
139 customArgs.BoundingDirs = context.Inputs
140 }
141 for i := range customArgs.BoundingDirs {
142 // Strip any trailing slashes - they are not exactly "correct" but
143 // this is friendlier.
144 boundingDirs = append(boundingDirs, strings.TrimRight(customArgs.BoundingDirs[i], "/"))
145 }
146 }
147
148 for _, i := range context.Inputs {
149 klog.V(5).Infof("Considering pkg %q", i)
150 pkg := context.Universe[i]
151 if pkg == nil {
152 // If the input had no Go files, for example.
153 continue
154 }
155
156 ptag := extractEnabledTag(pkg.Comments)
157 ptagValue := ""
158 ptagRegister := false
159 if ptag != nil {
160 ptagValue = ptag.value
161 if ptagValue != tagValuePackage {
162 klog.Fatalf("Package %v: unsupported %s value: %q", i, tagEnabledName, ptagValue)
163 }
164 ptagRegister = ptag.register
165 klog.V(5).Infof(" tag.value: %q, tag.register: %t", ptagValue, ptagRegister)
166 } else {
167 klog.V(5).Infof(" no tag")
168 }
169
170 // If the pkg-scoped tag says to generate, we can skip scanning types.
171 pkgNeedsGeneration := (ptagValue == tagValuePackage)
172 if !pkgNeedsGeneration {
173 // If the pkg-scoped tag did not exist, scan all types for one that
174 // explicitly wants generation. Ensure all types that want generation
175 // can be copied.
176 var uncopyable []string
177 for _, t := range pkg.Types {
178 klog.V(5).Infof(" considering type %q", t.Name.String())
179 ttag := extractEnabledTypeTag(t)
180 if ttag != nil && ttag.value == "true" {
181 klog.V(5).Infof(" tag=true")
182 if !copyableType(t) {
183 uncopyable = append(uncopyable, fmt.Sprintf("%v", t))
184 } else {
185 pkgNeedsGeneration = true
186 }
187 }
188 }
189 if len(uncopyable) > 0 {
190 klog.Fatalf("Types requested deepcopy generation but are not copyable: %s",
191 strings.Join(uncopyable, ", "))
192 }
193 }
194
195 if pkgNeedsGeneration {
196 klog.V(3).Infof("Package %q needs generation", i)
197 path := pkg.Path
198 // if the source path is within a /vendor/ directory (for example,
199 // k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1), allow
200 // generation to output to the proper relative path (under vendor).
201 // Otherwise, the generator will create the file in the wrong location
202 // in the output directory.
203 // TODO: build a more fundamental concept in gengo for dealing with modifications
204 // to vendored packages.
205 if strings.HasPrefix(pkg.SourcePath, arguments.OutputBase) {
206 expandedPath := strings.TrimPrefix(pkg.SourcePath, arguments.OutputBase)
207 if strings.Contains(expandedPath, "/vendor/") {
208 path = expandedPath
209 }
210 }
211 packages = append(packages,
212 &generator.DefaultPackage{
213 PackageName: strings.Split(filepath.Base(pkg.Path), ".")[0],
214 PackagePath: path,
215 HeaderText: header,
216 GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {
217 return []generator.Generator{
218 NewGenDeepCopy(arguments.OutputFileBaseName, pkg.Path, boundingDirs, (ptagValue == tagValuePackage), ptagRegister),
219 }
220 },
221 FilterFunc: func(c *generator.Context, t *types.Type) bool {
222 return t.Name.Package == pkg.Path
223 },
224 })
225 }
226 }
227 return packages
228 }
229
230 // genDeepCopy produces a file with autogenerated deep-copy functions.
231 type genDeepCopy struct {
232 generator.DefaultGen
233 targetPackage string
234 boundingDirs []string
235 allTypes bool
236 registerTypes bool
237 imports namer.ImportTracker
238 typesForInit []*types.Type
239 }
240
241 func NewGenDeepCopy(sanitizedName, targetPackage string, boundingDirs []string, allTypes, registerTypes bool) generator.Generator {
242 return &genDeepCopy{
243 DefaultGen: generator.DefaultGen{
244 OptionalName: sanitizedName,
245 },
246 targetPackage: targetPackage,
247 boundingDirs: boundingDirs,
248 allTypes: allTypes,
249 registerTypes: registerTypes,
250 imports: generator.NewImportTracker(),
251 typesForInit: make([]*types.Type, 0),
252 }
253 }
254
255 func (g *genDeepCopy) Namers(c *generator.Context) namer.NameSystems {
256 // Have the raw namer for this file track what it imports.
257 return namer.NameSystems{
258 "raw": namer.NewRawNamer(g.targetPackage, g.imports),
259 }
260 }
261
262 func (g *genDeepCopy) Filter(c *generator.Context, t *types.Type) bool {
263 // Filter out types not being processed or not copyable within the package.
264 enabled := g.allTypes
265 if !enabled {
266 ttag := extractEnabledTypeTag(t)
267 if ttag != nil && ttag.value == "true" {
268 enabled = true
269 }
270 }
271 if !enabled {
272 return false
273 }
274 if !copyableType(t) {
275 klog.V(2).Infof("Type %v is not copyable", t)
276 return false
277 }
278 klog.V(4).Infof("Type %v is copyable", t)
279 g.typesForInit = append(g.typesForInit, t)
280 return true
281 }
282
283 func (g *genDeepCopy) copyableAndInBounds(t *types.Type) bool {
284 if !copyableType(t) {
285 return false
286 }
287 // Only packages within the restricted range can be processed.
288 if !isRootedUnder(t.Name.Package, g.boundingDirs) {
289 return false
290 }
291 return true
292 }
293
294 // deepCopyMethod returns the signature of a DeepCopy() method, nil or an error
295 // if the type does not match. This allows more efficient deep copy
296 // implementations to be defined by the type's author. The correct signature
297 // for a type T is:
298 // func (t T) DeepCopy() T
299 // or:
300 // func (t *T) DeepCopy() *T
301 func deepCopyMethod(t *types.Type) (*types.Signature, error) {
302 f, found := t.Methods["DeepCopy"]
303 if !found {
304 return nil, nil
305 }
306 if len(f.Signature.Parameters) != 0 {
307 return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected no parameters", t)
308 }
309 if len(f.Signature.Results) != 1 {
310 return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected exactly one result", t)
311 }
312
313 ptrResult := f.Signature.Results[0].Kind == types.Pointer && f.Signature.Results[0].Elem.Name == t.Name
314 nonPtrResult := f.Signature.Results[0].Name == t.Name
315
316 if !ptrResult && !nonPtrResult {
317 return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected to return %s or *%s", t, t.Name.Name, t.Name.Name)
318 }
319
320 ptrRcvr := f.Signature.Receiver != nil && f.Signature.Receiver.Kind == types.Pointer && f.Signature.Receiver.Elem.Name == t.Name
321 nonPtrRcvr := f.Signature.Receiver != nil && f.Signature.Receiver.Name == t.Name
322
323 if ptrRcvr && !ptrResult {
324 return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected a *%s result for a *%s receiver", t, t.Name.Name, t.Name.Name)
325 }
326 if nonPtrRcvr && !nonPtrResult {
327 return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected a %s result for a %s receiver", t, t.Name.Name, t.Name.Name)
328 }
329
330 return f.Signature, nil
331 }
332
333 // deepCopyMethodOrDie returns the signatrue of a DeepCopy method, nil or calls klog.Fatalf
334 // if the type does not match.
335 func deepCopyMethodOrDie(t *types.Type) *types.Signature {
336 ret, err := deepCopyMethod(t)
337 if err != nil {
338 klog.Fatal(err)
339 }
340 return ret
341 }
342
343 // deepCopyIntoMethod returns the signature of a DeepCopyInto() method, nil or an error
344 // if the type is wrong. DeepCopyInto allows more efficient deep copy
345 // implementations to be defined by the type's author. The correct signature
346 // for a type T is:
347 // func (t T) DeepCopyInto(t *T)
348 // or:
349 // func (t *T) DeepCopyInto(t *T)
350 func deepCopyIntoMethod(t *types.Type) (*types.Signature, error) {
351 f, found := t.Methods["DeepCopyInto"]
352 if !found {
353 return nil, nil
354 }
355 if len(f.Signature.Parameters) != 1 {
356 return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected exactly one parameter", t)
357 }
358 if len(f.Signature.Results) != 0 {
359 return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected no result type", t)
360 }
361
362 ptrParam := f.Signature.Parameters[0].Kind == types.Pointer && f.Signature.Parameters[0].Elem.Name == t.Name
363
364 if !ptrParam {
365 return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected parameter of type *%s", t, t.Name.Name)
366 }
367
368 ptrRcvr := f.Signature.Receiver != nil && f.Signature.Receiver.Kind == types.Pointer && f.Signature.Receiver.Elem.Name == t.Name
369 nonPtrRcvr := f.Signature.Receiver != nil && f.Signature.Receiver.Name == t.Name
370
371 if !ptrRcvr && !nonPtrRcvr {
372 // this should never happen
373 return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected a receiver of type %s or *%s", t, t.Name.Name, t.Name.Name)
374 }
375
376 return f.Signature, nil
377 }
378
379 // deepCopyIntoMethodOrDie returns the signature of a DeepCopyInto() method, nil or calls klog.Fatalf
380 // if the type is wrong.
381 func deepCopyIntoMethodOrDie(t *types.Type) *types.Signature {
382 ret, err := deepCopyIntoMethod(t)
383 if err != nil {
384 klog.Fatal(err)
385 }
386 return ret
387 }
388
389 func isRootedUnder(pkg string, roots []string) bool {
390 // Add trailing / to avoid false matches, e.g. foo/bar vs foo/barn. This
391 // assumes that bounding dirs do not have trailing slashes.
392 pkg = pkg + "/"
393 for _, root := range roots {
394 if strings.HasPrefix(pkg, root+"/") {
395 return true
396 }
397 }
398 return false
399 }
400
401 func copyableType(t *types.Type) bool {
402 // If the type opts out of copy-generation, stop.
403 ttag := extractEnabledTypeTag(t)
404 if ttag != nil && ttag.value == "false" {
405 return false
406 }
407
408 // Filter out private types.
409 if namer.IsPrivateGoName(t.Name.Name) {
410 return false
411 }
412
413 if t.Kind == types.Alias {
414 // if the underlying built-in is not deepcopy-able, deepcopy is opt-in through definition of custom methods.
415 // Note that aliases of builtins, maps, slices can have deepcopy methods.
416 if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil {
417 return true
418 } else {
419 return t.Underlying.Kind != types.Builtin || copyableType(t.Underlying)
420 }
421 }
422
423 if t.Kind != types.Struct {
424 return false
425 }
426
427 return true
428 }
429
430 func underlyingType(t *types.Type) *types.Type {
431 for t.Kind == types.Alias {
432 t = t.Underlying
433 }
434 return t
435 }
436
437 func (g *genDeepCopy) isOtherPackage(pkg string) bool {
438 if pkg == g.targetPackage {
439 return false
440 }
441 if strings.HasSuffix(pkg, "\""+g.targetPackage+"\"") {
442 return false
443 }
444 return true
445 }
446
447 func (g *genDeepCopy) Imports(c *generator.Context) (imports []string) {
448 importLines := []string{}
449 for _, singleImport := range g.imports.ImportLines() {
450 if g.isOtherPackage(singleImport) {
451 importLines = append(importLines, singleImport)
452 }
453 }
454 return importLines
455 }
456
457 func argsFromType(ts ...*types.Type) generator.Args {
458 a := generator.Args{
459 "type": ts[0],
460 }
461 for i, t := range ts {
462 a[fmt.Sprintf("type%d", i+1)] = t
463 }
464 return a
465 }
466
467 func (g *genDeepCopy) Init(c *generator.Context, w io.Writer) error {
468 return nil
469 }
470
471 func (g *genDeepCopy) needsGeneration(t *types.Type) bool {
472 tag := extractEnabledTypeTag(t)
473 tv := ""
474 if tag != nil {
475 tv = tag.value
476 if tv != "true" && tv != "false" {
477 klog.Fatalf("Type %v: unsupported %s value: %q", t, tagEnabledName, tag.value)
478 }
479 }
480 if g.allTypes && tv == "false" {
481 // The whole package is being generated, but this type has opted out.
482 klog.V(5).Infof("Not generating for type %v because type opted out", t)
483 return false
484 }
485 if !g.allTypes && tv != "true" {
486 // The whole package is NOT being generated, and this type has NOT opted in.
487 klog.V(5).Infof("Not generating for type %v because type did not opt in", t)
488 return false
489 }
490 return true
491 }
492
493 func extractInterfacesTag(t *types.Type) []string {
494 var result []string
495 comments := append(append([]string{}, t.SecondClosestCommentLines...), t.CommentLines...)
496 values := types.ExtractCommentTags("+", comments)[interfacesTagName]
497 for _, v := range values {
498 if len(v) == 0 {
499 continue
500 }
501 intfs := strings.Split(v, ",")
502 for _, intf := range intfs {
503 if intf == "" {
504 continue
505 }
506 result = append(result, intf)
507 }
508 }
509 return result
510 }
511
512 func extractNonPointerInterfaces(t *types.Type) (bool, error) {
513 comments := append(append([]string{}, t.SecondClosestCommentLines...), t.CommentLines...)
514 values := types.ExtractCommentTags("+", comments)[interfacesNonPointerTagName]
515 if len(values) == 0 {
516 return false, nil
517 }
518 result := values[0] == "true"
519 for _, v := range values {
520 if v == "true" != result {
521 return false, fmt.Errorf("contradicting %v value %q found to previous value %v", interfacesNonPointerTagName, v, result)
522 }
523 }
524 return result, nil
525 }
526
527 func (g *genDeepCopy) deepCopyableInterfacesInner(c *generator.Context, t *types.Type) ([]*types.Type, error) {
528 if t.Kind != types.Struct {
529 return nil, nil
530 }
531
532 intfs := extractInterfacesTag(t)
533
534 var ts []*types.Type
535 for _, intf := range intfs {
536 t := types.ParseFullyQualifiedName(intf)
537 err := c.AddDir(t.Package)
538 if err != nil {
539 return nil, err
540 }
541 intfT := c.Universe.Type(t)
542 if intfT == nil {
543 return nil, fmt.Errorf("unknown type %q in %s tag of type %s", intf, interfacesTagName, intfT)
544 }
545 if intfT.Kind != types.Interface {
546 return nil, fmt.Errorf("type %q in %s tag of type %s is not an interface, but: %q", intf, interfacesTagName, t, intfT.Kind)
547 }
548 g.imports.AddType(intfT)
549 ts = append(ts, intfT)
550 }
551
552 return ts, nil
553 }
554
555 // deepCopyableInterfaces returns the interface types to implement and whether they apply to a non-pointer receiver.
556 func (g *genDeepCopy) deepCopyableInterfaces(c *generator.Context, t *types.Type) ([]*types.Type, bool, error) {
557 ts, err := g.deepCopyableInterfacesInner(c, t)
558 if err != nil {
559 return nil, false, err
560 }
561
562 set := map[string]*types.Type{}
563 for _, t := range ts {
564 set[t.String()] = t
565 }
566
567 result := []*types.Type{}
568 for _, t := range set {
569 result = append(result, t)
570 }
571
572 TypeSlice(result).Sort() // we need a stable sorting because it determines the order in generation
573
574 nonPointerReceiver, err := extractNonPointerInterfaces(t)
575 if err != nil {
576 return nil, false, err
577 }
578
579 return result, nonPointerReceiver, nil
580 }
581
582 type TypeSlice []*types.Type
583
584 func (s TypeSlice) Len() int { return len(s) }
585 func (s TypeSlice) Less(i, j int) bool { return s[i].String() < s[j].String() }
586 func (s TypeSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
587 func (s TypeSlice) Sort() { sort.Sort(s) }
588
589 func (g *genDeepCopy) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
590 if !g.needsGeneration(t) {
591 return nil
592 }
593 klog.V(5).Infof("Generating deepcopy function for type %v", t)
594
595 sw := generator.NewSnippetWriter(w, c, "$", "$")
596 args := argsFromType(t)
597
598 if deepCopyIntoMethodOrDie(t) == nil {
599 sw.Do("// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.\n", args)
600 if isReference(t) {
601 sw.Do("func (in $.type|raw$) DeepCopyInto(out *$.type|raw$) {\n", args)
602 sw.Do("{in:=&in\n", nil)
603 } else {
604 sw.Do("func (in *$.type|raw$) DeepCopyInto(out *$.type|raw$) {\n", args)
605 }
606 if deepCopyMethodOrDie(t) != nil {
607 if t.Methods["DeepCopy"].Signature.Receiver.Kind == types.Pointer {
608 sw.Do("clone := in.DeepCopy()\n", nil)
609 sw.Do("*out = *clone\n", nil)
610 } else {
611 sw.Do("*out = in.DeepCopy()\n", nil)
612 }
613 sw.Do("return\n", nil)
614 } else {
615 g.generateFor(t, sw)
616 sw.Do("return\n", nil)
617 }
618 if isReference(t) {
619 sw.Do("}\n", nil)
620 }
621 sw.Do("}\n\n", nil)
622 }
623
624 if deepCopyMethodOrDie(t) == nil {
625 sw.Do("// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new $.type|raw$.\n", args)
626 if isReference(t) {
627 sw.Do("func (in $.type|raw$) DeepCopy() $.type|raw$ {\n", args)
628 } else {
629 sw.Do("func (in *$.type|raw$) DeepCopy() *$.type|raw$ {\n", args)
630 }
631 sw.Do("if in == nil { return nil }\n", nil)
632 sw.Do("out := new($.type|raw$)\n", args)
633 sw.Do("in.DeepCopyInto(out)\n", nil)
634 if isReference(t) {
635 sw.Do("return *out\n", nil)
636 } else {
637 sw.Do("return out\n", nil)
638 }
639 sw.Do("}\n\n", nil)
640 }
641
642 intfs, nonPointerReceiver, err := g.deepCopyableInterfaces(c, t)
643 if err != nil {
644 return err
645 }
646 for _, intf := range intfs {
647 sw.Do(fmt.Sprintf("// DeepCopy%s is an autogenerated deepcopy function, copying the receiver, creating a new $.type2|raw$.\n", intf.Name.Name), argsFromType(t, intf))
648 if nonPointerReceiver {
649 sw.Do(fmt.Sprintf("func (in $.type|raw$) DeepCopy%s() $.type2|raw$ {\n", intf.Name.Name), argsFromType(t, intf))
650 sw.Do("return *in.DeepCopy()", nil)
651 sw.Do("}\n\n", nil)
652 } else {
653 sw.Do(fmt.Sprintf("func (in *$.type|raw$) DeepCopy%s() $.type2|raw$ {\n", intf.Name.Name), argsFromType(t, intf))
654 sw.Do("if c := in.DeepCopy(); c != nil {\n", nil)
655 sw.Do("return c\n", nil)
656 sw.Do("}\n", nil)
657 sw.Do("return nil\n", nil)
658 sw.Do("}\n\n", nil)
659 }
660 }
661
662 return sw.Error()
663 }
664
665 // isReference return true for pointer, maps, slices and aliases of those.
666 func isReference(t *types.Type) bool {
667 if t.Kind == types.Pointer || t.Kind == types.Map || t.Kind == types.Slice {
668 return true
669 }
670 return t.Kind == types.Alias && isReference(underlyingType(t))
671 }
672
673 // we use the system of shadowing 'in' and 'out' so that the same code is valid
674 // at any nesting level. This makes the autogenerator easy to understand, and
675 // the compiler shouldn't care.
676 func (g *genDeepCopy) generateFor(t *types.Type, sw *generator.SnippetWriter) {
677 // derive inner types if t is an alias. We call the do* methods below with the alias type.
678 // basic rule: generate according to inner type, but construct objects with the alias type.
679 ut := underlyingType(t)
680
681 var f func(*types.Type, *generator.SnippetWriter)
682 switch ut.Kind {
683 case types.Builtin:
684 f = g.doBuiltin
685 case types.Map:
686 f = g.doMap
687 case types.Slice:
688 f = g.doSlice
689 case types.Struct:
690 f = g.doStruct
691 case types.Pointer:
692 f = g.doPointer
693 case types.Interface:
694 // interfaces are handled in-line in the other cases
695 klog.Fatalf("Hit an interface type %v. This should never happen.", t)
696 case types.Alias:
697 // can never happen because we branch on the underlying type which is never an alias
698 klog.Fatalf("Hit an alias type %v. This should never happen.", t)
699 default:
700 klog.Fatalf("Hit an unsupported type %v.", t)
701 }
702 f(t, sw)
703 }
704
705 // doBuiltin generates code for a builtin or an alias to a builtin. The generated code is
706 // is the same for both cases, i.e. it's the code for the underlying type.
707 func (g *genDeepCopy) doBuiltin(t *types.Type, sw *generator.SnippetWriter) {
708 if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil {
709 sw.Do("*out = in.DeepCopy()\n", nil)
710 return
711 }
712
713 sw.Do("*out = *in\n", nil)
714 }
715
716 // doMap generates code for a map or an alias to a map. The generated code is
717 // is the same for both cases, i.e. it's the code for the underlying type.
718 func (g *genDeepCopy) doMap(t *types.Type, sw *generator.SnippetWriter) {
719 ut := underlyingType(t)
720 uet := underlyingType(ut.Elem)
721
722 if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil {
723 sw.Do("*out = in.DeepCopy()\n", nil)
724 return
725 }
726
727 if !ut.Key.IsAssignable() {
728 klog.Fatalf("Hit an unsupported type %v for: %v", uet, t)
729 }
730
731 sw.Do("*out = make($.|raw$, len(*in))\n", t)
732 sw.Do("for key, val := range *in {\n", nil)
733 dc, dci := deepCopyMethodOrDie(ut.Elem), deepCopyIntoMethodOrDie(ut.Elem)
734 switch {
735 case dc != nil || dci != nil:
736 // Note: a DeepCopy exists because it is added if DeepCopyInto is manually defined
737 leftPointer := ut.Elem.Kind == types.Pointer
738 rightPointer := !isReference(ut.Elem)
739 if dc != nil {
740 rightPointer = dc.Results[0].Kind == types.Pointer
741 }
742 if leftPointer == rightPointer {
743 sw.Do("(*out)[key] = val.DeepCopy()\n", nil)
744 } else if leftPointer {
745 sw.Do("x := val.DeepCopy()\n", nil)
746 sw.Do("(*out)[key] = &x\n", nil)
747 } else {
748 sw.Do("(*out)[key] = *val.DeepCopy()\n", nil)
749 }
750 case ut.Elem.IsAnonymousStruct(): // not uet here because it needs type cast
751 sw.Do("(*out)[key] = val\n", nil)
752 case uet.IsAssignable():
753 sw.Do("(*out)[key] = val\n", nil)
754 case uet.Kind == types.Interface:
755 // Note: do not generate code that won't compile as `DeepCopyinterface{}()` is not a valid function
756 if uet.Name.Name == "interface{}" {
757 klog.Fatalf("DeepCopy of %q is unsupported. Instead, use named interfaces with DeepCopy<named-interface> as one of the methods.", uet.Name.Name)
758 }
759 sw.Do("if val == nil {(*out)[key]=nil} else {\n", nil)
760 // Note: if t.Elem has been an alias "J" of an interface "I" in Go, we will see it
761 // as kind Interface of name "J" here, i.e. generate val.DeepCopyJ(). The golang
762 // parser does not give us the underlying interface name. So we cannot do any better.
763 sw.Do(fmt.Sprintf("(*out)[key] = val.DeepCopy%s()\n", uet.Name.Name), nil)
764 sw.Do("}\n", nil)
765 case uet.Kind == types.Slice || uet.Kind == types.Map || uet.Kind == types.Pointer:
766 sw.Do("var outVal $.|raw$\n", uet)
767 sw.Do("if val == nil { (*out)[key] = nil } else {\n", nil)
768 sw.Do("in, out := &val, &outVal\n", uet)
769 g.generateFor(ut.Elem, sw)
770 sw.Do("}\n", nil)
771 sw.Do("(*out)[key] = outVal\n", nil)
772 case uet.Kind == types.Struct:
773 sw.Do("(*out)[key] = *val.DeepCopy()\n", uet)
774 default:
775 klog.Fatalf("Hit an unsupported type %v for %v", uet, t)
776 }
777 sw.Do("}\n", nil)
778 }
779
780 // doSlice generates code for a slice or an alias to a slice. The generated code is
781 // is the same for both cases, i.e. it's the code for the underlying type.
782 func (g *genDeepCopy) doSlice(t *types.Type, sw *generator.SnippetWriter) {
783 ut := underlyingType(t)
784 uet := underlyingType(ut.Elem)
785
786 if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil {
787 sw.Do("*out = in.DeepCopy()\n", nil)
788 return
789 }
790
791 sw.Do("*out = make($.|raw$, len(*in))\n", t)
792 if deepCopyMethodOrDie(ut.Elem) != nil || deepCopyIntoMethodOrDie(ut.Elem) != nil {
793 sw.Do("for i := range *in {\n", nil)
794 // Note: a DeepCopyInto exists because it is added if DeepCopy is manually defined
795 sw.Do("(*in)[i].DeepCopyInto(&(*out)[i])\n", nil)
796 sw.Do("}\n", nil)
797 } else if uet.Kind == types.Builtin || uet.IsAssignable() {
798 sw.Do("copy(*out, *in)\n", nil)
799 } else {
800 sw.Do("for i := range *in {\n", nil)
801 if uet.Kind == types.Slice || uet.Kind == types.Map || uet.Kind == types.Pointer || deepCopyMethodOrDie(ut.Elem) != nil || deepCopyIntoMethodOrDie(ut.Elem) != nil {
802 sw.Do("if (*in)[i] != nil {\n", nil)
803 sw.Do("in, out := &(*in)[i], &(*out)[i]\n", nil)
804 g.generateFor(ut.Elem, sw)
805 sw.Do("}\n", nil)
806 } else if uet.Kind == types.Interface {
807 // Note: do not generate code that won't compile as `DeepCopyinterface{}()` is not a valid function
808 if uet.Name.Name == "interface{}" {
809 klog.Fatalf("DeepCopy of %q is unsupported. Instead, use named interfaces with DeepCopy<named-interface> as one of the methods.", uet.Name.Name)
810 }
811 sw.Do("if (*in)[i] != nil {\n", nil)
812 // Note: if t.Elem has been an alias "J" of an interface "I" in Go, we will see it
813 // as kind Interface of name "J" here, i.e. generate val.DeepCopyJ(). The golang
814 // parser does not give us the underlying interface name. So we cannot do any better.
815 sw.Do(fmt.Sprintf("(*out)[i] = (*in)[i].DeepCopy%s()\n", uet.Name.Name), nil)
816 sw.Do("}\n", nil)
817 } else if uet.Kind == types.Struct {
818 sw.Do("(*in)[i].DeepCopyInto(&(*out)[i])\n", nil)
819 } else {
820 klog.Fatalf("Hit an unsupported type %v for %v", uet, t)
821 }
822 sw.Do("}\n", nil)
823 }
824 }
825
826 // doStruct generates code for a struct or an alias to a struct. The generated code is
827 // is the same for both cases, i.e. it's the code for the underlying type.
828 func (g *genDeepCopy) doStruct(t *types.Type, sw *generator.SnippetWriter) {
829 ut := underlyingType(t)
830
831 if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil {
832 sw.Do("*out = in.DeepCopy()\n", nil)
833 return
834 }
835
836 // Simple copy covers a lot of cases.
837 sw.Do("*out = *in\n", nil)
838
839 // Now fix-up fields as needed.
840 for _, m := range ut.Members {
841 ft := m.Type
842 uft := underlyingType(ft)
843
844 args := generator.Args{
845 "type": ft,
846 "kind": ft.Kind,
847 "name": m.Name,
848 }
849 dc, dci := deepCopyMethodOrDie(ft), deepCopyIntoMethodOrDie(ft)
850 switch {
851 case dc != nil || dci != nil:
852 // Note: a DeepCopyInto exists because it is added if DeepCopy is manually defined
853 leftPointer := ft.Kind == types.Pointer
854 rightPointer := !isReference(ft)
855 if dc != nil {
856 rightPointer = dc.Results[0].Kind == types.Pointer
857 }
858 if leftPointer == rightPointer {
859 sw.Do("out.$.name$ = in.$.name$.DeepCopy()\n", args)
860 } else if leftPointer {
861 sw.Do("x := in.$.name$.DeepCopy()\n", args)
862 sw.Do("out.$.name$ = = &x\n", args)
863 } else {
864 sw.Do("in.$.name$.DeepCopyInto(&out.$.name$)\n", args)
865 }
866 case uft.Kind == types.Builtin:
867 // the initial *out = *in was enough
868 case uft.Kind == types.Map, uft.Kind == types.Slice, uft.Kind == types.Pointer:
869 // Fixup non-nil reference-semantic types.
870 sw.Do("if in.$.name$ != nil {\n", args)
871 sw.Do("in, out := &in.$.name$, &out.$.name$\n", args)
872 g.generateFor(ft, sw)
873 sw.Do("}\n", nil)
874 case uft.Kind == types.Array:
875 sw.Do("out.$.name$ = in.$.name$\n", args)
876 case uft.Kind == types.Struct:
877 if ft.IsAssignable() {
878 sw.Do("out.$.name$ = in.$.name$\n", args)
879 } else {
880 sw.Do("in.$.name$.DeepCopyInto(&out.$.name$)\n", args)
881 }
882 case uft.Kind == types.Interface:
883 // Note: do not generate code that won't compile as `DeepCopyinterface{}()` is not a valid function
884 if uft.Name.Name == "interface{}" {
885 klog.Fatalf("DeepCopy of %q is unsupported. Instead, use named interfaces with DeepCopy<named-interface> as one of the methods.", uft.Name.Name)
886 }
887 sw.Do("if in.$.name$ != nil {\n", args)
888 // Note: if t.Elem has been an alias "J" of an interface "I" in Go, we will see it
889 // as kind Interface of name "J" here, i.e. generate val.DeepCopyJ(). The golang
890 // parser does not give us the underlying interface name. So we cannot do any better.
891 sw.Do(fmt.Sprintf("out.$.name$ = in.$.name$.DeepCopy%s()\n", uft.Name.Name), args)
892 sw.Do("}\n", nil)
893 default:
894 klog.Fatalf("Hit an unsupported type %v for %v, from %v", uft, ft, t)
895 }
896 }
897 }
898
899 // doPointer generates code for a pointer or an alias to a pointer. The generated code is
900 // is the same for both cases, i.e. it's the code for the underlying type.
901 func (g *genDeepCopy) doPointer(t *types.Type, sw *generator.SnippetWriter) {
902 ut := underlyingType(t)
903 uet := underlyingType(ut.Elem)
904
905 dc, dci := deepCopyMethodOrDie(ut.Elem), deepCopyIntoMethodOrDie(ut.Elem)
906 switch {
907 case dc != nil || dci != nil:
908 rightPointer := !isReference(ut.Elem)
909 if dc != nil {
910 rightPointer = dc.Results[0].Kind == types.Pointer
911 }
912 if rightPointer {
913 sw.Do("*out = (*in).DeepCopy()\n", nil)
914 } else {
915 sw.Do("x := (*in).DeepCopy()\n", nil)
916 sw.Do("*out = &x\n", nil)
917 }
918 case uet.IsAssignable():
919 sw.Do("*out = new($.Elem|raw$)\n", ut)
920 sw.Do("**out = **in", nil)
921 case uet.Kind == types.Map, uet.Kind == types.Slice, uet.Kind == types.Pointer:
922 sw.Do("*out = new($.Elem|raw$)\n", ut)
923 sw.Do("if **in != nil {\n", nil)
924 sw.Do("in, out := *in, *out\n", nil)
925 g.generateFor(uet, sw)
926 sw.Do("}\n", nil)
927 case uet.Kind == types.Struct:
928 sw.Do("*out = new($.Elem|raw$)\n", ut)
929 sw.Do("(*in).DeepCopyInto(*out)\n", nil)
930 default:
931 klog.Fatalf("Hit an unsupported type %v for %v", uet, t)
932 }
933 }