gen.go 64 KB

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