forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
generator.go
513 lines (472 loc) · 15.4 KB
/
generator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
/*
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package conversion
import (
"fmt"
"io"
"reflect"
"sort"
"strings"
)
type Generator interface {
GenerateConversionsForType(version string, reflection reflect.Type) error
WriteConversionFunctions(w io.Writer) error
OverwritePackage(pkg, overwrite string)
}
func NewGenerator(scheme *Scheme) Generator {
return &generator{
scheme: scheme,
convertibles: make(map[reflect.Type]reflect.Type),
pkgOverwrites: make(map[string]string),
}
}
var complexTypes []reflect.Kind = []reflect.Kind{reflect.Map, reflect.Ptr, reflect.Slice, reflect.Interface, reflect.Struct}
type generator struct {
scheme *Scheme
convertibles map[reflect.Type]reflect.Type
// If pkgOverwrites is set for a given package name, that package name
// will be replaced while writing conversion function. If empty, package
// name will be omitted.
pkgOverwrites map[string]string
}
func (g *generator) GenerateConversionsForType(version string, reflection reflect.Type) error {
kind := reflection.Name()
internalObj, err := g.scheme.NewObject(g.scheme.InternalVersion, kind)
if err != nil {
return fmt.Errorf("cannot create an object of type %v in internal version", kind)
}
internalObjType := reflect.TypeOf(internalObj)
if internalObjType.Kind() != reflect.Ptr {
return fmt.Errorf("created object should be of type Ptr: ", internalObjType.Kind())
}
return g.generateConversionsBetween(reflection, internalObjType.Elem())
}
func (g *generator) generateConversionsBetween(inType, outType reflect.Type) error {
// Avoid processing the same type multiple times.
if value, found := g.convertibles[inType]; found {
if value != outType {
return fmt.Errorf("multiple possible convertibles for %v", inType)
}
return nil
}
if inType == outType {
// Don't generate conversion methods for the same type.
return nil
}
if inType.Kind() != outType.Kind() {
return fmt.Errorf("cannot convert types of different kinds: %v %v", inType, outType)
}
switch inType.Kind() {
case reflect.Map:
return g.generateConversionsForMap(inType, outType)
case reflect.Ptr:
return g.generateConversionsBetween(inType.Elem(), outType.Elem())
case reflect.Slice:
return g.generateConversionsForSlice(inType, outType)
case reflect.Interface:
// TODO(wojtek-t): Currently we rely on default conversion functions for interfaces.
// Add support for reflect.Interface.
return nil
case reflect.Struct:
return g.generateConversionsForStruct(inType, outType)
default:
// All simple types should be handled correctly with default conversion.
return nil
}
panic("This should never happen")
}
func isComplexType(reflection reflect.Type) bool {
for _, complexType := range complexTypes {
if complexType == reflection.Kind() {
return true
}
}
return false
}
func (g *generator) generateConversionsForMap(inType, outType reflect.Type) error {
inKey := inType.Key()
outKey := outType.Key()
if err := g.generateConversionsBetween(inKey, outKey); err != nil {
return err
}
inValue := inType.Elem()
outValue := outType.Elem()
if err := g.generateConversionsBetween(inValue, outValue); err != nil {
return err
}
// We don't add it to g.convertibles - maps should be handled correctly
// inside appropriate conversion functions.
return nil
}
func (g *generator) generateConversionsForSlice(inType, outType reflect.Type) error {
inElem := inType.Elem()
outElem := outType.Elem()
if err := g.generateConversionsBetween(inElem, outElem); err != nil {
return err
}
// We don't add it to g.convertibles - slices should be handled correctly
// inside appropriate conversion functions.
return nil
}
func (g *generator) generateConversionsForStruct(inType, outType reflect.Type) error {
for i := 0; i < inType.NumField(); i++ {
inField := inType.Field(i)
outField, found := outType.FieldByName(inField.Name)
if !found {
return fmt.Errorf("couldn't find a corresponding field %v in %v", inField.Name, outType)
}
if inField.Type.Kind() != outField.Type.Kind() {
return fmt.Errorf("cannot convert types of different kinds: %v %v", inField, outField)
}
if isComplexType(inField.Type) {
if err := g.generateConversionsBetween(inField.Type, outField.Type); err != nil {
return err
}
}
}
g.convertibles[inType] = outType
return nil
}
type byName []reflect.Type
func (s byName) Len() int {
return len(s)
}
func (s byName) Less(i, j int) bool {
return s[i].Name() < s[j].Name()
}
func (s byName) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (g *generator) WriteConversionFunctions(w io.Writer) error {
// It's desired to print conversion functions always in the same order
// (e.g. for better tracking of what has really been added).
var keys []reflect.Type
for key := range g.convertibles {
keys = append(keys, key)
}
sort.Sort(byName(keys))
indent := 2
for _, inType := range keys {
outType := g.convertibles[inType]
// All types in g.convertibles are structs.
if inType.Kind() != reflect.Struct {
return fmt.Errorf("non-struct conversions are not-supported")
}
if err := g.writeConversionForType(w, inType, outType, indent); err != nil {
return err
}
if err := g.writeConversionForType(w, outType, inType, indent); err != nil {
return err
}
}
return nil
}
func (g *generator) typeName(inType reflect.Type) string {
switch inType.Kind() {
case reflect.Map:
return fmt.Sprintf("map[%s]%s", g.typeName(inType.Key()), g.typeName(inType.Elem()))
case reflect.Slice:
return fmt.Sprintf("[]%s", g.typeName(inType.Elem()))
default:
typeWithPkg := fmt.Sprintf("%s", inType)
slices := strings.Split(typeWithPkg, ".")
if len(slices) == 1 {
// Default package.
return slices[0]
}
if len(slices) == 2 {
pkg := slices[0]
if val, found := g.pkgOverwrites[pkg]; found {
pkg = val
}
if pkg != "" {
pkg = pkg + "."
}
return pkg + slices[1]
}
panic("Incorrect type name: " + typeWithPkg)
}
}
func indentLine(w io.Writer, indent int) error {
indentation := ""
for i := 0; i < indent; i++ {
indentation = indentation + "\t"
}
_, err := io.WriteString(w, indentation)
return err
}
func writeLine(w io.Writer, indent int, line string) error {
if err := indentLine(w, indent); err != nil {
return err
}
if _, err := io.WriteString(w, line); err != nil {
return err
}
return nil
}
func writeHeader(w io.Writer, inType, outType string, indent int) error {
format := "func(in *%s, out *%s, s conversion.Scope) error {\n"
stmt := fmt.Sprintf(format, inType, outType)
return writeLine(w, indent, stmt)
}
func writeFooter(w io.Writer, indent int) error {
if err := writeLine(w, indent+1, "return nil\n"); err != nil {
return err
}
if err := writeLine(w, indent, "},\n"); err != nil {
return err
}
return nil
}
func (g *generator) writeConversionForMap(w io.Writer, inField, outField reflect.StructField, indent int) error {
ifFormat := "if in.%s != nil {\n"
ifStmt := fmt.Sprintf(ifFormat, inField.Name)
if err := writeLine(w, indent, ifStmt); err != nil {
return err
}
makeFormat := "out.%s = make(%s)\n"
makeStmt := fmt.Sprintf(makeFormat, outField.Name, g.typeName(outField.Type))
if err := writeLine(w, indent+1, makeStmt); err != nil {
return err
}
forFormat := "for key, val := range in.%s {\n"
forStmt := fmt.Sprintf(forFormat, inField.Name)
if err := writeLine(w, indent+1, forStmt); err != nil {
return err
}
// Whether we need to explicitly create a new value.
newValue := false
if isComplexType(inField.Type.Elem()) || !inField.Type.Elem().ConvertibleTo(outField.Type.Elem()) {
newValue = true
newFormat := "newVal := %s{}\n"
newStmt := fmt.Sprintf(newFormat, g.typeName(outField.Type.Elem()))
if err := writeLine(w, indent+2, newStmt); err != nil {
return err
}
convertStmt := "if err := s.Convert(&val, &newVal, 0); err != nil {\n"
if err := writeLine(w, indent+2, convertStmt); err != nil {
return err
}
if err := writeLine(w, indent+3, "return err\n"); err != nil {
return err
}
if err := writeLine(w, indent+2, "}\n"); err != nil {
return err
}
}
if inField.Type.Key().ConvertibleTo(outField.Type.Key()) {
value := "val"
if newValue {
value = "newVal"
}
assignStmt := ""
if inField.Type.Key().AssignableTo(outField.Type.Key()) {
assignStmt = fmt.Sprintf("out.%s[key] = %s\n", outField.Name, value)
} else {
assignStmt = fmt.Sprintf("out.%s[%s(key)] = %s\n", outField.Name, g.typeName(outField.Type.Key()), value)
}
if err := writeLine(w, indent+2, assignStmt); err != nil {
return err
}
} else {
// TODO(wojtek-t): Support maps with keys that are non-convertible to each other.
return fmt.Errorf("conversions between unconvertible keys in map are not supported.")
}
if err := writeLine(w, indent+1, "}\n"); err != nil {
return err
}
if err := writeLine(w, indent, "}\n"); err != nil {
return err
}
return nil
}
func (g *generator) writeConversionForSlice(w io.Writer, inField, outField reflect.StructField, indent int) error {
ifFormat := "if in.%s != nil {\n"
ifStmt := fmt.Sprintf(ifFormat, inField.Name)
if err := writeLine(w, indent, ifStmt); err != nil {
return err
}
makeFormat := "out.%s = make(%s, len(in.%s))\n"
makeStmt := fmt.Sprintf(makeFormat, outField.Name, g.typeName(outField.Type), inField.Name)
if err := writeLine(w, indent+1, makeStmt); err != nil {
return err
}
forFormat := "for i := range in.%s {\n"
forStmt := fmt.Sprintf(forFormat, inField.Name)
if err := writeLine(w, indent+1, forStmt); err != nil {
return err
}
if inField.Type.Elem().AssignableTo(outField.Type.Elem()) {
assignFormat := "out.%s[i] = in.%s[i]\n"
assignStmt := fmt.Sprintf(assignFormat, outField.Name, inField.Name)
if err := writeLine(w, indent+2, assignStmt); err != nil {
return err
}
} else {
assignFormat := "if err := s.Convert(&in.%s[i], &out.%s[i], 0); err != nil {\n"
assignStmt := fmt.Sprintf(assignFormat, inField.Name, outField.Name)
if err := writeLine(w, indent+2, assignStmt); err != nil {
return err
}
if err := writeLine(w, indent+3, "return err\n"); err != nil {
return err
}
if err := writeLine(w, indent+2, "}\n"); err != nil {
return err
}
}
if err := writeLine(w, indent+1, "}\n"); err != nil {
return err
}
if err := writeLine(w, indent, "}\n"); err != nil {
return err
}
return nil
}
func (g *generator) writeConversionForPtr(w io.Writer, inField, outField reflect.StructField, indent int) error {
switch inField.Type.Elem().Kind() {
case reflect.Map, reflect.Ptr, reflect.Slice, reflect.Interface, reflect.Struct:
// Don't copy these via assignment/conversion!
default:
// This should handle pointers to all simple types.
assignable := inField.Type.Elem().AssignableTo(outField.Type.Elem())
convertible := inField.Type.Elem().ConvertibleTo(outField.Type.Elem())
if assignable || convertible {
ifFormat := "if in.%s != nil {\n"
ifStmt := fmt.Sprintf(ifFormat, inField.Name)
if err := writeLine(w, indent, ifStmt); err != nil {
return err
}
newFormat := "out.%s = new(%s)\n"
newStmt := fmt.Sprintf(newFormat, outField.Name, g.typeName(outField.Type.Elem()))
if err := writeLine(w, indent+1, newStmt); err != nil {
return err
}
}
if assignable {
assignFormat := "*out.%s = *in.%s\n"
assignStmt := fmt.Sprintf(assignFormat, outField.Name, inField.Name)
if err := writeLine(w, indent+1, assignStmt); err != nil {
return err
}
} else if convertible {
assignFormat := "*out.%s = %s(*in.%s)\n"
assignStmt := fmt.Sprintf(assignFormat, outField.Name, g.typeName(outField.Type.Elem()), inField.Name)
if err := writeLine(w, indent+1, assignStmt); err != nil {
return err
}
}
if assignable || convertible {
if err := writeLine(w, indent, "}\n"); err != nil {
return err
}
return nil
}
}
assignFormat := "if err := s.Convert(&in.%s, &out.%s, 0); err != nil {\n"
assignStmt := fmt.Sprintf(assignFormat, inField.Name, outField.Name)
if err := writeLine(w, indent, assignStmt); err != nil {
return err
}
if err := writeLine(w, indent+1, "return err\n"); err != nil {
return err
}
if err := writeLine(w, indent, "}\n"); err != nil {
return err
}
return nil
}
func (g *generator) writeConversionForStruct(w io.Writer, inType, outType reflect.Type, indent int) error {
for i := 0; i < inType.NumField(); i++ {
inField := inType.Field(i)
outField, _ := outType.FieldByName(inField.Name)
switch inField.Type.Kind() {
case reflect.Map, reflect.Ptr, reflect.Slice, reflect.Interface, reflect.Struct:
// Don't copy these via assignment/conversion!
default:
// This should handle all simple types.
if inField.Type.AssignableTo(outField.Type) {
assignFormat := "out.%s = in.%s\n"
assignStmt := fmt.Sprintf(assignFormat, outField.Name, inField.Name)
if err := writeLine(w, indent, assignStmt); err != nil {
return err
}
continue
}
if inField.Type.ConvertibleTo(outField.Type) {
assignFormat := "out.%s = %s(in.%s)\n"
assignStmt := fmt.Sprintf(assignFormat, outField.Name, g.typeName(outField.Type), inField.Name)
if err := writeLine(w, indent, assignStmt); err != nil {
return err
}
continue
}
}
// If the field is a slice, copy its elements one by one.
if inField.Type.Kind() == reflect.Slice {
if err := g.writeConversionForSlice(w, inField, outField, indent); err != nil {
return err
}
continue
}
// If the field is a map, copy its elements one by one.
if inField.Type.Kind() == reflect.Map {
if err := g.writeConversionForMap(w, inField, outField, indent); err != nil {
return err
}
continue
}
// If the field is a pointer, we can try to assign underlying values.
if inField.Type.Kind() == reflect.Ptr {
if err := g.writeConversionForPtr(w, inField, outField, indent); err != nil {
return err
}
continue
}
// TODO(wojtek-t): At some point we may consider named functions and call
// appropriate function here instead of using generic Convert method that
// will call the same method underneath after some additional operations.
assignFormat := "if err := s.Convert(&in.%s, &out.%s, 0); err != nil {\n"
assignStmt := fmt.Sprintf(assignFormat, inField.Name, outField.Name)
if err := writeLine(w, indent, assignStmt); err != nil {
return err
}
if err := writeLine(w, indent+1, "return err\n"); err != nil {
return err
}
if err := writeLine(w, indent, "}\n"); err != nil {
return err
}
}
return nil
}
func (g *generator) writeConversionForType(w io.Writer, inType, outType reflect.Type, indent int) error {
if err := writeHeader(w, g.typeName(inType), g.typeName(outType), indent); err != nil {
return err
}
switch inType.Kind() {
case reflect.Struct:
if err := g.writeConversionForStruct(w, inType, outType, indent+1); err != nil {
return err
}
default:
return fmt.Errorf("Type not supported: %v", inType)
}
if err := writeFooter(w, indent); err != nil {
return err
}
return nil
}
func (g *generator) OverwritePackage(pkg, overwrite string) {
g.pkgOverwrites[pkg] = overwrite
}