gen.go 62 KB

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