gen.go 62 KB

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