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