gen.go 56 KB

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