e165c4271de6a13151629400d561c8913d6b5fde
[govpp.git] / cmd / binapi-generator / generate.go
1 // Copyright (c) 2017 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         "bufio"
19         "bytes"
20         "fmt"
21         "io"
22         "path/filepath"
23         "strings"
24         "unicode"
25 )
26
27 const (
28         govppApiImportPath = "git.fd.io/govpp.git/api" // import path of the govpp API package
29         inputFileExt       = ".api.json"               // file extension of the VPP binary API files
30         outputFileExt      = ".ba.go"                  // file extension of the Go generated files
31 )
32
33 // context is a structure storing data for code generation
34 type context struct {
35         inputFile  string // input file with VPP API in JSON
36         outputFile string // output file with generated Go package
37
38         inputData []byte // contents of the input file
39
40         moduleName  string // name of the source VPP module
41         packageName string // name of the Go package being generated
42
43         packageData *Package // parsed package data
44 }
45
46 // getContext returns context details of the code generation task
47 func getContext(inputFile, outputDir string) (*context, error) {
48         if !strings.HasSuffix(inputFile, inputFileExt) {
49                 return nil, fmt.Errorf("invalid input file name: %q", inputFile)
50         }
51
52         ctx := &context{
53                 inputFile: inputFile,
54         }
55
56         // package name
57         inputFileName := filepath.Base(inputFile)
58         ctx.moduleName = inputFileName[:strings.Index(inputFileName, ".")]
59
60         // alter package names for modules that are reserved keywords in Go
61         switch ctx.moduleName {
62         case "interface":
63                 ctx.packageName = "interfaces"
64         case "map":
65                 ctx.packageName = "maps"
66         default:
67                 ctx.packageName = ctx.moduleName
68         }
69
70         // output file
71         packageDir := filepath.Join(outputDir, ctx.packageName)
72         outputFileName := ctx.packageName + outputFileExt
73         ctx.outputFile = filepath.Join(packageDir, outputFileName)
74
75         return ctx, nil
76 }
77
78 // generatePackage generates code for the parsed package data and writes it into w
79 func generatePackage(ctx *context, w *bufio.Writer) error {
80         logf("generating package %q", ctx.packageName)
81
82         // generate file header
83         generateHeader(ctx, w)
84         generateImports(ctx, w)
85
86         if *includeAPIVer {
87                 const APIVerConstName = "VlAPIVersion"
88                 fmt.Fprintf(w, "// %s represents version of the binary API module.\n", APIVerConstName)
89                 fmt.Fprintf(w, "const %s = %v\n", APIVerConstName, ctx.packageData.APIVersion)
90                 fmt.Fprintln(w)
91         }
92
93         // generate services
94         if len(ctx.packageData.Services) > 0 {
95                 generateServices(ctx, w, ctx.packageData.Services)
96         }
97
98         // TODO: generate implementation for Services interface
99
100         // generate enums
101         if len(ctx.packageData.Enums) > 0 {
102                 fmt.Fprintf(w, "/* Enums */\n\n")
103
104                 for _, enum := range ctx.packageData.Enums {
105                         generateEnum(ctx, w, &enum)
106                 }
107         }
108
109         // generate aliases
110         if len(ctx.packageData.Aliases) > 0 {
111                 fmt.Fprintf(w, "/* Aliases */\n\n")
112
113                 for _, alias := range ctx.packageData.Aliases {
114                         generateAlias(ctx, w, &alias)
115                 }
116         }
117
118         // generate types
119         if len(ctx.packageData.Types) > 0 {
120                 fmt.Fprintf(w, "/* Types */\n\n")
121
122                 for _, typ := range ctx.packageData.Types {
123                         generateType(ctx, w, &typ)
124                 }
125         }
126
127         // generate unions
128         if len(ctx.packageData.Unions) > 0 {
129                 fmt.Fprintf(w, "/* Unions */\n\n")
130
131                 for _, union := range ctx.packageData.Unions {
132                         generateUnion(ctx, w, &union)
133                 }
134         }
135
136         // generate messages
137         if len(ctx.packageData.Messages) > 0 {
138                 fmt.Fprintf(w, "/* Messages */\n\n")
139
140                 for _, msg := range ctx.packageData.Messages {
141                         generateMessage(ctx, w, &msg)
142                 }
143         }
144
145         // generate message registrations
146         fmt.Fprintln(w)
147         fmt.Fprintln(w, "func init() {")
148         for _, msg := range ctx.packageData.Messages {
149                 name := camelCaseName(msg.Name)
150                 fmt.Fprintf(w, "\tapi.RegisterMessage((*%s)(nil), \"%s\")\n", name, ctx.moduleName+"."+name)
151         }
152         fmt.Fprintln(w, "}")
153
154         // flush the data:
155         if err := w.Flush(); err != nil {
156                 return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
157         }
158
159         return nil
160 }
161
162 // generateHeader writes generated package header into w
163 func generateHeader(ctx *context, w io.Writer) {
164         fmt.Fprintln(w, "// Code generated by GoVPP binapi-generator. DO NOT EDIT.")
165         fmt.Fprintf(w, "//  source: %s\n", ctx.inputFile)
166         fmt.Fprintln(w)
167
168         fmt.Fprintln(w, "/*")
169         fmt.Fprintf(w, " Package %s is a generated from VPP binary API module '%s'.\n", ctx.packageName, ctx.moduleName)
170         fmt.Fprintln(w)
171         fmt.Fprintln(w, " It contains following objects:")
172         var printObjNum = func(obj string, num int) {
173                 if num > 0 {
174                         if num > 1 {
175                                 if strings.HasSuffix(obj, "s") {
176                                         obj += "es"
177                                 } else {
178                                         obj += "s"
179                                 }
180                         }
181                         fmt.Fprintf(w, "\t%3d %s\n", num, obj)
182                 }
183         }
184         printObjNum("message", len(ctx.packageData.Messages))
185         printObjNum("type", len(ctx.packageData.Types))
186         printObjNum("alias", len(ctx.packageData.Aliases))
187         printObjNum("enum", len(ctx.packageData.Enums))
188         printObjNum("union", len(ctx.packageData.Unions))
189         printObjNum("service", len(ctx.packageData.Services))
190         fmt.Fprintln(w)
191         fmt.Fprintln(w, "*/")
192         fmt.Fprintf(w, "package %s\n", ctx.packageName)
193         fmt.Fprintln(w)
194 }
195
196 // generateImports writes generated package imports into w
197 func generateImports(ctx *context, w io.Writer) {
198         fmt.Fprintf(w, "import \"%s\"\n", govppApiImportPath)
199         fmt.Fprintf(w, "import \"%s\"\n", "github.com/lunixbochs/struc")
200         fmt.Fprintf(w, "import \"%s\"\n", "bytes")
201         fmt.Fprintln(w)
202
203         fmt.Fprintf(w, "// Reference imports to suppress errors if they are not otherwise used.\n")
204         fmt.Fprintf(w, "var _ = api.RegisterMessage\n")
205         fmt.Fprintf(w, "var _ = struc.Pack\n")
206         fmt.Fprintf(w, "var _ = bytes.NewBuffer\n")
207         fmt.Fprintln(w)
208 }
209
210 // generateComment writes generated comment for the object into w
211 func generateComment(ctx *context, w io.Writer, goName string, vppName string, objKind string) {
212         if objKind == "service" {
213                 fmt.Fprintf(w, "// %s represents VPP binary API services:\n", goName)
214         } else {
215                 fmt.Fprintf(w, "// %s represents VPP binary API %s '%s':\n", goName, objKind, vppName)
216         }
217
218         var isNotSpace = func(r rune) bool {
219                 return !unicode.IsSpace(r)
220         }
221
222         // print out the source of the generated object
223         mapType := false
224         objFound := false
225         objTitle := fmt.Sprintf(`"%s",`, vppName)
226         switch objKind {
227         case "alias", "service":
228                 objTitle = fmt.Sprintf(`"%s": {`, vppName)
229                 mapType = true
230         }
231
232         inputBuff := bytes.NewBuffer(ctx.inputData)
233         inputLine := 0
234
235         var trimIndent string
236         var indent int
237         for {
238                 line, err := inputBuff.ReadString('\n')
239                 if err != nil {
240                         break
241                 }
242                 inputLine++
243
244                 noSpaceAt := strings.IndexFunc(line, isNotSpace)
245                 if !objFound {
246                         indent = strings.Index(line, objTitle)
247                         if indent == -1 {
248                                 continue
249                         }
250                         trimIndent = line[:indent]
251                         // If no other non-whitespace character then we are at the message header.
252                         if trimmed := strings.TrimSpace(line); trimmed == objTitle {
253                                 objFound = true
254                                 fmt.Fprintln(w, "//")
255                         }
256                 } else if noSpaceAt < indent {
257                         break // end of the definition in JSON for array types
258                 } else if objFound && mapType && noSpaceAt <= indent {
259                         fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
260                         break // end of the definition in JSON for map types (aliases, services)
261                 }
262                 fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
263         }
264
265         fmt.Fprintln(w, "//")
266 }
267
268 // generateServices writes generated code for the Services interface into w
269 func generateServices(ctx *context, w *bufio.Writer, services []Service) {
270         // generate services comment
271         generateComment(ctx, w, "Services", "services", "service")
272
273         // generate interface
274         fmt.Fprintf(w, "type %s interface {\n", "Services")
275         for _, svc := range ctx.packageData.Services {
276                 generateService(ctx, w, &svc)
277         }
278         fmt.Fprintln(w, "}")
279
280         fmt.Fprintln(w)
281 }
282
283 // generateService writes generated code for the service into w
284 func generateService(ctx *context, w io.Writer, svc *Service) {
285         reqTyp := camelCaseName(svc.RequestType)
286
287         // method name is same as parameter type name by default
288         method := svc.MethodName()
289         params := fmt.Sprintf("*%s", reqTyp)
290         returns := "error"
291         if replyType := camelCaseName(svc.ReplyType); replyType != "" {
292                 repTyp := fmt.Sprintf("*%s", replyType)
293                 if svc.Stream {
294                         repTyp = fmt.Sprintf("[]%s", repTyp)
295                 }
296                 returns = fmt.Sprintf("(%s, error)", repTyp)
297         }
298
299         fmt.Fprintf(w, "\t%s(%s) %s\n", method, params, returns)
300 }
301
302 // generateEnum writes generated code for the enum into w
303 func generateEnum(ctx *context, w io.Writer, enum *Enum) {
304         name := camelCaseName(enum.Name)
305         typ := binapiTypes[enum.Type]
306
307         logf(" writing enum %q (%s) with %d entries", enum.Name, name, len(enum.Entries))
308
309         // generate enum comment
310         generateComment(ctx, w, name, enum.Name, "enum")
311
312         // generate enum definition
313         fmt.Fprintf(w, "type %s %s\n", name, typ)
314         fmt.Fprintln(w)
315
316         fmt.Fprintln(w, "const (")
317
318         // generate enum entries
319         for _, entry := range enum.Entries {
320                 fmt.Fprintf(w, "\t%s %s = %v\n", entry.Name, name, entry.Value)
321         }
322
323         fmt.Fprintln(w, ")")
324
325         fmt.Fprintln(w)
326 }
327
328 // generateAlias writes generated code for the alias into w
329 func generateAlias(ctx *context, w io.Writer, alias *Alias) {
330         name := camelCaseName(alias.Name)
331
332         logf(" writing type %q (%s), length: %d", alias.Name, name, alias.Length)
333
334         // generate struct comment
335         generateComment(ctx, w, name, alias.Name, "alias")
336
337         // generate struct definition
338         fmt.Fprintf(w, "type %s ", name)
339
340         if alias.Length > 0 {
341                 fmt.Fprintf(w, "[%d]", alias.Length)
342         }
343
344         dataType := convertToGoType(ctx, alias.Type)
345         fmt.Fprintf(w, "%s\n", dataType)
346
347         fmt.Fprintln(w)
348 }
349
350 // generateUnion writes generated code for the union into w
351 func generateUnion(ctx *context, w io.Writer, union *Union) {
352         name := camelCaseName(union.Name)
353
354         logf(" writing union %q (%s) with %d fields", union.Name, name, len(union.Fields))
355
356         // generate struct comment
357         generateComment(ctx, w, name, union.Name, "union")
358
359         // generate struct definition
360         fmt.Fprintln(w, "type", name, "struct {")
361
362         // maximum size for union
363         maxSize := getUnionSize(ctx, union)
364
365         // generate data field
366         fieldName := "Union_data"
367         fmt.Fprintf(w, "\t%s [%d]byte\n", fieldName, maxSize)
368
369         // generate end of the struct
370         fmt.Fprintln(w, "}")
371
372         // generate name getter
373         generateTypeNameGetter(w, name, union.Name)
374
375         // generate CRC getter
376         generateCrcGetter(w, name, union.CRC)
377
378         // generate getters for fields
379         for _, field := range union.Fields {
380                 fieldName := camelCaseName(field.Name)
381                 fieldType := convertToGoType(ctx, field.Type)
382                 generateUnionGetterSetter(w, name, fieldName, fieldType)
383         }
384
385         // generate union methods
386         //generateUnionMethods(w, name)
387
388         fmt.Fprintln(w)
389 }
390
391 // generateUnionMethods generates methods that implement struc.Custom
392 // interface to allow having Union_data field unexported
393 // TODO: do more testing when unions are actually used in some messages
394 func generateUnionMethods(w io.Writer, structName string) {
395         // generate struc.Custom implementation for union
396         fmt.Fprintf(w, `
397 func (u *%[1]s) Pack(p []byte, opt *struc.Options) (int, error) {
398         var b = new(bytes.Buffer)
399         if err := struc.PackWithOptions(b, u.union_data, opt); err != nil {
400                 return 0, err
401         }
402         copy(p, b.Bytes())
403         return b.Len(), nil
404 }
405 func (u *%[1]s) Unpack(r io.Reader, length int, opt *struc.Options) error {
406         return struc.UnpackWithOptions(r, u.union_data[:], opt)
407 }
408 func (u *%[1]s) Size(opt *struc.Options) int {
409         return len(u.union_data)
410 }
411 func (u *%[1]s) String() string {
412         return string(u.union_data[:])
413 }
414 `, structName)
415 }
416
417 func generateUnionGetterSetter(w io.Writer, structName string, getterField, getterStruct string) {
418         fmt.Fprintf(w, `
419 func (u *%[1]s) Set%[2]s(a %[3]s) {
420         var b = new(bytes.Buffer)
421         if err := struc.Pack(b, &a); err != nil {
422                 return
423         }
424         copy(u.Union_data[:], b.Bytes())
425 }
426 func (u *%[1]s) Get%[2]s() (a %[3]s) {
427         var b = bytes.NewReader(u.Union_data[:])
428         struc.Unpack(b, &a)
429         return
430 }
431 `, structName, getterField, getterStruct)
432 }
433
434 // generateType writes generated code for the type into w
435 func generateType(ctx *context, w io.Writer, typ *Type) {
436         name := camelCaseName(typ.Name)
437
438         logf(" writing type %q (%s) with %d fields", typ.Name, name, len(typ.Fields))
439
440         // generate struct comment
441         generateComment(ctx, w, name, typ.Name, "type")
442
443         // generate struct definition
444         fmt.Fprintf(w, "type %s struct {\n", name)
445
446         // generate struct fields
447         for i, field := range typ.Fields {
448                 // skip internal fields
449                 switch strings.ToLower(field.Name) {
450                 case "crc", "_vl_msg_id":
451                         continue
452                 }
453
454                 generateField(ctx, w, typ.Fields, i)
455         }
456
457         // generate end of the struct
458         fmt.Fprintln(w, "}")
459
460         // generate name getter
461         generateTypeNameGetter(w, name, typ.Name)
462
463         // generate CRC getter
464         generateCrcGetter(w, name, typ.CRC)
465
466         fmt.Fprintln(w)
467 }
468
469 // generateMessage writes generated code for the message into w
470 func generateMessage(ctx *context, w io.Writer, msg *Message) {
471         name := camelCaseName(msg.Name)
472
473         logf(" writing message %q (%s) with %d fields", msg.Name, name, len(msg.Fields))
474
475         // generate struct comment
476         generateComment(ctx, w, name, msg.Name, "message")
477
478         // generate struct definition
479         fmt.Fprintf(w, "type %s struct {", name)
480
481         msgType := otherMessage
482         wasClientIndex := false
483
484         // generate struct fields
485         n := 0
486         for i, field := range msg.Fields {
487                 if i == 1 {
488                         if field.Name == "client_index" {
489                                 // "client_index" as the second member,
490                                 // this might be an event message or a request
491                                 msgType = eventMessage
492                                 wasClientIndex = true
493                         } else if field.Name == "context" {
494                                 // reply needs "context" as the second member
495                                 msgType = replyMessage
496                         }
497                 } else if i == 2 {
498                         if wasClientIndex && field.Name == "context" {
499                                 // request needs "client_index" as the second member
500                                 // and "context" as the third member
501                                 msgType = requestMessage
502                         }
503                 }
504
505                 // skip internal fields
506                 switch strings.ToLower(field.Name) {
507                 case "crc", "_vl_msg_id":
508                         continue
509                 case "client_index", "context":
510                         if n == 0 {
511                                 continue
512                         }
513                 }
514                 n++
515                 if n == 1 {
516                         fmt.Fprintln(w)
517                 }
518
519                 generateField(ctx, w, msg.Fields, i)
520         }
521
522         // generate end of the struct
523         fmt.Fprintln(w, "}")
524
525         // generate name getter
526         generateMessageNameGetter(w, name, msg.Name)
527
528         // generate CRC getter
529         generateCrcGetter(w, name, msg.CRC)
530
531         // generate message type getter method
532         generateMessageTypeGetter(w, name, msgType)
533 }
534
535 // generateField writes generated code for the field into w
536 func generateField(ctx *context, w io.Writer, fields []Field, i int) {
537         field := fields[i]
538
539         fieldName := strings.TrimPrefix(field.Name, "_")
540         fieldName = camelCaseName(fieldName)
541
542         // generate length field for strings
543         if field.Type == "string" {
544                 fmt.Fprintf(w, "\tXXX_%sLen uint32 `struc:\"sizeof=%s\"`\n", fieldName, fieldName)
545         }
546
547         dataType := convertToGoType(ctx, field.Type)
548
549         fieldType := dataType
550         if field.IsArray() {
551                 if dataType == "uint8" {
552                         dataType = "byte"
553                 }
554                 fieldType = "[]" + dataType
555         }
556         fmt.Fprintf(w, "\t%s %s", fieldName, fieldType)
557
558         if field.Length > 0 {
559                 // fixed size array
560                 fmt.Fprintf(w, "\t`struc:\"[%d]%s\"`", field.Length, dataType)
561         } else {
562                 for _, f := range fields {
563                         if f.SizeFrom == field.Name {
564                                 // variable sized array
565                                 sizeOfName := camelCaseName(f.Name)
566                                 fmt.Fprintf(w, "\t`struc:\"sizeof=%s\"`", sizeOfName)
567                         }
568                 }
569         }
570
571         fmt.Fprintln(w)
572 }
573
574 // generateMessageNameGetter generates getter for original VPP message name into the provider writer
575 func generateMessageNameGetter(w io.Writer, structName, msgName string) {
576         fmt.Fprintf(w, `func (*%s) GetMessageName() string {
577         return %q
578 }
579 `, structName, msgName)
580 }
581
582 // generateTypeNameGetter generates getter for original VPP type name into the provider writer
583 func generateTypeNameGetter(w io.Writer, structName, msgName string) {
584         fmt.Fprintf(w, `func (*%s) GetTypeName() string {
585         return %q
586 }
587 `, structName, msgName)
588 }
589
590 // generateCrcGetter generates getter for CRC checksum of the message definition into the provider writer
591 func generateCrcGetter(w io.Writer, structName, crc string) {
592         crc = strings.TrimPrefix(crc, "0x")
593         fmt.Fprintf(w, `func (*%s) GetCrcString() string {
594         return %q
595 }
596 `, structName, crc)
597 }
598
599 // generateMessageTypeGetter generates message factory for the generated message into the provider writer
600 func generateMessageTypeGetter(w io.Writer, structName string, msgType MessageType) {
601         fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
602         if msgType == requestMessage {
603                 fmt.Fprintln(w, "\treturn api.RequestMessage")
604         } else if msgType == replyMessage {
605                 fmt.Fprintln(w, "\treturn api.ReplyMessage")
606         } else if msgType == eventMessage {
607                 fmt.Fprintln(w, "\treturn api.EventMessage")
608         } else {
609                 fmt.Fprintln(w, "\treturn api.OtherMessage")
610         }
611         fmt.Fprintln(w, "}")
612 }