Debian Codegraph @

vendor/github.com/ugorji/go/codec/gen.go

raw
1 // +build codecgen.exec
2
3 // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
4 // Use of this source code is governed by a MIT license found in the LICENSE file.
5
6 package codec
7
8 import (
9 "bytes"
10 "encoding/base64"
11 "errors"
12 "fmt"
13 "go/format"
14 "io"
15 "io/ioutil"
16 "math/rand"
17 "reflect"
18 "regexp"
19 "sort"
20 "strconv"
21 "strings"
22 "sync"
23 "text/template"
24 "time"
25 "unicode"
26 "unicode/utf8"
27 )
28
29 // ---------------------------------------------------
30 // codecgen supports the full cycle of reflection-based codec:
31 // - RawExt
32 // - Raw
33 // - Builtins
34 // - Extensions
35 // - (Binary|Text|JSON)(Unm|M)arshal
36 // - generic by-kind
37 //
38 // This means that, for dynamic things, we MUST use reflection to at least get the reflect.Type.
39 // In those areas, we try to only do reflection or interface-conversion when NECESSARY:
40 // - Extensions, only if Extensions are configured.
41 //
42 // However, codecgen doesn't support the following:
43 // - Canonical option. (codecgen IGNORES it currently)
44 // This is just because it has not been implemented.
45 //
46 // During encode/decode, Selfer takes precedence.
47 // A type implementing Selfer will know how to encode/decode itself statically.
48 //
49 // The following field types are supported:
50 // array: [n]T
51 // slice: []T
52 // map: map[K]V
53 // primitive: [u]int[n], float(32|64), bool, string
54 // struct
55 //
56 // ---------------------------------------------------
57 // Note that a Selfer cannot call (e|d).(En|De)code on itself,
58 // as this will cause a circular reference, as (En|De)code will call Selfer methods.
59 // Any type that implements Selfer must implement completely and not fallback to (En|De)code.
60 //
61 // In addition, code in this file manages the generation of fast-path implementations of
62 // encode/decode of slices/maps of primitive keys/values.
63 //
64 // Users MUST re-generate their implementations whenever the code shape changes.
65 // The generated code will panic if it was generated with a version older than the supporting library.
66 // ---------------------------------------------------
67 //
68 // codec framework is very feature rich.
69 // When encoding or decoding into an interface, it depends on the runtime type of the interface.
70 // The type of the interface may be a named type, an extension, etc.
71 // Consequently, we fallback to runtime codec for encoding/decoding interfaces.
72 // In addition, we fallback for any value which cannot be guaranteed at runtime.
73 // This allows us support ANY value, including any named types, specifically those which
74 // do not implement our interfaces (e.g. Selfer).
75 //
76 // This explains some slowness compared to other code generation codecs (e.g. msgp).
77 // This reduction in speed is only seen when your refers to interfaces,
78 // e.g. type T struct { A interface{}; B []interface{}; C map[string]interface{} }
79 //
80 // codecgen will panic if the file was generated with an old version of the library in use.
81 //
82 // Note:
83 // It was a conscious decision to have gen.go always explicitly call EncodeNil or TryDecodeAsNil.
84 // This way, there isn't a function call overhead just to see that we should not enter a block of code.
85 //
86 // Note:
87 // codecgen-generated code depends on the variables defined by fast-path.generated.go.
88 // consequently, you cannot run with tags "codecgen notfastpath".
89
90 // GenVersion is the current version of codecgen.
91 //
92 // NOTE: Increment this value each time codecgen changes fundamentally.
93 // Fundamental changes are:
94 // - helper methods change (signature change, new ones added, some removed, etc)
95 // - codecgen command line changes
96 //
97 // v1: Initial Version
98 // v2:
99 // v3: Changes for Kubernetes:
100 // changes in signature of some unpublished helper methods and codecgen cmdline arguments.
101 // v4: Removed separator support from (en|de)cDriver, and refactored codec(gen)
102 // v5: changes to support faster json decoding. Let encoder/decoder maintain state of collections.
103 // v6: removed unsafe from gen, and now uses codecgen.exec tag
104 const genVersion = 8
105
106 const (
107 genCodecPkg = "codec1978"
108 genTempVarPfx = "yy"
109 genTopLevelVarName = "x"
110
111 // ignore canBeNil parameter, and always set to true.
112 // This is because nil can appear anywhere, so we should always check.
113 genAnythingCanBeNil = true
114
115 // if genUseOneFunctionForDecStructMap, make a single codecDecodeSelferFromMap function;
116 // else make codecDecodeSelferFromMap{LenPrefix,CheckBreak} so that conditionals
117 // are not executed a lot.
118 //
119 // From testing, it didn't make much difference in runtime, so keep as true (one function only)
120 genUseOneFunctionForDecStructMap = true
121 )
122
123 type genStructMapStyle uint8
124
125 const (
126 genStructMapStyleConsolidated genStructMapStyle = iota
127 genStructMapStyleLenPrefix
128 genStructMapStyleCheckBreak
129 )
130
131 var (
132 genAllTypesSamePkgErr = errors.New("All types must be in the same package")
133 genExpectArrayOrMapErr = errors.New("unexpected type. Expecting array/map/slice")
134 genBase64enc = base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789__")
135 genQNameRegex = regexp.MustCompile(`[A-Za-z_.]+`)
136 )
137
138 // genRunner holds some state used during a Gen run.
139 type genRunner struct {
140 w io.Writer // output
141 c uint64 // counter used for generating varsfx
142 t []reflect.Type // list of types to run selfer on
143
144 tc reflect.Type // currently running selfer on this type
145 te map[uintptr]bool // types for which the encoder has been created
146 td map[uintptr]bool // types for which the decoder has been created
147 cp string // codec import path
148
149 im map[string]reflect.Type // imports to add
150 imn map[string]string // package names of imports to add
151 imc uint64 // counter for import numbers
152
153 is map[reflect.Type]struct{} // types seen during import search
154 bp string // base PkgPath, for which we are generating for
155
156 cpfx string // codec package prefix
157
158 tm map[reflect.Type]struct{} // types for which enc/dec must be generated
159 ts []reflect.Type // types for which enc/dec must be generated
160
161 xs string // top level variable/constant suffix
162 hn string // fn helper type name
163
164 ti *TypeInfos
165 // rr *rand.Rand // random generator for file-specific types
166
167 nx bool // no extensions
168 }
169
170 // Gen will write a complete go file containing Selfer implementations for each
171 // type passed. All the types must be in the same package.
172 //
173 // Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE.
174 func Gen(w io.Writer, buildTags, pkgName, uid string, noExtensions bool,
175 ti *TypeInfos, typ ...reflect.Type) {
176 // All types passed to this method do not have a codec.Selfer method implemented directly.
177 // codecgen already checks the AST and skips any types that define the codec.Selfer methods.
178 // Consequently, there's no need to check and trim them if they implement codec.Selfer
179
180 if len(typ) == 0 {
181 return
182 }
183 x := genRunner{
184 w: w,
185 t: typ,
186 te: make(map[uintptr]bool),
187 td: make(map[uintptr]bool),
188 im: make(map[string]reflect.Type),
189 imn: make(map[string]string),
190 is: make(map[reflect.Type]struct{}),
191 tm: make(map[reflect.Type]struct{}),
192 ts: []reflect.Type{},
193 bp: genImportPath(typ[0]),
194 xs: uid,
195 ti: ti,
196 nx: noExtensions,
197 }
198 if x.ti == nil {
199 x.ti = defTypeInfos
200 }
201 if x.xs == "" {
202 rr := rand.New(rand.NewSource(time.Now().UnixNano()))
203 x.xs = strconv.FormatInt(rr.Int63n(9999), 10)
204 }
205
206 // gather imports first:
207 x.cp = genImportPath(reflect.TypeOf(x))
208 x.imn[x.cp] = genCodecPkg
209 for _, t := range typ {
210 // fmt.Printf("###########: PkgPath: '%v', Name: '%s'\n", genImportPath(t), t.Name())
211 if genImportPath(t) != x.bp {
212 panic(genAllTypesSamePkgErr)
213 }
214 x.genRefPkgs(t)
215 }
216 if buildTags != "" {
217 x.line("// +build " + buildTags)
218 x.line("")
219 }
220 x.line(`
221
222 // ************************************************************
223 // DO NOT EDIT.
224 // THIS FILE IS AUTO-GENERATED BY codecgen.
225 // ************************************************************
226
227 `)
228 x.line("package " + pkgName)
229 x.line("")
230 x.line("import (")
231 if x.cp != x.bp {
232 x.cpfx = genCodecPkg + "."
233 x.linef("%s \"%s\"", genCodecPkg, x.cp)
234 }
235 // use a sorted set of im keys, so that we can get consistent output
236 imKeys := make([]string, 0, len(x.im))
237 for k, _ := range x.im {
238 imKeys = append(imKeys, k)
239 }
240 sort.Strings(imKeys)
241 for _, k := range imKeys { // for k, _ := range x.im {
242 x.linef("%s \"%s\"", x.imn[k], k)
243 }
244 // add required packages
245 for _, k := range [...]string{"reflect", "runtime", "fmt", "errors"} {
246 if _, ok := x.im[k]; !ok {
247 x.line("\"" + k + "\"")
248 }
249 }
250 x.line(")")
251 x.line("")
252
253 x.line("const (")
254 x.linef("// ----- content types ----")
255 x.linef("codecSelferC_UTF8%s = %v", x.xs, int64(c_UTF8))
256 x.linef("codecSelferC_RAW%s = %v", x.xs, int64(c_RAW))
257 x.linef("// ----- value types used ----")
258 x.linef("codecSelferValueTypeArray%s = %v", x.xs, int64(valueTypeArray))
259 x.linef("codecSelferValueTypeMap%s = %v", x.xs, int64(valueTypeMap))
260 x.linef("// ----- containerStateValues ----")
261 x.linef("codecSelfer_containerMapKey%s = %v", x.xs, int64(containerMapKey))
262 x.linef("codecSelfer_containerMapValue%s = %v", x.xs, int64(containerMapValue))
263 x.linef("codecSelfer_containerMapEnd%s = %v", x.xs, int64(containerMapEnd))
264 x.linef("codecSelfer_containerArrayElem%s = %v", x.xs, int64(containerArrayElem))
265 x.linef("codecSelfer_containerArrayEnd%s = %v", x.xs, int64(containerArrayEnd))
266 x.line(")")
267 x.line("var (")
268 x.line("codecSelferBitsize" + x.xs + " = uint8(reflect.TypeOf(uint(0)).Bits())")
269 x.line("codecSelferOnlyMapOrArrayEncodeToStructErr" + x.xs + " = errors.New(`only encoded map or array can be decoded into a struct`)")
270 x.line(")")
271 x.line("")
272
273 x.hn = "codecSelfer" + x.xs
274 x.line("type " + x.hn + " struct{}")
275 x.line("")
276
277 x.varsfxreset()
278 x.line("func init() {")
279 x.linef("if %sGenVersion != %v {", x.cpfx, genVersion)
280 x.line("_, file, _, _ := runtime.Caller(0)")
281 x.line(`err := fmt.Errorf("codecgen version mismatch: current: %v, need %v. Re-generate file: %v", `)
282 x.linef(`%v, %sGenVersion, file)`, genVersion, x.cpfx)
283 x.line("panic(err)")
284 x.linef("}")
285 x.line("if false { // reference the types, but skip this branch at build/run time")
286 var n int
287 // for k, t := range x.im {
288 for _, k := range imKeys {
289 t := x.im[k]
290 x.linef("var v%v %s.%s", n, x.imn[k], t.Name())
291 n++
292 }
293 if n > 0 {
294 x.out("_")
295 for i := 1; i < n; i++ {
296 x.out(", _")
297 }
298 x.out(" = v0")
299 for i := 1; i < n; i++ {
300 x.outf(", v%v", i)
301 }
302 }
303 x.line("} ") // close if false
304 x.line("}") // close init
305 x.line("")
306
307 // generate rest of type info
308 for _, t := range typ {
309 x.tc = t
310 x.selfer(true)
311 x.selfer(false)
312 }
313
314 for _, t := range x.ts {
315 rtid := rt2id(t)
316 // generate enc functions for all these slice/map types.
317 x.varsfxreset()
318 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)
319 x.genRequiredMethodVars(true)
320 switch t.Kind() {
321 case reflect.Array, reflect.Slice, reflect.Chan:
322 x.encListFallback("v", t)
323 case reflect.Map:
324 x.encMapFallback("v", t)
325 default:
326 panic(genExpectArrayOrMapErr)
327 }
328 x.line("}")
329 x.line("")
330
331 // generate dec functions for all these slice/map types.
332 x.varsfxreset()
333 x.linef("func (x %s) dec%s(v *%s, d *%sDecoder) {", x.hn, x.genMethodNameT(t), x.genTypeName(t), x.cpfx)
334 x.genRequiredMethodVars(false)
335 switch t.Kind() {
336 case reflect.Array, reflect.Slice, reflect.Chan:
337 x.decListFallback("v", rtid, t)
338 case reflect.Map:
339 x.decMapFallback("v", rtid, t)
340 default:
341 panic(genExpectArrayOrMapErr)
342 }
343 x.line("}")
344 x.line("")
345 }
346
347 x.line("")
348 }
349
350 func (x *genRunner) checkForSelfer(t reflect.Type, varname string) bool {
351 // return varname != genTopLevelVarName && t != x.tc
352 // the only time we checkForSelfer is if we are not at the TOP of the generated code.
353 return varname != genTopLevelVarName
354 }
355
356 func (x *genRunner) arr2str(t reflect.Type, s string) string {
357 if t.Kind() == reflect.Array {
358 return s
359 }
360 return ""
361 }
362
363 func (x *genRunner) genRequiredMethodVars(encode bool) {
364 x.line("var h " + x.hn)
365 if encode {
366 x.line("z, r := " + x.cpfx + "GenHelperEncoder(e)")
367 } else {
368 x.line("z, r := " + x.cpfx + "GenHelperDecoder(d)")
369 }
370 x.line("_, _, _ = h, z, r")
371 }
372
373 func (x *genRunner) genRefPkgs(t reflect.Type) {
374 if _, ok := x.is[t]; ok {
375 return
376 }
377 // fmt.Printf(">>>>>>: PkgPath: '%v', Name: '%s'\n", genImportPath(t), t.Name())
378 x.is[t] = struct{}{}
379 tpkg, tname := genImportPath(t), t.Name()
380 if tpkg != "" && tpkg != x.bp && tpkg != x.cp && tname != "" && tname[0] >= 'A' && tname[0] <= 'Z' {
381 if _, ok := x.im[tpkg]; !ok {
382 x.im[tpkg] = t
383 if idx := strings.LastIndex(tpkg, "/"); idx < 0 {
384 x.imn[tpkg] = tpkg
385 } else {
386 x.imc++
387 x.imn[tpkg] = "pkg" + strconv.FormatUint(x.imc, 10) + "_" + genGoIdentifier(tpkg[idx+1:], false)
388 }
389 }
390 }
391 switch t.Kind() {
392 case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Chan:
393 x.genRefPkgs(t.Elem())
394 case reflect.Map:
395 x.genRefPkgs(t.Elem())
396 x.genRefPkgs(t.Key())
397 case reflect.Struct:
398 for i := 0; i < t.NumField(); i++ {
399 if fname := t.Field(i).Name; fname != "" && fname[0] >= 'A' && fname[0] <= 'Z' {
400 x.genRefPkgs(t.Field(i).Type)
401 }
402 }
403 }
404 }
405
406 func (x *genRunner) line(s string) {
407 x.out(s)
408 if len(s) == 0 || s[len(s)-1] != '\n' {
409 x.out("\n")
410 }
411 }
412
413 func (x *genRunner) varsfx() string {
414 x.c++
415 return strconv.FormatUint(x.c, 10)
416 }
417
418 func (x *genRunner) varsfxreset() {
419 x.c = 0
420 }
421
422 func (x *genRunner) out(s string) {
423 if _, err := io.WriteString(x.w, s); err != nil {
424 panic(err)
425 }
426 }
427
428 func (x *genRunner) linef(s string, params ...interface{}) {
429 x.line(fmt.Sprintf(s, params...))
430 }
431
432 func (x *genRunner) outf(s string, params ...interface{}) {
433 x.out(fmt.Sprintf(s, params...))
434 }
435
436 func (x *genRunner) genTypeName(t reflect.Type) (n string) {
437 // defer func() { fmt.Printf(">>>> ####: genTypeName: t: %v, name: '%s'\n", t, n) }()
438
439 // if the type has a PkgPath, which doesn't match the current package,
440 // then include it.
441 // We cannot depend on t.String() because it includes current package,
442 // or t.PkgPath because it includes full import path,
443 //
444 var ptrPfx string
445 for t.Kind() == reflect.Ptr {
446 ptrPfx += "*"
447 t = t.Elem()
448 }
449 if tn := t.Name(); tn != "" {
450 return ptrPfx + x.genTypeNamePrim(t)
451 }
452 switch t.Kind() {
453 case reflect.Map:
454 return ptrPfx + "map[" + x.genTypeName(t.Key()) + "]" + x.genTypeName(t.Elem())
455 case reflect.Slice:
456 return ptrPfx + "[]" + x.genTypeName(t.Elem())
457 case reflect.Array:
458 return ptrPfx + "[" + strconv.FormatInt(int64(t.Len()), 10) + "]" + x.genTypeName(t.Elem())
459 case reflect.Chan:
460 return ptrPfx + t.ChanDir().String() + " " + x.genTypeName(t.Elem())
461 default:
462 if t == intfTyp {
463 return ptrPfx + "interface{}"
464 } else {
465 return ptrPfx + x.genTypeNamePrim(t)
466 }
467 }
468 }
469
470 func (x *genRunner) genTypeNamePrim(t reflect.Type) (n string) {
471 if t.Name() == "" {
472 return t.String()
473 } else if genImportPath(t) == "" || genImportPath(t) == genImportPath(x.tc) {
474 return t.Name()
475 } else {
476 return x.imn[genImportPath(t)] + "." + t.Name()
477 // return t.String() // best way to get the package name inclusive
478 }
479 }
480
481 func (x *genRunner) genZeroValueR(t reflect.Type) string {
482 // if t is a named type, w
483 switch t.Kind() {
484 case reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func,
485 reflect.Slice, reflect.Map, reflect.Invalid:
486 return "nil"
487 case reflect.Bool:
488 return "false"
489 case reflect.String:
490 return `""`
491 case reflect.Struct, reflect.Array:
492 return x.genTypeName(t) + "{}"
493 default: // all numbers
494 return "0"
495 }
496 }
497
498 func (x *genRunner) genMethodNameT(t reflect.Type) (s string) {
499 return genMethodNameT(t, x.tc)
500 }
501
502 func (x *genRunner) selfer(encode bool) {
503 t := x.tc
504 t0 := t
505 // always make decode use a pointer receiver,
506 // and structs always use a ptr receiver (encode|decode)
507 isptr := !encode || t.Kind() == reflect.Struct
508 x.varsfxreset()
509 fnSigPfx := "func (x "
510 if isptr {
511 fnSigPfx += "*"
512 }
513 fnSigPfx += x.genTypeName(t)
514
515 x.out(fnSigPfx)
516 if isptr {
517 t = reflect.PtrTo(t)
518 }
519 if encode {
520 x.line(") CodecEncodeSelf(e *" + x.cpfx + "Encoder) {")
521 x.genRequiredMethodVars(true)
522 // x.enc(genTopLevelVarName, t)
523 x.encVar(genTopLevelVarName, t)
524 } else {
525 x.line(") CodecDecodeSelf(d *" + x.cpfx + "Decoder) {")
526 x.genRequiredMethodVars(false)
527 // do not use decVar, as there is no need to check TryDecodeAsNil
528 // or way to elegantly handle that, and also setting it to a
529 // non-nil value doesn't affect the pointer passed.
530 // x.decVar(genTopLevelVarName, t, false)
531 x.dec(genTopLevelVarName, t0)
532 }
533 x.line("}")
534 x.line("")
535
536 if encode || t0.Kind() != reflect.Struct {
537 return
538 }
539
540 // write is containerMap
541 if genUseOneFunctionForDecStructMap {
542 x.out(fnSigPfx)
543 x.line(") codecDecodeSelfFromMap(l int, d *" + x.cpfx + "Decoder) {")
544 x.genRequiredMethodVars(false)
545 x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0, genStructMapStyleConsolidated)
546 x.line("}")
547 x.line("")
548 } else {
549 x.out(fnSigPfx)
550 x.line(") codecDecodeSelfFromMapLenPrefix(l int, d *" + x.cpfx + "Decoder) {")
551 x.genRequiredMethodVars(false)
552 x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0, genStructMapStyleLenPrefix)
553 x.line("}")
554 x.line("")
555
556 x.out(fnSigPfx)
557 x.line(") codecDecodeSelfFromMapCheckBreak(l int, d *" + x.cpfx + "Decoder) {")
558 x.genRequiredMethodVars(false)
559 x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0, genStructMapStyleCheckBreak)
560 x.line("}")
561 x.line("")
562 }
563
564 // write containerArray
565 x.out(fnSigPfx)
566 x.line(") codecDecodeSelfFromArray(l int, d *" + x.cpfx + "Decoder) {")
567 x.genRequiredMethodVars(false)
568 x.decStructArray(genTopLevelVarName, "l", "return", rt2id(t0), t0)
569 x.line("}")
570 x.line("")
571
572 }
573
574 // used for chan, array, slice, map
575 func (x *genRunner) xtraSM(varname string, encode bool, t reflect.Type) {
576 if encode {
577 x.linef("h.enc%s((%s%s)(%s), e)", x.genMethodNameT(t), x.arr2str(t, "*"), x.genTypeName(t), varname)
578 } else {
579 x.linef("h.dec%s((*%s)(%s), d)", x.genMethodNameT(t), x.genTypeName(t), varname)
580 }
581 x.registerXtraT(t)
582 }
583
584 func (x *genRunner) registerXtraT(t reflect.Type) {
585 // recursively register the types
586 if _, ok := x.tm[t]; ok {
587 return
588 }
589 var tkey reflect.Type
590 switch t.Kind() {
591 case reflect.Chan, reflect.Slice, reflect.Array:
592 case reflect.Map:
593 tkey = t.Key()
594 default:
595 return
596 }
597 x.tm[t] = struct{}{}
598 x.ts = append(x.ts, t)
599 // check if this refers to any xtra types eg. a slice of array: add the array
600 x.registerXtraT(t.Elem())
601 if tkey != nil {
602 x.registerXtraT(tkey)
603 }
604 }
605
606 // encVar will encode a variable.
607 // The parameter, t, is the reflect.Type of the variable itself
608 func (x *genRunner) encVar(varname string, t reflect.Type) {
609 // fmt.Printf(">>>>>> varname: %s, t: %v\n", varname, t)
610 var checkNil bool
611 switch t.Kind() {
612 case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan:
613 checkNil = true
614 }
615 if checkNil {
616 x.linef("if %s == nil { r.EncodeNil() } else { ", varname)
617 }
618 switch t.Kind() {
619 case reflect.Ptr:
620 switch t.Elem().Kind() {
621 case reflect.Struct, reflect.Array:
622 x.enc(varname, genNonPtr(t))
623 default:
624 i := x.varsfx()
625 x.line(genTempVarPfx + i + " := *" + varname)
626 x.enc(genTempVarPfx+i, genNonPtr(t))
627 }
628 case reflect.Struct, reflect.Array:
629 i := x.varsfx()
630 x.line(genTempVarPfx + i + " := &" + varname)
631 x.enc(genTempVarPfx+i, t)
632 default:
633 x.enc(varname, t)
634 }
635
636 if checkNil {
637 x.line("}")
638 }
639
640 }
641
642 // enc will encode a variable (varname) of type t,
643 // except t is of kind reflect.Struct or reflect.Array, wherein varname is of type ptrTo(T) (to prevent copying)
644 func (x *genRunner) enc(varname string, t reflect.Type) {
645 rtid := rt2id(t)
646 // We call CodecEncodeSelf if one of the following are honored:
647 // - the type already implements Selfer, call that
648 // - the type has a Selfer implementation just created, use that
649 // - the type is in the list of the ones we will generate for, but it is not currently being generated
650
651 mi := x.varsfx()
652 tptr := reflect.PtrTo(t)
653 tk := t.Kind()
654 if x.checkForSelfer(t, varname) {
655 if tk == reflect.Array || tk == reflect.Struct { // varname is of type *T
656 if tptr.Implements(selferTyp) || t.Implements(selferTyp) {
657 x.line(varname + ".CodecEncodeSelf(e)")
658 return
659 }
660 } else { // varname is of type T
661 if t.Implements(selferTyp) {
662 x.line(varname + ".CodecEncodeSelf(e)")
663 return
664 } else if tptr.Implements(selferTyp) {
665 x.linef("%ssf%s := &%s", genTempVarPfx, mi, varname)
666 x.linef("%ssf%s.CodecEncodeSelf(e)", genTempVarPfx, mi)
667 return
668 }
669 }
670
671 if _, ok := x.te[rtid]; ok {
672 x.line(varname + ".CodecEncodeSelf(e)")
673 return
674 }
675 }
676
677 inlist := false
678 for _, t0 := range x.t {
679 if t == t0 {
680 inlist = true
681 if x.checkForSelfer(t, varname) {
682 x.line(varname + ".CodecEncodeSelf(e)")
683 return
684 }
685 break
686 }
687 }
688
689 var rtidAdded bool
690 if t == x.tc {
691 x.te[rtid] = true
692 rtidAdded = true
693 }
694
695 // check if
696 // - type is RawExt, Raw
697 // - the type implements (Text|JSON|Binary)(Unm|M)arshal
698 x.linef("%sm%s := z.EncBinary()", genTempVarPfx, mi)
699 x.linef("_ = %sm%s", genTempVarPfx, mi)
700 x.line("if false {") //start if block
701 defer func() { x.line("}") }() //end if block
702
703 if t == rawTyp {
704 x.linef("} else { z.EncRaw(%v)", varname)
705 return
706 }
707 if t == rawExtTyp {
708 x.linef("} else { r.EncodeRawExt(%v, e)", varname)
709 return
710 }
711 // HACK: Support for Builtins.
712 // Currently, only Binc supports builtins, and the only builtin type is time.Time.
713 // Have a method that returns the rtid for time.Time if Handle is Binc.
714 if t == timeTyp {
715 vrtid := genTempVarPfx + "m" + x.varsfx()
716 x.linef("} else if %s := z.TimeRtidIfBinc(); %s != 0 { ", vrtid, vrtid)
717 x.linef("r.EncodeBuiltin(%s, %s)", vrtid, varname)
718 }
719 // only check for extensions if the type is named, and has a packagePath.
720 if !x.nx && genImportPath(t) != "" && t.Name() != "" {
721 // first check if extensions are configued, before doing the interface conversion
722 x.linef("} else if z.HasExtensions() && z.EncExt(%s) {", varname)
723 }
724 if tk == reflect.Array || tk == reflect.Struct { // varname is of type *T
725 if t.Implements(binaryMarshalerTyp) || tptr.Implements(binaryMarshalerTyp) {
726 x.linef("} else if %sm%s { z.EncBinaryMarshal(%v) ", genTempVarPfx, mi, varname)
727 }
728 if t.Implements(jsonMarshalerTyp) || tptr.Implements(jsonMarshalerTyp) {
729 x.linef("} else if !%sm%s && z.IsJSONHandle() { z.EncJSONMarshal(%v) ", genTempVarPfx, mi, varname)
730 } else if t.Implements(textMarshalerTyp) || tptr.Implements(textMarshalerTyp) {
731 x.linef("} else if !%sm%s { z.EncTextMarshal(%v) ", genTempVarPfx, mi, varname)
732 }
733 } else { // varname is of type T
734 if t.Implements(binaryMarshalerTyp) {
735 x.linef("} else if %sm%s { z.EncBinaryMarshal(%v) ", genTempVarPfx, mi, varname)
736 } else if tptr.Implements(binaryMarshalerTyp) {
737 x.linef("} else if %sm%s { z.EncBinaryMarshal(&%v) ", genTempVarPfx, mi, varname)
738 }
739 if t.Implements(jsonMarshalerTyp) {
740 x.linef("} else if !%sm%s && z.IsJSONHandle() { z.EncJSONMarshal(%v) ", genTempVarPfx, mi, varname)
741 } else if tptr.Implements(jsonMarshalerTyp) {
742 x.linef("} else if !%sm%s && z.IsJSONHandle() { z.EncJSONMarshal(&%v) ", genTempVarPfx, mi, varname)
743 } else if t.Implements(textMarshalerTyp) {
744 x.linef("} else if !%sm%s { z.EncTextMarshal(%v) ", genTempVarPfx, mi, varname)
745 } else if tptr.Implements(textMarshalerTyp) {
746 x.linef("} else if !%sm%s { z.EncTextMarshal(&%v) ", genTempVarPfx, mi, varname)
747 }
748 }
749 x.line("} else {")
750
751 switch t.Kind() {
752 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
753 x.line("r.EncodeInt(int64(" + varname + "))")
754 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
755 x.line("r.EncodeUint(uint64(" + varname + "))")
756 case reflect.Float32:
757 x.line("r.EncodeFloat32(float32(" + varname + "))")
758 case reflect.Float64:
759 x.line("r.EncodeFloat64(float64(" + varname + "))")
760 case reflect.Bool:
761 x.line("r.EncodeBool(bool(" + varname + "))")
762 case reflect.String:
763 x.line("r.EncodeString(codecSelferC_UTF8" + x.xs + ", string(" + varname + "))")
764 case reflect.Chan:
765 x.xtraSM(varname, true, t)
766 // x.encListFallback(varname, rtid, t)
767 case reflect.Array:
768 x.xtraSM(varname, true, t)
769 case reflect.Slice:
770 // if nil, call dedicated function
771 // if a []uint8, call dedicated function
772 // if a known fastpath slice, call dedicated function
773 // else write encode function in-line.
774 // - if elements are primitives or Selfers, call dedicated function on each member.
775 // - else call Encoder.encode(XXX) on it.
776 if rtid == uint8SliceTypId {
777 x.line("r.EncodeStringBytes(codecSelferC_RAW" + x.xs + ", []byte(" + varname + "))")
778 } else if fastpathAV.index(rtid) != -1 {
779 g := x.newGenV(t)
780 x.line("z.F." + g.MethodNamePfx("Enc", false) + "V(" + varname + ", e)")
781 } else {
782 x.xtraSM(varname, true, t)
783 // x.encListFallback(varname, rtid, t)
784 }
785 case reflect.Map:
786 // if nil, call dedicated function
787 // if a known fastpath map, call dedicated function
788 // else write encode function in-line.
789 // - if elements are primitives or Selfers, call dedicated function on each member.
790 // - else call Encoder.encode(XXX) on it.
791 // x.line("if " + varname + " == nil { \nr.EncodeNil()\n } else { ")
792 if fastpathAV.index(rtid) != -1 {
793 g := x.newGenV(t)
794 x.line("z.F." + g.MethodNamePfx("Enc", false) + "V(" + varname + ", e)")
795 } else {
796 x.xtraSM(varname, true, t)
797 // x.encMapFallback(varname, rtid, t)
798 }
799 case reflect.Struct:
800 if !inlist {
801 delete(x.te, rtid)
802 x.line("z.EncFallback(" + varname + ")")
803 break
804 }
805 x.encStruct(varname, rtid, t)
806 default:
807 if rtidAdded {
808 delete(x.te, rtid)
809 }
810 x.line("z.EncFallback(" + varname + ")")
811 }
812 }
813
814 func (x *genRunner) encZero(t reflect.Type) {
815 switch t.Kind() {
816 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
817 x.line("r.EncodeInt(0)")
818 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
819 x.line("r.EncodeUint(0)")
820 case reflect.Float32:
821 x.line("r.EncodeFloat32(0)")
822 case reflect.Float64:
823 x.line("r.EncodeFloat64(0)")
824 case reflect.Bool:
825 x.line("r.EncodeBool(false)")
826 case reflect.String:
827 x.line("r.EncodeString(codecSelferC_UTF8" + x.xs + `, "")`)
828 default:
829 x.line("r.EncodeNil()")
830 }
831 }
832
833 func (x *genRunner) encStruct(varname string, rtid uintptr, t reflect.Type) {
834 // Use knowledge from structfieldinfo (mbs, encodable fields. Ignore omitempty. )
835 // replicate code in kStruct i.e. for each field, deref type to non-pointer, and call x.enc on it
836
837 // if t === type currently running selfer on, do for all
838 ti := x.ti.get(rtid, t)
839 i := x.varsfx()
840 sepVarname := genTempVarPfx + "sep" + i
841 numfieldsvar := genTempVarPfx + "q" + i
842 ti2arrayvar := genTempVarPfx + "r" + i
843 struct2arrvar := genTempVarPfx + "2arr" + i
844
845 x.line(sepVarname + " := !z.EncBinary()")
846 x.linef("%s := z.EncBasicHandle().StructToArray", struct2arrvar)
847 tisfi := ti.sfip // always use sequence from file. decStruct expects same thing.
848 // due to omitEmpty, we need to calculate the
849 // number of non-empty things we write out first.
850 // This is required as we need to pre-determine the size of the container,
851 // to support length-prefixing.
852 if ti.anyOmitEmpty {
853 x.linef("var %s [%v]bool", numfieldsvar, len(tisfi))
854 x.linef("_ = %s", numfieldsvar)
855 }
856 x.linef("_, _ = %s, %s", sepVarname, struct2arrvar)
857 x.linef("const %s bool = %v", ti2arrayvar, ti.toArray)
858 var nn int
859 if ti.anyOmitEmpty {
860 for j, si := range tisfi {
861 if !si.omitEmpty {
862 nn++
863 continue
864 }
865 var t2 reflect.StructField
866 var omitline string
867 {
868 t2typ := t
869 varname3 := varname
870 for ij, ix := range si.is {
871 if uint8(ij) == si.nis {
872 break
873 }
874 for t2typ.Kind() == reflect.Ptr {
875 t2typ = t2typ.Elem()
876 }
877 t2 = t2typ.Field(int(ix))
878 t2typ = t2.Type
879 varname3 = varname3 + "." + t2.Name
880 if t2typ.Kind() == reflect.Ptr {
881 omitline += varname3 + " != nil && "
882 }
883 }
884 }
885 // never check omitEmpty on a struct type, as it may contain uncomparable map/slice/etc.
886 // also, for maps/slices/arrays, check if len ! 0 (not if == zero value)
887 switch t2.Type.Kind() {
888 case reflect.Struct:
889 omitline += " true"
890 case reflect.Map, reflect.Slice, reflect.Array, reflect.Chan:
891 omitline += "len(" + varname + "." + t2.Name + ") != 0"
892 default:
893 omitline += varname + "." + t2.Name + " != " + x.genZeroValueR(t2.Type)
894 }
895 x.linef("%s[%v] = %s", numfieldsvar, j, omitline)
896 }
897 }
898 // x.linef("var %snn%s int", genTempVarPfx, i)
899 x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray {
900 x.linef("r.WriteArrayStart(%d)", len(tisfi))
901 x.linef("} else {") // if not ti.toArray
902 if ti.anyOmitEmpty {
903 x.linef("var %snn%s = %v", genTempVarPfx, i, nn)
904 x.linef("for _, b := range %s { if b { %snn%s++ } }", numfieldsvar, genTempVarPfx, i)
905 x.linef("r.WriteMapStart(%snn%s)", genTempVarPfx, i)
906 x.linef("%snn%s = %v", genTempVarPfx, i, 0)
907 } else {
908 x.linef("r.WriteMapStart(%d)", len(tisfi))
909 }
910 x.line("}") // close if not StructToArray
911
912 for j, si := range tisfi {
913 i := x.varsfx()
914 isNilVarName := genTempVarPfx + "n" + i
915 var labelUsed bool
916 var t2 reflect.StructField
917 {
918 t2typ := t
919 varname3 := varname
920 for ij, ix := range si.is {
921 if uint8(ij) == si.nis {
922 break
923 }
924 // fmt.Printf("%%%% %v, ix: %v\n", t2typ, ix)
925 for t2typ.Kind() == reflect.Ptr {
926 t2typ = t2typ.Elem()
927 }
928 t2 = t2typ.Field(int(ix))
929 t2typ = t2.Type
930 varname3 = varname3 + "." + t2.Name
931 if t2typ.Kind() == reflect.Ptr {
932 if !labelUsed {
933 x.line("var " + isNilVarName + " bool")
934 }
935 x.line("if " + varname3 + " == nil { " + isNilVarName + " = true ")
936 x.line("goto LABEL" + i)
937 x.line("}")
938 labelUsed = true
939 // "varname3 = new(" + x.genTypeName(t3.Elem()) + ") }")
940 }
941 }
942 // t2 = t.FieldByIndex(si.is)
943 }
944 if labelUsed {
945 x.line("LABEL" + i + ":")
946 }
947 // if the type of the field is a Selfer, or one of the ones
948
949 x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray
950 if labelUsed {
951 x.linef("if %s { r.WriteArrayElem(); r.EncodeNil() } else { ", isNilVarName)
952 // x.linef("if %s { z.EncSendContainerState(codecSelfer_containerArrayElem%s); r.EncodeNil() } else { ", isNilVarName, x.xs)
953 }
954 x.line("r.WriteArrayElem()") // x.linef("z.EncSendContainerState(codecSelfer_containerArrayElem%s)", x.xs)
955 if si.omitEmpty {
956 x.linef("if %s[%v] {", numfieldsvar, j)
957 }
958 x.encVar(varname+"."+t2.Name, t2.Type)
959 if si.omitEmpty {
960 x.linef("} else {")
961 x.encZero(t2.Type)
962 x.linef("}")
963 }
964 if labelUsed {
965 x.line("}")
966 }
967
968 x.linef("} else {") // if not ti.toArray
969
970 if si.omitEmpty {
971 x.linef("if %s[%v] {", numfieldsvar, j)
972 }
973 x.line("r.WriteMapElemKey()") // x.linef("z.EncSendContainerState(codecSelfer_containerMapKey%s)", x.xs)
974 x.line("r.EncodeString(codecSelferC_UTF8" + x.xs + ", string(\"" + si.encName + "\"))")
975 x.line("r.WriteMapElemValue()") // x.linef("z.EncSendContainerState(codecSelfer_containerMapValue%s)", x.xs)
976 if labelUsed {
977 x.line("if " + isNilVarName + " { r.EncodeNil() } else { ")
978 x.encVar(varname+"."+t2.Name, t2.Type)
979 x.line("}")
980 } else {
981 x.encVar(varname+"."+t2.Name, t2.Type)
982 }
983 if si.omitEmpty {
984 x.line("}")
985 }
986 x.linef("} ") // end if/else ti.toArray
987 }
988 x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray {
989 x.line("r.WriteArrayEnd()") // x.linef("z.EncSendContainerState(codecSelfer_containerArrayEnd%s)", x.xs)
990 x.line("} else {")
991 x.line("r.WriteMapEnd()") // x.linef("z.EncSendContainerState(codecSelfer_containerMapEnd%s)", x.xs)
992 x.line("}")
993
994 }
995
996 func (x *genRunner) encListFallback(varname string, t reflect.Type) {
997 if t.AssignableTo(uint8SliceTyp) {
998 x.linef("r.EncodeStringBytes(codecSelferC_RAW%s, []byte(%s))", x.xs, varname)
999 return
1000 }
1001 if t.Kind() == reflect.Array && t.Elem().Kind() == reflect.Uint8 {
1002 x.linef("r.EncodeStringBytes(codecSelferC_RAW%s, ([%v]byte(%s))[:])", x.xs, t.Len(), varname)
1003 return
1004 }
1005 i := x.varsfx()
1006 g := genTempVarPfx
1007 x.line("r.WriteArrayStart(len(" + varname + "))")
1008 if t.Kind() == reflect.Chan {
1009 x.linef("for %si%s, %si2%s := 0, len(%s); %si%s < %si2%s; %si%s++ {", g, i, g, i, varname, g, i, g, i, g, i)
1010 x.line("r.WriteArrayElem()") // x.linef("z.EncSendContainerState(codecSelfer_containerArrayElem%s)", x.xs)
1011 x.linef("%sv%s := <-%s", g, i, varname)
1012 } else {
1013 // x.linef("for %si%s, %sv%s := range %s {", genTempVarPfx, i, genTempVarPfx, i, varname)
1014 x.linef("for _, %sv%s := range %s {", genTempVarPfx, i, varname)
1015 x.line("r.WriteArrayElem()") // x.linef("z.EncSendContainerState(codecSelfer_containerArrayElem%s)", x.xs)
1016 }
1017 x.encVar(genTempVarPfx+"v"+i, t.Elem())
1018 x.line("}")
1019 x.line("r.WriteArrayEnd()") // x.linef("z.EncSendContainerState(codecSelfer_containerArrayEnd%s)", x.xs)
1020 }
1021
1022 func (x *genRunner) encMapFallback(varname string, t reflect.Type) {
1023 // TODO: expand this to handle canonical.
1024 i := x.varsfx()
1025 x.line("r.WriteMapStart(len(" + varname + "))")
1026 x.linef("for %sk%s, %sv%s := range %s {", genTempVarPfx, i, genTempVarPfx, i, varname)
1027 // x.line("for " + genTempVarPfx + "k" + i + ", " + genTempVarPfx + "v" + i + " := range " + varname + " {")
1028 x.line("r.WriteMapElemKey()") // f("z.EncSendContainerState(codecSelfer_containerMapKey%s)", x.xs)
1029 x.encVar(genTempVarPfx+"k"+i, t.Key())
1030 x.line("r.WriteMapElemValue()") // f("z.EncSendContainerState(codecSelfer_containerMapValue%s)", x.xs)
1031 x.encVar(genTempVarPfx+"v"+i, t.Elem())
1032 x.line("}")
1033 x.line("r.WriteMapEnd()") // f("z.EncSendContainerState(codecSelfer_containerMapEnd%s)", x.xs)
1034 }
1035
1036 func (x *genRunner) decVar(varname, decodedNilVarname string, t reflect.Type, canBeNil bool) {
1037 // We only encode as nil if a nillable value.
1038 // This removes some of the wasted checks for TryDecodeAsNil.
1039 // We need to think about this more, to see what happens if omitempty, etc
1040 // cause a nil value to be stored when something is expected.
1041 // This could happen when decoding from a struct encoded as an array.
1042 // For that, decVar should be called with canNil=true, to force true as its value.
1043 i := x.varsfx()
1044 if !canBeNil {
1045 canBeNil = genAnythingCanBeNil || !genIsImmutable(t)
1046 }
1047 if canBeNil {
1048 x.line("if r.TryDecodeAsNil() {")
1049 if decodedNilVarname != "" {
1050 x.line(decodedNilVarname + " = true")
1051 } else if t.Kind() == reflect.Ptr {
1052 x.line("if " + varname + " != nil { ")
1053
1054 // if varname is a field of a struct (has a dot in it),
1055 // then just set it to nil
1056 if strings.IndexByte(varname, '.') != -1 {
1057 x.line(varname + " = nil")
1058 } else {
1059 x.line("*" + varname + " = " + x.genZeroValueR(t.Elem()))
1060 }
1061 x.line("}")
1062 } else {
1063 x.line(varname + " = " + x.genZeroValueR(t))
1064 }
1065 x.line("} else {")
1066 } else {
1067 x.line("// cannot be nil")
1068 }
1069 if t.Kind() != reflect.Ptr {
1070 if x.decTryAssignPrimitive(varname, t) {
1071 x.line(genTempVarPfx + "v" + i + " := &" + varname)
1072 x.dec(genTempVarPfx+"v"+i, t)
1073 }
1074 } else {
1075 x.linef("if %s == nil { %s = new(%s) }", varname, varname, x.genTypeName(t.Elem()))
1076 // Ensure we set underlying ptr to a non-nil value (so we can deref to it later).
1077 // There's a chance of a **T in here which is nil.
1078 var ptrPfx string
1079 for t = t.Elem(); t.Kind() == reflect.Ptr; t = t.Elem() {
1080 ptrPfx += "*"
1081 x.linef("if %s%s == nil { %s%s = new(%s)}",
1082 ptrPfx, varname, ptrPfx, varname, x.genTypeName(t))
1083 }
1084 // if varname has [ in it, then create temp variable for this ptr thingie
1085 if strings.Index(varname, "[") >= 0 {
1086 varname2 := genTempVarPfx + "w" + i
1087 x.line(varname2 + " := " + varname)
1088 varname = varname2
1089 }
1090
1091 if ptrPfx == "" {
1092 x.dec(varname, t)
1093 } else {
1094 x.line(genTempVarPfx + "z" + i + " := " + ptrPfx + varname)
1095 x.dec(genTempVarPfx+"z"+i, t)
1096 }
1097
1098 }
1099
1100 if canBeNil {
1101 x.line("} ")
1102 }
1103 }
1104
1105 // dec will decode a variable (varname) of type ptrTo(t).
1106 // t is always a basetype (i.e. not of kind reflect.Ptr).
1107 func (x *genRunner) dec(varname string, t reflect.Type) {
1108 // assumptions:
1109 // - the varname is to a pointer already. No need to take address of it
1110 // - t is always a baseType T (not a *T, etc).
1111 rtid := rt2id(t)
1112 tptr := reflect.PtrTo(t)
1113 if x.checkForSelfer(t, varname) {
1114 if t.Implements(selferTyp) || tptr.Implements(selferTyp) {
1115 x.line(varname + ".CodecDecodeSelf(d)")
1116 return
1117 }
1118 if _, ok := x.td[rtid]; ok {
1119 x.line(varname + ".CodecDecodeSelf(d)")
1120 return
1121 }
1122 }
1123
1124 inlist := false
1125 for _, t0 := range x.t {
1126 if t == t0 {
1127 inlist = true
1128 if x.checkForSelfer(t, varname) {
1129 x.line(varname + ".CodecDecodeSelf(d)")
1130 return
1131 }
1132 break
1133 }
1134 }
1135
1136 var rtidAdded bool
1137 if t == x.tc {
1138 x.td[rtid] = true
1139 rtidAdded = true
1140 }
1141
1142 // check if
1143 // - type is Raw, RawExt
1144 // - the type implements (Text|JSON|Binary)(Unm|M)arshal
1145 mi := x.varsfx()
1146 x.linef("%sm%s := z.DecBinary()", genTempVarPfx, mi)
1147 x.linef("_ = %sm%s", genTempVarPfx, mi)
1148 x.line("if false {") //start if block
1149 defer func() { x.line("}") }() //end if block
1150
1151 if t == rawTyp {
1152 x.linef("} else { *%v = z.DecRaw()", varname)
1153 return
1154 }
1155 if t == rawExtTyp {
1156 x.linef("} else { r.DecodeExt(%v, 0, nil)", varname)
1157 return
1158 }
1159
1160 // HACK: Support for Builtins.
1161 // Currently, only Binc supports builtins, and the only builtin type is time.Time.
1162 // Have a method that returns the rtid for time.Time if Handle is Binc.
1163 if t == timeTyp {
1164 vrtid := genTempVarPfx + "m" + x.varsfx()
1165 x.linef("} else if %s := z.TimeRtidIfBinc(); %s != 0 { ", vrtid, vrtid)
1166 x.linef("r.DecodeBuiltin(%s, %s)", vrtid, varname)
1167 }
1168 // only check for extensions if the type is named, and has a packagePath.
1169 if !x.nx && genImportPath(t) != "" && t.Name() != "" {
1170 // first check if extensions are configued, before doing the interface conversion
1171 x.linef("} else if z.HasExtensions() && z.DecExt(%s) {", varname)
1172 }
1173
1174 if t.Implements(binaryUnmarshalerTyp) || tptr.Implements(binaryUnmarshalerTyp) {
1175 x.linef("} else if %sm%s { z.DecBinaryUnmarshal(%v) ", genTempVarPfx, mi, varname)
1176 }
1177 if t.Implements(jsonUnmarshalerTyp) || tptr.Implements(jsonUnmarshalerTyp) {
1178 x.linef("} else if !%sm%s && z.IsJSONHandle() { z.DecJSONUnmarshal(%v)", genTempVarPfx, mi, varname)
1179 } else if t.Implements(textUnmarshalerTyp) || tptr.Implements(textUnmarshalerTyp) {
1180 x.linef("} else if !%sm%s { z.DecTextUnmarshal(%v)", genTempVarPfx, mi, varname)
1181 }
1182
1183 x.line("} else {")
1184
1185 // Since these are pointers, we cannot share, and have to use them one by one
1186 switch t.Kind() {
1187 case reflect.Int:
1188 x.line("*((*int)(" + varname + ")) = int(r.DecodeInt(codecSelferBitsize" + x.xs + "))")
1189 // x.line("z.DecInt((*int)(" + varname + "))")
1190 case reflect.Int8:
1191 x.line("*((*int8)(" + varname + ")) = int8(r.DecodeInt(8))")
1192 // x.line("z.DecInt8((*int8)(" + varname + "))")
1193 case reflect.Int16:
1194 x.line("*((*int16)(" + varname + ")) = int16(r.DecodeInt(16))")
1195 // x.line("z.DecInt16((*int16)(" + varname + "))")
1196 case reflect.Int32:
1197 x.line("*((*int32)(" + varname + ")) = int32(r.DecodeInt(32))")
1198 // x.line("z.DecInt32((*int32)(" + varname + "))")
1199 case reflect.Int64:
1200 x.line("*((*int64)(" + varname + ")) = int64(r.DecodeInt(64))")
1201 // x.line("z.DecInt64((*int64)(" + varname + "))")
1202
1203 case reflect.Uint:
1204 x.line("*((*uint)(" + varname + ")) = uint(r.DecodeUint(codecSelferBitsize" + x.xs + "))")
1205 // x.line("z.DecUint((*uint)(" + varname + "))")
1206 case reflect.Uint8:
1207 x.line("*((*uint8)(" + varname + ")) = uint8(r.DecodeUint(8))")
1208 // x.line("z.DecUint8((*uint8)(" + varname + "))")
1209 case reflect.Uint16:
1210 x.line("*((*uint16)(" + varname + ")) = uint16(r.DecodeUint(16))")
1211 //x.line("z.DecUint16((*uint16)(" + varname + "))")
1212 case reflect.Uint32:
1213 x.line("*((*uint32)(" + varname + ")) = uint32(r.DecodeUint(32))")
1214 //x.line("z.DecUint32((*uint32)(" + varname + "))")
1215 case reflect.Uint64:
1216 x.line("*((*uint64)(" + varname + ")) = uint64(r.DecodeUint(64))")
1217 //x.line("z.DecUint64((*uint64)(" + varname + "))")
1218 case reflect.Uintptr:
1219 x.line("*((*uintptr)(" + varname + ")) = uintptr(r.DecodeUint(codecSelferBitsize" + x.xs + "))")
1220
1221 case reflect.Float32:
1222 x.line("*((*float32)(" + varname + ")) = float32(r.DecodeFloat(true))")
1223 //x.line("z.DecFloat32((*float32)(" + varname + "))")
1224 case reflect.Float64:
1225 x.line("*((*float64)(" + varname + ")) = float64(r.DecodeFloat(false))")
1226 // x.line("z.DecFloat64((*float64)(" + varname + "))")
1227
1228 case reflect.Bool:
1229 x.line("*((*bool)(" + varname + ")) = r.DecodeBool()")
1230 // x.line("z.DecBool((*bool)(" + varname + "))")
1231 case reflect.String:
1232 x.line("*((*string)(" + varname + ")) = r.DecodeString()")
1233 // x.line("z.DecString((*string)(" + varname + "))")
1234 case reflect.Array, reflect.Chan:
1235 x.xtraSM(varname, false, t)
1236 // x.decListFallback(varname, rtid, true, t)
1237 case reflect.Slice:
1238 // if a []uint8, call dedicated function
1239 // if a known fastpath slice, call dedicated function
1240 // else write encode function in-line.
1241 // - if elements are primitives or Selfers, call dedicated function on each member.
1242 // - else call Encoder.encode(XXX) on it.
1243 if rtid == uint8SliceTypId {
1244 x.line("*" + varname + " = r.DecodeBytes(*(*[]byte)(" + varname + "), false)")
1245 } else if fastpathAV.index(rtid) != -1 {
1246 g := x.newGenV(t)
1247 x.line("z.F." + g.MethodNamePfx("Dec", false) + "X(" + varname + ", d)")
1248 } else {
1249 x.xtraSM(varname, false, t)
1250 // x.decListFallback(varname, rtid, false, t)
1251 }
1252 case reflect.Map:
1253 // if a known fastpath map, call dedicated function
1254 // else write encode function in-line.
1255 // - if elements are primitives or Selfers, call dedicated function on each member.
1256 // - else call Encoder.encode(XXX) on it.
1257 if fastpathAV.index(rtid) != -1 {
1258 g := x.newGenV(t)
1259 x.line("z.F." + g.MethodNamePfx("Dec", false) + "X(" + varname + ", d)")
1260 } else {
1261 x.xtraSM(varname, false, t)
1262 // x.decMapFallback(varname, rtid, t)
1263 }
1264 case reflect.Struct:
1265 if inlist {
1266 x.decStruct(varname, rtid, t)
1267 } else {
1268 // delete(x.td, rtid)
1269 x.line("z.DecFallback(" + varname + ", false)")
1270 }
1271 default:
1272 if rtidAdded {
1273 delete(x.te, rtid)
1274 }
1275 x.line("z.DecFallback(" + varname + ", true)")
1276 }
1277 }
1278
1279 func (x *genRunner) decTryAssignPrimitive(varname string, t reflect.Type) (tryAsPtr bool) {
1280 // This should only be used for exact primitives (ie un-named types).
1281 // Named types may be implementations of Selfer, Unmarshaler, etc.
1282 // They should be handled by dec(...)
1283
1284 if t.Name() != "" {
1285 tryAsPtr = true
1286 return
1287 }
1288
1289 switch t.Kind() {
1290 case reflect.Int:
1291 x.linef("%s = r.DecodeInt(codecSelferBitsize%s)", varname, x.xs)
1292 case reflect.Int8:
1293 x.linef("%s = r.DecodeInt(8)", varname)
1294 case reflect.Int16:
1295 x.linef("%s = r.DecodeInt(16)", varname)
1296 case reflect.Int32:
1297 x.linef("%s = r.DecodeInt(32)", varname)
1298 case reflect.Int64:
1299 x.linef("%s = r.DecodeInt(64)", varname)
1300
1301 case reflect.Uint:
1302 x.linef("%s = r.DecodeUint(codecSelferBitsize%s)", varname, x.xs)
1303 case reflect.Uint8:
1304 x.linef("%s = r.DecodeUint(8)", varname)
1305 case reflect.Uint16:
1306 x.linef("%s = r.DecodeUint(16)", varname)
1307 case reflect.Uint32:
1308 x.linef("%s = r.DecodeUint(32)", varname)
1309 case reflect.Uint64:
1310 x.linef("%s = r.DecodeUint(64)", varname)
1311 case reflect.Uintptr:
1312 x.linef("%s = r.DecodeUint(codecSelferBitsize%s)", varname, x.xs)
1313
1314 case reflect.Float32:
1315 x.linef("%s = r.DecodeFloat(true)", varname)
1316 case reflect.Float64:
1317 x.linef("%s = r.DecodeFloat(false)", varname)
1318
1319 case reflect.Bool:
1320 x.linef("%s = r.DecodeBool()", varname)
1321 case reflect.String:
1322 x.linef("%s = r.DecodeString()", varname)
1323 default:
1324 tryAsPtr = true
1325 }
1326 return
1327 }
1328
1329 func (x *genRunner) decListFallback(varname string, rtid uintptr, t reflect.Type) {
1330 if t.AssignableTo(uint8SliceTyp) {
1331 x.line("*" + varname + " = r.DecodeBytes(*((*[]byte)(" + varname + ")), false)")
1332 return
1333 }
1334 if t.Kind() == reflect.Array && t.Elem().Kind() == reflect.Uint8 {
1335 x.linef("r.DecodeBytes( ((*[%s]byte)(%s))[:], true)", t.Len(), varname)
1336 return
1337 }
1338 type tstruc struct {
1339 TempVar string
1340 Rand string
1341 Varname string
1342 CTyp string
1343 Typ string
1344 Immutable bool
1345 Size int
1346 }
1347 telem := t.Elem()
1348 ts := tstruc{genTempVarPfx, x.varsfx(), varname, x.genTypeName(t), x.genTypeName(telem), genIsImmutable(telem), int(telem.Size())}
1349
1350 funcs := make(template.FuncMap)
1351
1352 funcs["decLineVar"] = func(varname string) string {
1353 x.decVar(varname, "", telem, false)
1354 return ""
1355 }
1356 // funcs["decLine"] = func(pfx string) string {
1357 // x.decVar(ts.TempVar+pfx+ts.Rand, "", reflect.PtrTo(telem), false)
1358 // return ""
1359 // }
1360 funcs["var"] = func(s string) string {
1361 return ts.TempVar + s + ts.Rand
1362 }
1363 funcs["zero"] = func() string {
1364 return x.genZeroValueR(telem)
1365 }
1366 funcs["isArray"] = func() bool {
1367 return t.Kind() == reflect.Array
1368 }
1369 funcs["isSlice"] = func() bool {
1370 return t.Kind() == reflect.Slice
1371 }
1372 funcs["isChan"] = func() bool {
1373 return t.Kind() == reflect.Chan
1374 }
1375 tm, err := template.New("").Funcs(funcs).Parse(genDecListTmpl)
1376 if err != nil {
1377 panic(err)
1378 }
1379 if err = tm.Execute(x.w, &ts); err != nil {
1380 panic(err)
1381 }
1382 }
1383
1384 func (x *genRunner) decMapFallback(varname string, rtid uintptr, t reflect.Type) {
1385 type tstruc struct {
1386 TempVar string
1387 Sfx string
1388 Rand string
1389 Varname string
1390 KTyp string
1391 Typ string
1392 Size int
1393 }
1394 telem := t.Elem()
1395 tkey := t.Key()
1396 ts := tstruc{
1397 genTempVarPfx, x.xs, x.varsfx(), varname, x.genTypeName(tkey),
1398 x.genTypeName(telem), int(telem.Size() + tkey.Size()),
1399 }
1400
1401 funcs := make(template.FuncMap)
1402 funcs["decElemZero"] = func() string {
1403 return x.genZeroValueR(telem)
1404 }
1405 funcs["decElemKindImmutable"] = func() bool {
1406 return genIsImmutable(telem)
1407 }
1408 funcs["decElemKindPtr"] = func() bool {
1409 return telem.Kind() == reflect.Ptr
1410 }
1411 funcs["decElemKindIntf"] = func() bool {
1412 return telem.Kind() == reflect.Interface
1413 }
1414 funcs["decLineVarK"] = func(varname string) string {
1415 x.decVar(varname, "", tkey, false)
1416 return ""
1417 }
1418 funcs["decLineVar"] = func(varname, decodedNilVarname string) string {
1419 x.decVar(varname, decodedNilVarname, telem, false)
1420 return ""
1421 }
1422 // funcs["decLineK"] = func(pfx string) string {
1423 // x.decVar(ts.TempVar+pfx+ts.Rand, reflect.PtrTo(tkey), false)
1424 // return ""
1425 // }
1426 // funcs["decLine"] = func(pfx string) string {
1427 // x.decVar(ts.TempVar+pfx+ts.Rand, reflect.PtrTo(telem), false)
1428 // return ""
1429 // }
1430 funcs["var"] = func(s string) string {
1431 return ts.TempVar + s + ts.Rand
1432 }
1433
1434 tm, err := template.New("").Funcs(funcs).Parse(genDecMapTmpl)
1435 if err != nil {
1436 panic(err)
1437 }
1438 if err = tm.Execute(x.w, &ts); err != nil {
1439 panic(err)
1440 }
1441 }
1442
1443 func (x *genRunner) decStructMapSwitch(kName string, varname string, rtid uintptr, t reflect.Type) {
1444 ti := x.ti.get(rtid, t)
1445 tisfi := ti.sfip // always use sequence from file. decStruct expects same thing.
1446 x.line("switch (" + kName + ") {")
1447 for _, si := range tisfi {
1448 x.line("case \"" + si.encName + "\":")
1449 var t2 reflect.StructField
1450 {
1451 //we must accommodate anonymous fields, where the embedded field is a nil pointer in the value.
1452 // t2 = t.FieldByIndex(si.is)
1453 t2typ := t
1454 varname3 := varname
1455 for ij, ix := range si.is {
1456 if uint8(ij) == si.nis {
1457 break
1458 }
1459 for t2typ.Kind() == reflect.Ptr {
1460 t2typ = t2typ.Elem()
1461 }
1462 t2 = t2typ.Field(int(ix))
1463 t2typ = t2.Type
1464 varname3 = varname3 + "." + t2.Name
1465 if t2typ.Kind() == reflect.Ptr {
1466 x.linef("if %s == nil { %s = new(%s) }", varname3, varname3, x.genTypeName(t2typ.Elem()))
1467 }
1468 }
1469 }
1470 x.decVar(varname+"."+t2.Name, "", t2.Type, false)
1471 }
1472 x.line("default:")
1473 // pass the slice here, so that the string will not escape, and maybe save allocation
1474 x.line("z.DecStructFieldNotFound(-1, " + kName + ")")
1475 x.line("} // end switch " + kName)
1476 }
1477
1478 func (x *genRunner) decStructMap(varname, lenvarname string, rtid uintptr, t reflect.Type, style genStructMapStyle) {
1479 tpfx := genTempVarPfx
1480 i := x.varsfx()
1481 kName := tpfx + "s" + i
1482
1483 // x.line("var " + kName + "Arr = [32]byte{} // default string to decode into")
1484 // x.line("var " + kName + "Slc = " + kName + "Arr[:] // default slice to decode into")
1485 // use the scratch buffer to avoid allocation (most field names are < 32).
1486
1487 x.line("var " + kName + "Slc = z.DecScratchBuffer() // default slice to decode into")
1488
1489 x.line("_ = " + kName + "Slc")
1490 switch style {
1491 case genStructMapStyleLenPrefix:
1492 x.linef("for %sj%s := 0; %sj%s < %s; %sj%s++ {", tpfx, i, tpfx, i, lenvarname, tpfx, i)
1493 case genStructMapStyleCheckBreak:
1494 x.linef("for %sj%s := 0; !r.CheckBreak(); %sj%s++ {", tpfx, i, tpfx, i)
1495 default: // 0, otherwise.
1496 x.linef("var %shl%s bool = %s >= 0", tpfx, i, lenvarname) // has length
1497 x.linef("for %sj%s := 0; ; %sj%s++ {", tpfx, i, tpfx, i)
1498 x.linef("if %shl%s { if %sj%s >= %s { break }", tpfx, i, tpfx, i, lenvarname)
1499 x.line("} else { if r.CheckBreak() { break }; }")
1500 }
1501 x.line("r.ReadMapElemKey()") // f("z.DecSendContainerState(codecSelfer_containerMapKey%s)", x.xs)
1502 x.line(kName + "Slc = r.DecodeStringAsBytes()")
1503 // let string be scoped to this loop alone, so it doesn't escape.
1504 x.line(kName + " := string(" + kName + "Slc)")
1505 x.line("r.ReadMapElemValue()") // f("z.DecSendContainerState(codecSelfer_containerMapValue%s)", x.xs)
1506 x.decStructMapSwitch(kName, varname, rtid, t)
1507
1508 x.line("} // end for " + tpfx + "j" + i)
1509 x.line("r.ReadMapEnd()") // f("z.DecSendContainerState(codecSelfer_containerMapEnd%s)", x.xs)
1510 }
1511
1512 func (x *genRunner) decStructArray(varname, lenvarname, breakString string, rtid uintptr, t reflect.Type) {
1513 tpfx := genTempVarPfx
1514 i := x.varsfx()
1515 ti := x.ti.get(rtid, t)
1516 tisfi := ti.sfip // always use sequence from file. decStruct expects same thing.
1517 x.linef("var %sj%s int", tpfx, i)
1518 x.linef("var %sb%s bool", tpfx, i) // break
1519 x.linef("var %shl%s bool = %s >= 0", tpfx, i, lenvarname) // has length
1520 for _, si := range tisfi {
1521 var t2 reflect.StructField
1522 {
1523 //we must accommodate anonymous fields, where the embedded field is a nil pointer in the value.
1524 // t2 = t.FieldByIndex(si.is)
1525 t2typ := t
1526 varname3 := varname
1527 for ij, ix := range si.is {
1528 if uint8(ij) == si.nis {
1529 break
1530 }
1531 for t2typ.Kind() == reflect.Ptr {
1532 t2typ = t2typ.Elem()
1533 }
1534 t2 = t2typ.Field(int(ix))
1535 t2typ = t2.Type
1536 varname3 = varname3 + "." + t2.Name
1537 if t2typ.Kind() == reflect.Ptr {
1538 x.linef("if %s == nil { %s = new(%s) }", varname3, varname3, x.genTypeName(t2typ.Elem()))
1539 }
1540 }
1541 }
1542
1543 x.linef("%sj%s++; if %shl%s { %sb%s = %sj%s > %s } else { %sb%s = r.CheckBreak() }",
1544 tpfx, i, tpfx, i, tpfx, i,
1545 tpfx, i, lenvarname, tpfx, i)
1546 x.linef("if %sb%s { r.ReadArrayEnd(); %s }", tpfx, i, breakString)
1547 // x.linef("if %sb%s { z.DecSendContainerState(codecSelfer_containerArrayEnd%s); %s }", tpfx, i, x.xs, breakString)
1548 x.line("r.ReadArrayElem()") // f("z.DecSendContainerState(codecSelfer_containerArrayElem%s)", x.xs)
1549 x.decVar(varname+"."+t2.Name, "", t2.Type, true)
1550 }
1551 // read remaining values and throw away.
1552 x.line("for {")
1553 x.linef("%sj%s++; if %shl%s { %sb%s = %sj%s > %s } else { %sb%s = r.CheckBreak() }",
1554 tpfx, i, tpfx, i, tpfx, i,
1555 tpfx, i, lenvarname, tpfx, i)
1556 x.linef("if %sb%s { break }", tpfx, i)
1557 x.line("r.ReadArrayElem()") // f("z.DecSendContainerState(codecSelfer_containerArrayElem%s)", x.xs)
1558 x.linef(`z.DecStructFieldNotFound(%sj%s - 1, "")`, tpfx, i)
1559 x.line("}")
1560 x.line("r.ReadArrayEnd()") // f("z.DecSendContainerState(codecSelfer_containerArrayEnd%s)", x.xs)
1561 }
1562
1563 func (x *genRunner) decStruct(varname string, rtid uintptr, t reflect.Type) {
1564 // if container is map
1565 i := x.varsfx()
1566 x.linef("%sct%s := r.ContainerType()", genTempVarPfx, i)
1567 x.linef("if %sct%s == codecSelferValueTypeMap%s {", genTempVarPfx, i, x.xs)
1568 x.line(genTempVarPfx + "l" + i + " := r.ReadMapStart()")
1569 x.linef("if %sl%s == 0 {", genTempVarPfx, i)
1570 x.line("r.ReadMapEnd()") // f("z.DecSendContainerState(codecSelfer_containerMapEnd%s)", x.xs)
1571 if genUseOneFunctionForDecStructMap {
1572 x.line("} else { ")
1573 x.linef("x.codecDecodeSelfFromMap(%sl%s, d)", genTempVarPfx, i)
1574 } else {
1575 x.line("} else if " + genTempVarPfx + "l" + i + " > 0 { ")
1576 x.line("x.codecDecodeSelfFromMapLenPrefix(" + genTempVarPfx + "l" + i + ", d)")
1577 x.line("} else {")
1578 x.line("x.codecDecodeSelfFromMapCheckBreak(" + genTempVarPfx + "l" + i + ", d)")
1579 }
1580 x.line("}")
1581
1582 // else if container is array
1583 x.linef("} else if %sct%s == codecSelferValueTypeArray%s {", genTempVarPfx, i, x.xs)
1584 x.line(genTempVarPfx + "l" + i + " := r.ReadArrayStart()")
1585 x.linef("if %sl%s == 0 {", genTempVarPfx, i)
1586 x.line("r.ReadArrayEnd()") // f("z.DecSendContainerState(codecSelfer_containerArrayEnd%s)", x.xs)
1587 x.line("} else { ")
1588 x.linef("x.codecDecodeSelfFromArray(%sl%s, d)", genTempVarPfx, i)
1589 x.line("}")
1590 // else panic
1591 x.line("} else { ")
1592 x.line("panic(codecSelferOnlyMapOrArrayEncodeToStructErr" + x.xs + ")")
1593 x.line("} ")
1594 }
1595
1596 // --------
1597
1598 type genV struct {
1599 // genV is either a primitive (Primitive != "") or a map (MapKey != "") or a slice
1600 MapKey string
1601 Elem string
1602 Primitive string
1603 Size int
1604 }
1605
1606 func (x *genRunner) newGenV(t reflect.Type) (v genV) {
1607 switch t.Kind() {
1608 case reflect.Slice, reflect.Array:
1609 te := t.Elem()
1610 v.Elem = x.genTypeName(te)
1611 v.Size = int(te.Size())
1612 case reflect.Map:
1613 te, tk := t.Elem(), t.Key()
1614 v.Elem = x.genTypeName(te)
1615 v.MapKey = x.genTypeName(tk)
1616 v.Size = int(te.Size() + tk.Size())
1617 default:
1618 panic("unexpected type for newGenV. Requires map or slice type")
1619 }
1620 return
1621 }
1622
1623 func (x *genV) MethodNamePfx(prefix string, prim bool) string {
1624 var name []byte
1625 if prefix != "" {
1626 name = append(name, prefix...)
1627 }
1628 if prim {
1629 name = append(name, genTitleCaseName(x.Primitive)...)
1630 } else {
1631 if x.MapKey == "" {
1632 name = append(name, "Slice"...)
1633 } else {
1634 name = append(name, "Map"...)
1635 name = append(name, genTitleCaseName(x.MapKey)...)
1636 }
1637 name = append(name, genTitleCaseName(x.Elem)...)
1638 }
1639 return string(name)
1640
1641 }
1642
1643 // genImportPath returns import path of a non-predeclared named typed, or an empty string otherwise.
1644 //
1645 // This handles the misbehaviour that occurs when 1.5-style vendoring is enabled,
1646 // where PkgPath returns the full path, including the vendoring pre-fix that should have been stripped.
1647 // We strip it here.
1648 func genImportPath(t reflect.Type) (s string) {
1649 s = t.PkgPath()
1650 if genCheckVendor {
1651 // HACK: always handle vendoring. It should be typically on in go 1.6, 1.7
1652 s = stripVendor(s)
1653 }
1654 return
1655 }
1656
1657 // A go identifier is (letter|_)[letter|number|_]*
1658 func genGoIdentifier(s string, checkFirstChar bool) string {
1659 b := make([]byte, 0, len(s))
1660 t := make([]byte, 4)
1661 var n int
1662 for i, r := range s {
1663 if checkFirstChar && i == 0 && !unicode.IsLetter(r) {
1664 b = append(b, '_')
1665 }
1666 // r must be unicode_letter, unicode_digit or _
1667 if unicode.IsLetter(r) || unicode.IsDigit(r) {
1668 n = utf8.EncodeRune(t, r)
1669 b = append(b, t[:n]...)
1670 } else {
1671 b = append(b, '_')
1672 }
1673 }
1674 return string(b)
1675 }
1676
1677 func genNonPtr(t reflect.Type) reflect.Type {
1678 for t.Kind() == reflect.Ptr {
1679 t = t.Elem()
1680 }
1681 return t
1682 }
1683
1684 func genTitleCaseName(s string) string {
1685 switch s {
1686 case "interface{}", "interface {}":
1687 return "Intf"
1688 default:
1689 return strings.ToUpper(s[0:1]) + s[1:]
1690 }
1691 }
1692
1693 func genMethodNameT(t reflect.Type, tRef reflect.Type) (n string) {
1694 var ptrPfx string
1695 for t.Kind() == reflect.Ptr {
1696 ptrPfx += "Ptrto"
1697 t = t.Elem()
1698 }
1699 tstr := t.String()
1700 if tn := t.Name(); tn != "" {
1701 if tRef != nil && genImportPath(t) == genImportPath(tRef) {
1702 return ptrPfx + tn
1703 } else {
1704 if genQNameRegex.MatchString(tstr) {
1705 return ptrPfx + strings.Replace(tstr, ".", "_", 1000)
1706 } else {
1707 return ptrPfx + genCustomTypeName(tstr)
1708 }
1709 }
1710 }
1711 switch t.Kind() {
1712 case reflect.Map:
1713 return ptrPfx + "Map" + genMethodNameT(t.Key(), tRef) + genMethodNameT(t.Elem(), tRef)
1714 case reflect.Slice:
1715 return ptrPfx + "Slice" + genMethodNameT(t.Elem(), tRef)
1716 case reflect.Array:
1717 return ptrPfx + "Array" + strconv.FormatInt(int64(t.Len()), 10) + genMethodNameT(t.Elem(), tRef)
1718 case reflect.Chan:
1719 var cx string
1720 switch t.ChanDir() {
1721 case reflect.SendDir:
1722 cx = "ChanSend"
1723 case reflect.RecvDir:
1724 cx = "ChanRecv"
1725 default:
1726 cx = "Chan"
1727 }
1728 return ptrPfx + cx + genMethodNameT(t.Elem(), tRef)
1729 default:
1730 if t == intfTyp {
1731 return ptrPfx + "Interface"
1732 } else {
1733 if tRef != nil && genImportPath(t) == genImportPath(tRef) {
1734 if t.Name() != "" {
1735 return ptrPfx + t.Name()
1736 } else {
1737 return ptrPfx + genCustomTypeName(tstr)
1738 }
1739 } else {
1740 // best way to get the package name inclusive
1741 // return ptrPfx + strings.Replace(tstr, ".", "_", 1000)
1742 // return ptrPfx + genBase64enc.EncodeToString([]byte(tstr))
1743 if t.Name() != "" && genQNameRegex.MatchString(tstr) {
1744 return ptrPfx + strings.Replace(tstr, ".", "_", 1000)
1745 } else {
1746 return ptrPfx + genCustomTypeName(tstr)
1747 }
1748 }
1749 }
1750 }
1751 }
1752
1753 // genCustomNameForType base64encodes the t.String() value in such a way
1754 // that it can be used within a function name.
1755 func genCustomTypeName(tstr string) string {
1756 len2 := genBase64enc.EncodedLen(len(tstr))
1757 bufx := make([]byte, len2)
1758 genBase64enc.Encode(bufx, []byte(tstr))
1759 for i := len2 - 1; i >= 0; i-- {
1760 if bufx[i] == '=' {
1761 len2--
1762 } else {
1763 break
1764 }
1765 }
1766 return string(bufx[:len2])
1767 }
1768
1769 func genIsImmutable(t reflect.Type) (v bool) {
1770 return isImmutableKind(t.Kind())
1771 }
1772
1773 type genInternal struct {
1774 Version int
1775 Values []genV
1776 }
1777
1778 func (x genInternal) FastpathLen() (l int) {
1779 for _, v := range x.Values {
1780 if v.Primitive == "" {
1781 l++
1782 }
1783 }
1784 return
1785 }
1786
1787 func genInternalZeroValue(s string) string {
1788 switch s {
1789 case "interface{}", "interface {}":
1790 return "nil"
1791 case "bool":
1792 return "false"
1793 case "string":
1794 return `""`
1795 default:
1796 return "0"
1797 }
1798 }
1799
1800 func genInternalEncCommandAsString(s string, vname string) string {
1801 switch s {
1802 case "uint", "uint8", "uint16", "uint32", "uint64":
1803 return "ee.EncodeUint(uint64(" + vname + "))"
1804 case "int", "int8", "int16", "int32", "int64":
1805 return "ee.EncodeInt(int64(" + vname + "))"
1806 case "string":
1807 return "ee.EncodeString(c_UTF8, " + vname + ")"
1808 case "float32":
1809 return "ee.EncodeFloat32(" + vname + ")"
1810 case "float64":
1811 return "ee.EncodeFloat64(" + vname + ")"
1812 case "bool":
1813 return "ee.EncodeBool(" + vname + ")"
1814 case "symbol":
1815 return "ee.EncodeSymbol(" + vname + ")"
1816 default:
1817 return "e.encode(" + vname + ")"
1818 }
1819 }
1820
1821 func genInternalDecCommandAsString(s string) string {
1822 switch s {
1823 case "uint":
1824 return "uint(dd.DecodeUint(uintBitsize))"
1825 case "uint8":
1826 return "uint8(dd.DecodeUint(8))"
1827 case "uint16":
1828 return "uint16(dd.DecodeUint(16))"
1829 case "uint32":
1830 return "uint32(dd.DecodeUint(32))"
1831 case "uint64":
1832 return "dd.DecodeUint(64)"
1833 case "uintptr":
1834 return "uintptr(dd.DecodeUint(uintBitsize))"
1835 case "int":
1836 return "int(dd.DecodeInt(intBitsize))"
1837 case "int8":
1838 return "int8(dd.DecodeInt(8))"
1839 case "int16":
1840 return "int16(dd.DecodeInt(16))"
1841 case "int32":
1842 return "int32(dd.DecodeInt(32))"
1843 case "int64":
1844 return "dd.DecodeInt(64)"
1845
1846 case "string":
1847 return "dd.DecodeString()"
1848 case "float32":
1849 return "float32(dd.DecodeFloat(true))"
1850 case "float64":
1851 return "dd.DecodeFloat(false)"
1852 case "bool":
1853 return "dd.DecodeBool()"
1854 default:
1855 panic(errors.New("gen internal: unknown type for decode: " + s))
1856 }
1857 }
1858
1859 func genInternalSortType(s string, elem bool) string {
1860 for _, v := range [...]string{"int", "uint", "float", "bool", "string"} {
1861 if strings.HasPrefix(s, v) {
1862 if elem {
1863 if v == "int" || v == "uint" || v == "float" {
1864 return v + "64"
1865 } else {
1866 return v
1867 }
1868 }
1869 return v + "Slice"
1870 }
1871 }
1872 panic("sorttype: unexpected type: " + s)
1873 }
1874
1875 func stripVendor(s string) string {
1876 // HACK: Misbehaviour occurs in go 1.5. May have to re-visit this later.
1877 // if s contains /vendor/ OR startsWith vendor/, then return everything after it.
1878 const vendorStart = "vendor/"
1879 const vendorInline = "/vendor/"
1880 if i := strings.LastIndex(s, vendorInline); i >= 0 {
1881 s = s[i+len(vendorInline):]
1882 } else if strings.HasPrefix(s, vendorStart) {
1883 s = s[len(vendorStart):]
1884 }
1885 return s
1886 }
1887
1888 // var genInternalMu sync.Mutex
1889 var genInternalV = genInternal{Version: genVersion}
1890 var genInternalTmplFuncs template.FuncMap
1891 var genInternalOnce sync.Once
1892
1893 func genInternalInit() {
1894 types := [...]string{
1895 "interface{}",
1896 "string",
1897 "float32",
1898 "float64",
1899 "uint",
1900 "uint8",
1901 "uint16",
1902 "uint32",
1903 "uint64",
1904 "uintptr",
1905 "int",
1906 "int8",
1907 "int16",
1908 "int32",
1909 "int64",
1910 "bool",
1911 }
1912 // keep as slice, so it is in specific iteration order.
1913 // Initial order was uint64, string, interface{}, int, int64
1914 mapvaltypes := [...]string{
1915 "interface{}",
1916 "string",
1917 "uint",
1918 "uint8",
1919 "uint16",
1920 "uint32",
1921 "uint64",
1922 "uintptr",
1923 "int",
1924 "int8",
1925 "int16",
1926 "int32",
1927 "int64",
1928 "float32",
1929 "float64",
1930 "bool",
1931 }
1932 wordSizeBytes := int(intBitsize) / 8
1933
1934 mapvaltypes2 := map[string]int{
1935 "interface{}": 2 * wordSizeBytes,
1936 "string": 2 * wordSizeBytes,
1937 "uint": 1 * wordSizeBytes,
1938 "uint8": 1,
1939 "uint16": 2,
1940 "uint32": 4,
1941 "uint64": 8,
1942 "uintptr": 1 * wordSizeBytes,
1943 "int": 1 * wordSizeBytes,
1944 "int8": 1,
1945 "int16": 2,
1946 "int32": 4,
1947 "int64": 8,
1948 "float32": 4,
1949 "float64": 8,
1950 "bool": 1,
1951 }
1952 var gt = genInternal{Version: genVersion}
1953
1954 // For each slice or map type, there must be a (symmetrical) Encode and Decode fast-path function
1955 for _, s := range types {
1956 gt.Values = append(gt.Values, genV{Primitive: s, Size: mapvaltypes2[s]})
1957 if s != "uint8" { // do not generate fast path for slice of bytes. Treat specially already.
1958 gt.Values = append(gt.Values, genV{Elem: s, Size: mapvaltypes2[s]})
1959 }
1960 if _, ok := mapvaltypes2[s]; !ok {
1961 gt.Values = append(gt.Values, genV{MapKey: s, Elem: s, Size: 2 * mapvaltypes2[s]})
1962 }
1963 for _, ms := range mapvaltypes {
1964 gt.Values = append(gt.Values, genV{MapKey: s, Elem: ms, Size: mapvaltypes2[s] + mapvaltypes2[ms]})
1965 }
1966 }
1967
1968 funcs := make(template.FuncMap)
1969 // funcs["haspfx"] = strings.HasPrefix
1970 funcs["encmd"] = genInternalEncCommandAsString
1971 funcs["decmd"] = genInternalDecCommandAsString
1972 funcs["zerocmd"] = genInternalZeroValue
1973 funcs["hasprefix"] = strings.HasPrefix
1974 funcs["sorttype"] = genInternalSortType
1975
1976 genInternalV = gt
1977 genInternalTmplFuncs = funcs
1978 }
1979
1980 // genInternalGoFile is used to generate source files from templates.
1981 // It is run by the program author alone.
1982 // Unfortunately, it has to be exported so that it can be called from a command line tool.
1983 // *** DO NOT USE ***
1984 func genInternalGoFile(r io.Reader, w io.Writer) (err error) {
1985 genInternalOnce.Do(genInternalInit)
1986
1987 gt := genInternalV
1988
1989 t := template.New("").Funcs(genInternalTmplFuncs)
1990
1991 tmplstr, err := ioutil.ReadAll(r)
1992 if err != nil {
1993 return
1994 }
1995
1996 if t, err = t.Parse(string(tmplstr)); err != nil {
1997 return
1998 }
1999
2000 var out bytes.Buffer
2001 err = t.Execute(&out, gt)
2002 if err != nil {
2003 return
2004 }
2005
2006 bout, err := format.Source(out.Bytes())
2007 if err != nil {
2008 w.Write(out.Bytes()) // write out if error, so we can still see.
2009 // w.Write(bout) // write out if error, as much as possible, so we can still see.
2010 return
2011 }
2012 w.Write(bout)
2013 return
2014 }