Improvements for binapi-generator and support VPP 19.04 in statsclient
[govpp.git] / cmd / binapi-generator / parse.go
1 // Copyright (c) 2018 Cisco and/or its affiliates.
2 //
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:
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 package main
16
17 import (
18         "errors"
19         "fmt"
20         "sort"
21         "strings"
22
23         "github.com/bennyscetbun/jsongo"
24         "github.com/sirupsen/logrus"
25 )
26
27 // top level objects
28 const (
29         objTypes     = "types"
30         objMessages  = "messages"
31         objUnions    = "unions"
32         objEnums     = "enums"
33         objServices  = "services"
34         objAliases   = "aliases"
35         vlAPIVersion = "vl_api_version"
36         objOptions   = "options"
37 )
38
39 // various object fields
40 const (
41         crcField   = "crc"
42         msgIdField = "_vl_msg_id"
43
44         clientIndexField = "client_index"
45         contextField     = "context"
46
47         aliasLengthField = "length"
48         aliasTypeField   = "type"
49
50         replyField  = "reply"
51         streamField = "stream"
52         eventsField = "events"
53 )
54
55 // service name parts
56 const (
57         serviceEventPrefix   = "want_"
58         serviceDumpSuffix    = "_dump"
59         serviceDetailsSuffix = "_details"
60         serviceReplySuffix   = "_reply"
61         serviceNoReply       = "null"
62 )
63
64 // field meta info
65 const (
66         fieldMetaLimit = "limit"
67 )
68
69 // module options
70 const (
71         versionOption = "version"
72 )
73
74 // parsePackage parses provided JSON data into objects prepared for code generation
75 func parsePackage(ctx *context, jsonRoot *jsongo.JSONNode) (*Package, error) {
76         pkg := Package{
77                 Name:   ctx.packageName,
78                 RefMap: make(map[string]string),
79         }
80
81         // parse CRC for API version
82         if crc := jsonRoot.At(vlAPIVersion); crc.GetType() == jsongo.TypeValue {
83                 pkg.CRC = crc.Get().(string)
84         }
85
86         // parse version string
87         if opt := jsonRoot.Map(objOptions); opt.GetType() == jsongo.TypeMap {
88                 if ver := opt.Map(versionOption); ver.GetType() == jsongo.TypeValue {
89                         pkg.Version = ver.Get().(string)
90                 }
91         }
92
93         logf("parsing package %s (version: %s, CRC: %s)", pkg.Name, pkg.Version, pkg.CRC)
94         logf(" consists of:")
95         for _, key := range jsonRoot.GetKeys() {
96                 logf("  - %d %s", jsonRoot.At(key).Len(), key)
97         }
98
99         // parse enums
100         enums := jsonRoot.Map(objEnums)
101         pkg.Enums = make([]Enum, enums.Len())
102         for i := 0; i < enums.Len(); i++ {
103                 enumNode := enums.At(i)
104
105                 enum, err := parseEnum(ctx, enumNode)
106                 if err != nil {
107                         return nil, err
108                 }
109                 pkg.Enums[i] = *enum
110                 pkg.RefMap[toApiType(enum.Name)] = enum.Name
111         }
112         // sort enums
113         sort.SliceStable(pkg.Enums, func(i, j int) bool {
114                 return pkg.Enums[i].Name < pkg.Enums[j].Name
115         })
116
117         // parse aliases
118         aliases := jsonRoot.Map(objAliases)
119         if aliases.GetType() == jsongo.TypeMap {
120                 pkg.Aliases = make([]Alias, aliases.Len())
121                 for i, key := range aliases.GetKeys() {
122                         aliasNode := aliases.At(key)
123
124                         alias, err := parseAlias(ctx, key.(string), aliasNode)
125                         if err != nil {
126                                 return nil, err
127                         }
128                         pkg.Aliases[i] = *alias
129                         pkg.RefMap[toApiType(alias.Name)] = alias.Name
130                 }
131         }
132         // sort aliases to ensure consistent order
133         sort.Slice(pkg.Aliases, func(i, j int) bool {
134                 return pkg.Aliases[i].Name < pkg.Aliases[j].Name
135         })
136
137         // parse types
138         types := jsonRoot.Map(objTypes)
139         pkg.Types = make([]Type, types.Len())
140         for i := 0; i < types.Len(); i++ {
141                 typNode := types.At(i)
142
143                 typ, err := parseType(ctx, typNode)
144                 if err != nil {
145                         return nil, err
146                 }
147                 pkg.Types[i] = *typ
148                 pkg.RefMap[toApiType(typ.Name)] = typ.Name
149         }
150         // sort types
151         sort.SliceStable(pkg.Types, func(i, j int) bool {
152                 return pkg.Types[i].Name < pkg.Types[j].Name
153         })
154
155         // parse unions
156         unions := jsonRoot.Map(objUnions)
157         pkg.Unions = make([]Union, unions.Len())
158         for i := 0; i < unions.Len(); i++ {
159                 unionNode := unions.At(i)
160
161                 union, err := parseUnion(ctx, unionNode)
162                 if err != nil {
163                         return nil, err
164                 }
165                 pkg.Unions[i] = *union
166                 pkg.RefMap[toApiType(union.Name)] = union.Name
167         }
168         // sort unions
169         sort.SliceStable(pkg.Unions, func(i, j int) bool {
170                 return pkg.Unions[i].Name < pkg.Unions[j].Name
171         })
172
173         // parse messages
174         messages := jsonRoot.Map(objMessages)
175         pkg.Messages = make([]Message, messages.Len())
176         for i := 0; i < messages.Len(); i++ {
177                 msgNode := messages.At(i)
178
179                 msg, err := parseMessage(ctx, msgNode)
180                 if err != nil {
181                         return nil, err
182                 }
183                 pkg.Messages[i] = *msg
184         }
185         // sort messages
186         sort.SliceStable(pkg.Messages, func(i, j int) bool {
187                 return pkg.Messages[i].Name < pkg.Messages[j].Name
188         })
189
190         // parse services
191         services := jsonRoot.Map(objServices)
192         if services.GetType() == jsongo.TypeMap {
193                 pkg.Services = make([]Service, services.Len())
194                 for i, key := range services.GetKeys() {
195                         svcNode := services.At(key)
196
197                         svc, err := parseService(ctx, key.(string), svcNode)
198                         if err != nil {
199                                 return nil, err
200                         }
201                         pkg.Services[i] = *svc
202                 }
203         }
204         // sort services
205         sort.Slice(pkg.Services, func(i, j int) bool {
206                 // dumps first
207                 if pkg.Services[i].Stream != pkg.Services[j].Stream {
208                         return pkg.Services[i].Stream
209                 }
210                 return pkg.Services[i].RequestType < pkg.Services[j].RequestType
211         })
212
213         printPackage(&pkg)
214
215         return &pkg, nil
216 }
217
218 // parseEnum parses VPP binary API enum object from JSON node
219 func parseEnum(ctx *context, enumNode *jsongo.JSONNode) (*Enum, error) {
220         if enumNode.Len() == 0 || enumNode.At(0).GetType() != jsongo.TypeValue {
221                 return nil, errors.New("invalid JSON for enum specified")
222         }
223
224         enumName, ok := enumNode.At(0).Get().(string)
225         if !ok {
226                 return nil, fmt.Errorf("enum name is %T, not a string", enumNode.At(0).Get())
227         }
228         enumType, ok := enumNode.At(enumNode.Len() - 1).At("enumtype").Get().(string)
229         if !ok {
230                 return nil, fmt.Errorf("enum type invalid or missing")
231         }
232
233         enum := Enum{
234                 Name: enumName,
235                 Type: enumType,
236         }
237
238         // loop through enum entries, skip first (name) and last (enumtype)
239         for j := 1; j < enumNode.Len()-1; j++ {
240                 if enumNode.At(j).GetType() == jsongo.TypeArray {
241                         entry := enumNode.At(j)
242
243                         if entry.Len() < 2 || entry.At(0).GetType() != jsongo.TypeValue || entry.At(1).GetType() != jsongo.TypeValue {
244                                 return nil, errors.New("invalid JSON for enum entry specified")
245                         }
246
247                         entryName, ok := entry.At(0).Get().(string)
248                         if !ok {
249                                 return nil, fmt.Errorf("enum entry name is %T, not a string", entry.At(0).Get())
250                         }
251                         entryVal := entry.At(1).Get()
252
253                         enum.Entries = append(enum.Entries, EnumEntry{
254                                 Name:  entryName,
255                                 Value: entryVal,
256                         })
257                 }
258         }
259
260         return &enum, nil
261 }
262
263 // parseUnion parses VPP binary API union object from JSON node
264 func parseUnion(ctx *context, unionNode *jsongo.JSONNode) (*Union, error) {
265         if unionNode.Len() == 0 || unionNode.At(0).GetType() != jsongo.TypeValue {
266                 return nil, errors.New("invalid JSON for union specified")
267         }
268
269         unionName, ok := unionNode.At(0).Get().(string)
270         if !ok {
271                 return nil, fmt.Errorf("union name is %T, not a string", unionNode.At(0).Get())
272         }
273         var unionCRC string
274         if unionNode.At(unionNode.Len()-1).GetType() == jsongo.TypeMap {
275                 unionCRC = unionNode.At(unionNode.Len() - 1).At(crcField).Get().(string)
276         }
277
278         union := Union{
279                 Name: unionName,
280                 CRC:  unionCRC,
281         }
282
283         // loop through union fields, skip first (name)
284         for j := 1; j < unionNode.Len(); j++ {
285                 if unionNode.At(j).GetType() == jsongo.TypeArray {
286                         fieldNode := unionNode.At(j)
287
288                         field, err := parseField(ctx, fieldNode)
289                         if err != nil {
290                                 return nil, err
291                         }
292
293                         union.Fields = append(union.Fields, *field)
294                 }
295         }
296
297         return &union, nil
298 }
299
300 // parseType parses VPP binary API type object from JSON node
301 func parseType(ctx *context, typeNode *jsongo.JSONNode) (*Type, error) {
302         if typeNode.Len() == 0 || typeNode.At(0).GetType() != jsongo.TypeValue {
303                 return nil, errors.New("invalid JSON for type specified")
304         }
305
306         typeName, ok := typeNode.At(0).Get().(string)
307         if !ok {
308                 return nil, fmt.Errorf("type name is %T, not a string", typeNode.At(0).Get())
309         }
310         var typeCRC string
311         if lastField := typeNode.At(typeNode.Len() - 1); lastField.GetType() == jsongo.TypeMap {
312                 typeCRC = lastField.At(crcField).Get().(string)
313         }
314
315         typ := Type{
316                 Name: typeName,
317                 CRC:  typeCRC,
318         }
319
320         // loop through type fields, skip first (name)
321         for j := 1; j < typeNode.Len(); j++ {
322                 if typeNode.At(j).GetType() == jsongo.TypeArray {
323                         fieldNode := typeNode.At(j)
324
325                         field, err := parseField(ctx, fieldNode)
326                         if err != nil {
327                                 return nil, err
328                         }
329
330                         typ.Fields = append(typ.Fields, *field)
331                 }
332         }
333
334         return &typ, nil
335 }
336
337 // parseAlias parses VPP binary API alias object from JSON node
338 func parseAlias(ctx *context, aliasName string, aliasNode *jsongo.JSONNode) (*Alias, error) {
339         if aliasNode.Len() == 0 || aliasNode.At(aliasTypeField).GetType() != jsongo.TypeValue {
340                 return nil, errors.New("invalid JSON for alias specified")
341         }
342
343         alias := Alias{
344                 Name: aliasName,
345         }
346
347         if typeNode := aliasNode.At(aliasTypeField); typeNode.GetType() == jsongo.TypeValue {
348                 typ, ok := typeNode.Get().(string)
349                 if !ok {
350                         return nil, fmt.Errorf("alias type is %T, not a string", typeNode.Get())
351                 }
352                 if typ != "null" {
353                         alias.Type = typ
354                 }
355         }
356
357         if lengthNode := aliasNode.At(aliasLengthField); lengthNode.GetType() == jsongo.TypeValue {
358                 length, ok := lengthNode.Get().(float64)
359                 if !ok {
360                         return nil, fmt.Errorf("alias length is %T, not a float64", lengthNode.Get())
361                 }
362                 alias.Length = int(length)
363         }
364
365         return &alias, nil
366 }
367
368 // parseMessage parses VPP binary API message object from JSON node
369 func parseMessage(ctx *context, msgNode *jsongo.JSONNode) (*Message, error) {
370         if msgNode.Len() == 0 || msgNode.At(0).GetType() != jsongo.TypeValue {
371                 return nil, errors.New("invalid JSON for message specified")
372         }
373
374         msgName, ok := msgNode.At(0).Get().(string)
375         if !ok {
376                 return nil, fmt.Errorf("message name is %T, not a string", msgNode.At(0).Get())
377         }
378         msgCRC, ok := msgNode.At(msgNode.Len() - 1).At(crcField).Get().(string)
379         if !ok {
380
381                 return nil, fmt.Errorf("message crc invalid or missing")
382         }
383
384         msg := Message{
385                 Name: msgName,
386                 CRC:  msgCRC,
387         }
388
389         // loop through message fields, skip first (name) and last (crc)
390         for j := 1; j < msgNode.Len()-1; j++ {
391                 if msgNode.At(j).GetType() == jsongo.TypeArray {
392                         fieldNode := msgNode.At(j)
393
394                         field, err := parseField(ctx, fieldNode)
395                         if err != nil {
396                                 return nil, err
397                         }
398
399                         msg.Fields = append(msg.Fields, *field)
400                 }
401         }
402
403         return &msg, nil
404 }
405
406 // parseField parses VPP binary API object field from JSON node
407 func parseField(ctx *context, field *jsongo.JSONNode) (*Field, error) {
408         if field.Len() < 2 || field.At(0).GetType() != jsongo.TypeValue || field.At(1).GetType() != jsongo.TypeValue {
409                 return nil, errors.New("invalid JSON for field specified")
410         }
411
412         fieldType, ok := field.At(0).Get().(string)
413         if !ok {
414                 return nil, fmt.Errorf("field type is %T, not a string", field.At(0).Get())
415         }
416         fieldName, ok := field.At(1).Get().(string)
417         if !ok {
418                 return nil, fmt.Errorf("field name is %T, not a string", field.At(1).Get())
419         }
420
421         f := &Field{
422                 Name: fieldName,
423                 Type: fieldType,
424         }
425
426         if field.Len() >= 3 {
427                 if field.At(2).GetType() == jsongo.TypeValue {
428                         fieldLength, ok := field.At(2).Get().(float64)
429                         if !ok {
430                                 return nil, fmt.Errorf("field length is %T, not float64", field.At(2).Get())
431                         }
432                         f.Length = int(fieldLength)
433                 } else if field.At(2).GetType() == jsongo.TypeMap {
434                         fieldMeta := field.At(2)
435
436                         for _, key := range fieldMeta.GetKeys() {
437                                 metaNode := fieldMeta.At(key)
438
439                                 switch metaName := key.(string); metaName {
440                                 case fieldMetaLimit:
441                                         f.Meta.Limit = int(metaNode.Get().(float64))
442                                 default:
443                                         logrus.Warnf("unknown meta info (%s) for field (%s)", metaName, fieldName)
444                                 }
445                         }
446                 } else {
447                         return nil, errors.New("invalid JSON for field specified")
448                 }
449         }
450         if field.Len() >= 4 {
451                 fieldLengthFrom, ok := field.At(3).Get().(string)
452                 if !ok {
453                         return nil, fmt.Errorf("field length from is %T, not a string", field.At(3).Get())
454                 }
455                 f.SizeFrom = fieldLengthFrom
456         }
457
458         return f, nil
459 }
460
461 // parseService parses VPP binary API service object from JSON node
462 func parseService(ctx *context, svcName string, svcNode *jsongo.JSONNode) (*Service, error) {
463         if svcNode.Len() == 0 || svcNode.At(replyField).GetType() != jsongo.TypeValue {
464                 return nil, errors.New("invalid JSON for service specified")
465         }
466
467         svc := Service{
468                 Name:        svcName,
469                 RequestType: svcName,
470         }
471
472         if replyNode := svcNode.At(replyField); replyNode.GetType() == jsongo.TypeValue {
473                 reply, ok := replyNode.Get().(string)
474                 if !ok {
475                         return nil, fmt.Errorf("service reply is %T, not a string", replyNode.Get())
476                 }
477                 if reply != serviceNoReply {
478                         svc.ReplyType = reply
479                 }
480         }
481
482         // stream service (dumps)
483         if streamNode := svcNode.At(streamField); streamNode.GetType() == jsongo.TypeValue {
484                 var ok bool
485                 svc.Stream, ok = streamNode.Get().(bool)
486                 if !ok {
487                         return nil, fmt.Errorf("service stream is %T, not a string", streamNode.Get())
488                 }
489         }
490
491         // events service (event subscription)
492         if eventsNode := svcNode.At(eventsField); eventsNode.GetType() == jsongo.TypeArray {
493                 for j := 0; j < eventsNode.Len(); j++ {
494                         event := eventsNode.At(j).Get().(string)
495                         svc.Events = append(svc.Events, event)
496                 }
497         }
498
499         // validate service
500         if len(svc.Events) > 0 {
501                 // EVENT service
502                 if !strings.HasPrefix(svc.RequestType, serviceEventPrefix) {
503                         logrus.Debugf("unusual EVENTS service: %+v\n"+
504                                 "- events service %q does not have %q prefix in request.",
505                                 svc, svc.Name, serviceEventPrefix)
506                 }
507         } else if svc.Stream {
508                 // STREAM service
509                 if !strings.HasSuffix(svc.RequestType, serviceDumpSuffix) ||
510                         !strings.HasSuffix(svc.ReplyType, serviceDetailsSuffix) {
511                         logrus.Debugf("unusual STREAM service: %+v\n"+
512                                 "- stream service %q does not have %q suffix in request or reply does not have %q suffix.",
513                                 svc, svc.Name, serviceDumpSuffix, serviceDetailsSuffix)
514                 }
515         } else if svc.ReplyType != "" && svc.ReplyType != serviceNoReply {
516                 // REQUEST service
517                 // some messages might have `null` reply (for example: memclnt)
518                 if !strings.HasSuffix(svc.ReplyType, serviceReplySuffix) {
519                         logrus.Debugf("unusual REQUEST service: %+v\n"+
520                                 "- service %q does not have %q suffix in reply.",
521                                 svc, svc.Name, serviceReplySuffix)
522                 }
523         }
524
525         return &svc, nil
526 }