gen.go 68 KB

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