gen.go 63 KB

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