gen.go 71 KB

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