gen.go 61 KB

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