gen.go 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880
  1. // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. //go:build codecgen.exec
  4. // +build codecgen.exec
  5. package codec
  6. import (
  7. "bytes"
  8. "encoding/base32"
  9. "errors"
  10. "fmt"
  11. "go/format"
  12. "io"
  13. "io/ioutil"
  14. "math/rand"
  15. "os"
  16. "reflect"
  17. "regexp"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "text/template"
  23. "time"
  24. // "ugorji.net/zz"
  25. "unicode"
  26. "unicode/utf8"
  27. )
  28. // ---------------------------------------------------
  29. // codecgen supports the full cycle of reflection-based codec:
  30. // - RawExt
  31. // - Raw
  32. // - Extensions
  33. // - (Binary|Text|JSON)(Unm|M)arshal
  34. // - generic by-kind
  35. //
  36. // This means that, for dynamic things, we MUST use reflection to at least get the reflect.Type.
  37. // In those areas, we try to only do reflection or interface-conversion when NECESSARY:
  38. // - Extensions, only if Extensions are configured.
  39. //
  40. // However, note following codecgen caveats:
  41. // - Canonical option.
  42. // If Canonical=true, codecgen'ed code may delegate encoding maps to reflection-based code.
  43. // This is due to the runtime work needed to marshal a map in canonical mode.
  44. // However, if map key is a pre-defined/builtin numeric or string type, codecgen
  45. // will try to write it out itself
  46. // - CheckCircularRef option.
  47. // When encoding a struct, a circular reference can lead to a stack overflow.
  48. // If CheckCircularRef=true, codecgen'ed code will delegate encoding structs to reflection-based code.
  49. // - MissingFielder implementation.
  50. // If a type implements MissingFielder, a Selfer is not generated (with a warning message).
  51. // Statically reproducing the runtime work needed to extract the missing fields and marshal them
  52. // along with the struct fields, while handling the Canonical=true special case, was onerous to implement.
  53. //
  54. // During encode/decode, Selfer takes precedence.
  55. // A type implementing Selfer will know how to encode/decode itself statically.
  56. //
  57. // The following field types are supported:
  58. // array: [n]T
  59. // slice: []T
  60. // map: map[K]V
  61. // primitive: [u]int[n], float(32|64), bool, string
  62. // struct
  63. //
  64. // ---------------------------------------------------
  65. // Note that a Selfer cannot call (e|d).(En|De)code on itself,
  66. // as this will cause a circular reference, as (En|De)code will call Selfer methods.
  67. // Any type that implements Selfer must implement completely and not fallback to (En|De)code.
  68. //
  69. // In addition, code in this file manages the generation of fast-path implementations of
  70. // encode/decode of slices/maps of primitive keys/values.
  71. //
  72. // Users MUST re-generate their implementations whenever the code shape changes.
  73. // The generated code will panic if it was generated with a version older than the supporting library.
  74. // ---------------------------------------------------
  75. //
  76. // codec framework is very feature rich.
  77. // When encoding or decoding into an interface, it depends on the runtime type of the interface.
  78. // The type of the interface may be a named type, an extension, etc.
  79. // Consequently, we fallback to runtime codec for encoding/decoding interfaces.
  80. // In addition, we fallback for any value which cannot be guaranteed at runtime.
  81. // This allows us support ANY value, including any named types, specifically those which
  82. // do not implement our interfaces (e.g. Selfer).
  83. //
  84. // This explains some slowness compared to other code generation codecs (e.g. msgp).
  85. // This reduction in speed is only seen when your refers to interfaces,
  86. // e.g. type T struct { A interface{}; B []interface{}; C map[string]interface{} }
  87. //
  88. // codecgen will panic if the file was generated with an old version of the library in use.
  89. //
  90. // Note:
  91. // It was a conscious decision to have gen.go always explicitly call EncodeNil or TryDecodeAsNil.
  92. // This way, there isn't a function call overhead just to see that we should not enter a block of code.
  93. //
  94. // Note:
  95. // codecgen-generated code depends on the variables defined by fast-path.generated.go.
  96. // consequently, you cannot run with tags "codecgen codec.notfastpath".
  97. //
  98. // Note:
  99. // genInternalXXX functions are used for generating fast-path and other internally generated
  100. // files, and not for use in codecgen.
  101. // Size of a struct or value is not portable across machines, especially across 32-bit vs 64-bit
  102. // operating systems. This is due to types like int, uintptr, pointers, (and derived types like slice), etc
  103. // which use the natural word size on those machines, which may be 4 bytes (on 32-bit) or 8 bytes (on 64-bit).
  104. //
  105. // Within decInferLen calls, we may generate an explicit size of the entry.
  106. // We do this because decInferLen values are expected to be approximate,
  107. // and serve as a good hint on the size of the elements or key+value entry.
  108. //
  109. // Since development is done on 64-bit machines, the sizes will be roughly correctly
  110. // on 64-bit OS, and slightly larger than expected on 32-bit OS.
  111. // This is ok.
  112. //
  113. // For reference, look for 'Size' in fast-path.go.tmpl, gen-dec-(array|map).go.tmpl and gen.go (this file).
  114. // GenVersion is the current version of codecgen.
  115. //
  116. // MARKER: Increment this value each time codecgen changes fundamentally.
  117. // Also update codecgen/gen.go (minimumCodecVersion, genVersion, etc).
  118. // Fundamental changes are:
  119. // - helper methods change (signature change, new ones added, some removed, etc)
  120. // - codecgen command line changes
  121. //
  122. // v1: Initial Version
  123. // v2: -
  124. // v3: For Kubernetes: changes in signature of some unpublished helper methods and codecgen cmdline arguments.
  125. // v4: Removed separator support from (en|de)cDriver, and refactored codec(gen)
  126. // v5: changes to support faster json decoding. Let encoder/decoder maintain state of collections.
  127. // v6: removed unsafe from gen, and now uses codecgen.exec tag
  128. // v7: -
  129. // v8: current - we now maintain compatibility with old generated code.
  130. // v9: - skipped
  131. // v10: modified encDriver and decDriver interfaces.
  132. // v11: remove deprecated methods of encDriver and decDriver.
  133. // v12: removed deprecated methods from genHelper and changed container tracking logic
  134. // v13: 20190603 removed DecodeString - use DecodeStringAsBytes instead
  135. // v14: 20190611 refactored nil handling: TryDecodeAsNil -> selective TryNil, etc
  136. // v15: 20190626 encDriver.EncodeString handles StringToRaw flag inside handle
  137. // v16: 20190629 refactoring for v1.1.6
  138. // v17: 20200911 reduce number of types for which we generate fast path functions (v1.1.8)
  139. // v18: 20201004 changed definition of genHelper...Extension (to take interface{}) and eliminated I2Rtid method
  140. // v19: 20201115 updated codecgen cmdline flags and optimized output
  141. // v20: 20201120 refactored GenHelper to one exported function
  142. // v21: 20210104 refactored generated code to honor ZeroCopy=true for more efficiency
  143. // v22: 20210118 fixed issue in generated code when encoding a type which is also a codec.Selfer
  144. // v23: 20210203 changed slice/map types for which we generate fast-path functions
  145. // v24: 20210226 robust handling for Canonical|CheckCircularRef flags and MissingFielder implementations
  146. // v25: 20210406 pass base reflect.Type to side(En|De)code and (En|De)codeExt calls
  147. // v26: 20230201 genHelper changes for more inlining and consequent performance
  148. // v27: 20230219 fix error decoding struct from array - due to misplaced counter increment
  149. // v28: 20230224 fix decoding missing fields of struct from array, due to double counter increment
  150. const genVersion = 28
  151. const (
  152. genCodecPkg = "codec1978" // MARKER: keep in sync with codecgen/gen.go
  153. genTempVarPfx = "yy"
  154. genTopLevelVarName = "x"
  155. // ignore canBeNil parameter, and always set to true.
  156. // This is because nil can appear anywhere, so we should always check.
  157. genAnythingCanBeNil = true
  158. // genStructCanonical configures whether we generate 2 paths based on Canonical flag
  159. // when encoding struct fields.
  160. genStructCanonical = true
  161. // genFastpathCanonical configures whether we support Canonical in fast path.
  162. // The savings is not much.
  163. //
  164. // MARKER: This MUST ALWAYS BE TRUE. fast-path.go.tmp doesn't handle it being false.
  165. genFastpathCanonical = true
  166. // genFastpathTrimTypes configures whether we trim uncommon fastpath types.
  167. genFastpathTrimTypes = true
  168. )
  169. type genStringDecAsBytes string
  170. type genStringDecZC string
  171. var genStringDecAsBytesTyp = reflect.TypeOf(genStringDecAsBytes(""))
  172. var genStringDecZCTyp = reflect.TypeOf(genStringDecZC(""))
  173. var genFormats = []string{"Json", "Cbor", "Msgpack", "Binc", "Simple"}
  174. var (
  175. errGenAllTypesSamePkg = errors.New("All types must be in the same package")
  176. errGenExpectArrayOrMap = errors.New("unexpected type - expecting array/map/slice")
  177. errGenUnexpectedTypeFastpath = errors.New("fast-path: unexpected type - requires map or slice")
  178. // don't use base64, only 63 characters allowed in valid go identifiers
  179. // ie ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_
  180. //
  181. // don't use numbers, as a valid go identifer must start with a letter.
  182. genTypenameEnc = base32.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
  183. genQNameRegex = regexp.MustCompile(`[A-Za-z_.]+`)
  184. )
  185. type genBuf struct {
  186. buf []byte
  187. }
  188. func (x *genBuf) sIf(b bool, s, t string) *genBuf {
  189. if b {
  190. x.buf = append(x.buf, s...)
  191. } else {
  192. x.buf = append(x.buf, t...)
  193. }
  194. return x
  195. }
  196. func (x *genBuf) s(s string) *genBuf { x.buf = append(x.buf, s...); return x }
  197. func (x *genBuf) b(s []byte) *genBuf { x.buf = append(x.buf, s...); return x }
  198. func (x *genBuf) v() string { return string(x.buf) }
  199. func (x *genBuf) f(s string, args ...interface{}) { x.s(fmt.Sprintf(s, args...)) }
  200. func (x *genBuf) reset() {
  201. if x.buf != nil {
  202. x.buf = x.buf[:0]
  203. }
  204. }
  205. // genRunner holds some state used during a Gen run.
  206. type genRunner struct {
  207. w io.Writer // output
  208. c uint64 // counter used for generating varsfx
  209. f uint64 // counter used for saying false
  210. t []reflect.Type // list of types to run selfer on
  211. tc reflect.Type // currently running selfer on this type
  212. te map[uintptr]bool // types for which the encoder has been created
  213. td map[uintptr]bool // types for which the decoder has been created
  214. tz map[uintptr]bool // types for which GenIsZero has been created
  215. cp string // codec import path
  216. im map[string]reflect.Type // imports to add
  217. imn map[string]string // package names of imports to add
  218. imc uint64 // counter for import numbers
  219. is map[reflect.Type]struct{} // types seen during import search
  220. bp string // base PkgPath, for which we are generating for
  221. cpfx string // codec package prefix
  222. ty map[reflect.Type]struct{} // types for which GenIsZero *should* be created
  223. tm map[reflect.Type]struct{} // types for which enc/dec must be generated
  224. ts []reflect.Type // types for which enc/dec must be generated
  225. xs string // top level variable/constant suffix
  226. hn string // fn helper type name
  227. ti *TypeInfos
  228. // rr *rand.Rand // random generator for file-specific types
  229. jsonOnlyWhen, toArrayWhen, omitEmptyWhen *bool
  230. nx bool // no extensions
  231. }
  232. type genIfClause struct {
  233. hasIf bool
  234. }
  235. func (g *genIfClause) end(x *genRunner) {
  236. if g.hasIf {
  237. x.line("}")
  238. }
  239. }
  240. func (g *genIfClause) c(last bool) (v string) {
  241. if last {
  242. if g.hasIf {
  243. v = " } else { "
  244. }
  245. } else if g.hasIf {
  246. v = " } else if "
  247. } else {
  248. v = "if "
  249. g.hasIf = true
  250. }
  251. return
  252. }
  253. // Gen will write a complete go file containing Selfer implementations for each
  254. // type passed. All the types must be in the same package.
  255. //
  256. // Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINUOUSLY WITHOUT NOTICE.
  257. func Gen(w io.Writer, buildTags, pkgName, uid string, noExtensions bool,
  258. jsonOnlyWhen, toArrayWhen, omitEmptyWhen *bool,
  259. ti *TypeInfos, types ...reflect.Type) (warnings []string) {
  260. // All types passed to this method do not have a codec.Selfer method implemented directly.
  261. // codecgen already checks the AST and skips any types that define the codec.Selfer methods.
  262. // Consequently, there's no need to check and trim them if they implement codec.Selfer
  263. if len(types) == 0 {
  264. return
  265. }
  266. x := genRunner{
  267. w: w,
  268. t: types,
  269. te: make(map[uintptr]bool),
  270. td: make(map[uintptr]bool),
  271. tz: make(map[uintptr]bool),
  272. im: make(map[string]reflect.Type),
  273. imn: make(map[string]string),
  274. is: make(map[reflect.Type]struct{}),
  275. tm: make(map[reflect.Type]struct{}),
  276. ty: make(map[reflect.Type]struct{}),
  277. ts: []reflect.Type{},
  278. bp: genImportPath(types[0]),
  279. xs: uid,
  280. ti: ti,
  281. jsonOnlyWhen: jsonOnlyWhen,
  282. toArrayWhen: toArrayWhen,
  283. omitEmptyWhen: omitEmptyWhen,
  284. nx: noExtensions,
  285. }
  286. if x.ti == nil {
  287. x.ti = defTypeInfos
  288. }
  289. if x.xs == "" {
  290. rr := rand.New(rand.NewSource(time.Now().UnixNano()))
  291. x.xs = strconv.FormatInt(rr.Int63n(9999), 10)
  292. }
  293. // gather imports first:
  294. x.cp = genImportPath(reflect.TypeOf(x))
  295. x.imn[x.cp] = genCodecPkg
  296. // iterate, check if all in same package, and remove any missingfielders
  297. for i := 0; i < len(x.t); {
  298. t := x.t[i]
  299. // xdebugf("###########: PkgPath: '%v', Name: '%s'\n", genImportPath(t), t.Name())
  300. if genImportPath(t) != x.bp {
  301. halt.onerror(errGenAllTypesSamePkg)
  302. }
  303. ti1 := x.ti.get(rt2id(t), t)
  304. if ti1.flagMissingFielder || ti1.flagMissingFielderPtr {
  305. // output diagnostic message - that nothing generated for this type
  306. warnings = append(warnings, fmt.Sprintf("type: '%v' not generated; implements codec.MissingFielder", t))
  307. copy(x.t[i:], x.t[i+1:])
  308. x.t = x.t[:len(x.t)-1]
  309. continue
  310. }
  311. x.genRefPkgs(t)
  312. i++
  313. }
  314. x.line("// +build go1.6")
  315. if buildTags != "" {
  316. x.line("// +build " + buildTags)
  317. }
  318. x.line(`
  319. // Code generated by codecgen - DO NOT EDIT.
  320. `)
  321. x.line("package " + pkgName)
  322. x.line("")
  323. x.line("import (")
  324. if x.cp != x.bp {
  325. x.cpfx = genCodecPkg + "."
  326. x.linef("%s \"%s\"", genCodecPkg, x.cp)
  327. }
  328. // use a sorted set of im keys, so that we can get consistent output
  329. imKeys := make([]string, 0, len(x.im))
  330. for k := range x.im {
  331. imKeys = append(imKeys, k)
  332. }
  333. sort.Strings(imKeys)
  334. for _, k := range imKeys { // for k, _ := range x.im {
  335. if k == x.imn[k] {
  336. x.linef("\"%s\"", k)
  337. } else {
  338. x.linef("%s \"%s\"", x.imn[k], k)
  339. }
  340. }
  341. // add required packages
  342. for _, k := range [...]string{"runtime", "errors", "strconv", "sort"} { // "reflect", "fmt"
  343. if _, ok := x.im[k]; !ok {
  344. x.line("\"" + k + "\"")
  345. }
  346. }
  347. x.line(")")
  348. x.line("")
  349. x.line("const (")
  350. x.linef("// ----- content types ----")
  351. x.linef("codecSelferCcUTF8%s = %v", x.xs, int64(cUTF8))
  352. x.linef("codecSelferCcRAW%s = %v", x.xs, int64(cRAW))
  353. x.linef("// ----- value types used ----")
  354. for _, vt := range [...]valueType{
  355. valueTypeArray, valueTypeMap, valueTypeString,
  356. valueTypeInt, valueTypeUint, valueTypeFloat,
  357. valueTypeNil,
  358. } {
  359. x.linef("codecSelferValueType%s%s = %v", vt.String(), x.xs, int64(vt))
  360. }
  361. x.linef("codecSelferBitsize%s = uint8(32 << (^uint(0) >> 63))", x.xs)
  362. x.linef("codecSelferDecContainerLenNil%s = %d", x.xs, int64(containerLenNil))
  363. x.line(")")
  364. x.line("var (")
  365. x.line("errCodecSelferOnlyMapOrArrayEncodeToStruct" + x.xs + " = " + "errors.New(`only encoded map or array can be decoded into a struct`)")
  366. x.line("_ sort.Interface = nil")
  367. x.line(")")
  368. x.line("")
  369. x.hn = "codecSelfer" + x.xs
  370. x.line("type " + x.hn + " struct{}")
  371. x.line("")
  372. x.linef("func %sFalse() bool { return false }", x.hn)
  373. x.linef("func %sTrue() bool { return true }", x.hn)
  374. x.line("")
  375. // add types for sorting canonical
  376. for _, s := range []string{"string", "uint64", "int64", "float64"} {
  377. x.linef("type %s%sSlice []%s", x.hn, s, s)
  378. x.linef("func (p %s%sSlice) Len() int { return len(p) }", x.hn, s)
  379. x.linef("func (p %s%sSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }", x.hn, s)
  380. x.linef("func (p %s%sSlice) Less(i, j int) bool { return p[uint(i)] < p[uint(j)] }", x.hn, s)
  381. }
  382. x.line("")
  383. x.varsfxreset()
  384. x.line("func init() {")
  385. x.linef("if %sGenVersion != %v {", x.cpfx, genVersion)
  386. x.line("_, file, _, _ := runtime.Caller(0)")
  387. x.linef("ver := strconv.FormatInt(int64(%sGenVersion), 10)", x.cpfx)
  388. x.outf(`panic(errors.New("codecgen version mismatch: current: %v, need " + ver + ". Re-generate file: " + file))`, genVersion)
  389. x.linef("}")
  390. if len(imKeys) > 0 {
  391. x.line("if false { // reference the types, but skip this branch at build/run time")
  392. for _, k := range imKeys {
  393. t := x.im[k]
  394. x.linef("var _ %s.%s", x.imn[k], t.Name())
  395. }
  396. x.line("} ") // close if false
  397. }
  398. x.line("}") // close init
  399. x.line("")
  400. // generate rest of type info
  401. for _, t := range x.t {
  402. x.tc = t
  403. x.linef("func (%s) codecSelferViaCodecgen() {}", x.genTypeName(t))
  404. x.selfer(true)
  405. x.selfer(false)
  406. x.tryGenIsZero(t)
  407. }
  408. for _, t := range x.ts {
  409. rtid := rt2id(t)
  410. // generate enc functions for all these slice/map types.
  411. x.varsfxreset()
  412. 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)
  413. x.genRequiredMethodVars(true)
  414. switch t.Kind() {
  415. case reflect.Array, reflect.Slice, reflect.Chan:
  416. x.encListFallback("v", t)
  417. case reflect.Map:
  418. x.encMapFallback("v", t)
  419. default:
  420. halt.onerror(errGenExpectArrayOrMap)
  421. }
  422. x.line("}")
  423. x.line("")
  424. // generate dec functions for all these slice/map types.
  425. x.varsfxreset()
  426. x.linef("func (x %s) dec%s(v *%s, d *%sDecoder) {", x.hn, x.genMethodNameT(t), x.genTypeName(t), x.cpfx)
  427. x.genRequiredMethodVars(false)
  428. switch t.Kind() {
  429. case reflect.Array, reflect.Slice, reflect.Chan:
  430. x.decListFallback("v", rtid, t)
  431. case reflect.Map:
  432. x.decMapFallback("v", rtid, t)
  433. default:
  434. halt.onerror(errGenExpectArrayOrMap)
  435. }
  436. x.line("}")
  437. x.line("")
  438. }
  439. for t := range x.ty {
  440. x.tryGenIsZero(t)
  441. x.line("")
  442. }
  443. x.line("")
  444. return
  445. }
  446. func (x *genRunner) checkForSelfer(t reflect.Type, varname string) bool {
  447. // return varname != genTopLevelVarName && t != x.tc
  448. // the only time we checkForSelfer is if we are not at the TOP of the generated code.
  449. return varname != genTopLevelVarName
  450. }
  451. func (x *genRunner) arr2str(t reflect.Type, s string) string {
  452. if t.Kind() == reflect.Array {
  453. return s
  454. }
  455. return ""
  456. }
  457. func (x *genRunner) genRequiredMethodVars(encode bool) {
  458. x.line("var h " + x.hn)
  459. if encode {
  460. x.line("z, r := " + x.cpfx + "GenHelper().Encoder(e)")
  461. } else {
  462. x.line("z, r := " + x.cpfx + "GenHelper().Decoder(d)")
  463. }
  464. x.line("_, _, _ = h, z, r")
  465. }
  466. func (x *genRunner) genRefPkgs(t reflect.Type) {
  467. if _, ok := x.is[t]; ok {
  468. return
  469. }
  470. x.is[t] = struct{}{}
  471. tpkg, tname := genImportPath(t), t.Name()
  472. if tpkg != "" && tpkg != x.bp && tpkg != x.cp && tname != "" && tname[0] >= 'A' && tname[0] <= 'Z' {
  473. if _, ok := x.im[tpkg]; !ok {
  474. x.im[tpkg] = t
  475. if idx := strings.LastIndex(tpkg, "/"); idx < 0 {
  476. x.imn[tpkg] = tpkg
  477. } else {
  478. x.imc++
  479. x.imn[tpkg] = "pkg" + strconv.FormatUint(x.imc, 10) + "_" + genGoIdentifier(tpkg[idx+1:], false)
  480. }
  481. }
  482. }
  483. switch t.Kind() {
  484. case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Chan:
  485. x.genRefPkgs(t.Elem())
  486. case reflect.Map:
  487. x.genRefPkgs(t.Elem())
  488. x.genRefPkgs(t.Key())
  489. case reflect.Struct:
  490. for i := 0; i < t.NumField(); i++ {
  491. if fname := t.Field(i).Name; fname != "" && fname[0] >= 'A' && fname[0] <= 'Z' {
  492. x.genRefPkgs(t.Field(i).Type)
  493. }
  494. }
  495. }
  496. }
  497. // sayFalse will either say "false" or use a function call that returns false.
  498. func (x *genRunner) sayFalse() string {
  499. x.f++
  500. if x.f%2 == 0 {
  501. return x.hn + "False()"
  502. }
  503. return "false"
  504. }
  505. // sayFalse will either say "true" or use a function call that returns true.
  506. func (x *genRunner) sayTrue() string {
  507. x.f++
  508. if x.f%2 == 0 {
  509. return x.hn + "True()"
  510. }
  511. return "true"
  512. }
  513. func (x *genRunner) varsfx() string {
  514. x.c++
  515. return strconv.FormatUint(x.c, 10)
  516. }
  517. func (x *genRunner) varsfxreset() {
  518. x.c = 0
  519. }
  520. func (x *genRunner) out(s string) {
  521. _, err := io.WriteString(x.w, s)
  522. genCheckErr(err)
  523. }
  524. func (x *genRunner) outf(s string, params ...interface{}) {
  525. _, err := fmt.Fprintf(x.w, s, params...)
  526. genCheckErr(err)
  527. }
  528. func (x *genRunner) line(s string) {
  529. x.out(s)
  530. if len(s) == 0 || s[len(s)-1] != '\n' {
  531. x.out("\n")
  532. }
  533. }
  534. func (x *genRunner) lineIf(s string) {
  535. if s != "" {
  536. x.line(s)
  537. }
  538. }
  539. func (x *genRunner) linef(s string, params ...interface{}) {
  540. x.outf(s, params...)
  541. if len(s) == 0 || s[len(s)-1] != '\n' {
  542. x.out("\n")
  543. }
  544. }
  545. func (x *genRunner) genTypeName(t reflect.Type) (n string) {
  546. // if the type has a PkgPath, which doesn't match the current package,
  547. // then include it.
  548. // We cannot depend on t.String() because it includes current package,
  549. // or t.PkgPath because it includes full import path,
  550. //
  551. var ptrPfx string
  552. for t.Kind() == reflect.Ptr {
  553. ptrPfx += "*"
  554. t = t.Elem()
  555. }
  556. if tn := t.Name(); tn != "" {
  557. return ptrPfx + x.genTypeNamePrim(t)
  558. }
  559. switch t.Kind() {
  560. case reflect.Map:
  561. return ptrPfx + "map[" + x.genTypeName(t.Key()) + "]" + x.genTypeName(t.Elem())
  562. case reflect.Slice:
  563. return ptrPfx + "[]" + x.genTypeName(t.Elem())
  564. case reflect.Array:
  565. return ptrPfx + "[" + strconv.FormatInt(int64(t.Len()), 10) + "]" + x.genTypeName(t.Elem())
  566. case reflect.Chan:
  567. return ptrPfx + t.ChanDir().String() + " " + x.genTypeName(t.Elem())
  568. default:
  569. if t == intfTyp {
  570. return ptrPfx + "interface{}"
  571. } else {
  572. return ptrPfx + x.genTypeNamePrim(t)
  573. }
  574. }
  575. }
  576. func (x *genRunner) genTypeNamePrim(t reflect.Type) (n string) {
  577. if t.Name() == "" {
  578. return t.String()
  579. } else if genImportPath(t) == "" || genImportPath(t) == genImportPath(x.tc) {
  580. return t.Name()
  581. } else {
  582. return x.imn[genImportPath(t)] + "." + t.Name()
  583. // return t.String() // best way to get the package name inclusive
  584. }
  585. }
  586. func (x *genRunner) genZeroValueR(t reflect.Type) string {
  587. // if t is a named type, w
  588. switch t.Kind() {
  589. case reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func,
  590. reflect.Slice, reflect.Map, reflect.Invalid:
  591. return "nil"
  592. case reflect.Bool:
  593. return "false"
  594. case reflect.String:
  595. return `""`
  596. case reflect.Struct, reflect.Array:
  597. return x.genTypeName(t) + "{}"
  598. default: // all numbers
  599. return "0"
  600. }
  601. }
  602. func (x *genRunner) genMethodNameT(t reflect.Type) (s string) {
  603. return genMethodNameT(t, x.tc)
  604. }
  605. func (x *genRunner) tryGenIsZero(t reflect.Type) (done bool) {
  606. if t.Kind() != reflect.Struct || t.Implements(isCodecEmptyerTyp) {
  607. return
  608. }
  609. rtid := rt2id(t)
  610. if _, ok := x.tz[rtid]; ok {
  611. delete(x.ty, t)
  612. return
  613. }
  614. x.tz[rtid] = true
  615. delete(x.ty, t)
  616. ti := x.ti.get(rtid, t)
  617. tisfi := ti.sfi.source() // always use sequence from file. decStruct expects same thing.
  618. varname := genTopLevelVarName
  619. x.linef("func (%s *%s) IsCodecEmpty() bool {", varname, x.genTypeName(t))
  620. anonSeen := make(map[reflect.Type]bool)
  621. var omitline genBuf
  622. for _, si := range tisfi {
  623. if si.path.parent != nil {
  624. root := si.path.root()
  625. if anonSeen[root.typ] {
  626. continue
  627. }
  628. anonSeen[root.typ] = true
  629. }
  630. t2 := genOmitEmptyLinePreChecks(varname, t, si, &omitline, true)
  631. // if Ptr, we already checked if nil above
  632. if t2.Type.Kind() != reflect.Ptr {
  633. x.doEncOmitEmptyLine(t2, varname, &omitline)
  634. omitline.s(" || ")
  635. }
  636. }
  637. omitline.s(" false")
  638. x.linef("return !(%s)", omitline.v())
  639. x.line("}")
  640. x.line("")
  641. return true
  642. }
  643. func (x *genRunner) selfer(encode bool) {
  644. t := x.tc
  645. // ti := x.ti.get(rt2id(t), t)
  646. t0 := t
  647. // always make decode use a pointer receiver,
  648. // and structs/arrays always use a ptr receiver (encode|decode)
  649. isptr := !encode || t.Kind() == reflect.Array || (t.Kind() == reflect.Struct && t != timeTyp)
  650. x.varsfxreset()
  651. fnSigPfx := "func (" + genTopLevelVarName + " "
  652. if isptr {
  653. fnSigPfx += "*"
  654. }
  655. fnSigPfx += x.genTypeName(t)
  656. x.out(fnSigPfx)
  657. if isptr {
  658. t = reflect.PtrTo(t)
  659. }
  660. if encode {
  661. x.line(") CodecEncodeSelf(e *" + x.cpfx + "Encoder) {")
  662. x.genRequiredMethodVars(true)
  663. if t0.Kind() == reflect.Struct {
  664. x.linef("if z.EncBasicHandle().CheckCircularRef { z.EncEncode(%s); return }", genTopLevelVarName)
  665. }
  666. x.encVar(genTopLevelVarName, t)
  667. } else {
  668. x.line(") CodecDecodeSelf(d *" + x.cpfx + "Decoder) {")
  669. x.genRequiredMethodVars(false)
  670. // do not use decVar, as there is no need to check TryDecodeAsNil
  671. // or way to elegantly handle that, and also setting it to a
  672. // non-nil value doesn't affect the pointer passed.
  673. // x.decVar(genTopLevelVarName, t, false)
  674. x.dec(genTopLevelVarName, t0, true)
  675. }
  676. x.line("}")
  677. x.line("")
  678. if encode || t0.Kind() != reflect.Struct {
  679. return
  680. }
  681. // write is containerMap
  682. x.out(fnSigPfx)
  683. x.line(") codecDecodeSelfFromMap(l int, d *" + x.cpfx + "Decoder) {")
  684. x.genRequiredMethodVars(false)
  685. x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0)
  686. x.line("}")
  687. x.line("")
  688. // write containerArray
  689. x.out(fnSigPfx)
  690. x.line(") codecDecodeSelfFromArray(l int, d *" + x.cpfx + "Decoder) {")
  691. x.genRequiredMethodVars(false)
  692. x.decStructArray(genTopLevelVarName, "l", "return", rt2id(t0), t0)
  693. x.line("}")
  694. x.line("")
  695. }
  696. // used for chan, array, slice, map
  697. func (x *genRunner) xtraSM(varname string, t reflect.Type, ti *typeInfo, encode, isptr bool) {
  698. var ptrPfx, addrPfx string
  699. if isptr {
  700. ptrPfx = "*"
  701. } else {
  702. addrPfx = "&"
  703. }
  704. if encode {
  705. x.linef("h.enc%s((%s%s)(%s), e)", x.genMethodNameT(t), ptrPfx, x.genTypeName(t), varname)
  706. } else {
  707. x.linef("h.dec%s((*%s)(%s%s), d)", x.genMethodNameT(t), x.genTypeName(t), addrPfx, varname)
  708. }
  709. x.registerXtraT(t, ti)
  710. }
  711. func (x *genRunner) registerXtraT(t reflect.Type, ti *typeInfo) {
  712. // recursively register the types
  713. tk := t.Kind()
  714. if tk == reflect.Ptr {
  715. x.registerXtraT(t.Elem(), nil)
  716. return
  717. }
  718. if _, ok := x.tm[t]; ok {
  719. return
  720. }
  721. switch tk {
  722. case reflect.Chan, reflect.Slice, reflect.Array, reflect.Map:
  723. default:
  724. return
  725. }
  726. // only register the type if it will not default to a fast-path
  727. if ti == nil {
  728. ti = x.ti.get(rt2id(t), t)
  729. }
  730. if _, rtidu := genFastpathUnderlying(t, ti.rtid, ti); fastpathAvIndex(rtidu) != -1 {
  731. return
  732. }
  733. x.tm[t] = struct{}{}
  734. x.ts = append(x.ts, t)
  735. // check if this refers to any xtra types eg. a slice of array: add the array
  736. x.registerXtraT(t.Elem(), nil)
  737. if tk == reflect.Map {
  738. x.registerXtraT(t.Key(), nil)
  739. }
  740. }
  741. // encVar will encode a variable.
  742. // The parameter, t, is the reflect.Type of the variable itself
  743. func (x *genRunner) encVar(varname string, t reflect.Type) {
  744. var checkNil bool
  745. // case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan:
  746. // do not include checkNil for slice and maps, as we already checkNil below it
  747. switch t.Kind() {
  748. case reflect.Ptr, reflect.Interface, reflect.Chan:
  749. checkNil = true
  750. }
  751. x.encVarChkNil(varname, t, checkNil)
  752. }
  753. func (x *genRunner) encVarChkNil(varname string, t reflect.Type, checkNil bool) {
  754. if checkNil {
  755. x.linef("if %s == nil { r.EncodeNil() } else {", varname)
  756. }
  757. switch t.Kind() {
  758. case reflect.Ptr:
  759. telem := t.Elem()
  760. tek := telem.Kind()
  761. if tek == reflect.Array || (tek == reflect.Struct && telem != timeTyp) {
  762. x.enc(varname, genNonPtr(t), true)
  763. break
  764. }
  765. i := x.varsfx()
  766. x.line(genTempVarPfx + i + " := *" + varname)
  767. x.enc(genTempVarPfx+i, genNonPtr(t), false)
  768. case reflect.Struct, reflect.Array:
  769. if t == timeTyp {
  770. x.enc(varname, t, false)
  771. break
  772. }
  773. i := x.varsfx()
  774. x.line(genTempVarPfx + i + " := &" + varname)
  775. x.enc(genTempVarPfx+i, t, true)
  776. default:
  777. x.enc(varname, t, false)
  778. }
  779. if checkNil {
  780. x.line("}")
  781. }
  782. }
  783. // enc will encode a variable (varname) of type t, where t represents T.
  784. // if t is !time.Time and t is of kind reflect.Struct or reflect.Array, varname is of type *T
  785. // (to prevent copying),
  786. // else t is of type T
  787. func (x *genRunner) enc(varname string, t reflect.Type, isptr bool) {
  788. rtid := rt2id(t)
  789. ti2 := x.ti.get(rtid, t)
  790. // We call CodecEncodeSelf if one of the following are honored:
  791. // - the type already implements Selfer, call that
  792. // - the type has a Selfer implementation just created, use that
  793. // - the type is in the list of the ones we will generate for, but it is not currently being generated
  794. mi := x.varsfx()
  795. // tptr := reflect.PtrTo(t)
  796. // tk := t.Kind()
  797. // check if
  798. // - type is time.Time, RawExt, Raw
  799. // - the type implements (Text|JSON|Binary)(Unm|M)arshal
  800. var hasIf genIfClause
  801. defer hasIf.end(x) // end if block (if necessary)
  802. var ptrPfx, addrPfx string
  803. if isptr {
  804. ptrPfx = "*"
  805. } else {
  806. addrPfx = "&"
  807. }
  808. if t == timeTyp {
  809. x.linef("%s z.EncBasicHandle().TimeBuiltin() { r.EncodeTime(%s%s)", hasIf.c(false), ptrPfx, varname)
  810. // return
  811. }
  812. if t == rawTyp {
  813. x.linef("%s z.EncRaw(%s%s)", hasIf.c(true), ptrPfx, varname)
  814. return
  815. }
  816. if t == rawExtTyp {
  817. x.linef("%s r.EncodeRawExt(%s%s)", hasIf.c(true), addrPfx, varname)
  818. return
  819. }
  820. // only check for extensions if extensions are configured,
  821. // and the type is named, and has a packagePath,
  822. // and this is not the CodecEncodeSelf or CodecDecodeSelf method (i.e. it is not a Selfer)
  823. if !x.nx && varname != genTopLevelVarName && t != genStringDecAsBytesTyp &&
  824. t != genStringDecZCTyp && genImportPath(t) != "" && t.Name() != "" {
  825. yy := fmt.Sprintf("%sxt%s", genTempVarPfx, mi)
  826. x.linef("%s %s := z.Extension(%s); %s != nil { z.EncExtension(%s, %s) ",
  827. hasIf.c(false), yy, varname, yy, varname, yy)
  828. }
  829. if x.checkForSelfer(t, varname) {
  830. if ti2.flagSelfer {
  831. x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
  832. return
  833. }
  834. if ti2.flagSelferPtr {
  835. if isptr {
  836. x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
  837. } else {
  838. x.linef("%s %ssf%s := &%s", hasIf.c(true), genTempVarPfx, mi, varname)
  839. x.linef("%ssf%s.CodecEncodeSelf(e)", genTempVarPfx, mi)
  840. }
  841. return
  842. }
  843. if _, ok := x.te[rtid]; ok {
  844. x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
  845. return
  846. }
  847. }
  848. inlist := false
  849. for _, t0 := range x.t {
  850. if t == t0 {
  851. inlist = true
  852. if x.checkForSelfer(t, varname) {
  853. x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
  854. return
  855. }
  856. break
  857. }
  858. }
  859. var rtidAdded bool
  860. if t == x.tc {
  861. x.te[rtid] = true
  862. rtidAdded = true
  863. }
  864. if ti2.flagBinaryMarshaler {
  865. x.linef("%s z.EncBinary() { z.EncBinaryMarshal(%s%v) ", hasIf.c(false), ptrPfx, varname)
  866. } else if ti2.flagBinaryMarshalerPtr {
  867. x.linef("%s z.EncBinary() { z.EncBinaryMarshal(%s%v) ", hasIf.c(false), addrPfx, varname)
  868. }
  869. if ti2.flagJsonMarshaler {
  870. x.linef("%s !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(%s%v) ", hasIf.c(false), ptrPfx, varname)
  871. } else if ti2.flagJsonMarshalerPtr {
  872. x.linef("%s !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(%s%v) ", hasIf.c(false), addrPfx, varname)
  873. } else if ti2.flagTextMarshaler {
  874. x.linef("%s !z.EncBinary() { z.EncTextMarshal(%s%v) ", hasIf.c(false), ptrPfx, varname)
  875. } else if ti2.flagTextMarshalerPtr {
  876. x.linef("%s !z.EncBinary() { z.EncTextMarshal(%s%v) ", hasIf.c(false), addrPfx, varname)
  877. }
  878. x.lineIf(hasIf.c(true))
  879. switch t.Kind() {
  880. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  881. x.line("r.EncodeInt(int64(" + varname + "))")
  882. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  883. x.line("r.EncodeUint(uint64(" + varname + "))")
  884. case reflect.Float32:
  885. x.line("r.EncodeFloat32(float32(" + varname + "))")
  886. case reflect.Float64:
  887. x.line("r.EncodeFloat64(float64(" + varname + "))")
  888. case reflect.Complex64:
  889. x.linef("z.EncEncodeComplex64(complex64(%s))", varname)
  890. case reflect.Complex128:
  891. x.linef("z.EncEncodeComplex128(complex128(%s))", varname)
  892. case reflect.Bool:
  893. x.line("r.EncodeBool(bool(" + varname + "))")
  894. case reflect.String:
  895. x.linef("r.EncodeString(string(%s))", varname)
  896. case reflect.Chan:
  897. x.xtraSM(varname, t, ti2, true, false)
  898. // x.encListFallback(varname, rtid, t)
  899. case reflect.Array:
  900. _, rtidu := genFastpathUnderlying(t, rtid, ti2)
  901. if fastpathAvIndex(rtidu) != -1 {
  902. g := x.newFastpathGenV(ti2.key)
  903. x.linef("z.F.%sV((%s)(%s[:]), e)", g.MethodNamePfx("Enc", false), x.genTypeName(ti2.key), varname)
  904. } else {
  905. x.xtraSM(varname, t, ti2, true, true)
  906. }
  907. case reflect.Slice:
  908. // if nil, call dedicated function
  909. // if a []byte, call dedicated function
  910. // if a known fastpath slice, call dedicated function
  911. // else write encode function in-line.
  912. // - if elements are primitives or Selfers, call dedicated function on each member.
  913. // - else call Encoder.encode(XXX) on it.
  914. x.linef("if %s == nil { r.EncodeNil() } else {", varname)
  915. if rtid == uint8SliceTypId {
  916. x.line("r.EncodeStringBytesRaw([]byte(" + varname + "))")
  917. } else {
  918. tu, rtidu := genFastpathUnderlying(t, rtid, ti2)
  919. if fastpathAvIndex(rtidu) != -1 {
  920. g := x.newFastpathGenV(tu)
  921. if rtid == rtidu {
  922. x.linef("z.F.%sV(%s, e)", g.MethodNamePfx("Enc", false), varname)
  923. } else {
  924. x.linef("z.F.%sV((%s)(%s), e)", g.MethodNamePfx("Enc", false), x.genTypeName(tu), varname)
  925. }
  926. } else {
  927. x.xtraSM(varname, t, ti2, true, false)
  928. }
  929. }
  930. x.linef("} // end block: if %s slice == nil", varname)
  931. case reflect.Map:
  932. // if nil, call dedicated function
  933. // if a known fastpath map, call dedicated function
  934. // else write encode function in-line.
  935. // - if elements are primitives or Selfers, call dedicated function on each member.
  936. // - else call Encoder.encode(XXX) on it.
  937. x.linef("if %s == nil { r.EncodeNil() } else {", varname)
  938. tu, rtidu := genFastpathUnderlying(t, rtid, ti2)
  939. if fastpathAvIndex(rtidu) != -1 {
  940. g := x.newFastpathGenV(tu)
  941. if rtid == rtidu {
  942. x.linef("z.F.%sV(%s, e)", g.MethodNamePfx("Enc", false), varname)
  943. } else {
  944. x.linef("z.F.%sV((%s)(%s), e)", g.MethodNamePfx("Enc", false), x.genTypeName(tu), varname)
  945. }
  946. } else {
  947. x.xtraSM(varname, t, ti2, true, false)
  948. }
  949. x.linef("} // end block: if %s map == nil", varname)
  950. case reflect.Struct:
  951. if !inlist {
  952. delete(x.te, rtid)
  953. x.line("z.EncFallback(" + varname + ")")
  954. break
  955. }
  956. x.encStruct(varname, rtid, t)
  957. default:
  958. if rtidAdded {
  959. delete(x.te, rtid)
  960. }
  961. x.line("z.EncFallback(" + varname + ")")
  962. }
  963. }
  964. func (x *genRunner) encZero(t reflect.Type) {
  965. switch t.Kind() {
  966. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  967. x.line("r.EncodeInt(0)")
  968. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  969. x.line("r.EncodeUint(0)")
  970. case reflect.Float32:
  971. x.line("r.EncodeFloat32(0)")
  972. case reflect.Float64:
  973. x.line("r.EncodeFloat64(0)")
  974. case reflect.Complex64:
  975. x.line("z.EncEncodeComplex64(0)")
  976. case reflect.Complex128:
  977. x.line("z.EncEncodeComplex128(0)")
  978. case reflect.Bool:
  979. x.line("r.EncodeBool(false)")
  980. case reflect.String:
  981. x.linef(`r.EncodeString("")`)
  982. default:
  983. x.line("r.EncodeNil()")
  984. }
  985. }
  986. func genOmitEmptyLinePreChecks(varname string, t reflect.Type, si *structFieldInfo, omitline *genBuf, oneLevel bool) (t2 reflect.StructField) {
  987. // xdebug2f("calling genOmitEmptyLinePreChecks on: %v", t)
  988. t2typ := t
  989. varname3 := varname
  990. // go through the loop, record the t2 field explicitly,
  991. // and gather the omit line if embedded in pointers.
  992. fullpath := si.path.fullpath()
  993. for i, path := range fullpath {
  994. for t2typ.Kind() == reflect.Ptr {
  995. t2typ = t2typ.Elem()
  996. }
  997. t2 = t2typ.Field(int(path.index))
  998. t2typ = t2.Type
  999. varname3 = varname3 + "." + t2.Name
  1000. // do not include actual field in the omit line.
  1001. // that is done subsequently (right after - below).
  1002. if i+1 < len(fullpath) && t2typ.Kind() == reflect.Ptr {
  1003. omitline.s(varname3).s(" != nil && ")
  1004. }
  1005. if oneLevel {
  1006. break
  1007. }
  1008. }
  1009. return
  1010. }
  1011. func (x *genRunner) doEncOmitEmptyLine(t2 reflect.StructField, varname string, buf *genBuf) {
  1012. x.f = 0
  1013. x.encOmitEmptyLine(t2, varname, buf)
  1014. }
  1015. func (x *genRunner) encOmitEmptyLine(t2 reflect.StructField, varname string, buf *genBuf) {
  1016. // xdebugf("calling encOmitEmptyLine on: %v", t2.Type)
  1017. // smartly check omitEmpty on a struct type, as it may contain uncomparable map/slice/etc.
  1018. // also, for maps/slices, check if len ! 0 (not if == zero value)
  1019. varname2 := varname + "." + t2.Name
  1020. switch t2.Type.Kind() {
  1021. case reflect.Struct:
  1022. rtid2 := rt2id(t2.Type)
  1023. ti2 := x.ti.get(rtid2, t2.Type)
  1024. // xdebugf(">>>> structfield: omitempty: type: %s, field: %s\n", t2.Type.Name(), t2.Name)
  1025. if ti2.rtid == timeTypId {
  1026. buf.s("!(").s(varname2).s(".IsZero())")
  1027. break
  1028. }
  1029. if ti2.flagIsZeroerPtr || ti2.flagIsZeroer {
  1030. buf.s("!(").s(varname2).s(".IsZero())")
  1031. break
  1032. }
  1033. if t2.Type.Implements(isCodecEmptyerTyp) {
  1034. buf.s("!(").s(varname2).s(".IsCodecEmpty())")
  1035. break
  1036. }
  1037. _, ok := x.tz[rtid2]
  1038. if ok {
  1039. buf.s("!(").s(varname2).s(".IsCodecEmpty())")
  1040. break
  1041. }
  1042. // if we *should* create a IsCodecEmpty for it, but haven't yet, add it here
  1043. // _, ok = x.ty[rtid2]
  1044. if genImportPath(t2.Type) == x.bp {
  1045. x.ty[t2.Type] = struct{}{}
  1046. buf.s("!(").s(varname2).s(".IsCodecEmpty())")
  1047. break
  1048. }
  1049. if ti2.flagComparable {
  1050. buf.s(varname2).s(" != ").s(x.genZeroValueR(t2.Type))
  1051. break
  1052. }
  1053. // buf.s("(")
  1054. buf.s(x.sayFalse()) // buf.s("false")
  1055. var wrote bool
  1056. for i, n := 0, t2.Type.NumField(); i < n; i++ {
  1057. f := t2.Type.Field(i)
  1058. if f.PkgPath != "" { // unexported
  1059. continue
  1060. }
  1061. buf.s(" || ")
  1062. x.encOmitEmptyLine(f, varname2, buf)
  1063. wrote = true
  1064. }
  1065. if !wrote {
  1066. buf.s(" || ").s(x.sayTrue())
  1067. }
  1068. //buf.s(")")
  1069. case reflect.Bool:
  1070. buf.s("bool(").s(varname2).s(")")
  1071. case reflect.Map, reflect.Slice, reflect.Chan:
  1072. buf.s("len(").s(varname2).s(") != 0")
  1073. case reflect.Array:
  1074. tlen := t2.Type.Len()
  1075. if tlen == 0 {
  1076. buf.s(x.sayFalse())
  1077. } else if t2.Type.Comparable() {
  1078. buf.s(varname2).s(" != ").s(x.genZeroValueR(t2.Type))
  1079. } else { // then we cannot even compare the individual values
  1080. // TODO use playground to check if you can compare to a
  1081. // zero value of an array, even if array not comparable.
  1082. buf.s(x.sayTrue())
  1083. }
  1084. default:
  1085. buf.s(varname2).s(" != ").s(x.genZeroValueR(t2.Type))
  1086. }
  1087. }
  1088. func (x *genRunner) encStruct(varname string, rtid uintptr, t reflect.Type) {
  1089. // Use knowledge from structfieldinfo (mbs, encodable fields. Ignore omitempty. )
  1090. // replicate code in kStruct i.e. for each field, deref type to non-pointer, and call x.enc on it
  1091. // if t === type currently running selfer on, do for all
  1092. ti := x.ti.get(rtid, t)
  1093. i := x.varsfx()
  1094. // sepVarname := genTempVarPfx + "sep" + i
  1095. numfieldsvar := genTempVarPfx + "q" + i
  1096. ti2arrayvar := genTempVarPfx + "r" + i
  1097. struct2arrvar := genTempVarPfx + "2arr" + i
  1098. tisfi := ti.sfi.source() // always use sequence from file. decStruct expects same thing.
  1099. type genFQN struct {
  1100. i string
  1101. fqname string
  1102. nilLine genBuf
  1103. nilVar string
  1104. canNil bool
  1105. sf reflect.StructField
  1106. }
  1107. genFQNs := make([]genFQN, len(tisfi))
  1108. si2Pos := make(map[*structFieldInfo]int) // stores position in sorted structFieldInfos
  1109. for j, si := range tisfi {
  1110. si2Pos[si] = j
  1111. q := &genFQNs[j]
  1112. q.i = x.varsfx()
  1113. q.nilVar = genTempVarPfx + "n" + q.i
  1114. q.canNil = false
  1115. q.fqname = varname
  1116. {
  1117. t2typ := t
  1118. fullpath := si.path.fullpath()
  1119. for _, path := range fullpath {
  1120. for t2typ.Kind() == reflect.Ptr {
  1121. t2typ = t2typ.Elem()
  1122. }
  1123. q.sf = t2typ.Field(int(path.index))
  1124. t2typ = q.sf.Type
  1125. q.fqname += "." + q.sf.Name
  1126. if t2typ.Kind() == reflect.Ptr {
  1127. if !q.canNil {
  1128. q.nilLine.f("%s == nil", q.fqname)
  1129. q.canNil = true
  1130. } else {
  1131. q.nilLine.f(" || %s == nil", q.fqname)
  1132. }
  1133. }
  1134. }
  1135. }
  1136. }
  1137. // x.line(sepVarname + " := !z.EncBinary()")
  1138. x.linef("%s := z.EncBasicHandle().StructToArray", struct2arrvar)
  1139. // x.linef("_, _ = %s, %s", sepVarname, struct2arrvar)
  1140. x.linef("_ = %s", struct2arrvar)
  1141. x.linef("const %s bool = %v // struct tag has 'toArray'", ti2arrayvar, ti.toArray)
  1142. for j := range genFQNs {
  1143. q := &genFQNs[j]
  1144. if q.canNil {
  1145. x.linef("var %s bool = %s", q.nilVar, q.nilLine.v())
  1146. }
  1147. }
  1148. // var nn int
  1149. // due to omitEmpty, we need to calculate the
  1150. // number of non-empty things we write out first.
  1151. // This is required as we need to pre-determine the size of the container,
  1152. // to support length-prefixing.
  1153. omitEmptySometimes := x.omitEmptyWhen == nil
  1154. omitEmptyAlways := (x.omitEmptyWhen != nil && *(x.omitEmptyWhen))
  1155. // omitEmptyNever := (x.omitEmptyWhen != nil && !*(x.omitEmptyWhen))
  1156. toArraySometimes := x.toArrayWhen == nil
  1157. toArrayAlways := (x.toArrayWhen != nil && *(x.toArrayWhen))
  1158. toArrayNever := (x.toArrayWhen != nil && !(*(x.toArrayWhen)))
  1159. if (omitEmptySometimes && ti.anyOmitEmpty) || omitEmptyAlways {
  1160. x.linef("var %s = [%v]bool{ // should field at this index be written?", numfieldsvar, len(tisfi))
  1161. for _, si := range tisfi {
  1162. if omitEmptySometimes && !si.path.omitEmpty {
  1163. x.linef("true, // %s", si.encName) // si.fieldName)
  1164. continue
  1165. }
  1166. var omitline genBuf
  1167. t2 := genOmitEmptyLinePreChecks(varname, t, si, &omitline, false)
  1168. x.doEncOmitEmptyLine(t2, varname, &omitline)
  1169. x.linef("%s, // %s", omitline.v(), si.encName) // si.fieldName)
  1170. }
  1171. x.line("}")
  1172. x.linef("_ = %s", numfieldsvar)
  1173. }
  1174. if toArraySometimes {
  1175. x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray
  1176. }
  1177. if toArraySometimes || toArrayAlways {
  1178. x.linef("z.EncWriteArrayStart(%d)", len(tisfi))
  1179. for j, si := range tisfi {
  1180. doOmitEmptyCheck := (omitEmptySometimes && si.path.omitEmpty) || omitEmptyAlways
  1181. q := &genFQNs[j]
  1182. // if the type of the field is a Selfer, or one of the ones
  1183. if q.canNil {
  1184. x.linef("if %s { z.EncWriteArrayElem(); r.EncodeNil() } else { ", q.nilVar)
  1185. }
  1186. x.linef("z.EncWriteArrayElem()")
  1187. if doOmitEmptyCheck {
  1188. x.linef("if %s[%v] {", numfieldsvar, j)
  1189. }
  1190. x.encVarChkNil(q.fqname, q.sf.Type, false)
  1191. if doOmitEmptyCheck {
  1192. x.linef("} else {")
  1193. x.encZero(q.sf.Type)
  1194. x.linef("}")
  1195. }
  1196. if q.canNil {
  1197. x.line("}")
  1198. }
  1199. }
  1200. x.line("z.EncWriteArrayEnd()")
  1201. }
  1202. if toArraySometimes {
  1203. x.linef("} else {") // if not ti.toArray
  1204. }
  1205. if toArraySometimes || toArrayNever {
  1206. if (omitEmptySometimes && ti.anyOmitEmpty) || omitEmptyAlways {
  1207. x.linef("var %snn%s int", genTempVarPfx, i)
  1208. x.linef("for _, b := range %s { if b { %snn%s++ } }", numfieldsvar, genTempVarPfx, i)
  1209. x.linef("z.EncWriteMapStart(%snn%s)", genTempVarPfx, i)
  1210. x.linef("%snn%s = %v", genTempVarPfx, i, 0)
  1211. } else {
  1212. x.linef("z.EncWriteMapStart(%d)", len(tisfi))
  1213. }
  1214. fn := func(tisfi []*structFieldInfo) {
  1215. // tisfi here may be source or sorted, so use the src position stored elsewhere
  1216. for _, si := range tisfi {
  1217. pos := si2Pos[si]
  1218. q := &genFQNs[pos]
  1219. doOmitEmptyCheck := (omitEmptySometimes && si.path.omitEmpty) || omitEmptyAlways
  1220. if doOmitEmptyCheck {
  1221. x.linef("if %s[%v] {", numfieldsvar, pos)
  1222. }
  1223. x.linef("z.EncWriteMapElemKey()")
  1224. // emulate EncStructFieldKey
  1225. switch ti.keyType {
  1226. case valueTypeInt:
  1227. x.linef("r.EncodeInt(z.M.Int(strconv.ParseInt(`%s`, 10, 64)))", si.encName)
  1228. case valueTypeUint:
  1229. x.linef("r.EncodeUint(z.M.Uint(strconv.ParseUint(`%s`, 10, 64)))", si.encName)
  1230. case valueTypeFloat:
  1231. x.linef("r.EncodeFloat64(z.M.Float(strconv.ParseFloat(`%s`, 64)))", si.encName)
  1232. default: // string
  1233. if x.jsonOnlyWhen == nil {
  1234. if si.path.encNameAsciiAlphaNum {
  1235. x.linef(`if z.IsJSONHandle() { z.EncWr().WriteStr("\"%s\"") } else { `, si.encName)
  1236. }
  1237. x.linef("r.EncodeString(`%s`)", si.encName)
  1238. if si.path.encNameAsciiAlphaNum {
  1239. x.linef("}")
  1240. }
  1241. } else if *(x.jsonOnlyWhen) {
  1242. if si.path.encNameAsciiAlphaNum {
  1243. x.linef(`z.EncWr().WriteStr("\"%s\"")`, si.encName)
  1244. } else {
  1245. x.linef("r.EncodeString(`%s`)", si.encName)
  1246. }
  1247. } else {
  1248. x.linef("r.EncodeString(`%s`)", si.encName)
  1249. }
  1250. }
  1251. x.line("z.EncWriteMapElemValue()")
  1252. if q.canNil {
  1253. x.line("if " + q.nilVar + " { r.EncodeNil() } else { ")
  1254. x.encVarChkNil(q.fqname, q.sf.Type, false)
  1255. x.line("}")
  1256. } else {
  1257. x.encVarChkNil(q.fqname, q.sf.Type, false)
  1258. }
  1259. if doOmitEmptyCheck {
  1260. x.line("}")
  1261. }
  1262. }
  1263. }
  1264. if genStructCanonical {
  1265. x.linef("if z.EncBasicHandle().Canonical {") // if Canonical block
  1266. fn(ti.sfi.sorted())
  1267. x.linef("} else {") // else !Canonical block
  1268. fn(ti.sfi.source())
  1269. x.linef("}") // end if Canonical block
  1270. } else {
  1271. fn(tisfi)
  1272. }
  1273. x.line("z.EncWriteMapEnd()")
  1274. }
  1275. if toArraySometimes {
  1276. x.linef("} ") // end if/else ti.toArray
  1277. }
  1278. }
  1279. func (x *genRunner) encListFallback(varname string, t reflect.Type) {
  1280. x.linef("if %s == nil { r.EncodeNil(); return }", varname)
  1281. elemBytes := t.Elem().Kind() == reflect.Uint8
  1282. if t.AssignableTo(uint8SliceTyp) {
  1283. x.linef("r.EncodeStringBytesRaw([]byte(%s))", varname)
  1284. return
  1285. }
  1286. if t.Kind() == reflect.Array && elemBytes {
  1287. x.linef("r.EncodeStringBytesRaw(((*[%d]byte)(%s))[:])", t.Len(), varname)
  1288. return
  1289. }
  1290. i := x.varsfx()
  1291. if t.Kind() == reflect.Chan {
  1292. type ts struct {
  1293. Label, Chan, Slice, Sfx string
  1294. }
  1295. tm, err := template.New("").Parse(genEncChanTmpl)
  1296. genCheckErr(err)
  1297. x.linef("if %s == nil { r.EncodeNil() } else { ", varname)
  1298. x.linef("var sch%s []%s", i, x.genTypeName(t.Elem()))
  1299. err = tm.Execute(x.w, &ts{"Lsch" + i, varname, "sch" + i, i})
  1300. genCheckErr(err)
  1301. if elemBytes {
  1302. x.linef("r.EncodeStringBytesRaw([]byte(%s))", "sch"+i)
  1303. x.line("}")
  1304. return
  1305. }
  1306. varname = "sch" + i
  1307. }
  1308. x.line("z.EncWriteArrayStart(len(" + varname + "))")
  1309. // x.linef("for _, %sv%s := range %s {", genTempVarPfx, i, varname)
  1310. // x.linef("z.EncWriteArrayElem()")
  1311. // x.encVar(genTempVarPfx+"v"+i, t.Elem())
  1312. // x.line("}")
  1313. x.linef("for %sv%s := range %s {", genTempVarPfx, i, varname)
  1314. x.linef("z.EncWriteArrayElem()")
  1315. x.encVar(fmt.Sprintf("%s[%sv%s]", varname, genTempVarPfx, i), t.Elem())
  1316. x.line("}")
  1317. x.line("z.EncWriteArrayEnd()")
  1318. if t.Kind() == reflect.Chan {
  1319. x.line("}")
  1320. }
  1321. }
  1322. func (x *genRunner) encMapFallback(varname string, t reflect.Type) {
  1323. x.linef("if %s == nil { r.EncodeNil()", varname)
  1324. x.line("} else if z.EncBasicHandle().Canonical {")
  1325. // Solve for easy case accomodated by sort package without reflection i.e.
  1326. // map keys of type: float, int, string (pre-defined/builtin types).
  1327. //
  1328. // To do this, we will get the keys into an array of uint64|float64|string,
  1329. // sort them, then write them out, and grab the value and encode it appropriately
  1330. tkey := t.Key()
  1331. tkind := tkey.Kind()
  1332. // tkeybase := tkey
  1333. // for tkeybase.Kind() == reflect.Ptr {
  1334. // tkeybase = tkeybase.Elem()
  1335. // }
  1336. // tikey := x.ti.get(rt2id(tkeybase), tkeybase)
  1337. // pre-defined types have a name and no pkgpath and appropriate kind
  1338. predeclared := tkey.PkgPath() == "" && tkey.Name() != ""
  1339. canonSortKind := reflect.Invalid
  1340. switch tkind {
  1341. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1342. canonSortKind = reflect.Int64
  1343. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  1344. canonSortKind = reflect.Uint64
  1345. case reflect.Float32, reflect.Float64:
  1346. canonSortKind = reflect.Float64
  1347. case reflect.String:
  1348. canonSortKind = reflect.String
  1349. }
  1350. var i string = x.varsfx()
  1351. fnCanonNumBoolStrKind := func() {
  1352. if !predeclared {
  1353. x.linef("var %svv%s %s", genTempVarPfx, i, x.genTypeName(tkey))
  1354. x.linef("%sencfn%s := z.EncFnGivenAddr(&%svv%s)", genTempVarPfx, i, genTempVarPfx, i)
  1355. }
  1356. // get the type, get the slice type its mapped to, and complete the code
  1357. x.linef("%ss%s := make([]%s, 0, len(%s))", genTempVarPfx, i, canonSortKind, varname)
  1358. x.linef("for k, _ := range %s {", varname)
  1359. x.linef(" %ss%s = append(%ss%s, %s(k))", genTempVarPfx, i, genTempVarPfx, i, canonSortKind)
  1360. x.linef("}")
  1361. x.linef("sort.Sort(%s%sSlice(%ss%s))", x.hn, canonSortKind, genTempVarPfx, i)
  1362. x.linef("z.EncWriteMapStart(len(%s))", varname)
  1363. x.linef("for _, %sv%s := range %ss%s {", genTempVarPfx, i, genTempVarPfx, i)
  1364. x.linef(" z.EncWriteMapElemKey()")
  1365. if predeclared {
  1366. switch tkind {
  1367. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
  1368. x.linef("r.EncodeInt(int64(%sv%s))", genTempVarPfx, i)
  1369. case reflect.Int64:
  1370. x.linef("r.EncodeInt(%sv%s)", genTempVarPfx, i)
  1371. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uintptr:
  1372. x.linef("r.EncodeUint(%sv%s)", genTempVarPfx, i)
  1373. case reflect.Uint64:
  1374. x.linef("r.EncodeUint(uint64(%sv%s))", genTempVarPfx, i)
  1375. case reflect.Float32:
  1376. x.linef("r.EncodeFloat32(float32(%sv%s))", genTempVarPfx, i)
  1377. case reflect.Float64:
  1378. x.linef("r.EncodeFloat64(%sv%s)", genTempVarPfx, i)
  1379. case reflect.String:
  1380. x.linef("r.EncodeString(%sv%s)", genTempVarPfx, i)
  1381. }
  1382. } else {
  1383. x.linef("%svv%s = %s(%sv%s)", genTempVarPfx, i, x.genTypeName(tkey), genTempVarPfx, i)
  1384. x.linef("z.EncEncodeNumBoolStrKindGivenAddr(&%svv%s, %sencfn%s)", genTempVarPfx, i, genTempVarPfx, i)
  1385. }
  1386. x.linef(" z.EncWriteMapElemValue()")
  1387. vname := genTempVarPfx + "e" + i
  1388. if predeclared {
  1389. x.linef("%s := %s[%s(%sv%s)]", vname, varname, x.genTypeName(tkey), genTempVarPfx, i)
  1390. } else {
  1391. x.linef("%s := %s[%svv%s]", vname, varname, genTempVarPfx, i)
  1392. }
  1393. x.encVar(vname, t.Elem())
  1394. x.linef("}")
  1395. x.line("z.EncWriteMapEnd()")
  1396. }
  1397. // if canonSortKind != reflect.Invalid && !tikey.flagMarshalInterface {
  1398. // if predeclared {
  1399. // fnCanonNumBoolStrKind()
  1400. // } else {
  1401. // // handle if an extension
  1402. // x.linef("if z.Extension(%s(%s)) != nil { z.EncEncodeMapNonNil(%s) } else {",
  1403. // x.genTypeName(tkey), x.genZeroValueR(tkey), varname)
  1404. // fnCanonNumBoolStrKind()
  1405. // x.line("}")
  1406. // }
  1407. // } else {
  1408. // x.linef("z.EncEncodeMapNonNil(%s)", varname)
  1409. // }
  1410. if canonSortKind != reflect.Invalid {
  1411. fnCanonNumBoolStrKind()
  1412. } else {
  1413. x.linef("z.EncEncodeMapNonNil(%s)", varname)
  1414. }
  1415. x.line("} else {")
  1416. x.linef("z.EncWriteMapStart(len(%s))", varname)
  1417. x.linef("for %sk%s, %sv%s := range %s {", genTempVarPfx, i, genTempVarPfx, i, varname)
  1418. x.linef("z.EncWriteMapElemKey()")
  1419. x.encVar(genTempVarPfx+"k"+i, t.Key())
  1420. x.line("z.EncWriteMapElemValue()")
  1421. x.encVar(genTempVarPfx+"v"+i, t.Elem())
  1422. x.line("}")
  1423. x.line("z.EncWriteMapEnd()")
  1424. x.line("}")
  1425. }
  1426. func (x *genRunner) decVarInitPtr(varname, nilvar string, t reflect.Type, si *structFieldInfo,
  1427. newbuf, nilbuf *genBuf) (varname3 string, t2 reflect.StructField) {
  1428. //we must accommodate anonymous fields, where the embedded field is a nil pointer in the value.
  1429. // t2 = t.FieldByIndex(si.is)
  1430. varname3 = varname
  1431. t2typ := t
  1432. t2kind := t2typ.Kind()
  1433. var nilbufed bool
  1434. if si != nil {
  1435. fullpath := si.path.fullpath()
  1436. for _, path := range fullpath {
  1437. // only one-level pointers can be seen in a type
  1438. if t2typ.Kind() == reflect.Ptr {
  1439. t2typ = t2typ.Elem()
  1440. }
  1441. t2 = t2typ.Field(int(path.index))
  1442. t2typ = t2.Type
  1443. varname3 = varname3 + "." + t2.Name
  1444. t2kind = t2typ.Kind()
  1445. if t2kind != reflect.Ptr {
  1446. continue
  1447. }
  1448. if newbuf != nil {
  1449. if len(newbuf.buf) > 0 {
  1450. newbuf.s("\n")
  1451. }
  1452. newbuf.f("if %s == nil { %s = new(%s) }", varname3, varname3, x.genTypeName(t2typ.Elem()))
  1453. }
  1454. if nilbuf != nil {
  1455. if !nilbufed {
  1456. nilbuf.s("if ").s(varname3).s(" != nil")
  1457. nilbufed = true
  1458. } else {
  1459. nilbuf.s(" && ").s(varname3).s(" != nil")
  1460. }
  1461. }
  1462. }
  1463. }
  1464. if nilbuf != nil {
  1465. if nilbufed {
  1466. nilbuf.s(" { ").s("// remove the if-true\n")
  1467. }
  1468. if nilvar != "" {
  1469. nilbuf.s(nilvar).s(" = true")
  1470. } else if tk := t2typ.Kind(); tk == reflect.Ptr {
  1471. if strings.IndexByte(varname3, '.') != -1 || strings.IndexByte(varname3, '[') != -1 {
  1472. nilbuf.s(varname3).s(" = nil")
  1473. } else {
  1474. nilbuf.s("*").s(varname3).s(" = ").s(x.genZeroValueR(t2typ.Elem()))
  1475. }
  1476. } else {
  1477. nilbuf.s(varname3).s(" = ").s(x.genZeroValueR(t2typ))
  1478. }
  1479. if nilbufed {
  1480. nilbuf.s("}")
  1481. }
  1482. }
  1483. return
  1484. }
  1485. // decVar takes a variable called varname, of type t
  1486. func (x *genRunner) decVarMain(varname, rand string, t reflect.Type, checkNotNil bool) {
  1487. // We only encode as nil if a nillable value.
  1488. // This removes some of the wasted checks for TryDecodeAsNil.
  1489. // We need to think about this more, to see what happens if omitempty, etc
  1490. // cause a nil value to be stored when something is expected.
  1491. // This could happen when decoding from a struct encoded as an array.
  1492. // For that, decVar should be called with canNil=true, to force true as its value.
  1493. var varname2 string
  1494. if t.Kind() != reflect.Ptr {
  1495. if t.PkgPath() != "" || !x.decTryAssignPrimitive(varname, t, false) {
  1496. x.dec(varname, t, false)
  1497. }
  1498. } else {
  1499. if checkNotNil {
  1500. x.linef("if %s == nil { %s = new(%s) }", varname, varname, x.genTypeName(t.Elem()))
  1501. }
  1502. // Ensure we set underlying ptr to a non-nil value (so we can deref to it later).
  1503. // There's a chance of a **T in here which is nil.
  1504. var ptrPfx string
  1505. for t = t.Elem(); t.Kind() == reflect.Ptr; t = t.Elem() {
  1506. ptrPfx += "*"
  1507. if checkNotNil {
  1508. x.linef("if %s%s == nil { %s%s = new(%s)}", ptrPfx, varname, ptrPfx, varname, x.genTypeName(t))
  1509. }
  1510. }
  1511. // Should we create temp var if a slice/map indexing? No. dec(...) can now handle it.
  1512. if ptrPfx == "" {
  1513. x.dec(varname, t, true)
  1514. } else {
  1515. varname2 = genTempVarPfx + "z" + rand
  1516. x.line(varname2 + " := " + ptrPfx + varname)
  1517. x.dec(varname2, t, true)
  1518. }
  1519. }
  1520. }
  1521. // decVar takes a variable called varname, of type t
  1522. func (x *genRunner) decVar(varname, nilvar string, t reflect.Type, canBeNil, checkNotNil bool) {
  1523. // We only encode as nil if a nillable value.
  1524. // This removes some of the wasted checks for TryDecodeAsNil.
  1525. // We need to think about this more, to see what happens if omitempty, etc
  1526. // cause a nil value to be stored when something is expected.
  1527. // This could happen when decoding from a struct encoded as an array.
  1528. // For that, decVar should be called with canNil=true, to force true as its value.
  1529. i := x.varsfx()
  1530. if t.Kind() == reflect.Ptr {
  1531. var buf genBuf
  1532. x.decVarInitPtr(varname, nilvar, t, nil, nil, &buf)
  1533. x.linef("if r.TryNil() { %s } else {", buf.buf)
  1534. x.decVarMain(varname, i, t, checkNotNil)
  1535. x.line("} ")
  1536. } else {
  1537. x.decVarMain(varname, i, t, checkNotNil)
  1538. }
  1539. }
  1540. // dec will decode a variable (varname) of type t or ptrTo(t) if isptr==true.
  1541. func (x *genRunner) dec(varname string, t reflect.Type, isptr bool) {
  1542. // assumptions:
  1543. // - the varname is to a pointer already. No need to take address of it
  1544. // - t is always a baseType T (not a *T, etc).
  1545. rtid := rt2id(t)
  1546. ti2 := x.ti.get(rtid, t)
  1547. // check if
  1548. // - type is time.Time, Raw, RawExt
  1549. // - the type implements (Text|JSON|Binary)(Unm|M)arshal
  1550. mi := x.varsfx()
  1551. var hasIf genIfClause
  1552. defer hasIf.end(x)
  1553. var ptrPfx, addrPfx string
  1554. if isptr {
  1555. ptrPfx = "*"
  1556. } else {
  1557. addrPfx = "&"
  1558. }
  1559. if t == timeTyp {
  1560. x.linef("%s z.DecBasicHandle().TimeBuiltin() { %s%v = r.DecodeTime()", hasIf.c(false), ptrPfx, varname)
  1561. // return
  1562. }
  1563. if t == rawTyp {
  1564. x.linef("%s %s%v = z.DecRaw()", hasIf.c(true), ptrPfx, varname)
  1565. return
  1566. }
  1567. if t == rawExtTyp {
  1568. x.linef("%s r.DecodeExt(%s%v, 0, nil)", hasIf.c(true), addrPfx, varname)
  1569. return
  1570. }
  1571. // only check for extensions if extensions are configured,
  1572. // and the type is named, and has a packagePath,
  1573. // and this is not the CodecEncodeSelf or CodecDecodeSelf method (i.e. it is not a Selfer)
  1574. // xdebugf("genRunner.dec: varname: %v, t: %v, genImportPath: %v, t.Name: %v", varname, t, genImportPath(t), t.Name())
  1575. if !x.nx && varname != genTopLevelVarName && t != genStringDecAsBytesTyp &&
  1576. t != genStringDecZCTyp && genImportPath(t) != "" && t.Name() != "" {
  1577. // first check if extensions are configued, before doing the interface conversion
  1578. yy := fmt.Sprintf("%sxt%s", genTempVarPfx, mi)
  1579. x.linef("%s %s := z.Extension(%s); %s != nil { z.DecExtension(%s%s, %s) ", hasIf.c(false), yy, varname, yy, addrPfx, varname, yy)
  1580. }
  1581. if x.checkForSelfer(t, varname) {
  1582. if ti2.flagSelfer {
  1583. x.linef("%s %s.CodecDecodeSelf(d)", hasIf.c(true), varname)
  1584. return
  1585. }
  1586. if ti2.flagSelferPtr {
  1587. x.linef("%s %s.CodecDecodeSelf(d)", hasIf.c(true), varname)
  1588. return
  1589. }
  1590. if _, ok := x.td[rtid]; ok {
  1591. x.linef("%s %s.CodecDecodeSelf(d)", hasIf.c(true), varname)
  1592. return
  1593. }
  1594. }
  1595. inlist := false
  1596. for _, t0 := range x.t {
  1597. if t == t0 {
  1598. inlist = true
  1599. if x.checkForSelfer(t, varname) {
  1600. x.linef("%s %s.CodecDecodeSelf(d)", hasIf.c(true), varname)
  1601. return
  1602. }
  1603. break
  1604. }
  1605. }
  1606. var rtidAdded bool
  1607. if t == x.tc {
  1608. x.td[rtid] = true
  1609. rtidAdded = true
  1610. }
  1611. if ti2.flagBinaryUnmarshaler {
  1612. x.linef("%s z.DecBinary() { z.DecBinaryUnmarshal(%s%v) ", hasIf.c(false), ptrPfx, varname)
  1613. } else if ti2.flagBinaryUnmarshalerPtr {
  1614. x.linef("%s z.DecBinary() { z.DecBinaryUnmarshal(%s%v) ", hasIf.c(false), addrPfx, varname)
  1615. }
  1616. if ti2.flagJsonUnmarshaler {
  1617. x.linef("%s !z.DecBinary() && z.IsJSONHandle() { z.DecJSONUnmarshal(%s%v)", hasIf.c(false), ptrPfx, varname)
  1618. } else if ti2.flagJsonUnmarshalerPtr {
  1619. x.linef("%s !z.DecBinary() && z.IsJSONHandle() { z.DecJSONUnmarshal(%s%v)", hasIf.c(false), addrPfx, varname)
  1620. } else if ti2.flagTextUnmarshaler {
  1621. x.linef("%s !z.DecBinary() { z.DecTextUnmarshal(%s%v)", hasIf.c(false), ptrPfx, varname)
  1622. } else if ti2.flagTextUnmarshalerPtr {
  1623. x.linef("%s !z.DecBinary() { z.DecTextUnmarshal(%s%v)", hasIf.c(false), addrPfx, varname)
  1624. }
  1625. x.lineIf(hasIf.c(true))
  1626. if x.decTryAssignPrimitive(varname, t, isptr) {
  1627. return
  1628. }
  1629. switch t.Kind() {
  1630. case reflect.Chan:
  1631. x.xtraSM(varname, t, ti2, false, isptr)
  1632. case reflect.Array:
  1633. _, rtidu := genFastpathUnderlying(t, rtid, ti2)
  1634. if fastpathAvIndex(rtidu) != -1 {
  1635. g := x.newFastpathGenV(ti2.key)
  1636. x.linef("z.F.%sN((%s)(%s[:]), d)", g.MethodNamePfx("Dec", false), x.genTypeName(ti2.key), varname)
  1637. } else {
  1638. x.xtraSM(varname, t, ti2, false, isptr)
  1639. }
  1640. case reflect.Slice:
  1641. // if a []byte, call dedicated function
  1642. // if a known fastpath slice, call dedicated function
  1643. // else write encode function in-line.
  1644. // - if elements are primitives or Selfers, call dedicated function on each member.
  1645. // - else call Encoder.encode(XXX) on it.
  1646. if rtid == uint8SliceTypId {
  1647. x.linef("%s%s = z.DecodeBytesInto(%s(%s[]byte)(%s))", ptrPfx, varname, ptrPfx, ptrPfx, varname)
  1648. } else {
  1649. tu, rtidu := genFastpathUnderlying(t, rtid, ti2)
  1650. if fastpathAvIndex(rtidu) != -1 {
  1651. g := x.newFastpathGenV(tu)
  1652. if rtid == rtidu {
  1653. x.linef("z.F.%sX(%s%s, d)", g.MethodNamePfx("Dec", false), addrPfx, varname)
  1654. } else {
  1655. x.linef("z.F.%sX((*%s)(%s%s), d)", g.MethodNamePfx("Dec", false), x.genTypeName(tu), addrPfx, varname)
  1656. }
  1657. } else {
  1658. x.xtraSM(varname, t, ti2, false, isptr)
  1659. // x.decListFallback(varname, rtid, false, t)
  1660. }
  1661. }
  1662. case reflect.Map:
  1663. // if a known fastpath map, call dedicated function
  1664. // else write encode function in-line.
  1665. // - if elements are primitives or Selfers, call dedicated function on each member.
  1666. // - else call Encoder.encode(XXX) on it.
  1667. tu, rtidu := genFastpathUnderlying(t, rtid, ti2)
  1668. if fastpathAvIndex(rtidu) != -1 {
  1669. g := x.newFastpathGenV(tu)
  1670. if rtid == rtidu {
  1671. x.linef("z.F.%sX(%s%s, d)", g.MethodNamePfx("Dec", false), addrPfx, varname)
  1672. } else {
  1673. x.linef("z.F.%sX((*%s)(%s%s), d)", g.MethodNamePfx("Dec", false), x.genTypeName(tu), addrPfx, varname)
  1674. }
  1675. } else {
  1676. x.xtraSM(varname, t, ti2, false, isptr)
  1677. }
  1678. case reflect.Struct:
  1679. if inlist {
  1680. // no need to create temp variable if isptr, or x.F or x[F]
  1681. if isptr || strings.IndexByte(varname, '.') != -1 || strings.IndexByte(varname, '[') != -1 {
  1682. x.decStruct(varname, rtid, t)
  1683. } else {
  1684. varname2 := genTempVarPfx + "j" + mi
  1685. x.line(varname2 + " := &" + varname)
  1686. x.decStruct(varname2, rtid, t)
  1687. }
  1688. } else {
  1689. // delete(x.td, rtid)
  1690. x.line("z.DecFallback(" + addrPfx + varname + ", false)")
  1691. }
  1692. default:
  1693. if rtidAdded {
  1694. delete(x.te, rtid)
  1695. }
  1696. x.line("z.DecFallback(" + addrPfx + varname + ", true)")
  1697. }
  1698. }
  1699. func (x *genRunner) decTryAssignPrimitive(varname string, t reflect.Type, isptr bool) (done bool) {
  1700. // This should only be used for exact primitives (ie un-named types).
  1701. // Named types may be implementations of Selfer, Unmarshaler, etc.
  1702. // They should be handled by dec(...)
  1703. var ptr string
  1704. if isptr {
  1705. ptr = "*"
  1706. }
  1707. switch t.Kind() {
  1708. case reflect.Int:
  1709. x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), codecSelferBitsize%s))", ptr, varname, x.genTypeName(t), x.xs)
  1710. case reflect.Int8:
  1711. x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), 8))", ptr, varname, x.genTypeName(t))
  1712. case reflect.Int16:
  1713. x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), 16))", ptr, varname, x.genTypeName(t))
  1714. case reflect.Int32:
  1715. x.linef("%s%s = (%s)(z.C.IntV(r.DecodeInt64(), 32))", ptr, varname, x.genTypeName(t))
  1716. case reflect.Int64:
  1717. x.linef("%s%s = (%s)(r.DecodeInt64())", ptr, varname, x.genTypeName(t))
  1718. case reflect.Uint:
  1719. x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), codecSelferBitsize%s))", ptr, varname, x.genTypeName(t), x.xs)
  1720. case reflect.Uint8:
  1721. x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), 8))", ptr, varname, x.genTypeName(t))
  1722. case reflect.Uint16:
  1723. x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), 16))", ptr, varname, x.genTypeName(t))
  1724. case reflect.Uint32:
  1725. x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), 32))", ptr, varname, x.genTypeName(t))
  1726. case reflect.Uint64:
  1727. x.linef("%s%s = (%s)(r.DecodeUint64())", ptr, varname, x.genTypeName(t))
  1728. case reflect.Uintptr:
  1729. x.linef("%s%s = (%s)(z.C.UintV(r.DecodeUint64(), codecSelferBitsize%s))", ptr, varname, x.genTypeName(t), x.xs)
  1730. case reflect.Float32:
  1731. x.linef("%s%s = (%s)(z.DecDecodeFloat32())", ptr, varname, x.genTypeName(t))
  1732. case reflect.Float64:
  1733. x.linef("%s%s = (%s)(r.DecodeFloat64())", ptr, varname, x.genTypeName(t))
  1734. case reflect.Complex64:
  1735. x.linef("%s%s = (%s)(complex(z.DecDecodeFloat32(), 0))", ptr, varname, x.genTypeName(t))
  1736. case reflect.Complex128:
  1737. x.linef("%s%s = (%s)(complex(r.DecodeFloat64(), 0))", ptr, varname, x.genTypeName(t))
  1738. case reflect.Bool:
  1739. x.linef("%s%s = (%s)(r.DecodeBool())", ptr, varname, x.genTypeName(t))
  1740. case reflect.String:
  1741. if t == genStringDecAsBytesTyp {
  1742. x.linef("%s%s = r.DecodeStringAsBytes()", ptr, varname)
  1743. } else if t == genStringDecZCTyp {
  1744. x.linef("%s%s = (string)(z.DecStringZC(r.DecodeStringAsBytes()))", ptr, varname)
  1745. } else {
  1746. x.linef("%s%s = (%s)(z.DecStringZC(r.DecodeStringAsBytes()))", ptr, varname, x.genTypeName(t))
  1747. }
  1748. default:
  1749. return false
  1750. }
  1751. return true
  1752. }
  1753. func (x *genRunner) decListFallback(varname string, rtid uintptr, t reflect.Type) {
  1754. if t.AssignableTo(uint8SliceTyp) {
  1755. x.line("*" + varname + " = z.DecodeBytesInto(*((*[]byte)(" + varname + ")))")
  1756. return
  1757. }
  1758. if t.Kind() == reflect.Array && t.Elem().Kind() == reflect.Uint8 {
  1759. x.linef("r.DecodeBytes( ((*[%d]byte)(%s))[:])", t.Len(), varname)
  1760. return
  1761. }
  1762. type tstruc struct {
  1763. TempVar string
  1764. Sfx string
  1765. Rand string
  1766. Varname string
  1767. CTyp string
  1768. Typ string
  1769. Immutable bool
  1770. Size int
  1771. }
  1772. telem := t.Elem()
  1773. ts := tstruc{genTempVarPfx, x.xs, x.varsfx(), varname, x.genTypeName(t), x.genTypeName(telem), genIsImmutable(telem), int(telem.Size())}
  1774. funcs := make(template.FuncMap)
  1775. funcs["decLineVar"] = func(varname string) string {
  1776. x.decVar(varname, "", telem, false, true)
  1777. return ""
  1778. }
  1779. funcs["var"] = func(s string) string {
  1780. return ts.TempVar + s + ts.Rand
  1781. }
  1782. funcs["xs"] = func() string {
  1783. return ts.Sfx
  1784. }
  1785. funcs["zero"] = func() string {
  1786. return x.genZeroValueR(telem)
  1787. }
  1788. funcs["isArray"] = func() bool {
  1789. return t.Kind() == reflect.Array
  1790. }
  1791. funcs["isSlice"] = func() bool {
  1792. return t.Kind() == reflect.Slice
  1793. }
  1794. funcs["isChan"] = func() bool {
  1795. return t.Kind() == reflect.Chan
  1796. }
  1797. tm, err := template.New("").Funcs(funcs).Parse(genDecListTmpl)
  1798. genCheckErr(err)
  1799. genCheckErr(tm.Execute(x.w, &ts))
  1800. }
  1801. func (x *genRunner) decMapFallback(varname string, rtid uintptr, t reflect.Type) {
  1802. type tstruc struct {
  1803. TempVar string
  1804. Sfx string
  1805. Rand string
  1806. Varname string
  1807. KTyp string
  1808. Typ string
  1809. Size int
  1810. }
  1811. telem := t.Elem()
  1812. tkey := t.Key()
  1813. ts := tstruc{
  1814. genTempVarPfx, x.xs, x.varsfx(), varname, x.genTypeName(tkey),
  1815. x.genTypeName(telem), int(telem.Size() + tkey.Size()),
  1816. }
  1817. funcs := make(template.FuncMap)
  1818. funcs["decElemZero"] = func() string {
  1819. return x.genZeroValueR(telem)
  1820. }
  1821. funcs["decElemKindImmutable"] = func() bool {
  1822. return genIsImmutable(telem)
  1823. }
  1824. funcs["decElemKindPtr"] = func() bool {
  1825. return telem.Kind() == reflect.Ptr
  1826. }
  1827. funcs["decElemKindIntf"] = func() bool {
  1828. return telem.Kind() == reflect.Interface
  1829. }
  1830. funcs["decLineVarKStrBytes"] = func(varname string) string {
  1831. x.decVar(varname, "", genStringDecAsBytesTyp, false, true)
  1832. return ""
  1833. }
  1834. funcs["decLineVarKStrZC"] = func(varname string) string {
  1835. x.decVar(varname, "", genStringDecZCTyp, false, true)
  1836. return ""
  1837. }
  1838. funcs["decLineVarK"] = func(varname string) string {
  1839. x.decVar(varname, "", tkey, false, true)
  1840. return ""
  1841. }
  1842. funcs["decLineVar"] = func(varname, decodedNilVarname string) string {
  1843. x.decVar(varname, decodedNilVarname, telem, false, true)
  1844. return ""
  1845. }
  1846. funcs["var"] = func(s string) string {
  1847. return ts.TempVar + s + ts.Rand
  1848. }
  1849. funcs["xs"] = func() string {
  1850. return ts.Sfx
  1851. }
  1852. tm, err := template.New("").Funcs(funcs).Parse(genDecMapTmpl)
  1853. genCheckErr(err)
  1854. genCheckErr(tm.Execute(x.w, &ts))
  1855. }
  1856. func (x *genRunner) decStructMapSwitch(kName string, varname string, rtid uintptr, t reflect.Type) {
  1857. ti := x.ti.get(rtid, t)
  1858. tisfi := ti.sfi.source() // always use sequence from file. decStruct expects same thing.
  1859. x.line("switch string(" + kName + ") {")
  1860. var newbuf, nilbuf genBuf
  1861. for _, si := range tisfi {
  1862. x.line("case \"" + si.encName + "\":")
  1863. newbuf.reset()
  1864. nilbuf.reset()
  1865. varname3, t2 := x.decVarInitPtr(varname, "", t, si, &newbuf, &nilbuf)
  1866. if len(newbuf.buf) > 0 {
  1867. x.linef("if r.TryNil() { %s } else { %s", nilbuf.buf, newbuf.buf)
  1868. }
  1869. x.decVarMain(varname3, x.varsfx(), t2.Type, false)
  1870. if len(newbuf.buf) > 0 {
  1871. x.line("}")
  1872. }
  1873. }
  1874. x.line("default:")
  1875. // pass the slice here, so that the string will not escape, and maybe save allocation
  1876. x.linef("z.DecStructFieldNotFound(-1, string(%s))", kName)
  1877. x.linef("} // end switch %s", kName)
  1878. }
  1879. func (x *genRunner) decStructMap(varname, lenvarname string, rtid uintptr, t reflect.Type) {
  1880. tpfx := genTempVarPfx
  1881. ti := x.ti.get(rtid, t)
  1882. i := x.varsfx()
  1883. kName := tpfx + "s" + i
  1884. x.linef("var %shl%s bool = %s >= 0", tpfx, i, lenvarname) // has length
  1885. x.linef("for %sj%s := 0; z.DecContainerNext(%sj%s, %s, %shl%s); %sj%s++ {",
  1886. tpfx, i, tpfx, i, lenvarname, tpfx, i, tpfx, i)
  1887. x.line("z.DecReadMapElemKey()")
  1888. // emulate decstructfieldkey
  1889. switch ti.keyType {
  1890. case valueTypeInt:
  1891. x.linef("%s := strconv.AppendInt(z.DecScratchArrayBuffer()[:0], r.DecodeInt64(), 10)", kName)
  1892. case valueTypeUint:
  1893. x.linef("%s := strconv.AppendUint(z.DecScratchArrayBuffer()[:0], r.DecodeUint64(), 10)", kName)
  1894. case valueTypeFloat:
  1895. x.linef("%s := strconv.AppendFloat(z.DecScratchArrayBuffer()[:0], r.DecodeFloat64(), 'f', -1, 64)", kName)
  1896. default: // string
  1897. x.linef("%s := r.DecodeStringAsBytes()", kName)
  1898. }
  1899. x.line("z.DecReadMapElemValue()")
  1900. x.decStructMapSwitch(kName, varname, rtid, t)
  1901. x.line("} // end for " + tpfx + "j" + i)
  1902. }
  1903. func (x *genRunner) decStructArray(varname, lenvarname, breakString string, rtid uintptr, t reflect.Type) {
  1904. tpfx := genTempVarPfx
  1905. i := x.varsfx()
  1906. ti := x.ti.get(rtid, t)
  1907. tisfi := ti.sfi.source() // always use sequence from file. decStruct expects same thing.
  1908. x.linef("var %sj%s int", tpfx, i)
  1909. x.linef("var %sb%s bool", tpfx, i) // break
  1910. x.linef("var %shl%s bool = %s >= 0", tpfx, i, lenvarname) // has length
  1911. var newbuf, nilbuf genBuf
  1912. for _, si := range tisfi {
  1913. x.linef("%sb%s = !z.DecContainerNext(%sj%s, %s, %shl%s)", tpfx, i, tpfx, i, lenvarname, tpfx, i)
  1914. x.linef("if %sb%s { z.DecReadArrayEnd(); %s }", tpfx, i, breakString)
  1915. x.line("z.DecReadArrayElem()")
  1916. newbuf.reset()
  1917. nilbuf.reset()
  1918. varname3, t2 := x.decVarInitPtr(varname, "", t, si, &newbuf, &nilbuf)
  1919. if len(newbuf.buf) > 0 {
  1920. x.linef("if r.TryNil() { %s } else { %s", nilbuf.buf, newbuf.buf)
  1921. }
  1922. x.decVarMain(varname3, x.varsfx(), t2.Type, false)
  1923. if len(newbuf.buf) > 0 {
  1924. x.line("}")
  1925. }
  1926. x.linef("%sj%s++", tpfx, i)
  1927. }
  1928. // read remaining values and throw away.
  1929. x.linef("for ; z.DecContainerNext(%sj%s, %s, %shl%s); %sj%s++ {",
  1930. tpfx, i, lenvarname, tpfx, i, tpfx, i)
  1931. x.line("z.DecReadArrayElem()")
  1932. x.linef(`z.DecStructFieldNotFound(%sj%s - 1, "")`, tpfx, i)
  1933. x.line("}")
  1934. }
  1935. func (x *genRunner) decStruct(varname string, rtid uintptr, t reflect.Type) {
  1936. // varname MUST be a ptr, or a struct field or a slice element.
  1937. i := x.varsfx()
  1938. x.linef("%sct%s := r.ContainerType()", genTempVarPfx, i)
  1939. x.linef("if %sct%s == codecSelferValueTypeNil%s {", genTempVarPfx, i, x.xs)
  1940. x.linef("*(%s) = %s{}", varname, x.genTypeName(t))
  1941. x.linef("} else if %sct%s == codecSelferValueTypeMap%s {", genTempVarPfx, i, x.xs)
  1942. x.line(genTempVarPfx + "l" + i + " := z.DecReadMapStart()")
  1943. x.linef("if %sl%s == 0 {", genTempVarPfx, i)
  1944. x.line("} else { ")
  1945. x.linef("%s.codecDecodeSelfFromMap(%sl%s, d)", varname, genTempVarPfx, i)
  1946. x.line("}")
  1947. x.line("z.DecReadMapEnd()")
  1948. // else if container is array
  1949. x.linef("} else if %sct%s == codecSelferValueTypeArray%s {", genTempVarPfx, i, x.xs)
  1950. x.line(genTempVarPfx + "l" + i + " := z.DecReadArrayStart()")
  1951. x.linef("if %sl%s != 0 {", genTempVarPfx, i)
  1952. x.linef("%s.codecDecodeSelfFromArray(%sl%s, d)", varname, genTempVarPfx, i)
  1953. x.line("}")
  1954. x.line("z.DecReadArrayEnd()")
  1955. // else panic
  1956. x.line("} else { ")
  1957. x.line("panic(errCodecSelferOnlyMapOrArrayEncodeToStruct" + x.xs + ")")
  1958. x.line("} ")
  1959. }
  1960. // --------
  1961. type fastpathGenV struct {
  1962. // fastpathGenV is either a primitive (Primitive != "") or a map (MapKey != "") or a slice
  1963. MapKey string
  1964. Elem string
  1965. Primitive string
  1966. Size int
  1967. NoCanonical bool
  1968. }
  1969. func (x *genRunner) newFastpathGenV(t reflect.Type) (v fastpathGenV) {
  1970. v.NoCanonical = !genFastpathCanonical
  1971. switch t.Kind() {
  1972. case reflect.Slice, reflect.Array:
  1973. te := t.Elem()
  1974. v.Elem = x.genTypeName(te)
  1975. v.Size = int(te.Size())
  1976. case reflect.Map:
  1977. te := t.Elem()
  1978. tk := t.Key()
  1979. v.Elem = x.genTypeName(te)
  1980. v.MapKey = x.genTypeName(tk)
  1981. v.Size = int(te.Size() + tk.Size())
  1982. default:
  1983. halt.onerror(errGenUnexpectedTypeFastpath)
  1984. }
  1985. return
  1986. }
  1987. func (x *fastpathGenV) MethodNamePfx(prefix string, prim bool) string {
  1988. var name []byte
  1989. if prefix != "" {
  1990. name = append(name, prefix...)
  1991. }
  1992. if prim {
  1993. name = append(name, genTitleCaseName(x.Primitive)...)
  1994. } else {
  1995. if x.MapKey == "" {
  1996. name = append(name, "Slice"...)
  1997. } else {
  1998. name = append(name, "Map"...)
  1999. name = append(name, genTitleCaseName(x.MapKey)...)
  2000. }
  2001. name = append(name, genTitleCaseName(x.Elem)...)
  2002. }
  2003. return string(name)
  2004. }
  2005. // genImportPath returns import path of a non-predeclared named typed, or an empty string otherwise.
  2006. //
  2007. // This handles the misbehaviour that occurs when 1.5-style vendoring is enabled,
  2008. // where PkgPath returns the full path, including the vendoring pre-fix that should have been stripped.
  2009. // We strip it here.
  2010. func genImportPath(t reflect.Type) (s string) {
  2011. s = t.PkgPath()
  2012. if genCheckVendor {
  2013. // HACK: always handle vendoring. It should be typically on in go 1.6, 1.7
  2014. s = genStripVendor(s)
  2015. }
  2016. return
  2017. }
  2018. // A go identifier is (letter|_)[letter|number|_]*
  2019. func genGoIdentifier(s string, checkFirstChar bool) string {
  2020. b := make([]byte, 0, len(s))
  2021. t := make([]byte, 4)
  2022. var n int
  2023. for i, r := range s {
  2024. if checkFirstChar && i == 0 && !unicode.IsLetter(r) {
  2025. b = append(b, '_')
  2026. }
  2027. // r must be unicode_letter, unicode_digit or _
  2028. if unicode.IsLetter(r) || unicode.IsDigit(r) {
  2029. n = utf8.EncodeRune(t, r)
  2030. b = append(b, t[:n]...)
  2031. } else {
  2032. b = append(b, '_')
  2033. }
  2034. }
  2035. return string(b)
  2036. }
  2037. func genNonPtr(t reflect.Type) reflect.Type {
  2038. for t.Kind() == reflect.Ptr {
  2039. t = t.Elem()
  2040. }
  2041. return t
  2042. }
  2043. func genFastpathUnderlying(t reflect.Type, rtid uintptr, ti *typeInfo) (tu reflect.Type, rtidu uintptr) {
  2044. tu = t
  2045. rtidu = rtid
  2046. if ti.flagHasPkgPath {
  2047. tu = ti.fastpathUnderlying
  2048. rtidu = rt2id(tu)
  2049. }
  2050. return
  2051. }
  2052. func genTitleCaseName(s string) string {
  2053. switch s {
  2054. case "interface{}", "interface {}":
  2055. return "Intf"
  2056. case "[]byte", "[]uint8", "bytes":
  2057. return "Bytes"
  2058. default:
  2059. return strings.ToUpper(s[0:1]) + s[1:]
  2060. }
  2061. }
  2062. func genMethodNameT(t reflect.Type, tRef reflect.Type) (n string) {
  2063. var ptrPfx string
  2064. for t.Kind() == reflect.Ptr {
  2065. ptrPfx += "Ptrto"
  2066. t = t.Elem()
  2067. }
  2068. tstr := t.String()
  2069. if tn := t.Name(); tn != "" {
  2070. if tRef != nil && genImportPath(t) == genImportPath(tRef) {
  2071. return ptrPfx + tn
  2072. } else {
  2073. if genQNameRegex.MatchString(tstr) {
  2074. return ptrPfx + strings.Replace(tstr, ".", "_", 1000)
  2075. } else {
  2076. return ptrPfx + genCustomTypeName(tstr)
  2077. }
  2078. }
  2079. }
  2080. switch t.Kind() {
  2081. case reflect.Map:
  2082. return ptrPfx + "Map" + genMethodNameT(t.Key(), tRef) + genMethodNameT(t.Elem(), tRef)
  2083. case reflect.Slice:
  2084. return ptrPfx + "Slice" + genMethodNameT(t.Elem(), tRef)
  2085. case reflect.Array:
  2086. return ptrPfx + "Array" + strconv.FormatInt(int64(t.Len()), 10) + genMethodNameT(t.Elem(), tRef)
  2087. case reflect.Chan:
  2088. var cx string
  2089. switch t.ChanDir() {
  2090. case reflect.SendDir:
  2091. cx = "ChanSend"
  2092. case reflect.RecvDir:
  2093. cx = "ChanRecv"
  2094. default:
  2095. cx = "Chan"
  2096. }
  2097. return ptrPfx + cx + genMethodNameT(t.Elem(), tRef)
  2098. default:
  2099. if t == intfTyp {
  2100. return ptrPfx + "Interface"
  2101. } else {
  2102. if tRef != nil && genImportPath(t) == genImportPath(tRef) {
  2103. if t.Name() != "" {
  2104. return ptrPfx + t.Name()
  2105. } else {
  2106. return ptrPfx + genCustomTypeName(tstr)
  2107. }
  2108. } else {
  2109. // best way to get the package name inclusive
  2110. if t.Name() != "" && genQNameRegex.MatchString(tstr) {
  2111. return ptrPfx + strings.Replace(tstr, ".", "_", 1000)
  2112. } else {
  2113. return ptrPfx + genCustomTypeName(tstr)
  2114. }
  2115. }
  2116. }
  2117. }
  2118. }
  2119. // genCustomNameForType base32 encodes the t.String() value in such a way
  2120. // that it can be used within a function name.
  2121. func genCustomTypeName(tstr string) string {
  2122. len2 := genTypenameEnc.EncodedLen(len(tstr))
  2123. bufx := make([]byte, len2)
  2124. genTypenameEnc.Encode(bufx, []byte(tstr))
  2125. for i := len2 - 1; i >= 0; i-- {
  2126. if bufx[i] == '=' {
  2127. len2--
  2128. } else {
  2129. break
  2130. }
  2131. }
  2132. return string(bufx[:len2])
  2133. }
  2134. func genIsImmutable(t reflect.Type) (v bool) {
  2135. return scalarBitset.isset(byte(t.Kind()))
  2136. }
  2137. type genInternal struct {
  2138. Version int
  2139. Values []fastpathGenV
  2140. Formats []string
  2141. }
  2142. func (x genInternal) FastpathLen() (l int) {
  2143. for _, v := range x.Values {
  2144. // if v.Primitive == "" && !(v.MapKey == "" && v.Elem == "uint8") {
  2145. if v.Primitive == "" {
  2146. l++
  2147. }
  2148. }
  2149. return
  2150. }
  2151. func genInternalZeroValue(s string) string {
  2152. switch s {
  2153. case "interface{}", "interface {}":
  2154. return "nil"
  2155. case "[]byte", "[]uint8", "bytes":
  2156. return "nil"
  2157. case "bool":
  2158. return "false"
  2159. case "string":
  2160. return `""`
  2161. default:
  2162. return "0"
  2163. }
  2164. }
  2165. var genInternalNonZeroValueIdx [6]uint64
  2166. var genInternalNonZeroValueStrs = [...][6]string{
  2167. {`"string-is-an-interface-1"`, "true", `"some-string-1"`, `[]byte("some-string-1")`, "11.1", "111"},
  2168. {`"string-is-an-interface-2"`, "false", `"some-string-2"`, `[]byte("some-string-2")`, "22.2", "77"},
  2169. {`"string-is-an-interface-3"`, "true", `"some-string-3"`, `[]byte("some-string-3")`, "33.3e3", "127"},
  2170. }
  2171. // Note: last numbers must be in range: 0-127 (as they may be put into a int8, uint8, etc)
  2172. func genInternalNonZeroValue(s string) string {
  2173. var i int
  2174. switch s {
  2175. case "interface{}", "interface {}":
  2176. i = 0
  2177. case "bool":
  2178. i = 1
  2179. case "string":
  2180. i = 2
  2181. case "bytes", "[]byte", "[]uint8":
  2182. i = 3
  2183. case "float32", "float64", "float", "double", "complex", "complex64", "complex128":
  2184. i = 4
  2185. default:
  2186. i = 5
  2187. }
  2188. genInternalNonZeroValueIdx[i]++
  2189. idx := genInternalNonZeroValueIdx[i]
  2190. slen := uint64(len(genInternalNonZeroValueStrs))
  2191. return genInternalNonZeroValueStrs[idx%slen][i] // return string, to remove ambiguity
  2192. }
  2193. // Note: used for fastpath only
  2194. func genInternalEncCommandAsString(s string, vname string) string {
  2195. switch s {
  2196. case "uint64":
  2197. return "e.e.EncodeUint(" + vname + ")"
  2198. case "uint", "uint8", "uint16", "uint32":
  2199. return "e.e.EncodeUint(uint64(" + vname + "))"
  2200. case "int64":
  2201. return "e.e.EncodeInt(" + vname + ")"
  2202. case "int", "int8", "int16", "int32":
  2203. return "e.e.EncodeInt(int64(" + vname + "))"
  2204. case "[]byte", "[]uint8", "bytes":
  2205. return "e.e.EncodeStringBytesRaw(" + vname + ")"
  2206. case "string":
  2207. return "e.e.EncodeString(" + vname + ")"
  2208. case "float32":
  2209. return "e.e.EncodeFloat32(" + vname + ")"
  2210. case "float64":
  2211. return "e.e.EncodeFloat64(" + vname + ")"
  2212. case "bool":
  2213. return "e.e.EncodeBool(" + vname + ")"
  2214. // case "symbol":
  2215. // return "e.e.EncodeSymbol(" + vname + ")"
  2216. default:
  2217. return "e.encode(" + vname + ")"
  2218. }
  2219. }
  2220. // Note: used for fastpath only
  2221. func genInternalDecCommandAsString(s string, mapkey bool) string {
  2222. switch s {
  2223. case "uint":
  2224. return "uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize))"
  2225. case "uint8":
  2226. return "uint8(chkOvf.UintV(d.d.DecodeUint64(), 8))"
  2227. case "uint16":
  2228. return "uint16(chkOvf.UintV(d.d.DecodeUint64(), 16))"
  2229. case "uint32":
  2230. return "uint32(chkOvf.UintV(d.d.DecodeUint64(), 32))"
  2231. case "uint64":
  2232. return "d.d.DecodeUint64()"
  2233. case "uintptr":
  2234. return "uintptr(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize))"
  2235. case "int":
  2236. return "int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize))"
  2237. case "int8":
  2238. return "int8(chkOvf.IntV(d.d.DecodeInt64(), 8))"
  2239. case "int16":
  2240. return "int16(chkOvf.IntV(d.d.DecodeInt64(), 16))"
  2241. case "int32":
  2242. return "int32(chkOvf.IntV(d.d.DecodeInt64(), 32))"
  2243. case "int64":
  2244. return "d.d.DecodeInt64()"
  2245. case "string":
  2246. // if mapkey {
  2247. // return "d.stringZC(d.d.DecodeStringAsBytes())"
  2248. // }
  2249. // return "string(d.d.DecodeStringAsBytes())"
  2250. return "d.stringZC(d.d.DecodeStringAsBytes())"
  2251. case "[]byte", "[]uint8", "bytes":
  2252. return "d.d.DecodeBytes([]byte{})"
  2253. case "float32":
  2254. return "float32(d.decodeFloat32())"
  2255. case "float64":
  2256. return "d.d.DecodeFloat64()"
  2257. case "complex64":
  2258. return "complex(d.decodeFloat32(), 0)"
  2259. case "complex128":
  2260. return "complex(d.d.DecodeFloat64(), 0)"
  2261. case "bool":
  2262. return "d.d.DecodeBool()"
  2263. default:
  2264. halt.onerror(errors.New("gen internal: unknown type for decode: " + s))
  2265. }
  2266. return ""
  2267. }
  2268. // func genInternalSortType(s string, elem bool) string {
  2269. // for _, v := range [...]string{
  2270. // "int",
  2271. // "uint",
  2272. // "float",
  2273. // "bool",
  2274. // "string",
  2275. // "bytes", "[]uint8", "[]byte",
  2276. // } {
  2277. // if v == "[]byte" || v == "[]uint8" {
  2278. // v = "bytes"
  2279. // }
  2280. // if strings.HasPrefix(s, v) {
  2281. // if v == "int" || v == "uint" || v == "float" {
  2282. // v += "64"
  2283. // }
  2284. // if elem {
  2285. // return v
  2286. // }
  2287. // return v + "Slice"
  2288. // }
  2289. // }
  2290. // halt.onerror(errors.New("sorttype: unexpected type: " + s))
  2291. // }
  2292. func genInternalSortType(s string, elem bool) string {
  2293. if elem {
  2294. return s
  2295. }
  2296. return s + "Slice"
  2297. }
  2298. // MARKER: keep in sync with codecgen/gen.go
  2299. func genStripVendor(s string) string {
  2300. // HACK: Misbehaviour occurs in go 1.5. May have to re-visit this later.
  2301. // if s contains /vendor/ OR startsWith vendor/, then return everything after it.
  2302. const vendorStart = "vendor/"
  2303. const vendorInline = "/vendor/"
  2304. if i := strings.LastIndex(s, vendorInline); i >= 0 {
  2305. s = s[i+len(vendorInline):]
  2306. } else if strings.HasPrefix(s, vendorStart) {
  2307. s = s[len(vendorStart):]
  2308. }
  2309. return s
  2310. }
  2311. // var genInternalMu sync.Mutex
  2312. var genInternalV = genInternal{Version: genVersion}
  2313. var genInternalTmplFuncs template.FuncMap
  2314. var genInternalOnce sync.Once
  2315. func genInternalInit() {
  2316. wordSizeBytes := int(intBitsize) / 8
  2317. typesizes := map[string]int{
  2318. "interface{}": 2 * wordSizeBytes,
  2319. "string": 2 * wordSizeBytes,
  2320. "[]byte": 3 * wordSizeBytes,
  2321. "uint": 1 * wordSizeBytes,
  2322. "uint8": 1,
  2323. "uint16": 2,
  2324. "uint32": 4,
  2325. "uint64": 8,
  2326. "uintptr": 1 * wordSizeBytes,
  2327. "int": 1 * wordSizeBytes,
  2328. "int8": 1,
  2329. "int16": 2,
  2330. "int32": 4,
  2331. "int64": 8,
  2332. "float32": 4,
  2333. "float64": 8,
  2334. "complex64": 8,
  2335. "complex128": 16,
  2336. "bool": 1,
  2337. }
  2338. // keep as slice, so it is in specific iteration order.
  2339. // Initial order was uint64, string, interface{}, int, int64, ...
  2340. var types = [...]string{
  2341. "interface{}",
  2342. "string",
  2343. "[]byte",
  2344. "float32",
  2345. "float64",
  2346. "uint",
  2347. "uint8",
  2348. "uint16",
  2349. "uint32",
  2350. "uint64",
  2351. "uintptr",
  2352. "int",
  2353. "int8",
  2354. "int16",
  2355. "int32",
  2356. "int64",
  2357. "bool",
  2358. }
  2359. var primitivetypes, slicetypes, mapkeytypes, mapvaltypes []string
  2360. primitivetypes = types[:]
  2361. slicetypes = types[:]
  2362. mapkeytypes = types[:]
  2363. mapvaltypes = types[:]
  2364. if genFastpathTrimTypes {
  2365. // Note: we only create fast-paths for commonly used types.
  2366. // Consequently, things like int8, uint16, uint, etc are commented out.
  2367. slicetypes = genInternalFastpathSliceTypes()
  2368. mapkeytypes = genInternalFastpathMapKeyTypes()
  2369. mapvaltypes = genInternalFastpathMapValueTypes()
  2370. }
  2371. // var mapkeytypes [len(&types) - 1]string // skip bool
  2372. // copy(mapkeytypes[:], types[:])
  2373. // var mb []byte
  2374. // mb = append(mb, '|')
  2375. // for _, s := range mapkeytypes {
  2376. // mb = append(mb, s...)
  2377. // mb = append(mb, '|')
  2378. // }
  2379. // var mapkeytypestr = string(mb)
  2380. var gt = genInternal{Version: genVersion, Formats: genFormats}
  2381. // For each slice or map type, there must be a (symmetrical) Encode and Decode fast-path function
  2382. for _, s := range primitivetypes {
  2383. gt.Values = append(gt.Values,
  2384. fastpathGenV{Primitive: s, Size: typesizes[s], NoCanonical: !genFastpathCanonical})
  2385. }
  2386. for _, s := range slicetypes {
  2387. // if s != "uint8" { // do not generate fast path for slice of bytes. Treat specially already.
  2388. // gt.Values = append(gt.Values, fastpathGenV{Elem: s, Size: typesizes[s]})
  2389. // }
  2390. gt.Values = append(gt.Values,
  2391. fastpathGenV{Elem: s, Size: typesizes[s], NoCanonical: !genFastpathCanonical})
  2392. }
  2393. for _, s := range mapkeytypes {
  2394. // if _, ok := typesizes[s]; !ok {
  2395. // if strings.Contains(mapkeytypestr, "|"+s+"|") {
  2396. // gt.Values = append(gt.Values, fastpathGenV{MapKey: s, Elem: s, Size: 2 * typesizes[s]})
  2397. // }
  2398. for _, ms := range mapvaltypes {
  2399. gt.Values = append(gt.Values,
  2400. fastpathGenV{MapKey: s, Elem: ms, Size: typesizes[s] + typesizes[ms], NoCanonical: !genFastpathCanonical})
  2401. }
  2402. }
  2403. funcs := make(template.FuncMap)
  2404. // funcs["haspfx"] = strings.HasPrefix
  2405. funcs["encmd"] = genInternalEncCommandAsString
  2406. funcs["decmd"] = genInternalDecCommandAsString
  2407. funcs["zerocmd"] = genInternalZeroValue
  2408. funcs["nonzerocmd"] = genInternalNonZeroValue
  2409. funcs["hasprefix"] = strings.HasPrefix
  2410. funcs["sorttype"] = genInternalSortType
  2411. genInternalV = gt
  2412. genInternalTmplFuncs = funcs
  2413. }
  2414. // genInternalGoFile is used to generate source files from templates.
  2415. func genInternalGoFile(r io.Reader, w io.Writer) (err error) {
  2416. genInternalOnce.Do(genInternalInit)
  2417. gt := genInternalV
  2418. t := template.New("").Funcs(genInternalTmplFuncs)
  2419. tmplstr, err := ioutil.ReadAll(r)
  2420. if err != nil {
  2421. return
  2422. }
  2423. if t, err = t.Parse(string(tmplstr)); err != nil {
  2424. return
  2425. }
  2426. var out bytes.Buffer
  2427. err = t.Execute(&out, gt)
  2428. if err != nil {
  2429. return
  2430. }
  2431. bout, err := format.Source(out.Bytes())
  2432. if err != nil {
  2433. w.Write(out.Bytes()) // write out if error, so we can still see.
  2434. // w.Write(bout) // write out if error, as much as possible, so we can still see.
  2435. return
  2436. }
  2437. w.Write(bout)
  2438. return
  2439. }
  2440. func genInternalFastpathSliceTypes() []string {
  2441. return []string{
  2442. "interface{}",
  2443. "string",
  2444. "[]byte",
  2445. "float32",
  2446. "float64",
  2447. // "uint",
  2448. // "uint8", // no need for fastpath of []uint8, as it is handled specially
  2449. "uint8", // keep fast-path, so it doesn't have to go through reflection
  2450. // "uint16",
  2451. // "uint32",
  2452. "uint64",
  2453. // "uintptr",
  2454. "int",
  2455. // "int8",
  2456. // "int16",
  2457. "int32", // rune
  2458. "int64",
  2459. "bool",
  2460. }
  2461. }
  2462. func genInternalFastpathMapKeyTypes() []string {
  2463. return []string{
  2464. // "interface{}",
  2465. "string",
  2466. // "[]byte",
  2467. // "float32",
  2468. // "float64",
  2469. // "uint",
  2470. "uint8", // byte
  2471. // "uint16",
  2472. // "uint32",
  2473. "uint64", // used for keys
  2474. // "uintptr",
  2475. "int", // default number key
  2476. // "int8",
  2477. // "int16",
  2478. "int32", // rune
  2479. // "int64",
  2480. // "bool",
  2481. }
  2482. }
  2483. func genInternalFastpathMapValueTypes() []string {
  2484. return []string{
  2485. "interface{}",
  2486. "string",
  2487. "[]byte",
  2488. // "uint",
  2489. "uint8", // byte
  2490. // "uint16",
  2491. // "uint32",
  2492. "uint64", // used for keys, etc
  2493. // "uintptr",
  2494. "int", // default number
  2495. //"int8",
  2496. // "int16",
  2497. "int32", // rune (mostly used for unicode)
  2498. // "int64",
  2499. // "float32",
  2500. "float64",
  2501. "bool",
  2502. }
  2503. }
  2504. // sort-slice ...
  2505. // generates sort implementations for
  2506. // various slice types and combination slice+reflect.Value types.
  2507. //
  2508. // The combination slice+reflect.Value types are used
  2509. // during canonical encode, and the others are used during fast-path
  2510. // encoding of map keys.
  2511. // genInternalSortableTypes returns the types
  2512. // that are used for fast-path canonical's encoding of maps.
  2513. //
  2514. // For now, we only support the highest sizes for
  2515. // int64, uint64, float64, bool, string, bytes.
  2516. func genInternalSortableTypes() []string {
  2517. return genInternalFastpathMapKeyTypes()
  2518. }
  2519. // genInternalSortablePlusTypes returns the types
  2520. // that are used for reflection-based canonical's encoding of maps.
  2521. //
  2522. // For now, we only support the highest sizes for
  2523. // int64, uint64, float64, string, bytes.
  2524. func genInternalSortablePlusTypes() []string {
  2525. return []string{
  2526. "string",
  2527. "float64",
  2528. "uint64",
  2529. // "uintptr",
  2530. "int64",
  2531. // "bool",
  2532. "time",
  2533. "bytes",
  2534. }
  2535. }
  2536. func genTypeForShortName(s string) string {
  2537. switch s {
  2538. case "time":
  2539. return "time.Time"
  2540. case "bytes":
  2541. return "[]byte"
  2542. }
  2543. return s
  2544. }
  2545. func genArgs(args ...interface{}) map[string]interface{} {
  2546. m := make(map[string]interface{}, len(args)/2)
  2547. for i := 0; i < len(args); {
  2548. m[args[i].(string)] = args[i+1]
  2549. i += 2
  2550. }
  2551. return m
  2552. }
  2553. func genEndsWith(s0 string, sn ...string) bool {
  2554. for _, s := range sn {
  2555. if strings.HasSuffix(s0, s) {
  2556. return true
  2557. }
  2558. }
  2559. return false
  2560. }
  2561. func genCheckErr(err error) {
  2562. halt.onerror(err)
  2563. }
  2564. func genRunSortTmpl2Go(fnameIn, fnameOut string) {
  2565. var err error
  2566. funcs := make(template.FuncMap)
  2567. funcs["sortables"] = genInternalSortableTypes
  2568. funcs["sortablesplus"] = genInternalSortablePlusTypes
  2569. funcs["tshort"] = genTypeForShortName
  2570. funcs["endswith"] = genEndsWith
  2571. funcs["args"] = genArgs
  2572. t := template.New("").Funcs(funcs)
  2573. fin, err := os.Open(fnameIn)
  2574. genCheckErr(err)
  2575. defer fin.Close()
  2576. fout, err := os.Create(fnameOut)
  2577. genCheckErr(err)
  2578. defer fout.Close()
  2579. tmplstr, err := ioutil.ReadAll(fin)
  2580. genCheckErr(err)
  2581. t, err = t.Parse(string(tmplstr))
  2582. genCheckErr(err)
  2583. var out bytes.Buffer
  2584. err = t.Execute(&out, 0)
  2585. genCheckErr(err)
  2586. bout, err := format.Source(out.Bytes())
  2587. if err != nil {
  2588. fout.Write(out.Bytes()) // write out if error, so we can still see.
  2589. }
  2590. genCheckErr(err)
  2591. // write out if error, as much as possible, so we can still see.
  2592. _, err = fout.Write(bout)
  2593. genCheckErr(err)
  2594. }
  2595. func genRunTmpl2Go(fnameIn, fnameOut string) {
  2596. // println("____ " + fnameIn + " --> " + fnameOut + " ______")
  2597. fin, err := os.Open(fnameIn)
  2598. genCheckErr(err)
  2599. defer fin.Close()
  2600. fout, err := os.Create(fnameOut)
  2601. genCheckErr(err)
  2602. defer fout.Close()
  2603. err = genInternalGoFile(fin, fout)
  2604. genCheckErr(err)
  2605. }
  2606. // --- some methods here for other types, which are only used in codecgen
  2607. // depth returns number of valid nodes in the hierachy
  2608. func (path *structFieldInfoPathNode) root() *structFieldInfoPathNode {
  2609. TOP:
  2610. if path.parent != nil {
  2611. path = path.parent
  2612. goto TOP
  2613. }
  2614. return path
  2615. }
  2616. func (path *structFieldInfoPathNode) fullpath() (p []*structFieldInfoPathNode) {
  2617. // this method is mostly called by a command-line tool - it's not optimized, and that's ok.
  2618. // it shouldn't be used in typical runtime use - as it does unnecessary allocation.
  2619. d := path.depth()
  2620. p = make([]*structFieldInfoPathNode, d)
  2621. for d--; d >= 0; d-- {
  2622. p[d] = path
  2623. path = path.parent
  2624. }
  2625. return
  2626. }