gen.go 63 KB

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