populate.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. // Protocol Buffers for Go with Gadgets
  2. //
  3. // Copyright (c) 2013, The GoGo Authors. All rights reserved.
  4. // http://github.com/gogo/protobuf
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. /*
  29. The populate plugin generates a NewPopulated function.
  30. This function returns a newly populated structure.
  31. It is enabled by the following extensions:
  32. - populate
  33. - populate_all
  34. Let us look at:
  35. github.com/gogo/protobuf/test/example/example.proto
  36. Btw all the output can be seen at:
  37. github.com/gogo/protobuf/test/example/*
  38. The following message:
  39. option (gogoproto.populate_all) = true;
  40. message B {
  41. optional A A = 1 [(gogoproto.nullable) = false, (gogoproto.embed) = true];
  42. repeated bytes G = 2 [(gogoproto.customtype) = "github.com/gogo/protobuf/test/custom.Uint128", (gogoproto.nullable) = false];
  43. }
  44. given to the populate plugin, will generate code the following code:
  45. func NewPopulatedB(r randyExample, easy bool) *B {
  46. this := &B{}
  47. v2 := NewPopulatedA(r, easy)
  48. this.A = *v2
  49. if r.Intn(10) != 0 {
  50. v3 := r.Intn(10)
  51. this.G = make([]github_com_gogo_protobuf_test_custom.Uint128, v3)
  52. for i := 0; i < v3; i++ {
  53. v4 := github_com_gogo_protobuf_test_custom.NewPopulatedUint128(r)
  54. this.G[i] = *v4
  55. }
  56. }
  57. if !easy && r.Intn(10) != 0 {
  58. this.XXX_unrecognized = randUnrecognizedExample(r, 3)
  59. }
  60. return this
  61. }
  62. The idea that is useful for testing.
  63. Most of the other plugins' generated test code uses it.
  64. You will still be able to use the generated test code of other packages
  65. if you turn off the popluate plugin and write your own custom NewPopulated function.
  66. If the easy flag is not set the XXX_unrecognized and XXX_extensions fields are also populated.
  67. These have caused problems with JSON marshalling and unmarshalling tests.
  68. */
  69. package populate
  70. import (
  71. "fmt"
  72. "math"
  73. "strconv"
  74. "strings"
  75. "github.com/gogo/protobuf/gogoproto"
  76. "github.com/gogo/protobuf/proto"
  77. descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
  78. "github.com/gogo/protobuf/protoc-gen-gogo/generator"
  79. "github.com/gogo/protobuf/vanity"
  80. )
  81. type VarGen interface {
  82. Next() string
  83. Current() string
  84. }
  85. type varGen struct {
  86. index int64
  87. }
  88. func NewVarGen() VarGen {
  89. return &varGen{0}
  90. }
  91. func (this *varGen) Next() string {
  92. this.index++
  93. return fmt.Sprintf("v%d", this.index)
  94. }
  95. func (this *varGen) Current() string {
  96. return fmt.Sprintf("v%d", this.index)
  97. }
  98. type plugin struct {
  99. *generator.Generator
  100. generator.PluginImports
  101. varGen VarGen
  102. atleastOne bool
  103. localName string
  104. typesPkg generator.Single
  105. }
  106. func NewPlugin() *plugin {
  107. return &plugin{}
  108. }
  109. func (p *plugin) Name() string {
  110. return "populate"
  111. }
  112. func (p *plugin) Init(g *generator.Generator) {
  113. p.Generator = g
  114. }
  115. func value(typeName string, fieldType descriptor.FieldDescriptorProto_Type) string {
  116. switch fieldType {
  117. case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
  118. return typeName + "(r.Float64())"
  119. case descriptor.FieldDescriptorProto_TYPE_FLOAT:
  120. return typeName + "(r.Float32())"
  121. case descriptor.FieldDescriptorProto_TYPE_INT64,
  122. descriptor.FieldDescriptorProto_TYPE_SFIXED64,
  123. descriptor.FieldDescriptorProto_TYPE_SINT64:
  124. return typeName + "(r.Int63())"
  125. case descriptor.FieldDescriptorProto_TYPE_UINT64,
  126. descriptor.FieldDescriptorProto_TYPE_FIXED64:
  127. return typeName + "(uint64(r.Uint32()))"
  128. case descriptor.FieldDescriptorProto_TYPE_INT32,
  129. descriptor.FieldDescriptorProto_TYPE_SINT32,
  130. descriptor.FieldDescriptorProto_TYPE_SFIXED32,
  131. descriptor.FieldDescriptorProto_TYPE_ENUM:
  132. return typeName + "(r.Int31())"
  133. case descriptor.FieldDescriptorProto_TYPE_UINT32,
  134. descriptor.FieldDescriptorProto_TYPE_FIXED32:
  135. return typeName + "(r.Uint32())"
  136. case descriptor.FieldDescriptorProto_TYPE_BOOL:
  137. return typeName + `(bool(r.Intn(2) == 0))`
  138. case descriptor.FieldDescriptorProto_TYPE_STRING,
  139. descriptor.FieldDescriptorProto_TYPE_GROUP,
  140. descriptor.FieldDescriptorProto_TYPE_MESSAGE,
  141. descriptor.FieldDescriptorProto_TYPE_BYTES:
  142. }
  143. panic(fmt.Errorf("unexpected type %v", typeName))
  144. }
  145. func negative(fieldType descriptor.FieldDescriptorProto_Type) bool {
  146. switch fieldType {
  147. case descriptor.FieldDescriptorProto_TYPE_UINT64,
  148. descriptor.FieldDescriptorProto_TYPE_FIXED64,
  149. descriptor.FieldDescriptorProto_TYPE_UINT32,
  150. descriptor.FieldDescriptorProto_TYPE_FIXED32,
  151. descriptor.FieldDescriptorProto_TYPE_BOOL:
  152. return false
  153. }
  154. return true
  155. }
  156. func (p *plugin) getFuncName(goTypName string, field *descriptor.FieldDescriptorProto) string {
  157. funcName := "NewPopulated" + goTypName
  158. goTypNames := strings.Split(goTypName, ".")
  159. if len(goTypNames) == 2 {
  160. funcName = goTypNames[0] + ".NewPopulated" + goTypNames[1]
  161. } else if len(goTypNames) != 1 {
  162. panic(fmt.Errorf("unreachable: too many dots in %v", goTypName))
  163. }
  164. if field != nil {
  165. switch {
  166. case gogoproto.IsStdTime(field):
  167. funcName = p.typesPkg.Use() + ".NewPopulatedStdTime"
  168. case gogoproto.IsStdDuration(field):
  169. funcName = p.typesPkg.Use() + ".NewPopulatedStdDuration"
  170. case gogoproto.IsStdDouble(field):
  171. funcName = p.typesPkg.Use() + ".NewPopulatedStdDouble"
  172. case gogoproto.IsStdFloat(field):
  173. funcName = p.typesPkg.Use() + ".NewPopulatedStdFloat"
  174. case gogoproto.IsStdInt64(field):
  175. funcName = p.typesPkg.Use() + ".NewPopulatedStdInt64"
  176. case gogoproto.IsStdUInt64(field):
  177. funcName = p.typesPkg.Use() + ".NewPopulatedStdUInt64"
  178. case gogoproto.IsStdInt32(field):
  179. funcName = p.typesPkg.Use() + ".NewPopulatedStdInt32"
  180. case gogoproto.IsStdUInt32(field):
  181. funcName = p.typesPkg.Use() + ".NewPopulatedStdUInt32"
  182. case gogoproto.IsStdBool(field):
  183. funcName = p.typesPkg.Use() + ".NewPopulatedStdBool"
  184. case gogoproto.IsStdString(field):
  185. funcName = p.typesPkg.Use() + ".NewPopulatedStdString"
  186. case gogoproto.IsStdBytes(field):
  187. funcName = p.typesPkg.Use() + ".NewPopulatedStdBytes"
  188. }
  189. }
  190. return funcName
  191. }
  192. func (p *plugin) getFuncCall(goTypName string, field *descriptor.FieldDescriptorProto) string {
  193. funcName := p.getFuncName(goTypName, field)
  194. funcCall := funcName + "(r, easy)"
  195. return funcCall
  196. }
  197. func (p *plugin) getCustomFuncCall(goTypName string) string {
  198. funcName := p.getFuncName(goTypName, nil)
  199. funcCall := funcName + "(r)"
  200. return funcCall
  201. }
  202. func (p *plugin) getEnumVal(field *descriptor.FieldDescriptorProto, goTyp string) string {
  203. enum := p.ObjectNamed(field.GetTypeName()).(*generator.EnumDescriptor)
  204. l := len(enum.Value)
  205. values := make([]string, l)
  206. for i := range enum.Value {
  207. values[i] = strconv.Itoa(int(*enum.Value[i].Number))
  208. }
  209. arr := "[]int32{" + strings.Join(values, ",") + "}"
  210. val := strings.Join([]string{generator.GoTypeToName(goTyp), `(`, arr, `[r.Intn(`, fmt.Sprintf("%d", l), `)])`}, "")
  211. return val
  212. }
  213. func (p *plugin) GenerateField(file *generator.FileDescriptor, message *generator.Descriptor, field *descriptor.FieldDescriptorProto) {
  214. proto3 := gogoproto.IsProto3(file.FileDescriptorProto)
  215. goTyp, _ := p.GoType(message, field)
  216. fieldname := p.GetOneOfFieldName(message, field)
  217. goTypName := generator.GoTypeToName(goTyp)
  218. if p.IsMap(field) {
  219. m := p.GoMapType(nil, field)
  220. keygoTyp, _ := p.GoType(nil, m.KeyField)
  221. keygoTyp = strings.Replace(keygoTyp, "*", "", 1)
  222. keygoAliasTyp, _ := p.GoType(nil, m.KeyAliasField)
  223. keygoAliasTyp = strings.Replace(keygoAliasTyp, "*", "", 1)
  224. valuegoTyp, _ := p.GoType(nil, m.ValueField)
  225. valuegoAliasTyp, _ := p.GoType(nil, m.ValueAliasField)
  226. keytypName := generator.GoTypeToName(keygoTyp)
  227. keygoAliasTyp = generator.GoTypeToName(keygoAliasTyp)
  228. valuetypAliasName := generator.GoTypeToName(valuegoAliasTyp)
  229. nullable, valuegoTyp, valuegoAliasTyp := generator.GoMapValueTypes(field, m.ValueField, valuegoTyp, valuegoAliasTyp)
  230. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  231. p.P(`this.`, fieldname, ` = make(`, m.GoType, `)`)
  232. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  233. p.In()
  234. keyval := ""
  235. if m.KeyField.IsString() {
  236. keyval = fmt.Sprintf("randString%v(r)", p.localName)
  237. } else {
  238. keyval = value(keytypName, m.KeyField.GetType())
  239. }
  240. if keygoAliasTyp != keygoTyp {
  241. keyval = keygoAliasTyp + `(` + keyval + `)`
  242. }
  243. if m.ValueField.IsMessage() || p.IsGroup(field) ||
  244. (m.ValueField.IsBytes() && gogoproto.IsCustomType(field)) {
  245. s := `this.` + fieldname + `[` + keyval + `] = `
  246. if gogoproto.IsStdType(field) {
  247. valuegoTyp = valuegoAliasTyp
  248. }
  249. funcCall := p.getCustomFuncCall(goTypName)
  250. if !gogoproto.IsCustomType(field) {
  251. goTypName = generator.GoTypeToName(valuegoTyp)
  252. funcCall = p.getFuncCall(goTypName, m.ValueAliasField)
  253. }
  254. if !nullable {
  255. funcCall = `*` + funcCall
  256. }
  257. if valuegoTyp != valuegoAliasTyp {
  258. funcCall = `(` + valuegoAliasTyp + `)(` + funcCall + `)`
  259. }
  260. s += funcCall
  261. p.P(s)
  262. } else if m.ValueField.IsEnum() {
  263. s := `this.` + fieldname + `[` + keyval + `]` + ` = ` + p.getEnumVal(m.ValueField, valuegoTyp)
  264. p.P(s)
  265. } else if m.ValueField.IsBytes() {
  266. count := p.varGen.Next()
  267. p.P(count, ` := r.Intn(100)`)
  268. p.P(p.varGen.Next(), ` := `, keyval)
  269. p.P(`this.`, fieldname, `[`, p.varGen.Current(), `] = make(`, valuegoTyp, `, `, count, `)`)
  270. p.P(`for i := 0; i < `, count, `; i++ {`)
  271. p.In()
  272. p.P(`this.`, fieldname, `[`, p.varGen.Current(), `][i] = byte(r.Intn(256))`)
  273. p.Out()
  274. p.P(`}`)
  275. } else if m.ValueField.IsString() {
  276. s := `this.` + fieldname + `[` + keyval + `]` + ` = ` + fmt.Sprintf("randString%v(r)", p.localName)
  277. p.P(s)
  278. } else {
  279. p.P(p.varGen.Next(), ` := `, keyval)
  280. p.P(`this.`, fieldname, `[`, p.varGen.Current(), `] = `, value(valuetypAliasName, m.ValueField.GetType()))
  281. if negative(m.ValueField.GetType()) {
  282. p.P(`if r.Intn(2) == 0 {`)
  283. p.In()
  284. p.P(`this.`, fieldname, `[`, p.varGen.Current(), `] *= -1`)
  285. p.Out()
  286. p.P(`}`)
  287. }
  288. }
  289. p.Out()
  290. p.P(`}`)
  291. } else if gogoproto.IsCustomType(field) {
  292. funcCall := p.getCustomFuncCall(goTypName)
  293. if field.IsRepeated() {
  294. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  295. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  296. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  297. p.In()
  298. p.P(p.varGen.Next(), `:= `, funcCall)
  299. p.P(`this.`, fieldname, `[i] = *`, p.varGen.Current())
  300. p.Out()
  301. p.P(`}`)
  302. } else if gogoproto.IsNullable(field) {
  303. p.P(`this.`, fieldname, ` = `, funcCall)
  304. } else {
  305. p.P(p.varGen.Next(), `:= `, funcCall)
  306. p.P(`this.`, fieldname, ` = *`, p.varGen.Current())
  307. }
  308. } else if field.IsMessage() || p.IsGroup(field) {
  309. funcCall := p.getFuncCall(goTypName, field)
  310. if field.IsRepeated() {
  311. p.P(p.varGen.Next(), ` := r.Intn(5)`)
  312. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  313. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  314. p.In()
  315. if gogoproto.IsNullable(field) {
  316. p.P(`this.`, fieldname, `[i] = `, funcCall)
  317. } else {
  318. p.P(p.varGen.Next(), `:= `, funcCall)
  319. p.P(`this.`, fieldname, `[i] = *`, p.varGen.Current())
  320. }
  321. p.Out()
  322. p.P(`}`)
  323. } else {
  324. if gogoproto.IsNullable(field) {
  325. p.P(`this.`, fieldname, ` = `, funcCall)
  326. } else {
  327. p.P(p.varGen.Next(), `:= `, funcCall)
  328. p.P(`this.`, fieldname, ` = *`, p.varGen.Current())
  329. }
  330. }
  331. } else {
  332. if field.IsEnum() {
  333. val := p.getEnumVal(field, goTyp)
  334. if field.IsRepeated() {
  335. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  336. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  337. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  338. p.In()
  339. p.P(`this.`, fieldname, `[i] = `, val)
  340. p.Out()
  341. p.P(`}`)
  342. } else if !gogoproto.IsNullable(field) || proto3 {
  343. p.P(`this.`, fieldname, ` = `, val)
  344. } else {
  345. p.P(p.varGen.Next(), ` := `, val)
  346. p.P(`this.`, fieldname, ` = &`, p.varGen.Current())
  347. }
  348. } else if field.IsBytes() {
  349. if field.IsRepeated() {
  350. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  351. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  352. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  353. p.In()
  354. p.P(p.varGen.Next(), ` := r.Intn(100)`)
  355. p.P(`this.`, fieldname, `[i] = make([]byte,`, p.varGen.Current(), `)`)
  356. p.P(`for j := 0; j < `, p.varGen.Current(), `; j++ {`)
  357. p.In()
  358. p.P(`this.`, fieldname, `[i][j] = byte(r.Intn(256))`)
  359. p.Out()
  360. p.P(`}`)
  361. p.Out()
  362. p.P(`}`)
  363. } else {
  364. p.P(p.varGen.Next(), ` := r.Intn(100)`)
  365. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  366. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  367. p.In()
  368. p.P(`this.`, fieldname, `[i] = byte(r.Intn(256))`)
  369. p.Out()
  370. p.P(`}`)
  371. }
  372. } else if field.IsString() {
  373. typName := generator.GoTypeToName(goTyp)
  374. val := fmt.Sprintf("%s(randString%v(r))", typName, p.localName)
  375. if field.IsRepeated() {
  376. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  377. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  378. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  379. p.In()
  380. p.P(`this.`, fieldname, `[i] = `, val)
  381. p.Out()
  382. p.P(`}`)
  383. } else if !gogoproto.IsNullable(field) || proto3 {
  384. p.P(`this.`, fieldname, ` = `, val)
  385. } else {
  386. p.P(p.varGen.Next(), `:= `, val)
  387. p.P(`this.`, fieldname, ` = &`, p.varGen.Current())
  388. }
  389. } else {
  390. typName := generator.GoTypeToName(goTyp)
  391. if field.IsRepeated() {
  392. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  393. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  394. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  395. p.In()
  396. p.P(`this.`, fieldname, `[i] = `, value(typName, field.GetType()))
  397. if negative(field.GetType()) {
  398. p.P(`if r.Intn(2) == 0 {`)
  399. p.In()
  400. p.P(`this.`, fieldname, `[i] *= -1`)
  401. p.Out()
  402. p.P(`}`)
  403. }
  404. p.Out()
  405. p.P(`}`)
  406. } else if !gogoproto.IsNullable(field) || proto3 {
  407. p.P(`this.`, fieldname, ` = `, value(typName, field.GetType()))
  408. if negative(field.GetType()) {
  409. p.P(`if r.Intn(2) == 0 {`)
  410. p.In()
  411. p.P(`this.`, fieldname, ` *= -1`)
  412. p.Out()
  413. p.P(`}`)
  414. }
  415. } else {
  416. p.P(p.varGen.Next(), ` := `, value(typName, field.GetType()))
  417. if negative(field.GetType()) {
  418. p.P(`if r.Intn(2) == 0 {`)
  419. p.In()
  420. p.P(p.varGen.Current(), ` *= -1`)
  421. p.Out()
  422. p.P(`}`)
  423. }
  424. p.P(`this.`, fieldname, ` = &`, p.varGen.Current())
  425. }
  426. }
  427. }
  428. }
  429. func (p *plugin) hasLoop(pkg string, field *descriptor.FieldDescriptorProto, visited []*generator.Descriptor, excludes []*generator.Descriptor) *generator.Descriptor {
  430. if field.IsMessage() || p.IsGroup(field) || p.IsMap(field) {
  431. var fieldMessage *generator.Descriptor
  432. if p.IsMap(field) {
  433. m := p.GoMapType(nil, field)
  434. if !m.ValueField.IsMessage() {
  435. return nil
  436. }
  437. fieldMessage = p.ObjectNamed(m.ValueField.GetTypeName()).(*generator.Descriptor)
  438. } else {
  439. fieldMessage = p.ObjectNamed(field.GetTypeName()).(*generator.Descriptor)
  440. }
  441. fieldTypeName := generator.CamelCaseSlice(fieldMessage.TypeName())
  442. for _, message := range visited {
  443. messageTypeName := generator.CamelCaseSlice(message.TypeName())
  444. if fieldTypeName == messageTypeName {
  445. for _, e := range excludes {
  446. if fieldTypeName == generator.CamelCaseSlice(e.TypeName()) {
  447. return nil
  448. }
  449. }
  450. return fieldMessage
  451. }
  452. }
  453. for _, f := range fieldMessage.Field {
  454. if strings.HasPrefix(f.GetTypeName(), "."+pkg) {
  455. visited = append(visited, fieldMessage)
  456. loopTo := p.hasLoop(pkg, f, visited, excludes)
  457. if loopTo != nil {
  458. return loopTo
  459. }
  460. }
  461. }
  462. }
  463. return nil
  464. }
  465. func (p *plugin) loops(pkg string, field *descriptor.FieldDescriptorProto, message *generator.Descriptor) int {
  466. //fmt.Fprintf(os.Stderr, "loops %v %v\n", field.GetTypeName(), generator.CamelCaseSlice(message.TypeName()))
  467. excludes := []*generator.Descriptor{}
  468. loops := 0
  469. for {
  470. visited := []*generator.Descriptor{}
  471. loopTo := p.hasLoop(pkg, field, visited, excludes)
  472. if loopTo == nil {
  473. break
  474. }
  475. //fmt.Fprintf(os.Stderr, "loopTo %v\n", generator.CamelCaseSlice(loopTo.TypeName()))
  476. excludes = append(excludes, loopTo)
  477. loops++
  478. }
  479. return loops
  480. }
  481. func (p *plugin) Generate(file *generator.FileDescriptor) {
  482. p.atleastOne = false
  483. p.PluginImports = generator.NewPluginImports(p.Generator)
  484. p.varGen = NewVarGen()
  485. proto3 := gogoproto.IsProto3(file.FileDescriptorProto)
  486. p.typesPkg = p.NewImport("github.com/gogo/protobuf/types")
  487. p.localName = generator.FileName(file)
  488. protoPkg := p.NewImport("github.com/gogo/protobuf/proto")
  489. if !gogoproto.ImportsGoGoProto(file.FileDescriptorProto) {
  490. protoPkg = p.NewImport("github.com/golang/protobuf/proto")
  491. }
  492. for _, message := range file.Messages() {
  493. if !gogoproto.HasPopulate(file.FileDescriptorProto, message.DescriptorProto) {
  494. continue
  495. }
  496. if message.DescriptorProto.GetOptions().GetMapEntry() {
  497. continue
  498. }
  499. p.atleastOne = true
  500. ccTypeName := generator.CamelCaseSlice(message.TypeName())
  501. loopLevels := make([]int, len(message.Field))
  502. maxLoopLevel := 0
  503. for i, field := range message.Field {
  504. loopLevels[i] = p.loops(file.GetPackage(), field, message)
  505. if loopLevels[i] > maxLoopLevel {
  506. maxLoopLevel = loopLevels[i]
  507. }
  508. }
  509. ranTotal := 0
  510. for i := range loopLevels {
  511. ranTotal += int(math.Pow10(maxLoopLevel - loopLevels[i]))
  512. }
  513. p.P(`func NewPopulated`, ccTypeName, `(r randy`, p.localName, `, easy bool) *`, ccTypeName, ` {`)
  514. p.In()
  515. p.P(`this := &`, ccTypeName, `{}`)
  516. if gogoproto.IsUnion(message.File().FileDescriptorProto, message.DescriptorProto) && len(message.Field) > 0 {
  517. p.P(`fieldNum := r.Intn(`, fmt.Sprintf("%d", ranTotal), `)`)
  518. p.P(`switch fieldNum {`)
  519. k := 0
  520. for i, field := range message.Field {
  521. is := []string{}
  522. ran := int(math.Pow10(maxLoopLevel - loopLevels[i]))
  523. for j := 0; j < ran; j++ {
  524. is = append(is, fmt.Sprintf("%d", j+k))
  525. }
  526. k += ran
  527. p.P(`case `, strings.Join(is, ","), `:`)
  528. p.In()
  529. p.GenerateField(file, message, field)
  530. p.Out()
  531. }
  532. p.P(`}`)
  533. } else {
  534. var maxFieldNumber int32
  535. oneofs := make(map[string]struct{})
  536. for fieldIndex, field := range message.Field {
  537. if field.GetNumber() > maxFieldNumber {
  538. maxFieldNumber = field.GetNumber()
  539. }
  540. oneof := field.OneofIndex != nil
  541. if !oneof {
  542. if field.IsRequired() || (!gogoproto.IsNullable(field) && !field.IsRepeated()) || (proto3 && !field.IsMessage()) {
  543. p.GenerateField(file, message, field)
  544. } else {
  545. if loopLevels[fieldIndex] > 0 {
  546. p.P(`if r.Intn(5) == 0 {`)
  547. } else {
  548. p.P(`if r.Intn(5) != 0 {`)
  549. }
  550. p.In()
  551. p.GenerateField(file, message, field)
  552. p.Out()
  553. p.P(`}`)
  554. }
  555. } else {
  556. fieldname := p.GetFieldName(message, field)
  557. if _, ok := oneofs[fieldname]; ok {
  558. continue
  559. } else {
  560. oneofs[fieldname] = struct{}{}
  561. }
  562. fieldNumbers := []int32{}
  563. for _, f := range message.Field {
  564. fname := p.GetFieldName(message, f)
  565. if fname == fieldname {
  566. fieldNumbers = append(fieldNumbers, f.GetNumber())
  567. }
  568. }
  569. p.P(`oneofNumber_`, fieldname, ` := `, fmt.Sprintf("%#v", fieldNumbers), `[r.Intn(`, strconv.Itoa(len(fieldNumbers)), `)]`)
  570. p.P(`switch oneofNumber_`, fieldname, ` {`)
  571. for _, f := range message.Field {
  572. fname := p.GetFieldName(message, f)
  573. if fname != fieldname {
  574. continue
  575. }
  576. p.P(`case `, strconv.Itoa(int(f.GetNumber())), `:`)
  577. p.In()
  578. ccTypeName := p.OneOfTypeName(message, f)
  579. p.P(`this.`, fname, ` = NewPopulated`, ccTypeName, `(r, easy)`)
  580. p.Out()
  581. }
  582. p.P(`}`)
  583. }
  584. }
  585. if message.DescriptorProto.HasExtension() {
  586. p.P(`if !easy && r.Intn(10) != 0 {`)
  587. p.In()
  588. p.P(`l := r.Intn(5)`)
  589. p.P(`for i := 0; i < l; i++ {`)
  590. p.In()
  591. if len(message.DescriptorProto.GetExtensionRange()) > 1 {
  592. p.P(`eIndex := r.Intn(`, strconv.Itoa(len(message.DescriptorProto.GetExtensionRange())), `)`)
  593. p.P(`fieldNumber := 0`)
  594. p.P(`switch eIndex {`)
  595. for i, e := range message.DescriptorProto.GetExtensionRange() {
  596. p.P(`case `, strconv.Itoa(i), `:`)
  597. p.In()
  598. p.P(`fieldNumber = r.Intn(`, strconv.Itoa(int(e.GetEnd()-e.GetStart())), `) + `, strconv.Itoa(int(e.GetStart())))
  599. p.Out()
  600. if e.GetEnd() > maxFieldNumber {
  601. maxFieldNumber = e.GetEnd()
  602. }
  603. }
  604. p.P(`}`)
  605. } else {
  606. e := message.DescriptorProto.GetExtensionRange()[0]
  607. p.P(`fieldNumber := r.Intn(`, strconv.Itoa(int(e.GetEnd()-e.GetStart())), `) + `, strconv.Itoa(int(e.GetStart())))
  608. if e.GetEnd() > maxFieldNumber {
  609. maxFieldNumber = e.GetEnd()
  610. }
  611. }
  612. p.P(`wire := r.Intn(4)`)
  613. p.P(`if wire == 3 { wire = 5 }`)
  614. p.P(`dAtA := randField`, p.localName, `(nil, r, fieldNumber, wire)`)
  615. p.P(protoPkg.Use(), `.SetRawExtension(this, int32(fieldNumber), dAtA)`)
  616. p.Out()
  617. p.P(`}`)
  618. p.Out()
  619. p.P(`}`)
  620. }
  621. if maxFieldNumber < (1 << 10) {
  622. p.P(`if !easy && r.Intn(10) != 0 {`)
  623. p.In()
  624. if gogoproto.HasUnrecognized(file.FileDescriptorProto, message.DescriptorProto) {
  625. p.P(`this.XXX_unrecognized = randUnrecognized`, p.localName, `(r, `, strconv.Itoa(int(maxFieldNumber+1)), `)`)
  626. }
  627. p.Out()
  628. p.P(`}`)
  629. }
  630. }
  631. p.P(`return this`)
  632. p.Out()
  633. p.P(`}`)
  634. p.P(``)
  635. //Generate NewPopulated functions for oneof fields
  636. m := proto.Clone(message.DescriptorProto).(*descriptor.DescriptorProto)
  637. for _, f := range m.Field {
  638. oneof := f.OneofIndex != nil
  639. if !oneof {
  640. continue
  641. }
  642. ccTypeName := p.OneOfTypeName(message, f)
  643. p.P(`func NewPopulated`, ccTypeName, `(r randy`, p.localName, `, easy bool) *`, ccTypeName, ` {`)
  644. p.In()
  645. p.P(`this := &`, ccTypeName, `{}`)
  646. vanity.TurnOffNullableForNativeTypes(f)
  647. p.GenerateField(file, message, f)
  648. p.P(`return this`)
  649. p.Out()
  650. p.P(`}`)
  651. }
  652. }
  653. if !p.atleastOne {
  654. return
  655. }
  656. p.P(`type randy`, p.localName, ` interface {`)
  657. p.In()
  658. p.P(`Float32() float32`)
  659. p.P(`Float64() float64`)
  660. p.P(`Int63() int64`)
  661. p.P(`Int31() int32`)
  662. p.P(`Uint32() uint32`)
  663. p.P(`Intn(n int) int`)
  664. p.Out()
  665. p.P(`}`)
  666. p.P(`func randUTF8Rune`, p.localName, `(r randy`, p.localName, `) rune {`)
  667. p.In()
  668. p.P(`ru := r.Intn(62)`)
  669. p.P(`if ru < 10 {`)
  670. p.In()
  671. p.P(`return rune(ru+48)`)
  672. p.Out()
  673. p.P(`} else if ru < 36 {`)
  674. p.In()
  675. p.P(`return rune(ru+55)`)
  676. p.Out()
  677. p.P(`}`)
  678. p.P(`return rune(ru+61)`)
  679. p.Out()
  680. p.P(`}`)
  681. p.P(`func randString`, p.localName, `(r randy`, p.localName, `) string {`)
  682. p.In()
  683. p.P(p.varGen.Next(), ` := r.Intn(100)`)
  684. p.P(`tmps := make([]rune, `, p.varGen.Current(), `)`)
  685. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  686. p.In()
  687. p.P(`tmps[i] = randUTF8Rune`, p.localName, `(r)`)
  688. p.Out()
  689. p.P(`}`)
  690. p.P(`return string(tmps)`)
  691. p.Out()
  692. p.P(`}`)
  693. p.P(`func randUnrecognized`, p.localName, `(r randy`, p.localName, `, maxFieldNumber int) (dAtA []byte) {`)
  694. p.In()
  695. p.P(`l := r.Intn(5)`)
  696. p.P(`for i := 0; i < l; i++ {`)
  697. p.In()
  698. p.P(`wire := r.Intn(4)`)
  699. p.P(`if wire == 3 { wire = 5 }`)
  700. p.P(`fieldNumber := maxFieldNumber + r.Intn(100)`)
  701. p.P(`dAtA = randField`, p.localName, `(dAtA, r, fieldNumber, wire)`)
  702. p.Out()
  703. p.P(`}`)
  704. p.P(`return dAtA`)
  705. p.Out()
  706. p.P(`}`)
  707. p.P(`func randField`, p.localName, `(dAtA []byte, r randy`, p.localName, `, fieldNumber int, wire int) []byte {`)
  708. p.In()
  709. p.P(`key := uint32(fieldNumber)<<3 | uint32(wire)`)
  710. p.P(`switch wire {`)
  711. p.P(`case 0:`)
  712. p.In()
  713. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(key))`)
  714. p.P(p.varGen.Next(), ` := r.Int63()`)
  715. p.P(`if r.Intn(2) == 0 {`)
  716. p.In()
  717. p.P(p.varGen.Current(), ` *= -1`)
  718. p.Out()
  719. p.P(`}`)
  720. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(`, p.varGen.Current(), `))`)
  721. p.Out()
  722. p.P(`case 1:`)
  723. p.In()
  724. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(key))`)
  725. p.P(`dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))`)
  726. p.Out()
  727. p.P(`case 2:`)
  728. p.In()
  729. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(key))`)
  730. p.P(`ll := r.Intn(100)`)
  731. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(ll))`)
  732. p.P(`for j := 0; j < ll; j++ {`)
  733. p.In()
  734. p.P(`dAtA = append(dAtA, byte(r.Intn(256)))`)
  735. p.Out()
  736. p.P(`}`)
  737. p.Out()
  738. p.P(`default:`)
  739. p.In()
  740. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(key))`)
  741. p.P(`dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))`)
  742. p.Out()
  743. p.P(`}`)
  744. p.P(`return dAtA`)
  745. p.Out()
  746. p.P(`}`)
  747. p.P(`func encodeVarintPopulate`, p.localName, `(dAtA []byte, v uint64) []byte {`)
  748. p.In()
  749. p.P(`for v >= 1<<7 {`)
  750. p.In()
  751. p.P(`dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))`)
  752. p.P(`v >>= 7`)
  753. p.Out()
  754. p.P(`}`)
  755. p.P(`dAtA = append(dAtA, uint8(v))`)
  756. p.P(`return dAtA`)
  757. p.Out()
  758. p.P(`}`)
  759. }
  760. func init() {
  761. generator.RegisterPlugin(NewPlugin())
  762. }