1 // Copyright (c) 2017 Cisco and/or its affiliates.
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:
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
32 "github.com/bennyscetbun/jsongo"
35 // MessageType represents the type of a VPP message.
39 requestMessage messageType = iota // VPP request message
40 replyMessage // VPP reply message
41 eventMessage // VPP event message
42 otherMessage // other VPP message
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
50 // context is a structure storing details of a particular code generation task
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
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.")
67 if *inputFile == "" && *inputDir == "" {
68 fmt.Fprintln(os.Stderr, "ERROR: input-file or input-dir must be specified")
74 // process one input file
75 err = generateFromFile(*inputFile, *outputDir)
77 fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", *inputFile, err)
80 // process all files in specified directory
81 files, err := getInputFiles(*inputDir)
83 fmt.Fprintf(os.Stderr, "ERROR: code generation failed: %v\n", err)
85 for _, file := range files {
86 tmpErr = generateFromFile(file, *outputDir)
88 fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", file, err)
89 err = tmpErr // remember that the error occurred
98 // getInputFiles returns all input files located in specified directory
99 func getInputFiles(inputDir string) ([]string, error) {
100 files, err := ioutil.ReadDir(inputDir)
102 return nil, fmt.Errorf("reading directory %s failed: %v", inputDir, err)
104 res := make([]string, 0)
105 for _, f := range files {
106 if strings.HasSuffix(f.Name(), inputFileExt) {
107 res = append(res, inputDir+"/"+f.Name())
113 // generateFromFile generates Go bindings from one input JSON file
114 func generateFromFile(inputFile, outputDir string) error {
115 ctx, err := getContext(inputFile, outputDir)
120 inputData, err := readFile(inputFile)
124 ctx.inputBuff = bytes.NewBuffer(inputData)
127 jsonRoot, err := parseJSON(inputData)
132 // create output directory
133 err = os.MkdirAll(ctx.packageDir, 0777)
135 return fmt.Errorf("creating output directory %s failed: %v", ctx.packageDir, err)
139 f, err := os.Create(ctx.outputFile)
142 return fmt.Errorf("creating output file %s failed: %v", ctx.outputFile, err)
144 w := bufio.NewWriter(f)
146 // generate Go package code
147 err = generatePackage(ctx, w, jsonRoot)
152 // go format the output file (non-fatal if fails)
153 exec.Command("gofmt", "-w", ctx.outputFile).Run()
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)
164 ctx := &context{inputFile: inputFile}
165 inputFileName := filepath.Base(inputFile)
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"
173 ctx.packageDir = outputDir + "/" + ctx.packageName + "/"
174 ctx.outputFile = ctx.packageDir + ctx.packageName + ".go"
179 // readFile reads content of a file into memory
180 func readFile(inputFile string) ([]byte, error) {
182 inputData, err := ioutil.ReadFile(inputFile)
185 return nil, fmt.Errorf("reading data from file failed: %v", err)
188 return inputData, nil
191 // parseJSON parses a JSON data into an in-memory tree
192 func parseJSON(inputData []byte) (*jsongo.JSONNode, error) {
193 root := jsongo.JSONNode{}
195 err := json.Unmarshal(inputData, &root)
197 return nil, fmt.Errorf("JSON unmarshall failed: %v", err)
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)
209 // generate data types
210 ctx.types = make(map[string]string)
211 types := jsonRoot.Map("types")
212 for i := 0; i < types.Len(); i++ {
214 err := generateMessage(ctx, w, typ, true)
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)
233 return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
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")
245 msgName, ok := msg.At(0).Get().(string)
247 return fmt.Errorf("invalid JSON for message specified, message name is %T, not a string", msg.At(0).Get())
249 structName := camelCaseName(strings.Title(msgName))
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() {
259 // determine whether ths is a request / reply / other message
260 fieldName, ok := fld.At(1).Get().(string)
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
272 if wasClientIndex && fieldName == "context" {
273 // request needs "client_index" as the second member and "context" as the third member
274 msgType = requestMessage
279 err := processMessageField(ctx, &fields, fld, isType)
286 // generate struct comment
287 generateMessageComment(ctx, w, structName, msgName, isType)
289 // generate struct header
290 fmt.Fprintln(w, "type", structName, "struct {")
292 // print out the fields
293 for _, field := range fields {
294 fmt.Fprintln(w, field)
297 // generate end of the struct
300 // generate name getter
302 generateTypeNameGetter(w, structName, msgName)
304 generateMessageNameGetter(w, structName, msgName)
307 // generate message type getter method
309 generateMessageTypeGetter(w, structName, msgType)
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)
318 // generate message factory
320 generateMessageFactory(w, structName)
323 // if this is a type, save it in the map for later use
325 ctx.types[fmt.Sprintf("vl_api_%s_t", msgName)] = structName
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")
336 fieldVppType, ok := fld.At(0).Get().(string)
338 return fmt.Errorf("invalid JSON for message specified, field type is %T, not a string", fld.At(0).Get())
340 fieldName, ok := fld.At(1).Get().(string)
342 return fmt.Errorf("invalid JSON for message specified, field name is %T, not a string", fld.At(1).Get())
345 // skip internal fields
346 fieldNameLower := strings.ToLower(fieldName)
347 if fieldNameLower == "crc" || fieldNameLower == "_vl_msg_id" {
350 if !isType && len(*fields) == 0 && (fieldNameLower == "client_index" || fieldNameLower == "context") {
354 fieldName = strings.TrimPrefix(fieldName, "_")
355 fieldName = camelCaseName(strings.Title(fieldName))
361 fieldStr += "\t" + fieldName + " "
364 arraySize = int(fld.At(2).Get().(float64))
368 dataType := translateVppType(ctx, fieldVppType, isArray)
373 // variable sized array
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)
387 fieldStr += fmt.Sprintf("\t`struc:\"[%d]%s\"`", arraySize, dataType)
391 *fields = append(*fields, fieldStr)
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+"'")
401 fmt.Fprintln(w, "package "+ctx.packageName)
403 fmt.Fprintln(w, "import \""+apiImportPath+"\"")
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())
414 // generateMessageComment generates comment for a message into provider writer
415 func generateMessageComment(ctx *context, w io.Writer, structName string, msgName string, isType bool) {
418 fmt.Fprintln(w, "// "+structName+" represents the VPP binary API data type '"+msgName+"'.")
420 fmt.Fprintln(w, "// "+structName+" represents the VPP binary API message '"+msgName+"'.")
423 // print out the source of the generated message - the JSON
426 lineBuff, err := ctx.inputBuff.ReadBytes('\n')
431 line := string(lineBuff)
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)
441 fmt.Fprint(w, "//", line)
442 if len(strings.Trim(line, " ")) < 4 {
443 break // end of the message in JSON
447 fmt.Fprintln(w, "//")
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+"\"")
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+"\"")
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")
474 fmt.Fprintln(w, "\treturn api.OtherMessage")
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+"\"")
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+"{}")
494 // translateVppType translates the VPP data type into Go data type
495 func translateVppType(ctx *context, vppType string, isArray bool) string {
522 typ, ok := ctx.types[vppType]
527 panic(fmt.Sprintf("Unknown VPP type %s", vppType))
530 // camelCaseName returns correct name identifier (camelCase).
531 func camelCaseName(name string) (should string) {
532 // Fast path for simple cases: "_" and all lowercase.
537 for _, r := range name {
538 if !unicode.IsLower(r) {
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) {
555 } else if runes[i+1] == '_' {
556 // underscore; shift the remainder forward over any run of underscores
559 for i+n+1 < len(runes) && runes[i+n+1] == '_' {
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]) {
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]) {
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)
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])
598 // commonInitialisms is a set of common initialisms that need to stay in upper case.
599 var commonInitialisms = map[string]bool{