1 // Copyright (c) 2018 Cisco and/or its affiliates.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
23 "github.com/bennyscetbun/jsongo"
26 // parsePackage parses provided JSON data into objects prepared for code generation
27 func parsePackage(ctx *context, jsonRoot *jsongo.JSONNode) (*Package, error) {
28 logf(" %s contains: %d services, %d messages, %d types, %d enums, %d unions, %d aliases (version: %s)",
30 jsonRoot.Map("services").Len(),
31 jsonRoot.Map("messages").Len(),
32 jsonRoot.Map("types").Len(),
33 jsonRoot.Map("enums").Len(),
34 jsonRoot.Map("unions").Len(),
35 jsonRoot.Map("aliases").Len(),
36 jsonRoot.Map("vl_api_version").Get(),
40 APIVersion: jsonRoot.Map("vl_api_version").Get().(string),
41 RefMap: make(map[string]string),
45 enums := jsonRoot.Map("enums")
46 pkg.Enums = make([]Enum, enums.Len())
47 for i := 0; i < enums.Len(); i++ {
48 enumNode := enums.At(i)
50 enum, err := parseEnum(ctx, enumNode)
55 pkg.RefMap[toApiType(enum.Name)] = enum.Name
59 aliases := jsonRoot.Map("aliases")
60 if aliases.GetType() == jsongo.TypeMap {
61 pkg.Aliases = make([]Alias, aliases.Len())
62 for i, key := range aliases.GetKeys() {
63 aliasNode := aliases.At(key)
65 alias, err := parseAlias(ctx, key.(string), aliasNode)
69 pkg.Aliases[i] = *alias
70 pkg.RefMap[toApiType(alias.Name)] = alias.Name
73 // sort aliases to ensure consistent order
74 sort.Slice(pkg.Aliases, func(i, j int) bool {
75 return pkg.Aliases[i].Name < pkg.Aliases[j].Name
79 types := jsonRoot.Map("types")
80 pkg.Types = make([]Type, types.Len())
81 for i := 0; i < types.Len(); i++ {
82 typNode := types.At(i)
84 typ, err := parseType(ctx, typNode)
89 pkg.RefMap[toApiType(typ.Name)] = typ.Name
93 unions := jsonRoot.Map("unions")
94 pkg.Unions = make([]Union, unions.Len())
95 for i := 0; i < unions.Len(); i++ {
96 unionNode := unions.At(i)
98 union, err := parseUnion(ctx, unionNode)
102 pkg.Unions[i] = *union
103 pkg.RefMap[toApiType(union.Name)] = union.Name
107 messages := jsonRoot.Map("messages")
108 pkg.Messages = make([]Message, messages.Len())
109 for i := 0; i < messages.Len(); i++ {
110 msgNode := messages.At(i)
112 msg, err := parseMessage(ctx, msgNode)
116 pkg.Messages[i] = *msg
120 services := jsonRoot.Map("services")
121 if services.GetType() == jsongo.TypeMap {
122 pkg.Services = make([]Service, services.Len())
123 for i, key := range services.GetKeys() {
124 svcNode := services.At(key)
126 svc, err := parseService(ctx, key.(string), svcNode)
130 pkg.Services[i] = *svc
134 sort.Slice(pkg.Services, func(i, j int) bool {
136 if pkg.Services[i].Stream != pkg.Services[j].Stream {
137 return pkg.Services[i].Stream
139 return pkg.Services[i].RequestType < pkg.Services[j].RequestType
148 // printPackage prints all loaded objects for package
149 func printPackage(pkg *Package) {
150 if len(pkg.Enums) > 0 {
151 logf("loaded %d enums:", len(pkg.Enums))
152 for k, enum := range pkg.Enums {
153 logf(" - enum #%d\t%+v", k, enum)
156 if len(pkg.Unions) > 0 {
157 logf("loaded %d unions:", len(pkg.Unions))
158 for k, union := range pkg.Unions {
159 logf(" - union #%d\t%+v", k, union)
162 if len(pkg.Types) > 0 {
163 logf("loaded %d types:", len(pkg.Types))
164 for _, typ := range pkg.Types {
165 logf(" - type: %q (%d fields)", typ.Name, len(typ.Fields))
168 if len(pkg.Messages) > 0 {
169 logf("loaded %d messages:", len(pkg.Messages))
170 for _, msg := range pkg.Messages {
171 logf(" - message: %q (%d fields)", msg.Name, len(msg.Fields))
174 if len(pkg.Services) > 0 {
175 logf("loaded %d services:", len(pkg.Services))
176 for _, svc := range pkg.Services {
180 } else if len(svc.Events) > 0 {
181 info = fmt.Sprintf("(EVENTS: %v)", svc.Events)
183 logf(" - service: %q -> %q %s", svc.RequestType, svc.ReplyType, info)
188 // parseEnum parses VPP binary API enum object from JSON node
189 func parseEnum(ctx *context, enumNode *jsongo.JSONNode) (*Enum, error) {
190 if enumNode.Len() == 0 || enumNode.At(0).GetType() != jsongo.TypeValue {
191 return nil, errors.New("invalid JSON for enum specified")
194 enumName, ok := enumNode.At(0).Get().(string)
196 return nil, fmt.Errorf("enum name is %T, not a string", enumNode.At(0).Get())
198 enumType, ok := enumNode.At(enumNode.Len() - 1).At("enumtype").Get().(string)
200 return nil, fmt.Errorf("enum type invalid or missing")
208 // loop through enum entries, skip first (name) and last (enumtype)
209 for j := 1; j < enumNode.Len()-1; j++ {
210 if enumNode.At(j).GetType() == jsongo.TypeArray {
211 entry := enumNode.At(j)
213 if entry.Len() < 2 || entry.At(0).GetType() != jsongo.TypeValue || entry.At(1).GetType() != jsongo.TypeValue {
214 return nil, errors.New("invalid JSON for enum entry specified")
217 entryName, ok := entry.At(0).Get().(string)
219 return nil, fmt.Errorf("enum entry name is %T, not a string", entry.At(0).Get())
221 entryVal := entry.At(1).Get()
223 enum.Entries = append(enum.Entries, EnumEntry{
233 // parseUnion parses VPP binary API union object from JSON node
234 func parseUnion(ctx *context, unionNode *jsongo.JSONNode) (*Union, error) {
235 if unionNode.Len() == 0 || unionNode.At(0).GetType() != jsongo.TypeValue {
236 return nil, errors.New("invalid JSON for union specified")
239 unionName, ok := unionNode.At(0).Get().(string)
241 return nil, fmt.Errorf("union name is %T, not a string", unionNode.At(0).Get())
243 unionCRC, ok := unionNode.At(unionNode.Len() - 1).At("crc").Get().(string)
245 return nil, fmt.Errorf("union crc invalid or missing")
253 // loop through union fields, skip first (name) and last (crc)
254 for j := 1; j < unionNode.Len()-1; j++ {
255 if unionNode.At(j).GetType() == jsongo.TypeArray {
256 fieldNode := unionNode.At(j)
258 field, err := parseField(ctx, fieldNode)
263 union.Fields = append(union.Fields, *field)
270 // parseType parses VPP binary API type object from JSON node
271 func parseType(ctx *context, typeNode *jsongo.JSONNode) (*Type, error) {
272 if typeNode.Len() == 0 || typeNode.At(0).GetType() != jsongo.TypeValue {
273 return nil, errors.New("invalid JSON for type specified")
276 typeName, ok := typeNode.At(0).Get().(string)
278 return nil, fmt.Errorf("type name is %T, not a string", typeNode.At(0).Get())
280 typeCRC, ok := typeNode.At(typeNode.Len() - 1).At("crc").Get().(string)
282 return nil, fmt.Errorf("type crc invalid or missing")
290 // loop through type fields, skip first (name) and last (crc)
291 for j := 1; j < typeNode.Len()-1; j++ {
292 if typeNode.At(j).GetType() == jsongo.TypeArray {
293 fieldNode := typeNode.At(j)
295 field, err := parseField(ctx, fieldNode)
300 typ.Fields = append(typ.Fields, *field)
308 aliasesLength = "length"
312 // parseAlias parses VPP binary API alias object from JSON node
313 func parseAlias(ctx *context, aliasName string, aliasNode *jsongo.JSONNode) (*Alias, error) {
314 if aliasNode.Len() == 0 || aliasNode.At(aliasesType).GetType() != jsongo.TypeValue {
315 return nil, errors.New("invalid JSON for alias specified")
322 if typeNode := aliasNode.At(aliasesType); typeNode.GetType() == jsongo.TypeValue {
323 typ, ok := typeNode.Get().(string)
325 return nil, fmt.Errorf("alias type is %T, not a string", typeNode.Get())
332 if lengthNode := aliasNode.At(aliasesLength); lengthNode.GetType() == jsongo.TypeValue {
333 length, ok := lengthNode.Get().(float64)
335 return nil, fmt.Errorf("alias length is %T, not a float64", lengthNode.Get())
337 alias.Length = int(length)
343 // parseMessage parses VPP binary API message object from JSON node
344 func parseMessage(ctx *context, msgNode *jsongo.JSONNode) (*Message, error) {
345 if msgNode.Len() == 0 || msgNode.At(0).GetType() != jsongo.TypeValue {
346 return nil, errors.New("invalid JSON for message specified")
349 msgName, ok := msgNode.At(0).Get().(string)
351 return nil, fmt.Errorf("message name is %T, not a string", msgNode.At(0).Get())
353 msgCRC, ok := msgNode.At(msgNode.Len() - 1).At("crc").Get().(string)
356 return nil, fmt.Errorf("message crc invalid or missing")
364 // loop through message fields, skip first (name) and last (crc)
365 for j := 1; j < msgNode.Len()-1; j++ {
366 if msgNode.At(j).GetType() == jsongo.TypeArray {
367 fieldNode := msgNode.At(j)
369 field, err := parseField(ctx, fieldNode)
374 msg.Fields = append(msg.Fields, *field)
381 // parseField parses VPP binary API object field from JSON node
382 func parseField(ctx *context, field *jsongo.JSONNode) (*Field, error) {
383 if field.Len() < 2 || field.At(0).GetType() != jsongo.TypeValue || field.At(1).GetType() != jsongo.TypeValue {
384 return nil, errors.New("invalid JSON for field specified")
387 fieldType, ok := field.At(0).Get().(string)
389 return nil, fmt.Errorf("field type is %T, not a string", field.At(0).Get())
391 fieldName, ok := field.At(1).Get().(string)
393 return nil, fmt.Errorf("field name is %T, not a string", field.At(1).Get())
395 var fieldLength float64
396 if field.Len() >= 3 {
397 fieldLength, ok = field.At(2).Get().(float64)
399 return nil, fmt.Errorf("field length is %T, not float64", field.At(2).Get())
402 var fieldLengthFrom string
403 if field.Len() >= 4 {
404 fieldLengthFrom, ok = field.At(3).Get().(string)
406 return nil, fmt.Errorf("field length from is %T, not a string", field.At(3).Get())
413 Length: int(fieldLength),
414 SizeFrom: fieldLengthFrom,
418 // parseService parses VPP binary API service object from JSON node
419 func parseService(ctx *context, svcName string, svcNode *jsongo.JSONNode) (*Service, error) {
420 if svcNode.Len() == 0 || svcNode.At("reply").GetType() != jsongo.TypeValue {
421 return nil, errors.New("invalid JSON for service specified")
425 Name: ctx.moduleName + "." + svcName,
426 RequestType: svcName,
429 if replyNode := svcNode.At("reply"); replyNode.GetType() == jsongo.TypeValue {
430 reply, ok := replyNode.Get().(string)
432 return nil, fmt.Errorf("service reply is %T, not a string", replyNode.Get())
435 svc.ReplyType = reply
439 // stream service (dumps)
440 if streamNode := svcNode.At("stream"); streamNode.GetType() == jsongo.TypeValue {
442 svc.Stream, ok = streamNode.Get().(bool)
444 return nil, fmt.Errorf("service stream is %T, not a string", streamNode.Get())
448 // events service (event subscription)
449 if eventsNode := svcNode.At("events"); eventsNode.GetType() == jsongo.TypeArray {
450 for j := 0; j < eventsNode.Len(); j++ {
451 event := eventsNode.At(j).Get().(string)
452 svc.Events = append(svc.Events, event)
457 if svc.IsEventService() {
458 if !strings.HasPrefix(svc.RequestType, "want_") {
459 log.Warnf("Unusual EVENTS SERVICE: %+v\n"+
460 "- events service %q does not have 'want_' prefix in request.",
463 } else if svc.IsDumpService() {
464 if !strings.HasSuffix(svc.RequestType, "_dump") ||
465 !strings.HasSuffix(svc.ReplyType, "_details") {
466 log.Warnf("Unusual STREAM SERVICE: %+v\n"+
467 "- stream service %q does not have '_dump' suffix in request or reply does not have '_details' suffix.",
470 } else if svc.IsRequestService() {
471 if !strings.HasSuffix(svc.ReplyType, "_reply") {
472 log.Warnf("Unusual REQUEST SERVICE: %+v\n"+
473 "- service %q does not have '_reply' suffix in reply.",
481 // toApiType returns name that is used as type reference in VPP binary API
482 func toApiType(name string) string {
483 return fmt.Sprintf("vl_api_%s_t", name)
486 // convertToGoType translates the VPP binary API type into Go type
487 func convertToGoType(ctx *context, binapiType string) (typ string) {
488 if t, ok := binapiTypes[binapiType]; ok {
491 } else if r, ok := ctx.packageData.RefMap[binapiType]; ok {
492 // specific types (enums/types/unions)
493 typ = camelCaseName(r)
496 case "bool", "string":
500 log.Warnf("found unknown VPP binary API type %q, using byte", binapiType)
507 func getSizeOfType(typ *Type) (size int) {
508 for _, field := range typ.Fields {
509 size += getSizeOfBinapiTypeLength(field.Type, field.Length)
514 func getSizeOfBinapiTypeLength(typ string, length int) (size int) {
515 if n := getBinapiTypeSize(typ); n > 0 {
525 func getTypeByRef(ctx *context, ref string) *Type {
526 for _, typ := range ctx.packageData.Types {
527 if ref == toApiType(typ.Name) {
534 func getAliasByRef(ctx *context, ref string) *Alias {
535 for _, alias := range ctx.packageData.Aliases {
536 if ref == toApiType(alias.Name) {
543 func getUnionSize(ctx *context, union *Union) (maxSize int) {
544 for _, field := range union.Fields {
545 typ := getTypeByRef(ctx, field.Type)
547 if size := getSizeOfType(typ); size > maxSize {
552 alias := getAliasByRef(ctx, field.Type)
554 if size := getSizeOfBinapiTypeLength(alias.Type, alias.Length); size > maxSize {
559 logf("no type or alias found for union %s field type %q", union.Name, field.Type)