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 otherMessage // other VPP message
45 apiImportPath = "git.fd.io/govpp.git/api" // import path of the govpp API
46 inputFileExt = ".json" // filename extension of files that should be processed as the input
49 // context is a structure storing details of a particular code generation task
51 inputFile string // file with input JSON data
52 inputBuff *bytes.Buffer // contents of the input file
53 inputLine int // currently processed line in the input file
54 outputFile string // file with output data
55 packageName string // name of the Go package being generated
56 packageDir string // directory where the package source files are located
57 types map[string]string // map of the VPP typedef names to generated Go typedef names
61 inputFile := flag.String("input-file", "", "Input JSON file.")
62 inputDir := flag.String("input-dir", ".", "Input directory with JSON files.")
63 outputDir := flag.String("output-dir", ".", "Output directory where package folders will be generated.")
66 if *inputFile == "" && *inputDir == "" {
67 fmt.Fprintln(os.Stderr, "ERROR: input-file or input-dir must be specified")
73 // process one input file
74 err = generateFromFile(*inputFile, *outputDir)
76 fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", *inputFile, err)
79 // process all files in specified directory
80 files, err := getInputFiles(*inputDir)
82 fmt.Fprintf(os.Stderr, "ERROR: code generation failed: %v\n", err)
84 for _, file := range files {
85 tmpErr = generateFromFile(file, *outputDir)
87 fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", file, err)
88 err = tmpErr // remember that the error occurred
97 // getInputFiles returns all input files located in specified directory
98 func getInputFiles(inputDir string) ([]string, error) {
99 files, err := ioutil.ReadDir(inputDir)
101 return nil, fmt.Errorf("reading directory %s failed: %v", inputDir, err)
103 res := make([]string, 0)
104 for _, f := range files {
105 if strings.HasSuffix(f.Name(), inputFileExt) {
106 res = append(res, inputDir+"/"+f.Name())
112 // generateFromFile generates Go bindings from one input JSON file
113 func generateFromFile(inputFile, outputDir string) error {
114 ctx, err := getContext(inputFile, outputDir)
119 inputData, err := readFile(inputFile)
123 ctx.inputBuff = bytes.NewBuffer(inputData)
126 jsonRoot, err := parseJSON(inputData)
131 // create output directory
132 err = os.MkdirAll(ctx.packageDir, 0777)
134 return fmt.Errorf("creating output directory %s failed: %v", ctx.packageDir, err)
138 f, err := os.Create(ctx.outputFile)
141 return fmt.Errorf("creating output file %s failed: %v", ctx.outputFile, err)
143 w := bufio.NewWriter(f)
145 // generate Go package code
146 err = generatePackage(ctx, w, jsonRoot)
151 // go format the output file (non-fatal if fails)
152 exec.Command("gofmt", "-w", ctx.outputFile).Run()
157 // getContext returns context details of the code generation task
158 func getContext(inputFile, outputDir string) (*context, error) {
159 if !strings.HasSuffix(inputFile, inputFileExt) {
160 return nil, fmt.Errorf("invalid input file name %s", inputFile)
163 ctx := &context{inputFile: inputFile}
164 inputFileName := filepath.Base(inputFile)
166 ctx.packageName = inputFileName[0:strings.Index(inputFileName, ".")]
167 if ctx.packageName == "interface" {
168 // 'interface' cannot be a package name, it is a go keyword
169 ctx.packageName = "interfaces"
172 ctx.packageDir = outputDir + "/" + ctx.packageName + "/"
173 ctx.outputFile = ctx.packageDir + ctx.packageName + ".go"
178 // readFile reads content of a file into memory
179 func readFile(inputFile string) ([]byte, error) {
181 inputData, err := ioutil.ReadFile(inputFile)
184 return nil, fmt.Errorf("reading data from file failed: %v", err)
187 return inputData, nil
190 // parseJSON parses a JSON data into an in-memory tree
191 func parseJSON(inputData []byte) (*jsongo.JSONNode, error) {
192 root := jsongo.JSONNode{}
194 err := json.Unmarshal(inputData, &root)
196 return nil, fmt.Errorf("JSON unmarshall failed: %v", err)
203 // generatePackage generates Go code of a package from provided JSON
204 func generatePackage(ctx *context, w *bufio.Writer, jsonRoot *jsongo.JSONNode) error {
205 // generate file header
206 generatePackageHeader(ctx, w, jsonRoot)
208 // generate data types
209 ctx.types = make(map[string]string)
210 types := jsonRoot.Map("types")
211 for i := 0; i < types.Len(); i++ {
213 err := generateMessage(ctx, w, typ, true)
220 messages := jsonRoot.Map("messages")
221 for i := 0; i < messages.Len(); i++ {
222 msg := messages.At(i)
223 err := generateMessage(ctx, w, msg, false)
232 return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
238 // generateMessage generates Go code of one VPP message encoded in JSON into provided writer
239 func generateMessage(ctx *context, w io.Writer, msg *jsongo.JSONNode, isType bool) error {
240 if msg.Len() == 0 || msg.At(0).GetType() != jsongo.TypeValue {
241 return errors.New("invalid JSON for message specified")
244 msgName, ok := msg.At(0).Get().(string)
246 return fmt.Errorf("invalid JSON for message specified, message name is %T, not a string", msg.At(0).Get())
248 structName := camelCaseName(strings.Title(msgName))
250 // generate struct fields into the slice & determine message type
251 fields := make([]string, 0)
252 msgType := otherMessage
253 wasClientIndex := false
254 for j := 0; j < msg.Len(); j++ {
255 if jsongo.TypeArray == msg.At(j).GetType() {
258 // determine whether ths is a request / reply / other message
259 fieldName, ok := fld.At(1).Get().(string)
262 if fieldName == "client_index" {
263 wasClientIndex = true
264 } else if fieldName == "context" {
265 // reply needs "context" as the second member
266 msgType = replyMessage
269 if wasClientIndex && fieldName == "context" {
270 // request needs "client_index" as the second member and "context" as the third member
271 msgType = requestMessage
276 err := processMessageField(ctx, &fields, fld, isType)
283 // generate struct comment
284 generateMessageComment(ctx, w, structName, msgName, isType)
286 // generate struct header
287 fmt.Fprintln(w, "type", structName, "struct {")
289 // print out the fields
290 for _, field := range fields {
291 fmt.Fprintln(w, field)
294 // generate end of the struct
297 // generate name getter
299 generateTypeNameGetter(w, structName, msgName)
301 generateMessageNameGetter(w, structName, msgName)
304 // generate message type getter method
306 generateMessageTypeGetter(w, structName, msgType)
309 // generate CRC getter
310 crcIf := msg.At(msg.Len() - 1).At("crc").Get()
311 if crc, ok := crcIf.(string); ok {
312 generateCrcGetter(w, structName, crc)
315 // generate message factory
317 generateMessageFactory(w, structName)
320 // if this is a type, save it in the map for later use
322 ctx.types[fmt.Sprintf("vl_api_%s_t", msgName)] = structName
328 // processMessageField process JSON describing one message field into Go code emitted into provided slice of message fields
329 func processMessageField(ctx *context, fields *[]string, fld *jsongo.JSONNode, isType bool) error {
330 if fld.Len() < 2 || fld.At(0).GetType() != jsongo.TypeValue || fld.At(1).GetType() != jsongo.TypeValue {
331 return errors.New("invalid JSON for message field specified")
333 fieldVppType, ok := fld.At(0).Get().(string)
335 return fmt.Errorf("invalid JSON for message specified, field type is %T, not a string", fld.At(0).Get())
337 fieldName, ok := fld.At(1).Get().(string)
339 return fmt.Errorf("invalid JSON for message specified, field name is %T, not a string", fld.At(1).Get())
342 // skip internal fields
343 fieldNameLower := strings.ToLower(fieldName)
344 if fieldNameLower == "crc" || fieldNameLower == "_vl_msg_id" {
347 if !isType && len(*fields) == 0 && (fieldNameLower == "client_index" || fieldNameLower == "context") {
351 fieldName = strings.TrimPrefix(fieldName, "_")
352 fieldName = camelCaseName(strings.Title(fieldName))
358 fieldStr += "\t" + fieldName + " "
361 arraySize = int(fld.At(2).Get().(float64))
365 dataType := translateVppType(ctx, fieldVppType, isArray)
370 // variable sized array
372 // array size is specified by another field
373 arraySizeField := string(fld.At(3).Get().(string))
374 arraySizeField = camelCaseName(strings.Title(arraySizeField))
375 // find & update the field that specifies the array size
376 for i, f := range *fields {
377 if strings.Contains(f, fmt.Sprintf("\t%s ", arraySizeField)) {
378 (*fields)[i] += fmt.Sprintf("\t`struc:\"sizeof=%s\"`", fieldName)
384 fieldStr += fmt.Sprintf("\t`struc:\"[%d]%s\"`", arraySize, dataType)
388 *fields = append(*fields, fieldStr)
392 // generatePackageHeader generates package header into provider writer
393 func generatePackageHeader(ctx *context, w io.Writer, rootNode *jsongo.JSONNode) {
394 fmt.Fprintln(w, "// Code generated by govpp binapi-generator DO NOT EDIT.")
395 fmt.Fprintln(w, "// Package "+ctx.packageName+" represents the VPP binary API of the '"+ctx.packageName+"' VPP module.")
396 fmt.Fprintln(w, "// Generated from '"+ctx.inputFile+"'")
398 fmt.Fprintln(w, "package "+ctx.packageName)
400 fmt.Fprintln(w, "import \""+apiImportPath+"\"")
403 fmt.Fprintln(w, "// VlApiVersion contains version of the API.")
404 vlAPIVersion := rootNode.Map("vl_api_version")
405 if vlAPIVersion != nil {
406 fmt.Fprintln(w, "const VlAPIVersion = ", vlAPIVersion.Get())
411 // generateMessageComment generates comment for a message into provider writer
412 func generateMessageComment(ctx *context, w io.Writer, structName string, msgName string, isType bool) {
415 fmt.Fprintln(w, "// "+structName+" represents the VPP binary API data type '"+msgName+"'.")
417 fmt.Fprintln(w, "// "+structName+" represents the VPP binary API message '"+msgName+"'.")
420 // print out the source of the generated message - the JSON
423 lineBuff, err := ctx.inputBuff.ReadBytes('\n')
428 line := string(lineBuff)
431 if strings.Contains(line, msgName) {
432 fmt.Fprintf(w, "// Generated from '%s', line %d:\n", ctx.inputFile, ctx.inputLine)
433 fmt.Fprintln(w, "//")
434 fmt.Fprint(w, "//", line)
438 fmt.Fprint(w, "//", line)
439 if len(strings.Trim(line, " ")) < 4 {
440 break // end of the message in JSON
444 fmt.Fprintln(w, "//")
447 // generateMessageNameGetter generates getter for original VPP message name into the provider writer
448 func generateMessageNameGetter(w io.Writer, structName string, msgName string) {
449 fmt.Fprintln(w, "func (*"+structName+") GetMessageName() string {")
450 fmt.Fprintln(w, "\treturn \""+msgName+"\"")
454 // generateTypeNameGetter generates getter for original VPP type name into the provider writer
455 func generateTypeNameGetter(w io.Writer, structName string, msgName string) {
456 fmt.Fprintln(w, "func (*"+structName+") GetTypeName() string {")
457 fmt.Fprintln(w, "\treturn \""+msgName+"\"")
461 // generateMessageTypeGetter generates message factory for the generated message into the provider writer
462 func generateMessageTypeGetter(w io.Writer, structName string, msgType messageType) {
463 fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
464 if msgType == requestMessage {
465 fmt.Fprintln(w, "\treturn api.RequestMessage")
466 } else if msgType == replyMessage {
467 fmt.Fprintln(w, "\treturn api.ReplyMessage")
469 fmt.Fprintln(w, "\treturn api.OtherMessage")
474 // generateCrcGetter generates getter for CRC checksum of the message definition into the provider writer
475 func generateCrcGetter(w io.Writer, structName string, crc string) {
476 crc = strings.TrimPrefix(crc, "0x")
477 fmt.Fprintln(w, "func (*"+structName+") GetCrcString() string {")
478 fmt.Fprintln(w, "\treturn \""+crc+"\"")
482 // generateMessageFactory generates message factory for the generated message into the provider writer
483 func generateMessageFactory(w io.Writer, structName string) {
484 fmt.Fprintln(w, "func New"+structName+"() api.Message {")
485 fmt.Fprintln(w, "\treturn &"+structName+"{}")
489 // translateVppType translates the VPP data type into Go data type
490 func translateVppType(ctx *context, vppType string, isArray bool) string {
517 typ, ok := ctx.types[vppType]
522 panic(fmt.Sprintf("Unknown VPP type %s", vppType))
525 // camelCaseName returns correct name identifier (camelCase).
526 func camelCaseName(name string) (should string) {
527 // Fast path for simple cases: "_" and all lowercase.
532 for _, r := range name {
533 if !unicode.IsLower(r) {
542 // Split camelCase at any lower->upper transition, and split on underscores.
543 // Check each word for common initialisms.
544 runes := []rune(name)
545 w, i := 0, 0 // index of start of word, scan
546 for i+1 <= len(runes) {
547 eow := false // whether we hit the end of a word
548 if i+1 == len(runes) {
550 } else if runes[i+1] == '_' {
551 // underscore; shift the remainder forward over any run of underscores
554 for i+n+1 < len(runes) && runes[i+n+1] == '_' {
558 // Leave at most one underscore if the underscore is between two digits
559 if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) {
563 copy(runes[i+1:], runes[i+n+1:])
564 runes = runes[:len(runes)-n]
565 } else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) {
575 word := string(runes[w:i])
576 if u := strings.ToUpper(word); commonInitialisms[u] {
577 // Keep consistent case, which is lowercase only at the start.
578 if w == 0 && unicode.IsLower(runes[w]) {
579 u = strings.ToLower(u)
581 // All the common initialisms are ASCII,
582 // so we can replace the bytes exactly.
583 copy(runes[w:], []rune(u))
584 } else if w > 0 && strings.ToLower(word) == word {
585 // already all lowercase, and not the first word, so uppercase the first character.
586 runes[w] = unicode.ToUpper(runes[w])
593 // commonInitialisms is a set of common initialisms that need to stay in upper case.
594 var commonInitialisms = map[string]bool{