generator fix - add new message type
[govpp.git] / cmd / binapi-generator / generator.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         "encoding/json"
21         "errors"
22         "flag"
23         "fmt"
24         "io"
25         "io/ioutil"
26         "os"
27         "os/exec"
28         "path/filepath"
29         "strings"
30         "unicode"
31
32         "github.com/bennyscetbun/jsongo"
33 )
34
35 // MessageType represents the type of a VPP message.
36 type messageType int
37
38 const (
39         requestMessage messageType = iota // VPP request message
40         replyMessage                      // VPP reply message
41         eventMessage                      // VPP event message
42         otherMessage                      // other VPP message
43 )
44
45 const (
46         apiImportPath = "git.fd.io/govpp.git/api" // import path of the govpp API
47         inputFileExt  = ".json"                   // filename extension of files that should be processed as the input
48 )
49
50 // context is a structure storing details of a particular code generation task
51 type context struct {
52         inputFile   string            // file with input JSON data
53         inputBuff   *bytes.Buffer     // contents of the input file
54         inputLine   int               // currently processed line in the input file
55         outputFile  string            // file with output data
56         packageName string            // name of the Go package being generated
57         packageDir  string            // directory where the package source files are located
58         types       map[string]string // map of the VPP typedef names to generated Go typedef names
59 }
60
61 func main() {
62         inputFile := flag.String("input-file", "", "Input JSON file.")
63         inputDir := flag.String("input-dir", ".", "Input directory with JSON files.")
64         outputDir := flag.String("output-dir", ".", "Output directory where package folders will be generated.")
65         flag.Parse()
66
67         if *inputFile == "" && *inputDir == "" {
68                 fmt.Fprintln(os.Stderr, "ERROR: input-file or input-dir must be specified")
69                 os.Exit(1)
70         }
71
72         var err, tmpErr error
73         if *inputFile != "" {
74                 // process one input file
75                 err = generateFromFile(*inputFile, *outputDir)
76                 if err != nil {
77                         fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", *inputFile, err)
78                 }
79         } else {
80                 // process all files in specified directory
81                 files, err := getInputFiles(*inputDir)
82                 if err != nil {
83                         fmt.Fprintf(os.Stderr, "ERROR: code generation failed: %v\n", err)
84                 }
85                 for _, file := range files {
86                         tmpErr = generateFromFile(file, *outputDir)
87                         if tmpErr != nil {
88                                 fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", file, err)
89                                 err = tmpErr // remember that the error occurred
90                         }
91                 }
92         }
93         if err != nil {
94                 os.Exit(1)
95         }
96 }
97
98 // getInputFiles returns all input files located in specified directory
99 func getInputFiles(inputDir string) ([]string, error) {
100         files, err := ioutil.ReadDir(inputDir)
101         if err != nil {
102                 return nil, fmt.Errorf("reading directory %s failed: %v", inputDir, err)
103         }
104         res := make([]string, 0)
105         for _, f := range files {
106                 if strings.HasSuffix(f.Name(), inputFileExt) {
107                         res = append(res, inputDir+"/"+f.Name())
108                 }
109         }
110         return res, nil
111 }
112
113 // generateFromFile generates Go bindings from one input JSON file
114 func generateFromFile(inputFile, outputDir string) error {
115         ctx, err := getContext(inputFile, outputDir)
116         if err != nil {
117                 return err
118         }
119         // read the file
120         inputData, err := readFile(inputFile)
121         if err != nil {
122                 return err
123         }
124         ctx.inputBuff = bytes.NewBuffer(inputData)
125
126         // parse JSON
127         jsonRoot, err := parseJSON(inputData)
128         if err != nil {
129                 return err
130         }
131
132         // create output directory
133         err = os.MkdirAll(ctx.packageDir, 0777)
134         if err != nil {
135                 return fmt.Errorf("creating output directory %s failed: %v", ctx.packageDir, err)
136         }
137
138         // open output file
139         f, err := os.Create(ctx.outputFile)
140         defer f.Close()
141         if err != nil {
142                 return fmt.Errorf("creating output file %s failed: %v", ctx.outputFile, err)
143         }
144         w := bufio.NewWriter(f)
145
146         // generate Go package code
147         err = generatePackage(ctx, w, jsonRoot)
148         if err != nil {
149                 return err
150         }
151
152         // go format the output file (non-fatal if fails)
153         exec.Command("gofmt", "-w", ctx.outputFile).Run()
154
155         return nil
156 }
157
158 // getContext returns context details of the code generation task
159 func getContext(inputFile, outputDir string) (*context, error) {
160         if !strings.HasSuffix(inputFile, inputFileExt) {
161                 return nil, fmt.Errorf("invalid input file name %s", inputFile)
162         }
163
164         ctx := &context{inputFile: inputFile}
165         inputFileName := filepath.Base(inputFile)
166
167         ctx.packageName = inputFileName[0:strings.Index(inputFileName, ".")]
168         if ctx.packageName == "interface" {
169                 // 'interface' cannot be a package name, it is a go keyword
170                 ctx.packageName = "interfaces"
171         }
172
173         ctx.packageDir = outputDir + "/" + ctx.packageName + "/"
174         ctx.outputFile = ctx.packageDir + ctx.packageName + ".go"
175
176         return ctx, nil
177 }
178
179 // readFile reads content of a file into memory
180 func readFile(inputFile string) ([]byte, error) {
181
182         inputData, err := ioutil.ReadFile(inputFile)
183
184         if err != nil {
185                 return nil, fmt.Errorf("reading data from file failed: %v", err)
186         }
187
188         return inputData, nil
189 }
190
191 // parseJSON parses a JSON data into an in-memory tree
192 func parseJSON(inputData []byte) (*jsongo.JSONNode, error) {
193         root := jsongo.JSONNode{}
194
195         err := json.Unmarshal(inputData, &root)
196         if err != nil {
197                 return nil, fmt.Errorf("JSON unmarshall failed: %v", err)
198         }
199
200         return &root, nil
201
202 }
203
204 // generatePackage generates Go code of a package from provided JSON
205 func generatePackage(ctx *context, w *bufio.Writer, jsonRoot *jsongo.JSONNode) error {
206         // generate file header
207         generatePackageHeader(ctx, w, jsonRoot)
208
209         // generate data types
210         ctx.types = make(map[string]string)
211         types := jsonRoot.Map("types")
212         for i := 0; i < types.Len(); i++ {
213                 typ := types.At(i)
214                 err := generateMessage(ctx, w, typ, true)
215                 if err != nil {
216                         return err
217                 }
218         }
219
220         // generate messages
221         messages := jsonRoot.Map("messages")
222         for i := 0; i < messages.Len(); i++ {
223                 msg := messages.At(i)
224                 err := generateMessage(ctx, w, msg, false)
225                 if err != nil {
226                         return err
227                 }
228         }
229
230         // flush the data:
231         err := w.Flush()
232         if err != nil {
233                 return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
234         }
235
236         return nil
237 }
238
239 // generateMessage generates Go code of one VPP message encoded in JSON into provided writer
240 func generateMessage(ctx *context, w io.Writer, msg *jsongo.JSONNode, isType bool) error {
241         if msg.Len() == 0 || msg.At(0).GetType() != jsongo.TypeValue {
242                 return errors.New("invalid JSON for message specified")
243         }
244
245         msgName, ok := msg.At(0).Get().(string)
246         if !ok {
247                 return fmt.Errorf("invalid JSON for message specified, message name is %T, not a string", msg.At(0).Get())
248         }
249         structName := camelCaseName(strings.Title(msgName))
250
251         // generate struct fields into the slice & determine message type
252         fields := make([]string, 0)
253         msgType := otherMessage
254         wasClientIndex := false
255         for j := 0; j < msg.Len(); j++ {
256                 if jsongo.TypeArray == msg.At(j).GetType() {
257                         fld := msg.At(j)
258                         if !isType {
259                                 // determine whether ths is a request / reply / other message
260                                 fieldName, ok := fld.At(1).Get().(string)
261                                 if ok {
262                                         if j == 2 {
263                                                 if fieldName == "client_index" {
264                                                         // "client_index" as the second member, this might be an event message or a request
265                                                         msgType = eventMessage
266                                                         wasClientIndex = true
267                                                 } else if fieldName == "context" {
268                                                         // reply needs "context" as the second member
269                                                         msgType = replyMessage
270                                                 }
271                                         } else if j == 3 {
272                                                 if wasClientIndex && fieldName == "context" {
273                                                         // request needs "client_index" as the second member and "context" as the third member
274                                                         msgType = requestMessage
275                                                 }
276                                         }
277                                 }
278                         }
279                         err := processMessageField(ctx, &fields, fld, isType)
280                         if err != nil {
281                                 return err
282                         }
283                 }
284         }
285
286         // generate struct comment
287         generateMessageComment(ctx, w, structName, msgName, isType)
288
289         // generate struct header
290         fmt.Fprintln(w, "type", structName, "struct {")
291
292         // print out the fields
293         for _, field := range fields {
294                 fmt.Fprintln(w, field)
295         }
296
297         // generate end of the struct
298         fmt.Fprintln(w, "}")
299
300         // generate name getter
301         if isType {
302                 generateTypeNameGetter(w, structName, msgName)
303         } else {
304                 generateMessageNameGetter(w, structName, msgName)
305         }
306
307         // generate message type getter method
308         if !isType {
309                 generateMessageTypeGetter(w, structName, msgType)
310         }
311
312         // generate CRC getter
313         crcIf := msg.At(msg.Len() - 1).At("crc").Get()
314         if crc, ok := crcIf.(string); ok {
315                 generateCrcGetter(w, structName, crc)
316         }
317
318         // generate message factory
319         if !isType {
320                 generateMessageFactory(w, structName)
321         }
322
323         // if this is a type, save it in the map for later use
324         if isType {
325                 ctx.types[fmt.Sprintf("vl_api_%s_t", msgName)] = structName
326         }
327
328         return nil
329 }
330
331 // processMessageField process JSON describing one message field into Go code emitted into provided slice of message fields
332 func processMessageField(ctx *context, fields *[]string, fld *jsongo.JSONNode, isType bool) error {
333         if fld.Len() < 2 || fld.At(0).GetType() != jsongo.TypeValue || fld.At(1).GetType() != jsongo.TypeValue {
334                 return errors.New("invalid JSON for message field specified")
335         }
336         fieldVppType, ok := fld.At(0).Get().(string)
337         if !ok {
338                 return fmt.Errorf("invalid JSON for message specified, field type is %T, not a string", fld.At(0).Get())
339         }
340         fieldName, ok := fld.At(1).Get().(string)
341         if !ok {
342                 return fmt.Errorf("invalid JSON for message specified, field name is %T, not a string", fld.At(1).Get())
343         }
344
345         // skip internal fields
346         fieldNameLower := strings.ToLower(fieldName)
347         if fieldNameLower == "crc" || fieldNameLower == "_vl_msg_id" {
348                 return nil
349         }
350         if !isType && len(*fields) == 0 && (fieldNameLower == "client_index" || fieldNameLower == "context") {
351                 return nil
352         }
353
354         fieldName = strings.TrimPrefix(fieldName, "_")
355         fieldName = camelCaseName(strings.Title(fieldName))
356
357         fieldStr := ""
358         isArray := false
359         arraySize := 0
360
361         fieldStr += "\t" + fieldName + " "
362         if fld.Len() > 2 {
363                 isArray = true
364                 arraySize = int(fld.At(2).Get().(float64))
365                 fieldStr += "[]"
366         }
367
368         dataType := translateVppType(ctx, fieldVppType, isArray)
369         fieldStr += dataType
370
371         if isArray {
372                 if arraySize == 0 {
373                         // variable sized array
374                         if fld.Len() > 3 {
375                                 // array size is specified by another field
376                                 arraySizeField := string(fld.At(3).Get().(string))
377                                 arraySizeField = camelCaseName(strings.Title(arraySizeField))
378                                 // find & update the field that specifies the array size
379                                 for i, f := range *fields {
380                                         if strings.Contains(f, fmt.Sprintf("\t%s ", arraySizeField)) {
381                                                 (*fields)[i] += fmt.Sprintf("\t`struc:\"sizeof=%s\"`", fieldName)
382                                         }
383                                 }
384                         }
385                 } else {
386                         // fixed size array
387                         fieldStr += fmt.Sprintf("\t`struc:\"[%d]%s\"`", arraySize, dataType)
388                 }
389         }
390
391         *fields = append(*fields, fieldStr)
392         return nil
393 }
394
395 // generatePackageHeader generates package header into provider writer
396 func generatePackageHeader(ctx *context, w io.Writer, rootNode *jsongo.JSONNode) {
397         fmt.Fprintln(w, "// Code generated by govpp binapi-generator DO NOT EDIT.")
398         fmt.Fprintln(w, "// Package "+ctx.packageName+" represents the VPP binary API of the '"+ctx.packageName+"' VPP module.")
399         fmt.Fprintln(w, "// Generated from '"+ctx.inputFile+"'")
400
401         fmt.Fprintln(w, "package "+ctx.packageName)
402
403         fmt.Fprintln(w, "import \""+apiImportPath+"\"")
404
405         fmt.Fprintln(w)
406         fmt.Fprintln(w, "// VlApiVersion contains version of the API.")
407         vlAPIVersion := rootNode.Map("vl_api_version")
408         if vlAPIVersion != nil {
409                 fmt.Fprintln(w, "const VlAPIVersion = ", vlAPIVersion.Get())
410         }
411         fmt.Fprintln(w)
412 }
413
414 // generateMessageComment generates comment for a message into provider writer
415 func generateMessageComment(ctx *context, w io.Writer, structName string, msgName string, isType bool) {
416         fmt.Fprintln(w)
417         if isType {
418                 fmt.Fprintln(w, "// "+structName+" represents the VPP binary API data type '"+msgName+"'.")
419         } else {
420                 fmt.Fprintln(w, "// "+structName+" represents the VPP binary API message '"+msgName+"'.")
421         }
422
423         // print out the source of the generated message - the JSON
424         msgFound := false
425         for {
426                 lineBuff, err := ctx.inputBuff.ReadBytes('\n')
427                 if err != nil {
428                         break
429                 }
430                 ctx.inputLine++
431                 line := string(lineBuff)
432
433                 if !msgFound {
434                         if strings.Contains(line, msgName) {
435                                 fmt.Fprintf(w, "// Generated from '%s', line %d:\n", ctx.inputFile, ctx.inputLine)
436                                 fmt.Fprintln(w, "//")
437                                 fmt.Fprint(w, "//", line)
438                                 msgFound = true
439                         }
440                 } else {
441                         fmt.Fprint(w, "//", line)
442                         if len(strings.Trim(line, " ")) < 4 {
443                                 break // end of the message in JSON
444                         }
445                 }
446         }
447         fmt.Fprintln(w, "//")
448 }
449
450 // generateMessageNameGetter generates getter for original VPP message name into the provider writer
451 func generateMessageNameGetter(w io.Writer, structName string, msgName string) {
452         fmt.Fprintln(w, "func (*"+structName+") GetMessageName() string {")
453         fmt.Fprintln(w, "\treturn \""+msgName+"\"")
454         fmt.Fprintln(w, "}")
455 }
456
457 // generateTypeNameGetter generates getter for original VPP type name into the provider writer
458 func generateTypeNameGetter(w io.Writer, structName string, msgName string) {
459         fmt.Fprintln(w, "func (*"+structName+") GetTypeName() string {")
460         fmt.Fprintln(w, "\treturn \""+msgName+"\"")
461         fmt.Fprintln(w, "}")
462 }
463
464 // generateMessageTypeGetter generates message factory for the generated message into the provider writer
465 func generateMessageTypeGetter(w io.Writer, structName string, msgType messageType) {
466         fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
467         if msgType == requestMessage {
468                 fmt.Fprintln(w, "\treturn api.RequestMessage")
469         } else if msgType == replyMessage {
470                 fmt.Fprintln(w, "\treturn api.ReplyMessage")
471         } else if msgType == eventMessage {
472                 fmt.Fprintln(w, "\treturn api.EventMessage")
473         } else {
474                 fmt.Fprintln(w, "\treturn api.OtherMessage")
475         }
476         fmt.Fprintln(w, "}")
477 }
478
479 // generateCrcGetter generates getter for CRC checksum of the message definition into the provider writer
480 func generateCrcGetter(w io.Writer, structName string, crc string) {
481         crc = strings.TrimPrefix(crc, "0x")
482         fmt.Fprintln(w, "func (*"+structName+") GetCrcString() string {")
483         fmt.Fprintln(w, "\treturn \""+crc+"\"")
484         fmt.Fprintln(w, "}")
485 }
486
487 // generateMessageFactory generates message factory for the generated message into the provider writer
488 func generateMessageFactory(w io.Writer, structName string) {
489         fmt.Fprintln(w, "func New"+structName+"() api.Message {")
490         fmt.Fprintln(w, "\treturn &"+structName+"{}")
491         fmt.Fprintln(w, "}")
492 }
493
494 // translateVppType translates the VPP data type into Go data type
495 func translateVppType(ctx *context, vppType string, isArray bool) string {
496         // basic types
497         switch vppType {
498         case "u8":
499                 if isArray {
500                         return "byte"
501                 }
502                 return "uint8"
503         case "i8":
504                 return "int8"
505         case "u16":
506                 return "uint16"
507         case "i16":
508                 return "int16"
509         case "u32":
510                 return "uint32"
511         case "i32":
512                 return "int32"
513         case "u64":
514                 return "uint64"
515         case "i64":
516                 return "int64"
517         case "f64":
518                 return "float64"
519         }
520
521         // typedefs
522         typ, ok := ctx.types[vppType]
523         if ok {
524                 return typ
525         }
526
527         panic(fmt.Sprintf("Unknown VPP type %s", vppType))
528 }
529
530 // camelCaseName returns correct name identifier (camelCase).
531 func camelCaseName(name string) (should string) {
532         // Fast path for simple cases: "_" and all lowercase.
533         if name == "_" {
534                 return name
535         }
536         allLower := true
537         for _, r := range name {
538                 if !unicode.IsLower(r) {
539                         allLower = false
540                         break
541                 }
542         }
543         if allLower {
544                 return name
545         }
546
547         // Split camelCase at any lower->upper transition, and split on underscores.
548         // Check each word for common initialisms.
549         runes := []rune(name)
550         w, i := 0, 0 // index of start of word, scan
551         for i+1 <= len(runes) {
552                 eow := false // whether we hit the end of a word
553                 if i+1 == len(runes) {
554                         eow = true
555                 } else if runes[i+1] == '_' {
556                         // underscore; shift the remainder forward over any run of underscores
557                         eow = true
558                         n := 1
559                         for i+n+1 < len(runes) && runes[i+n+1] == '_' {
560                                 n++
561                         }
562
563                         // Leave at most one underscore if the underscore is between two digits
564                         if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) {
565                                 n--
566                         }
567
568                         copy(runes[i+1:], runes[i+n+1:])
569                         runes = runes[:len(runes)-n]
570                 } else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) {
571                         // lower->non-lower
572                         eow = true
573                 }
574                 i++
575                 if !eow {
576                         continue
577                 }
578
579                 // [w,i) is a word.
580                 word := string(runes[w:i])
581                 if u := strings.ToUpper(word); commonInitialisms[u] {
582                         // Keep consistent case, which is lowercase only at the start.
583                         if w == 0 && unicode.IsLower(runes[w]) {
584                                 u = strings.ToLower(u)
585                         }
586                         // All the common initialisms are ASCII,
587                         // so we can replace the bytes exactly.
588                         copy(runes[w:], []rune(u))
589                 } else if w > 0 && strings.ToLower(word) == word {
590                         // already all lowercase, and not the first word, so uppercase the first character.
591                         runes[w] = unicode.ToUpper(runes[w])
592                 }
593                 w = i
594         }
595         return string(runes)
596 }
597
598 // commonInitialisms is a set of common initialisms that need to stay in upper case.
599 var commonInitialisms = map[string]bool{
600         "ACL":   true,
601         "API":   true,
602         "ASCII": true,
603         "CPU":   true,
604         "CSS":   true,
605         "DNS":   true,
606         "EOF":   true,
607         "GUID":  true,
608         "HTML":  true,
609         "HTTP":  true,
610         "HTTPS": true,
611         "ID":    true,
612         "IP":    true,
613         "ICMP":  true,
614         "JSON":  true,
615         "LHS":   true,
616         "QPS":   true,
617         "RAM":   true,
618         "RHS":   true,
619         "RPC":   true,
620         "SLA":   true,
621         "SMTP":  true,
622         "SQL":   true,
623         "SSH":   true,
624         "TCP":   true,
625         "TLS":   true,
626         "TTL":   true,
627         "UDP":   true,
628         "UI":    true,
629         "UID":   true,
630         "UUID":  true,
631         "URI":   true,
632         "URL":   true,
633         "UTF8":  true,
634         "VM":    true,
635         "XML":   true,
636         "XMPP":  true,
637         "XSRF":  true,
638         "XSS":   true,
639 }