gen.go 62 KB

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