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