gen.go 86 KB

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