gen.go 68 KB

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