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