gen.go 55 KB

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