gen.go 59 KB

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