-
Notifications
You must be signed in to change notification settings - Fork 295
/
Copy pathgen.go
2880 lines (2626 loc) · 85.6 KB
/
gen.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build codecgen.exec
// +build codecgen.exec
package codec
import (
"bytes"
"encoding/base32"
"errors"
"fmt"
"go/format"
"io"
"io/ioutil"
"math/rand"
"os"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
// "ugorji.net/zz"
"unicode"
"unicode/utf8"
)
// ---------------------------------------------------
// codecgen supports the full cycle of reflection-based codec:
// - RawExt
// - Raw
// - Extensions
// - (Binary|Text|JSON)(Unm|M)arshal
// - generic by-kind
//
// This means that, for dynamic things, we MUST use reflection to at least get the reflect.Type.
// In those areas, we try to only do reflection or interface-conversion when NECESSARY:
// - Extensions, only if Extensions are configured.
//
// However, note following codecgen caveats:
// - Canonical option.
// If Canonical=true, codecgen'ed code may delegate encoding maps to reflection-based code.
// This is due to the runtime work needed to marshal a map in canonical mode.
// However, if map key is a pre-defined/builtin numeric or string type, codecgen
// will try to write it out itself
// - CheckCircularRef option.
// When encoding a struct, a circular reference can lead to a stack overflow.
// If CheckCircularRef=true, codecgen'ed code will delegate encoding structs to reflection-based code.
// - MissingFielder implementation.
// If a type implements MissingFielder, a Selfer is not generated (with a warning message).
// Statically reproducing the runtime work needed to extract the missing fields and marshal them
// along with the struct fields, while handling the Canonical=true special case, was onerous to implement.
//
// During encode/decode, Selfer takes precedence.
// A type implementing Selfer will know how to encode/decode itself statically.
//
// The following field types are supported:
// array: [n]T
// slice: []T
// map: map[K]V
// primitive: [u]int[n], float(32|64), bool, string
// struct
//
// ---------------------------------------------------
// Note that a Selfer cannot call (e|d).(En|De)code on itself,
// as this will cause a circular reference, as (En|De)code will call Selfer methods.
// Any type that implements Selfer must implement completely and not fallback to (En|De)code.
//
// In addition, code in this file manages the generation of fast-path implementations of
// encode/decode of slices/maps of primitive keys/values.
//
// Users MUST re-generate their implementations whenever the code shape changes.
// The generated code will panic if it was generated with a version older than the supporting library.
// ---------------------------------------------------
//
// codec framework is very feature rich.
// When encoding or decoding into an interface, it depends on the runtime type of the interface.
// The type of the interface may be a named type, an extension, etc.
// Consequently, we fallback to runtime codec for encoding/decoding interfaces.
// In addition, we fallback for any value which cannot be guaranteed at runtime.
// This allows us support ANY value, including any named types, specifically those which
// do not implement our interfaces (e.g. Selfer).
//
// This explains some slowness compared to other code generation codecs (e.g. msgp).
// This reduction in speed is only seen when your refers to interfaces,
// e.g. type T struct { A interface{}; B []interface{}; C map[string]interface{} }
//
// codecgen will panic if the file was generated with an old version of the library in use.
//
// Note:
// It was a conscious decision to have gen.go always explicitly call EncodeNil or TryDecodeAsNil.
// This way, there isn't a function call overhead just to see that we should not enter a block of code.
//
// Note:
// codecgen-generated code depends on the variables defined by fast-path.generated.go.
// consequently, you cannot run with tags "codecgen codec.notfastpath".
//
// Note:
// genInternalXXX functions are used for generating fast-path and other internally generated
// files, and not for use in codecgen.
// Size of a struct or value is not portable across machines, especially across 32-bit vs 64-bit
// operating systems. This is due to types like int, uintptr, pointers, (and derived types like slice), etc
// which use the natural word size on those machines, which may be 4 bytes (on 32-bit) or 8 bytes (on 64-bit).
//
// Within decInferLen calls, we may generate an explicit size of the entry.
// We do this because decInferLen values are expected to be approximate,
// and serve as a good hint on the size of the elements or key+value entry.
//
// Since development is done on 64-bit machines, the sizes will be roughly correctly
// on 64-bit OS, and slightly larger than expected on 32-bit OS.
// This is ok.
//
// For reference, look for 'Size' in fast-path.go.tmpl, gen-dec-(array|map).go.tmpl and gen.go (this file).
// GenVersion is the current version of codecgen.
//
// MARKER: Increment this value each time codecgen changes fundamentally.
// Also update codecgen/gen.go (minimumCodecVersion, genVersion, etc).
// Fundamental changes are:
// - helper methods change (signature change, new ones added, some removed, etc)
// - codecgen command line changes
//
// v1: Initial Version
// v2: -
// v3: For Kubernetes: changes in signature of some unpublished helper methods and codecgen cmdline arguments.
// v4: Removed separator support from (en|de)cDriver, and refactored codec(gen)
// v5: changes to support faster json decoding. Let encoder/decoder maintain state of collections.
// v6: removed unsafe from gen, and now uses codecgen.exec tag
// v7: -
// v8: current - we now maintain compatibility with old generated code.
// v9: - skipped
// v10: modified encDriver and decDriver interfaces.
// v11: remove deprecated methods of encDriver and decDriver.
// v12: removed deprecated methods from genHelper and changed container tracking logic
// v13: 20190603 removed DecodeString - use DecodeStringAsBytes instead
// v14: 20190611 refactored nil handling: TryDecodeAsNil -> selective TryNil, etc
// v15: 20190626 encDriver.EncodeString handles StringToRaw flag inside handle
// v16: 20190629 refactoring for v1.1.6
// v17: 20200911 reduce number of types for which we generate fast path functions (v1.1.8)
// v18: 20201004 changed definition of genHelper...Extension (to take interface{}) and eliminated I2Rtid method
// v19: 20201115 updated codecgen cmdline flags and optimized output
// v20: 20201120 refactored GenHelper to one exported function
// v21: 20210104 refactored generated code to honor ZeroCopy=true for more efficiency
// v22: 20210118 fixed issue in generated code when encoding a type which is also a codec.Selfer
// v23: 20210203 changed slice/map types for which we generate fast-path functions
// v24: 20210226 robust handling for Canonical|CheckCircularRef flags and MissingFielder implementations
// v25: 20210406 pass base reflect.Type to side(En|De)code and (En|De)codeExt calls
// v26: 20230201 genHelper changes for more inlining and consequent performance
// v27: 20230219 fix error decoding struct from array - due to misplaced counter increment
// v28: 20230224 fix decoding missing fields of struct from array, due to double counter increment
const genVersion = 28
const (
genCodecPkg = "codec1978" // MARKER: keep in sync with codecgen/gen.go
genTempVarPfx = "yy"
genTopLevelVarName = "x"
// ignore canBeNil parameter, and always set to true.
// This is because nil can appear anywhere, so we should always check.
genAnythingCanBeNil = true
// genStructCanonical configures whether we generate 2 paths based on Canonical flag
// when encoding struct fields.
genStructCanonical = true
// genFastpathCanonical configures whether we support Canonical in fast path.
// The savings is not much.
//
// MARKER: This MUST ALWAYS BE TRUE. fast-path.go.tmp doesn't handle it being false.
genFastpathCanonical = true
// genFastpathTrimTypes configures whether we trim uncommon fastpath types.
genFastpathTrimTypes = true
)
type genStringDecAsBytes string
type genStringDecZC string
var genStringDecAsBytesTyp = reflect.TypeOf(genStringDecAsBytes(""))
var genStringDecZCTyp = reflect.TypeOf(genStringDecZC(""))
var genFormats = []string{"Json", "Cbor", "Msgpack", "Binc", "Simple"}
var (
errGenAllTypesSamePkg = errors.New("All types must be in the same package")
errGenExpectArrayOrMap = errors.New("unexpected type - expecting array/map/slice")
errGenUnexpectedTypeFastpath = errors.New("fast-path: unexpected type - requires map or slice")
// don't use base64, only 63 characters allowed in valid go identifiers
// ie ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_
//
// don't use numbers, as a valid go identifer must start with a letter.
genTypenameEnc = base32.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
genQNameRegex = regexp.MustCompile(`[A-Za-z_.]+`)
)
type genBuf struct {
buf []byte
}
func (x *genBuf) sIf(b bool, s, t string) *genBuf {
if b {
x.buf = append(x.buf, s...)
} else {
x.buf = append(x.buf, t...)
}
return x
}
func (x *genBuf) s(s string) *genBuf { x.buf = append(x.buf, s...); return x }
func (x *genBuf) b(s []byte) *genBuf { x.buf = append(x.buf, s...); return x }
func (x *genBuf) v() string { return string(x.buf) }
func (x *genBuf) f(s string, args ...interface{}) { x.s(fmt.Sprintf(s, args...)) }
func (x *genBuf) reset() {
if x.buf != nil {
x.buf = x.buf[:0]
}
}
// genRunner holds some state used during a Gen run.
type genRunner struct {
w io.Writer // output
c uint64 // counter used for generating varsfx
f uint64 // counter used for saying false
t []reflect.Type // list of types to run selfer on
tc reflect.Type // currently running selfer on this type
te map[uintptr]bool // types for which the encoder has been created
td map[uintptr]bool // types for which the decoder has been created
tz map[uintptr]bool // types for which GenIsZero has been created
cp string // codec import path
im map[string]reflect.Type // imports to add
imn map[string]string // package names of imports to add
imc uint64 // counter for import numbers
is map[reflect.Type]struct{} // types seen during import search
bp string // base PkgPath, for which we are generating for
cpfx string // codec package prefix
ty map[reflect.Type]struct{} // types for which GenIsZero *should* be created
tm map[reflect.Type]struct{} // types for which enc/dec must be generated
ts []reflect.Type // types for which enc/dec must be generated
xs string // top level variable/constant suffix
hn string // fn helper type name
ti *TypeInfos
// rr *rand.Rand // random generator for file-specific types
jsonOnlyWhen, toArrayWhen, omitEmptyWhen *bool
nx bool // no extensions
}
type genIfClause struct {
hasIf bool
}
func (g *genIfClause) end(x *genRunner) {
if g.hasIf {
x.line("}")
}
}
func (g *genIfClause) c(last bool) (v string) {
if last {
if g.hasIf {
v = " } else { "
}
} else if g.hasIf {
v = " } else if "
} else {
v = "if "
g.hasIf = true
}
return
}
// Gen will write a complete go file containing Selfer implementations for each
// type passed. All the types must be in the same package.
//
// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINUOUSLY WITHOUT NOTICE.
func Gen(w io.Writer, buildTags, pkgName, uid string, noExtensions bool,
jsonOnlyWhen, toArrayWhen, omitEmptyWhen *bool,
ti *TypeInfos, types ...reflect.Type) (warnings []string) {
// All types passed to this method do not have a codec.Selfer method implemented directly.
// codecgen already checks the AST and skips any types that define the codec.Selfer methods.
// Consequently, there's no need to check and trim them if they implement codec.Selfer
if len(types) == 0 {
return
}
x := genRunner{
w: w,
t: types,
te: make(map[uintptr]bool),
td: make(map[uintptr]bool),
tz: make(map[uintptr]bool),
im: make(map[string]reflect.Type),
imn: make(map[string]string),
is: make(map[reflect.Type]struct{}),
tm: make(map[reflect.Type]struct{}),
ty: make(map[reflect.Type]struct{}),
ts: []reflect.Type{},
bp: genImportPath(types[0]),
xs: uid,
ti: ti,
jsonOnlyWhen: jsonOnlyWhen,
toArrayWhen: toArrayWhen,
omitEmptyWhen: omitEmptyWhen,
nx: noExtensions,
}
if x.ti == nil {
x.ti = defTypeInfos
}
if x.xs == "" {
rr := rand.New(rand.NewSource(time.Now().UnixNano()))
x.xs = strconv.FormatInt(rr.Int63n(9999), 10)
}
// gather imports first:
x.cp = genImportPath(reflect.TypeOf(x))
x.imn[x.cp] = genCodecPkg
// iterate, check if all in same package, and remove any missingfielders
for i := 0; i < len(x.t); {
t := x.t[i]
// xdebugf("###########: PkgPath: '%v', Name: '%s'\n", genImportPath(t), t.Name())
if genImportPath(t) != x.bp {
halt.onerror(errGenAllTypesSamePkg)
}
ti1 := x.ti.get(rt2id(t), t)
if ti1.flagMissingFielder || ti1.flagMissingFielderPtr {
// output diagnostic message - that nothing generated for this type
warnings = append(warnings, fmt.Sprintf("type: '%v' not generated; implements codec.MissingFielder", t))
copy(x.t[i:], x.t[i+1:])
x.t = x.t[:len(x.t)-1]
continue
}
x.genRefPkgs(t)
i++
}
x.line("// +build go1.6")
if buildTags != "" {
x.line("// +build " + buildTags)
}
x.line(`
// Code generated by codecgen - DO NOT EDIT.
`)
x.line("package " + pkgName)
x.line("")
x.line("import (")
if x.cp != x.bp {
x.cpfx = genCodecPkg + "."
x.linef("%s \"%s\"", genCodecPkg, x.cp)
}
// use a sorted set of im keys, so that we can get consistent output
imKeys := make([]string, 0, len(x.im))
for k := range x.im {
imKeys = append(imKeys, k)
}
sort.Strings(imKeys)
for _, k := range imKeys { // for k, _ := range x.im {
if k == x.imn[k] {
x.linef("\"%s\"", k)
} else {
x.linef("%s \"%s\"", x.imn[k], k)
}
}
// add required packages
for _, k := range [...]string{"runtime", "errors", "strconv", "sort"} { // "reflect", "fmt"
if _, ok := x.im[k]; !ok {
x.line("\"" + k + "\"")
}
}
x.line(")")
x.line("")
x.line("const (")
x.linef("// ----- content types ----")
x.linef("codecSelferCcUTF8%s = %v", x.xs, int64(cUTF8))
x.linef("codecSelferCcRAW%s = %v", x.xs, int64(cRAW))
x.linef("// ----- value types used ----")
for _, vt := range [...]valueType{
valueTypeArray, valueTypeMap, valueTypeString,
valueTypeInt, valueTypeUint, valueTypeFloat,
valueTypeNil,
} {
x.linef("codecSelferValueType%s%s = %v", vt.String(), x.xs, int64(vt))
}
x.linef("codecSelferBitsize%s = uint8(32 << (^uint(0) >> 63))", x.xs)
x.linef("codecSelferDecContainerLenNil%s = %d", x.xs, int64(containerLenNil))
x.line(")")
x.line("var (")
x.line("errCodecSelferOnlyMapOrArrayEncodeToStruct" + x.xs + " = " + "errors.New(`only encoded map or array can be decoded into a struct`)")
x.line("_ sort.Interface = nil")
x.line(")")
x.line("")
x.hn = "codecSelfer" + x.xs
x.line("type " + x.hn + " struct{}")
x.line("")
x.linef("func %sFalse() bool { return false }", x.hn)
x.linef("func %sTrue() bool { return true }", x.hn)
x.line("")
// add types for sorting canonical
for _, s := range []string{"string", "uint64", "int64", "float64"} {
x.linef("type %s%sSlice []%s", x.hn, s, s)
x.linef("func (p %s%sSlice) Len() int { return len(p) }", x.hn, s)
x.linef("func (p %s%sSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }", x.hn, s)
x.linef("func (p %s%sSlice) Less(i, j int) bool { return p[uint(i)] < p[uint(j)] }", x.hn, s)
}
x.line("")
x.varsfxreset()
x.line("func init() {")
x.linef("if %sGenVersion != %v {", x.cpfx, genVersion)
x.line("_, file, _, _ := runtime.Caller(0)")
x.linef("ver := strconv.FormatInt(int64(%sGenVersion), 10)", x.cpfx)
x.outf(`panic(errors.New("codecgen version mismatch: current: %v, need " + ver + ". Re-generate file: " + file))`, genVersion)
x.linef("}")
if len(imKeys) > 0 {
x.line("if false { // reference the types, but skip this branch at build/run time")
for _, k := range imKeys {
t := x.im[k]
x.linef("var _ %s.%s", x.imn[k], t.Name())
}
x.line("} ") // close if false
}
x.line("}") // close init
x.line("")
// generate rest of type info
for _, t := range x.t {
x.tc = t
x.linef("func (%s) codecSelferViaCodecgen() {}", x.genTypeName(t))
x.selfer(true)
x.selfer(false)
x.tryGenIsZero(t)
}
for _, t := range x.ts {
rtid := rt2id(t)
// generate enc functions for all these slice/map types.
x.varsfxreset()
x.linef("func (x %s) enc%s(v %s%s, e *%sEncoder) {", x.hn, x.genMethodNameT(t), x.arr2str(t, "*"), x.genTypeName(t), x.cpfx)
x.genRequiredMethodVars(true)
switch t.Kind() {
case reflect.Array, reflect.Slice, reflect.Chan:
x.encListFallback("v", t)
case reflect.Map:
x.encMapFallback("v", t)
default:
halt.onerror(errGenExpectArrayOrMap)
}
x.line("}")
x.line("")
// generate dec functions for all these slice/map types.
x.varsfxreset()
x.linef("func (x %s) dec%s(v *%s, d *%sDecoder) {", x.hn, x.genMethodNameT(t), x.genTypeName(t), x.cpfx)
x.genRequiredMethodVars(false)
switch t.Kind() {
case reflect.Array, reflect.Slice, reflect.Chan:
x.decListFallback("v", rtid, t)
case reflect.Map:
x.decMapFallback("v", rtid, t)
default:
halt.onerror(errGenExpectArrayOrMap)
}
x.line("}")
x.line("")
}
for t := range x.ty {
x.tryGenIsZero(t)
x.line("")
}
x.line("")
return
}
func (x *genRunner) checkForSelfer(t reflect.Type, varname string) bool {
// return varname != genTopLevelVarName && t != x.tc
// the only time we checkForSelfer is if we are not at the TOP of the generated code.
return varname != genTopLevelVarName
}
func (x *genRunner) arr2str(t reflect.Type, s string) string {
if t.Kind() == reflect.Array {
return s
}
return ""
}
func (x *genRunner) genRequiredMethodVars(encode bool) {
x.line("var h " + x.hn)
if encode {
x.line("z, r := " + x.cpfx + "GenHelper().Encoder(e)")
} else {
x.line("z, r := " + x.cpfx + "GenHelper().Decoder(d)")
}
x.line("_, _, _ = h, z, r")
}
func (x *genRunner) genRefPkgs(t reflect.Type) {
if _, ok := x.is[t]; ok {
return
}
x.is[t] = struct{}{}
tpkg, tname := genImportPath(t), t.Name()
if tpkg != "" && tpkg != x.bp && tpkg != x.cp && tname != "" && tname[0] >= 'A' && tname[0] <= 'Z' {
if _, ok := x.im[tpkg]; !ok {
x.im[tpkg] = t
if idx := strings.LastIndex(tpkg, "/"); idx < 0 {
x.imn[tpkg] = tpkg
} else {
x.imc++
x.imn[tpkg] = "pkg" + strconv.FormatUint(x.imc, 10) + "_" + genGoIdentifier(tpkg[idx+1:], false)
}
}
}
switch t.Kind() {
case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Chan:
x.genRefPkgs(t.Elem())
case reflect.Map:
x.genRefPkgs(t.Elem())
x.genRefPkgs(t.Key())
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
if fname := t.Field(i).Name; fname != "" && fname[0] >= 'A' && fname[0] <= 'Z' {
x.genRefPkgs(t.Field(i).Type)
}
}
}
}
// sayFalse will either say "false" or use a function call that returns false.
func (x *genRunner) sayFalse() string {
x.f++
if x.f%2 == 0 {
return x.hn + "False()"
}
return "false"
}
// sayFalse will either say "true" or use a function call that returns true.
func (x *genRunner) sayTrue() string {
x.f++
if x.f%2 == 0 {
return x.hn + "True()"
}
return "true"
}
func (x *genRunner) varsfx() string {
x.c++
return strconv.FormatUint(x.c, 10)
}
func (x *genRunner) varsfxreset() {
x.c = 0
}
func (x *genRunner) out(s string) {
_, err := io.WriteString(x.w, s)
genCheckErr(err)
}
func (x *genRunner) outf(s string, params ...interface{}) {
_, err := fmt.Fprintf(x.w, s, params...)
genCheckErr(err)
}
func (x *genRunner) line(s string) {
x.out(s)
if len(s) == 0 || s[len(s)-1] != '\n' {
x.out("\n")
}
}
func (x *genRunner) lineIf(s string) {
if s != "" {
x.line(s)
}
}
func (x *genRunner) linef(s string, params ...interface{}) {
x.outf(s, params...)
if len(s) == 0 || s[len(s)-1] != '\n' {
x.out("\n")
}
}
func (x *genRunner) genTypeName(t reflect.Type) (n string) {
// if the type has a PkgPath, which doesn't match the current package,
// then include it.
// We cannot depend on t.String() because it includes current package,
// or t.PkgPath because it includes full import path,
//
var ptrPfx string
for t.Kind() == reflect.Ptr {
ptrPfx += "*"
t = t.Elem()
}
if tn := t.Name(); tn != "" {
return ptrPfx + x.genTypeNamePrim(t)
}
switch t.Kind() {
case reflect.Map:
return ptrPfx + "map[" + x.genTypeName(t.Key()) + "]" + x.genTypeName(t.Elem())
case reflect.Slice:
return ptrPfx + "[]" + x.genTypeName(t.Elem())
case reflect.Array:
return ptrPfx + "[" + strconv.FormatInt(int64(t.Len()), 10) + "]" + x.genTypeName(t.Elem())
case reflect.Chan:
return ptrPfx + t.ChanDir().String() + " " + x.genTypeName(t.Elem())
default:
if t == intfTyp {
return ptrPfx + "interface{}"
} else {
return ptrPfx + x.genTypeNamePrim(t)
}
}
}
func (x *genRunner) genTypeNamePrim(t reflect.Type) (n string) {
if t.Name() == "" {
return t.String()
} else if genImportPath(t) == "" || genImportPath(t) == genImportPath(x.tc) {
return t.Name()
} else {
return x.imn[genImportPath(t)] + "." + t.Name()
// return t.String() // best way to get the package name inclusive
}
}
func (x *genRunner) genZeroValueR(t reflect.Type) string {
// if t is a named type, w
switch t.Kind() {
case reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func,
reflect.Slice, reflect.Map, reflect.Invalid:
return "nil"
case reflect.Bool:
return "false"
case reflect.String:
return `""`
case reflect.Struct, reflect.Array:
return x.genTypeName(t) + "{}"
default: // all numbers
return "0"
}
}
func (x *genRunner) genMethodNameT(t reflect.Type) (s string) {
return genMethodNameT(t, x.tc)
}
func (x *genRunner) tryGenIsZero(t reflect.Type) (done bool) {
if t.Kind() != reflect.Struct || t.Implements(isCodecEmptyerTyp) {
return
}
rtid := rt2id(t)
if _, ok := x.tz[rtid]; ok {
delete(x.ty, t)
return
}
x.tz[rtid] = true
delete(x.ty, t)
ti := x.ti.get(rtid, t)
tisfi := ti.sfi.source() // always use sequence from file. decStruct expects same thing.
varname := genTopLevelVarName
x.linef("func (%s *%s) IsCodecEmpty() bool {", varname, x.genTypeName(t))
anonSeen := make(map[reflect.Type]bool)
var omitline genBuf
for _, si := range tisfi {
if si.path.parent != nil {
root := si.path.root()
if anonSeen[root.typ] {
continue
}
anonSeen[root.typ] = true
}
t2 := genOmitEmptyLinePreChecks(varname, t, si, &omitline, true)
// if Ptr, we already checked if nil above
if t2.Type.Kind() != reflect.Ptr {
x.doEncOmitEmptyLine(t2, varname, &omitline)
omitline.s(" || ")
}
}
omitline.s(" false")
x.linef("return !(%s)", omitline.v())
x.line("}")
x.line("")
return true
}
func (x *genRunner) selfer(encode bool) {
t := x.tc
// ti := x.ti.get(rt2id(t), t)
t0 := t
// always make decode use a pointer receiver,
// and structs/arrays always use a ptr receiver (encode|decode)
isptr := !encode || t.Kind() == reflect.Array || (t.Kind() == reflect.Struct && t != timeTyp)
x.varsfxreset()
fnSigPfx := "func (" + genTopLevelVarName + " "
if isptr {
fnSigPfx += "*"
}
fnSigPfx += x.genTypeName(t)
x.out(fnSigPfx)
if isptr {
t = reflect.PtrTo(t)
}
if encode {
x.line(") CodecEncodeSelf(e *" + x.cpfx + "Encoder) {")
x.genRequiredMethodVars(true)
if t0.Kind() == reflect.Struct {
x.linef("if z.EncBasicHandle().CheckCircularRef { z.EncEncode(%s); return }", genTopLevelVarName)
}
x.encVar(genTopLevelVarName, t)
} else {
x.line(") CodecDecodeSelf(d *" + x.cpfx + "Decoder) {")
x.genRequiredMethodVars(false)
// do not use decVar, as there is no need to check TryDecodeAsNil
// or way to elegantly handle that, and also setting it to a
// non-nil value doesn't affect the pointer passed.
// x.decVar(genTopLevelVarName, t, false)
x.dec(genTopLevelVarName, t0, true)
}
x.line("}")
x.line("")
if encode || t0.Kind() != reflect.Struct {
return
}
// write is containerMap
x.out(fnSigPfx)
x.line(") codecDecodeSelfFromMap(l int, d *" + x.cpfx + "Decoder) {")
x.genRequiredMethodVars(false)
x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0)
x.line("}")
x.line("")
// write containerArray
x.out(fnSigPfx)
x.line(") codecDecodeSelfFromArray(l int, d *" + x.cpfx + "Decoder) {")
x.genRequiredMethodVars(false)
x.decStructArray(genTopLevelVarName, "l", "return", rt2id(t0), t0)
x.line("}")
x.line("")
}
// used for chan, array, slice, map
func (x *genRunner) xtraSM(varname string, t reflect.Type, ti *typeInfo, encode, isptr bool) {
var ptrPfx, addrPfx string
if isptr {
ptrPfx = "*"
} else {
addrPfx = "&"
}
if encode {
x.linef("h.enc%s((%s%s)(%s), e)", x.genMethodNameT(t), ptrPfx, x.genTypeName(t), varname)
} else {
x.linef("h.dec%s((*%s)(%s%s), d)", x.genMethodNameT(t), x.genTypeName(t), addrPfx, varname)
}
x.registerXtraT(t, ti)
}
func (x *genRunner) registerXtraT(t reflect.Type, ti *typeInfo) {
// recursively register the types
tk := t.Kind()
if tk == reflect.Ptr {
x.registerXtraT(t.Elem(), nil)
return
}
if _, ok := x.tm[t]; ok {
return
}
switch tk {
case reflect.Chan, reflect.Slice, reflect.Array, reflect.Map:
default:
return
}
// only register the type if it will not default to a fast-path
if ti == nil {
ti = x.ti.get(rt2id(t), t)
}
if _, rtidu := genFastpathUnderlying(t, ti.rtid, ti); fastpathAvIndex(rtidu) != -1 {
return
}
x.tm[t] = struct{}{}
x.ts = append(x.ts, t)
// check if this refers to any xtra types eg. a slice of array: add the array
x.registerXtraT(t.Elem(), nil)
if tk == reflect.Map {
x.registerXtraT(t.Key(), nil)
}
}
// encVar will encode a variable.
// The parameter, t, is the reflect.Type of the variable itself
func (x *genRunner) encVar(varname string, t reflect.Type) {
var checkNil bool
// case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan:
// do not include checkNil for slice and maps, as we already checkNil below it
switch t.Kind() {
case reflect.Ptr, reflect.Interface, reflect.Chan:
checkNil = true
}
x.encVarChkNil(varname, t, checkNil)
}
func (x *genRunner) encVarChkNil(varname string, t reflect.Type, checkNil bool) {
if checkNil {
x.linef("if %s == nil { r.EncodeNil() } else {", varname)
}
switch t.Kind() {
case reflect.Ptr:
telem := t.Elem()
tek := telem.Kind()
if tek == reflect.Array || (tek == reflect.Struct && telem != timeTyp) {
x.enc(varname, genNonPtr(t), true)
break
}
i := x.varsfx()
x.line(genTempVarPfx + i + " := *" + varname)
x.enc(genTempVarPfx+i, genNonPtr(t), false)
case reflect.Struct, reflect.Array:
if t == timeTyp {
x.enc(varname, t, false)
break
}
i := x.varsfx()
x.line(genTempVarPfx + i + " := &" + varname)
x.enc(genTempVarPfx+i, t, true)
default:
x.enc(varname, t, false)
}
if checkNil {
x.line("}")
}
}
// enc will encode a variable (varname) of type t, where t represents T.
// if t is !time.Time and t is of kind reflect.Struct or reflect.Array, varname is of type *T
// (to prevent copying),
// else t is of type T
func (x *genRunner) enc(varname string, t reflect.Type, isptr bool) {
rtid := rt2id(t)
ti2 := x.ti.get(rtid, t)
// We call CodecEncodeSelf if one of the following are honored:
// - the type already implements Selfer, call that
// - the type has a Selfer implementation just created, use that
// - the type is in the list of the ones we will generate for, but it is not currently being generated
mi := x.varsfx()
// tptr := reflect.PtrTo(t)
// tk := t.Kind()
// check if
// - type is time.Time, RawExt, Raw
// - the type implements (Text|JSON|Binary)(Unm|M)arshal
var hasIf genIfClause
defer hasIf.end(x) // end if block (if necessary)
var ptrPfx, addrPfx string
if isptr {
ptrPfx = "*"
} else {
addrPfx = "&"
}
if t == timeTyp {
x.linef("%s z.EncBasicHandle().TimeBuiltin() { r.EncodeTime(%s%s)", hasIf.c(false), ptrPfx, varname)
// return
}
if t == rawTyp {
x.linef("%s z.EncRaw(%s%s)", hasIf.c(true), ptrPfx, varname)
return
}
if t == rawExtTyp {
x.linef("%s r.EncodeRawExt(%s%s)", hasIf.c(true), addrPfx, varname)
return
}
// only check for extensions if extensions are configured,
// and the type is named, and has a packagePath,
// and this is not the CodecEncodeSelf or CodecDecodeSelf method (i.e. it is not a Selfer)
if !x.nx && varname != genTopLevelVarName && t != genStringDecAsBytesTyp &&
t != genStringDecZCTyp && genImportPath(t) != "" && t.Name() != "" {
yy := fmt.Sprintf("%sxt%s", genTempVarPfx, mi)
x.linef("%s %s := z.Extension(%s); %s != nil { z.EncExtension(%s, %s) ",
hasIf.c(false), yy, varname, yy, varname, yy)
}
if x.checkForSelfer(t, varname) {
if ti2.flagSelfer {
x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
return
}
if ti2.flagSelferPtr {
if isptr {
x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
} else {
x.linef("%s %ssf%s := &%s", hasIf.c(true), genTempVarPfx, mi, varname)
x.linef("%ssf%s.CodecEncodeSelf(e)", genTempVarPfx, mi)
}
return
}
if _, ok := x.te[rtid]; ok {
x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
return
}
}
inlist := false
for _, t0 := range x.t {
if t == t0 {
inlist = true
if x.checkForSelfer(t, varname) {
x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
return
}
break
}
}
var rtidAdded bool
if t == x.tc {
x.te[rtid] = true
rtidAdded = true
}
if ti2.flagBinaryMarshaler {
x.linef("%s z.EncBinary() { z.EncBinaryMarshal(%s%v) ", hasIf.c(false), ptrPfx, varname)
} else if ti2.flagBinaryMarshalerPtr {
x.linef("%s z.EncBinary() { z.EncBinaryMarshal(%s%v) ", hasIf.c(false), addrPfx, varname)
}
if ti2.flagJsonMarshaler {
x.linef("%s !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(%s%v) ", hasIf.c(false), ptrPfx, varname)
} else if ti2.flagJsonMarshalerPtr {
x.linef("%s !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(%s%v) ", hasIf.c(false), addrPfx, varname)
} else if ti2.flagTextMarshaler {
x.linef("%s !z.EncBinary() { z.EncTextMarshal(%s%v) ", hasIf.c(false), ptrPfx, varname)
} else if ti2.flagTextMarshalerPtr {
x.linef("%s !z.EncBinary() { z.EncTextMarshal(%s%v) ", hasIf.c(false), addrPfx, varname)
}
x.lineIf(hasIf.c(true))
switch t.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
x.line("r.EncodeInt(int64(" + varname + "))")
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
x.line("r.EncodeUint(uint64(" + varname + "))")
case reflect.Float32:
x.line("r.EncodeFloat32(float32(" + varname + "))")
case reflect.Float64:
x.line("r.EncodeFloat64(float64(" + varname + "))")
case reflect.Complex64:
x.linef("z.EncEncodeComplex64(complex64(%s))", varname)
case reflect.Complex128:
x.linef("z.EncEncodeComplex128(complex128(%s))", varname)
case reflect.Bool:
x.line("r.EncodeBool(bool(" + varname + "))")
case reflect.String:
x.linef("r.EncodeString(string(%s))", varname)
case reflect.Chan:
x.xtraSM(varname, t, ti2, true, false)
// x.encListFallback(varname, rtid, t)