gen.go 69 KB

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