populate.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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) 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. switch funcName {
  165. case "time.NewPopulatedTime":
  166. funcName = p.typesPkg.Use() + ".NewPopulatedStdTime"
  167. case "time.NewPopulatedDuration":
  168. funcName = p.typesPkg.Use() + ".NewPopulatedStdDuration"
  169. }
  170. return funcName
  171. }
  172. func (p *plugin) getFuncCall(goTypName string) string {
  173. funcName := p.getFuncName(goTypName)
  174. funcCall := funcName + "(r, easy)"
  175. return funcCall
  176. }
  177. func (p *plugin) getCustomFuncCall(goTypName string) string {
  178. funcName := p.getFuncName(goTypName)
  179. funcCall := funcName + "(r)"
  180. return funcCall
  181. }
  182. func (p *plugin) getEnumVal(field *descriptor.FieldDescriptorProto, goTyp string) string {
  183. enum := p.ObjectNamed(field.GetTypeName()).(*generator.EnumDescriptor)
  184. l := len(enum.Value)
  185. values := make([]string, l)
  186. for i := range enum.Value {
  187. values[i] = strconv.Itoa(int(*enum.Value[i].Number))
  188. }
  189. arr := "[]int32{" + strings.Join(values, ",") + "}"
  190. val := strings.Join([]string{generator.GoTypeToName(goTyp), `(`, arr, `[r.Intn(`, fmt.Sprintf("%d", l), `)])`}, "")
  191. return val
  192. }
  193. func (p *plugin) GenerateField(file *generator.FileDescriptor, message *generator.Descriptor, field *descriptor.FieldDescriptorProto) {
  194. proto3 := gogoproto.IsProto3(file.FileDescriptorProto)
  195. goTyp, _ := p.GoType(message, field)
  196. fieldname := p.GetOneOfFieldName(message, field)
  197. goTypName := generator.GoTypeToName(goTyp)
  198. if p.IsMap(field) {
  199. m := p.GoMapType(nil, field)
  200. keygoTyp, _ := p.GoType(nil, m.KeyField)
  201. keygoTyp = strings.Replace(keygoTyp, "*", "", 1)
  202. keygoAliasTyp, _ := p.GoType(nil, m.KeyAliasField)
  203. keygoAliasTyp = strings.Replace(keygoAliasTyp, "*", "", 1)
  204. valuegoTyp, _ := p.GoType(nil, m.ValueField)
  205. valuegoAliasTyp, _ := p.GoType(nil, m.ValueAliasField)
  206. keytypName := generator.GoTypeToName(keygoTyp)
  207. keygoAliasTyp = generator.GoTypeToName(keygoAliasTyp)
  208. valuetypAliasName := generator.GoTypeToName(valuegoAliasTyp)
  209. nullable, valuegoTyp, valuegoAliasTyp := generator.GoMapValueTypes(field, m.ValueField, valuegoTyp, valuegoAliasTyp)
  210. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  211. p.P(`this.`, fieldname, ` = make(`, m.GoType, `)`)
  212. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  213. p.In()
  214. keyval := ""
  215. if m.KeyField.IsString() {
  216. keyval = fmt.Sprintf("randString%v(r)", p.localName)
  217. } else {
  218. keyval = value(keytypName, m.KeyField.GetType())
  219. }
  220. if keygoAliasTyp != keygoTyp {
  221. keyval = keygoAliasTyp + `(` + keyval + `)`
  222. }
  223. if m.ValueField.IsMessage() || p.IsGroup(field) ||
  224. (m.ValueField.IsBytes() && gogoproto.IsCustomType(field)) {
  225. s := `this.` + fieldname + `[` + keyval + `] = `
  226. if gogoproto.IsStdTime(field) || gogoproto.IsStdDuration(field) {
  227. valuegoTyp = valuegoAliasTyp
  228. }
  229. funcCall := p.getCustomFuncCall(goTypName)
  230. if !gogoproto.IsCustomType(field) {
  231. goTypName = generator.GoTypeToName(valuegoTyp)
  232. funcCall = p.getFuncCall(goTypName)
  233. }
  234. if !nullable {
  235. funcCall = `*` + funcCall
  236. }
  237. if valuegoTyp != valuegoAliasTyp {
  238. funcCall = `(` + valuegoAliasTyp + `)(` + funcCall + `)`
  239. }
  240. s += funcCall
  241. p.P(s)
  242. } else if m.ValueField.IsEnum() {
  243. s := `this.` + fieldname + `[` + keyval + `]` + ` = ` + p.getEnumVal(m.ValueField, valuegoTyp)
  244. p.P(s)
  245. } else if m.ValueField.IsBytes() {
  246. count := p.varGen.Next()
  247. p.P(count, ` := r.Intn(100)`)
  248. p.P(p.varGen.Next(), ` := `, keyval)
  249. p.P(`this.`, fieldname, `[`, p.varGen.Current(), `] = make(`, valuegoTyp, `, `, count, `)`)
  250. p.P(`for i := 0; i < `, count, `; i++ {`)
  251. p.In()
  252. p.P(`this.`, fieldname, `[`, p.varGen.Current(), `][i] = byte(r.Intn(256))`)
  253. p.Out()
  254. p.P(`}`)
  255. } else if m.ValueField.IsString() {
  256. s := `this.` + fieldname + `[` + keyval + `]` + ` = ` + fmt.Sprintf("randString%v(r)", p.localName)
  257. p.P(s)
  258. } else {
  259. p.P(p.varGen.Next(), ` := `, keyval)
  260. p.P(`this.`, fieldname, `[`, p.varGen.Current(), `] = `, value(valuetypAliasName, m.ValueField.GetType()))
  261. if negative(m.ValueField.GetType()) {
  262. p.P(`if r.Intn(2) == 0 {`)
  263. p.In()
  264. p.P(`this.`, fieldname, `[`, p.varGen.Current(), `] *= -1`)
  265. p.Out()
  266. p.P(`}`)
  267. }
  268. }
  269. p.Out()
  270. p.P(`}`)
  271. } else if gogoproto.IsCustomType(field) {
  272. funcCall := p.getCustomFuncCall(goTypName)
  273. if field.IsRepeated() {
  274. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  275. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  276. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  277. p.In()
  278. p.P(p.varGen.Next(), `:= `, funcCall)
  279. p.P(`this.`, fieldname, `[i] = *`, p.varGen.Current())
  280. p.Out()
  281. p.P(`}`)
  282. } else if gogoproto.IsNullable(field) {
  283. p.P(`this.`, fieldname, ` = `, funcCall)
  284. } else {
  285. p.P(p.varGen.Next(), `:= `, funcCall)
  286. p.P(`this.`, fieldname, ` = *`, p.varGen.Current())
  287. }
  288. } else if field.IsMessage() || p.IsGroup(field) {
  289. funcCall := p.getFuncCall(goTypName)
  290. if field.IsRepeated() {
  291. p.P(p.varGen.Next(), ` := r.Intn(5)`)
  292. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  293. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  294. p.In()
  295. if gogoproto.IsNullable(field) {
  296. p.P(`this.`, fieldname, `[i] = `, funcCall)
  297. } else {
  298. p.P(p.varGen.Next(), `:= `, funcCall)
  299. p.P(`this.`, fieldname, `[i] = *`, p.varGen.Current())
  300. }
  301. p.Out()
  302. p.P(`}`)
  303. } else {
  304. if gogoproto.IsNullable(field) {
  305. p.P(`this.`, fieldname, ` = `, funcCall)
  306. } else {
  307. p.P(p.varGen.Next(), `:= `, funcCall)
  308. p.P(`this.`, fieldname, ` = *`, p.varGen.Current())
  309. }
  310. }
  311. } else {
  312. if field.IsEnum() {
  313. val := p.getEnumVal(field, goTyp)
  314. if field.IsRepeated() {
  315. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  316. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  317. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  318. p.In()
  319. p.P(`this.`, fieldname, `[i] = `, val)
  320. p.Out()
  321. p.P(`}`)
  322. } else if !gogoproto.IsNullable(field) || proto3 {
  323. p.P(`this.`, fieldname, ` = `, val)
  324. } else {
  325. p.P(p.varGen.Next(), ` := `, val)
  326. p.P(`this.`, fieldname, ` = &`, p.varGen.Current())
  327. }
  328. } else if field.IsBytes() {
  329. if field.IsRepeated() {
  330. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  331. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  332. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  333. p.In()
  334. p.P(p.varGen.Next(), ` := r.Intn(100)`)
  335. p.P(`this.`, fieldname, `[i] = make([]byte,`, p.varGen.Current(), `)`)
  336. p.P(`for j := 0; j < `, p.varGen.Current(), `; j++ {`)
  337. p.In()
  338. p.P(`this.`, fieldname, `[i][j] = byte(r.Intn(256))`)
  339. p.Out()
  340. p.P(`}`)
  341. p.Out()
  342. p.P(`}`)
  343. } else {
  344. p.P(p.varGen.Next(), ` := r.Intn(100)`)
  345. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  346. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  347. p.In()
  348. p.P(`this.`, fieldname, `[i] = byte(r.Intn(256))`)
  349. p.Out()
  350. p.P(`}`)
  351. }
  352. } else if field.IsString() {
  353. typName := generator.GoTypeToName(goTyp)
  354. val := fmt.Sprintf("%s(randString%v(r))", typName, p.localName)
  355. if field.IsRepeated() {
  356. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  357. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  358. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  359. p.In()
  360. p.P(`this.`, fieldname, `[i] = `, val)
  361. p.Out()
  362. p.P(`}`)
  363. } else if !gogoproto.IsNullable(field) || proto3 {
  364. p.P(`this.`, fieldname, ` = `, val)
  365. } else {
  366. p.P(p.varGen.Next(), `:= `, val)
  367. p.P(`this.`, fieldname, ` = &`, p.varGen.Current())
  368. }
  369. } else {
  370. typName := generator.GoTypeToName(goTyp)
  371. if field.IsRepeated() {
  372. p.P(p.varGen.Next(), ` := r.Intn(10)`)
  373. p.P(`this.`, fieldname, ` = make(`, goTyp, `, `, p.varGen.Current(), `)`)
  374. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  375. p.In()
  376. p.P(`this.`, fieldname, `[i] = `, value(typName, field.GetType()))
  377. if negative(field.GetType()) {
  378. p.P(`if r.Intn(2) == 0 {`)
  379. p.In()
  380. p.P(`this.`, fieldname, `[i] *= -1`)
  381. p.Out()
  382. p.P(`}`)
  383. }
  384. p.Out()
  385. p.P(`}`)
  386. } else if !gogoproto.IsNullable(field) || proto3 {
  387. p.P(`this.`, fieldname, ` = `, value(typName, field.GetType()))
  388. if negative(field.GetType()) {
  389. p.P(`if r.Intn(2) == 0 {`)
  390. p.In()
  391. p.P(`this.`, fieldname, ` *= -1`)
  392. p.Out()
  393. p.P(`}`)
  394. }
  395. } else {
  396. p.P(p.varGen.Next(), ` := `, value(typName, field.GetType()))
  397. if negative(field.GetType()) {
  398. p.P(`if r.Intn(2) == 0 {`)
  399. p.In()
  400. p.P(p.varGen.Current(), ` *= -1`)
  401. p.Out()
  402. p.P(`}`)
  403. }
  404. p.P(`this.`, fieldname, ` = &`, p.varGen.Current())
  405. }
  406. }
  407. }
  408. }
  409. func (p *plugin) hasLoop(pkg string, field *descriptor.FieldDescriptorProto, visited []*generator.Descriptor, excludes []*generator.Descriptor) *generator.Descriptor {
  410. if field.IsMessage() || p.IsGroup(field) || p.IsMap(field) {
  411. var fieldMessage *generator.Descriptor
  412. if p.IsMap(field) {
  413. m := p.GoMapType(nil, field)
  414. if !m.ValueField.IsMessage() {
  415. return nil
  416. }
  417. fieldMessage = p.ObjectNamed(m.ValueField.GetTypeName()).(*generator.Descriptor)
  418. } else {
  419. fieldMessage = p.ObjectNamed(field.GetTypeName()).(*generator.Descriptor)
  420. }
  421. fieldTypeName := generator.CamelCaseSlice(fieldMessage.TypeName())
  422. for _, message := range visited {
  423. messageTypeName := generator.CamelCaseSlice(message.TypeName())
  424. if fieldTypeName == messageTypeName {
  425. for _, e := range excludes {
  426. if fieldTypeName == generator.CamelCaseSlice(e.TypeName()) {
  427. return nil
  428. }
  429. }
  430. return fieldMessage
  431. }
  432. }
  433. for _, f := range fieldMessage.Field {
  434. if strings.HasPrefix(f.GetTypeName(), "."+pkg) {
  435. visited = append(visited, fieldMessage)
  436. loopTo := p.hasLoop(pkg, f, visited, excludes)
  437. if loopTo != nil {
  438. return loopTo
  439. }
  440. }
  441. }
  442. }
  443. return nil
  444. }
  445. func (p *plugin) loops(pkg string, field *descriptor.FieldDescriptorProto, message *generator.Descriptor) int {
  446. //fmt.Fprintf(os.Stderr, "loops %v %v\n", field.GetTypeName(), generator.CamelCaseSlice(message.TypeName()))
  447. excludes := []*generator.Descriptor{}
  448. loops := 0
  449. for {
  450. visited := []*generator.Descriptor{}
  451. loopTo := p.hasLoop(pkg, field, visited, excludes)
  452. if loopTo == nil {
  453. break
  454. }
  455. //fmt.Fprintf(os.Stderr, "loopTo %v\n", generator.CamelCaseSlice(loopTo.TypeName()))
  456. excludes = append(excludes, loopTo)
  457. loops++
  458. }
  459. return loops
  460. }
  461. func (p *plugin) Generate(file *generator.FileDescriptor) {
  462. p.atleastOne = false
  463. p.PluginImports = generator.NewPluginImports(p.Generator)
  464. p.varGen = NewVarGen()
  465. proto3 := gogoproto.IsProto3(file.FileDescriptorProto)
  466. p.typesPkg = p.NewImport("github.com/gogo/protobuf/types")
  467. p.localName = generator.FileName(file)
  468. protoPkg := p.NewImport("github.com/gogo/protobuf/proto")
  469. if !gogoproto.ImportsGoGoProto(file.FileDescriptorProto) {
  470. protoPkg = p.NewImport("github.com/golang/protobuf/proto")
  471. }
  472. for _, message := range file.Messages() {
  473. if !gogoproto.HasPopulate(file.FileDescriptorProto, message.DescriptorProto) {
  474. continue
  475. }
  476. if message.DescriptorProto.GetOptions().GetMapEntry() {
  477. continue
  478. }
  479. p.atleastOne = true
  480. ccTypeName := generator.CamelCaseSlice(message.TypeName())
  481. loopLevels := make([]int, len(message.Field))
  482. maxLoopLevel := 0
  483. for i, field := range message.Field {
  484. loopLevels[i] = p.loops(file.GetPackage(), field, message)
  485. if loopLevels[i] > maxLoopLevel {
  486. maxLoopLevel = loopLevels[i]
  487. }
  488. }
  489. ranTotal := 0
  490. for i := range loopLevels {
  491. ranTotal += int(math.Pow10(maxLoopLevel - loopLevels[i]))
  492. }
  493. p.P(`func NewPopulated`, ccTypeName, `(r randy`, p.localName, `, easy bool) *`, ccTypeName, ` {`)
  494. p.In()
  495. p.P(`this := &`, ccTypeName, `{}`)
  496. if gogoproto.IsUnion(message.File().FileDescriptorProto, message.DescriptorProto) && len(message.Field) > 0 {
  497. p.P(`fieldNum := r.Intn(`, fmt.Sprintf("%d", ranTotal), `)`)
  498. p.P(`switch fieldNum {`)
  499. k := 0
  500. for i, field := range message.Field {
  501. is := []string{}
  502. ran := int(math.Pow10(maxLoopLevel - loopLevels[i]))
  503. for j := 0; j < ran; j++ {
  504. is = append(is, fmt.Sprintf("%d", j+k))
  505. }
  506. k += ran
  507. p.P(`case `, strings.Join(is, ","), `:`)
  508. p.In()
  509. p.GenerateField(file, message, field)
  510. p.Out()
  511. }
  512. p.P(`}`)
  513. } else {
  514. var maxFieldNumber int32
  515. oneofs := make(map[string]struct{})
  516. for fieldIndex, field := range message.Field {
  517. if field.GetNumber() > maxFieldNumber {
  518. maxFieldNumber = field.GetNumber()
  519. }
  520. oneof := field.OneofIndex != nil
  521. if !oneof {
  522. if field.IsRequired() || (!gogoproto.IsNullable(field) && !field.IsRepeated()) || (proto3 && !field.IsMessage()) {
  523. p.GenerateField(file, message, field)
  524. } else {
  525. if loopLevels[fieldIndex] > 0 {
  526. p.P(`if r.Intn(10) == 0 {`)
  527. } else {
  528. p.P(`if r.Intn(10) != 0 {`)
  529. }
  530. p.In()
  531. p.GenerateField(file, message, field)
  532. p.Out()
  533. p.P(`}`)
  534. }
  535. } else {
  536. fieldname := p.GetFieldName(message, field)
  537. if _, ok := oneofs[fieldname]; ok {
  538. continue
  539. } else {
  540. oneofs[fieldname] = struct{}{}
  541. }
  542. fieldNumbers := []int32{}
  543. for _, f := range message.Field {
  544. fname := p.GetFieldName(message, f)
  545. if fname == fieldname {
  546. fieldNumbers = append(fieldNumbers, f.GetNumber())
  547. }
  548. }
  549. p.P(`oneofNumber_`, fieldname, ` := `, fmt.Sprintf("%#v", fieldNumbers), `[r.Intn(`, strconv.Itoa(len(fieldNumbers)), `)]`)
  550. p.P(`switch oneofNumber_`, fieldname, ` {`)
  551. for _, f := range message.Field {
  552. fname := p.GetFieldName(message, f)
  553. if fname != fieldname {
  554. continue
  555. }
  556. p.P(`case `, strconv.Itoa(int(f.GetNumber())), `:`)
  557. p.In()
  558. ccTypeName := p.OneOfTypeName(message, f)
  559. p.P(`this.`, fname, ` = NewPopulated`, ccTypeName, `(r, easy)`)
  560. p.Out()
  561. }
  562. p.P(`}`)
  563. }
  564. }
  565. if message.DescriptorProto.HasExtension() {
  566. p.P(`if !easy && r.Intn(10) != 0 {`)
  567. p.In()
  568. p.P(`l := r.Intn(5)`)
  569. p.P(`for i := 0; i < l; i++ {`)
  570. p.In()
  571. if len(message.DescriptorProto.GetExtensionRange()) > 1 {
  572. p.P(`eIndex := r.Intn(`, strconv.Itoa(len(message.DescriptorProto.GetExtensionRange())), `)`)
  573. p.P(`fieldNumber := 0`)
  574. p.P(`switch eIndex {`)
  575. for i, e := range message.DescriptorProto.GetExtensionRange() {
  576. p.P(`case `, strconv.Itoa(i), `:`)
  577. p.In()
  578. p.P(`fieldNumber = r.Intn(`, strconv.Itoa(int(e.GetEnd()-e.GetStart())), `) + `, strconv.Itoa(int(e.GetStart())))
  579. p.Out()
  580. if e.GetEnd() > maxFieldNumber {
  581. maxFieldNumber = e.GetEnd()
  582. }
  583. }
  584. p.P(`}`)
  585. } else {
  586. e := message.DescriptorProto.GetExtensionRange()[0]
  587. p.P(`fieldNumber := r.Intn(`, strconv.Itoa(int(e.GetEnd()-e.GetStart())), `) + `, strconv.Itoa(int(e.GetStart())))
  588. if e.GetEnd() > maxFieldNumber {
  589. maxFieldNumber = e.GetEnd()
  590. }
  591. }
  592. p.P(`wire := r.Intn(4)`)
  593. p.P(`if wire == 3 { wire = 5 }`)
  594. p.P(`dAtA := randField`, p.localName, `(nil, r, fieldNumber, wire)`)
  595. p.P(protoPkg.Use(), `.SetRawExtension(this, int32(fieldNumber), dAtA)`)
  596. p.Out()
  597. p.P(`}`)
  598. p.Out()
  599. p.P(`}`)
  600. }
  601. if maxFieldNumber < (1 << 10) {
  602. p.P(`if !easy && r.Intn(10) != 0 {`)
  603. p.In()
  604. if gogoproto.HasUnrecognized(file.FileDescriptorProto, message.DescriptorProto) {
  605. p.P(`this.XXX_unrecognized = randUnrecognized`, p.localName, `(r, `, strconv.Itoa(int(maxFieldNumber+1)), `)`)
  606. }
  607. p.Out()
  608. p.P(`}`)
  609. }
  610. }
  611. p.P(`return this`)
  612. p.Out()
  613. p.P(`}`)
  614. p.P(``)
  615. //Generate NewPopulated functions for oneof fields
  616. m := proto.Clone(message.DescriptorProto).(*descriptor.DescriptorProto)
  617. for _, f := range m.Field {
  618. oneof := f.OneofIndex != nil
  619. if !oneof {
  620. continue
  621. }
  622. ccTypeName := p.OneOfTypeName(message, f)
  623. p.P(`func NewPopulated`, ccTypeName, `(r randy`, p.localName, `, easy bool) *`, ccTypeName, ` {`)
  624. p.In()
  625. p.P(`this := &`, ccTypeName, `{}`)
  626. vanity.TurnOffNullableForNativeTypes(f)
  627. p.GenerateField(file, message, f)
  628. p.P(`return this`)
  629. p.Out()
  630. p.P(`}`)
  631. }
  632. }
  633. if !p.atleastOne {
  634. return
  635. }
  636. p.P(`type randy`, p.localName, ` interface {`)
  637. p.In()
  638. p.P(`Float32() float32`)
  639. p.P(`Float64() float64`)
  640. p.P(`Int63() int64`)
  641. p.P(`Int31() int32`)
  642. p.P(`Uint32() uint32`)
  643. p.P(`Intn(n int) int`)
  644. p.Out()
  645. p.P(`}`)
  646. p.P(`func randUTF8Rune`, p.localName, `(r randy`, p.localName, `) rune {`)
  647. p.In()
  648. p.P(`ru := r.Intn(62)`)
  649. p.P(`if ru < 10 {`)
  650. p.In()
  651. p.P(`return rune(ru+48)`)
  652. p.Out()
  653. p.P(`} else if ru < 36 {`)
  654. p.In()
  655. p.P(`return rune(ru+55)`)
  656. p.Out()
  657. p.P(`}`)
  658. p.P(`return rune(ru+61)`)
  659. p.Out()
  660. p.P(`}`)
  661. p.P(`func randString`, p.localName, `(r randy`, p.localName, `) string {`)
  662. p.In()
  663. p.P(p.varGen.Next(), ` := r.Intn(100)`)
  664. p.P(`tmps := make([]rune, `, p.varGen.Current(), `)`)
  665. p.P(`for i := 0; i < `, p.varGen.Current(), `; i++ {`)
  666. p.In()
  667. p.P(`tmps[i] = randUTF8Rune`, p.localName, `(r)`)
  668. p.Out()
  669. p.P(`}`)
  670. p.P(`return string(tmps)`)
  671. p.Out()
  672. p.P(`}`)
  673. p.P(`func randUnrecognized`, p.localName, `(r randy`, p.localName, `, maxFieldNumber int) (dAtA []byte) {`)
  674. p.In()
  675. p.P(`l := r.Intn(5)`)
  676. p.P(`for i := 0; i < l; i++ {`)
  677. p.In()
  678. p.P(`wire := r.Intn(4)`)
  679. p.P(`if wire == 3 { wire = 5 }`)
  680. p.P(`fieldNumber := maxFieldNumber + r.Intn(100)`)
  681. p.P(`dAtA = randField`, p.localName, `(dAtA, r, fieldNumber, wire)`)
  682. p.Out()
  683. p.P(`}`)
  684. p.P(`return dAtA`)
  685. p.Out()
  686. p.P(`}`)
  687. p.P(`func randField`, p.localName, `(dAtA []byte, r randy`, p.localName, `, fieldNumber int, wire int) []byte {`)
  688. p.In()
  689. p.P(`key := uint32(fieldNumber)<<3 | uint32(wire)`)
  690. p.P(`switch wire {`)
  691. p.P(`case 0:`)
  692. p.In()
  693. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(key))`)
  694. p.P(p.varGen.Next(), ` := r.Int63()`)
  695. p.P(`if r.Intn(2) == 0 {`)
  696. p.In()
  697. p.P(p.varGen.Current(), ` *= -1`)
  698. p.Out()
  699. p.P(`}`)
  700. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(`, p.varGen.Current(), `))`)
  701. p.Out()
  702. p.P(`case 1:`)
  703. p.In()
  704. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(key))`)
  705. 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)))`)
  706. p.Out()
  707. p.P(`case 2:`)
  708. p.In()
  709. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(key))`)
  710. p.P(`ll := r.Intn(100)`)
  711. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(ll))`)
  712. p.P(`for j := 0; j < ll; j++ {`)
  713. p.In()
  714. p.P(`dAtA = append(dAtA, byte(r.Intn(256)))`)
  715. p.Out()
  716. p.P(`}`)
  717. p.Out()
  718. p.P(`default:`)
  719. p.In()
  720. p.P(`dAtA = encodeVarintPopulate`, p.localName, `(dAtA, uint64(key))`)
  721. p.P(`dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))`)
  722. p.Out()
  723. p.P(`}`)
  724. p.P(`return dAtA`)
  725. p.Out()
  726. p.P(`}`)
  727. p.P(`func encodeVarintPopulate`, p.localName, `(dAtA []byte, v uint64) []byte {`)
  728. p.In()
  729. p.P(`for v >= 1<<7 {`)
  730. p.In()
  731. p.P(`dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))`)
  732. p.P(`v >>= 7`)
  733. p.Out()
  734. p.P(`}`)
  735. p.P(`dAtA = append(dAtA, uint8(v))`)
  736. p.P(`return dAtA`)
  737. p.Out()
  738. p.P(`}`)
  739. }
  740. func init() {
  741. generator.RegisterPlugin(NewPlugin())
  742. }