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 inputData []byte // contents of the input file
54 inputBuff *bytes.Buffer // contents of the input file currently being read
55 inputLine int // currently processed line in the input file
56 outputFile string // file with output data
57 packageName string // name of the Go package being generated
58 packageDir string // directory where the package source files are located
59 types map[string]string // map of the VPP typedef names to generated Go typedef names
63 inputFile := flag.String("input-file", "", "Input JSON file.")
64 inputDir := flag.String("input-dir", ".", "Input directory with JSON files.")
65 outputDir := flag.String("output-dir", ".", "Output directory where package folders will be generated.")
68 if *inputFile == "" && *inputDir == "" {
69 fmt.Fprintln(os.Stderr, "ERROR: input-file or input-dir must be specified")
75 // process one input file
76 err = generateFromFile(*inputFile, *outputDir)
78 fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", *inputFile, err)
81 // process all files in specified directory
82 files, err := getInputFiles(*inputDir)
84 fmt.Fprintf(os.Stderr, "ERROR: code generation failed: %v\n", err)
86 for _, file := range files {
87 tmpErr = generateFromFile(file, *outputDir)
89 fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", file, err)
90 err = tmpErr // remember that the error occurred
99 // getInputFiles returns all input files located in specified directory
100 func getInputFiles(inputDir string) ([]string, error) {
101 files, err := ioutil.ReadDir(inputDir)
103 return nil, fmt.Errorf("reading directory %s failed: %v", inputDir, err)
105 res := make([]string, 0)
106 for _, f := range files {
107 if strings.HasSuffix(f.Name(), inputFileExt) {
108 res = append(res, inputDir+"/"+f.Name())
114 // generateFromFile generates Go bindings from one input JSON file
115 func generateFromFile(inputFile, outputDir string) error {
116 ctx, err := getContext(inputFile, outputDir)
121 ctx.inputData, err = readFile(inputFile)
127 jsonRoot, err := parseJSON(ctx.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.inputBuff = bytes.NewBuffer(ctx.inputData)
212 ctx.types = make(map[string]string)
213 types := jsonRoot.Map("types")
214 for i := 0; i < types.Len(); i++ {
216 err := generateMessage(ctx, w, typ, true)
223 ctx.inputBuff = bytes.NewBuffer(ctx.inputData)
225 messages := jsonRoot.Map("messages")
226 for i := 0; i < messages.Len(); i++ {
227 msg := messages.At(i)
228 err := generateMessage(ctx, w, msg, false)
237 return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
243 // generateMessage generates Go code of one VPP message encoded in JSON into provided writer
244 func generateMessage(ctx *context, w io.Writer, msg *jsongo.JSONNode, isType bool) error {
245 if msg.Len() == 0 || msg.At(0).GetType() != jsongo.TypeValue {
246 return errors.New("invalid JSON for message specified")
249 msgName, ok := msg.At(0).Get().(string)
251 return fmt.Errorf("invalid JSON for message specified, message name is %T, not a string", msg.At(0).Get())
253 structName := camelCaseName(strings.Title(msgName))
255 // generate struct fields into the slice & determine message type
256 fields := make([]string, 0)
257 msgType := otherMessage
258 wasClientIndex := false
259 for j := 0; j < msg.Len(); j++ {
260 if jsongo.TypeArray == msg.At(j).GetType() {
263 // determine whether ths is a request / reply / other message
264 fieldName, ok := fld.At(1).Get().(string)
267 if fieldName == "client_index" {
268 // "client_index" as the second member, this might be an event message or a request
269 msgType = eventMessage
270 wasClientIndex = true
271 } else if fieldName == "context" {
272 // reply needs "context" as the second member
273 msgType = replyMessage
276 if wasClientIndex && fieldName == "context" {
277 // request needs "client_index" as the second member and "context" as the third member
278 msgType = requestMessage
283 err := processMessageField(ctx, &fields, fld, isType)
290 // generate struct comment
291 generateMessageComment(ctx, w, structName, msgName, isType)
293 // generate struct header
294 fmt.Fprintln(w, "type", structName, "struct {")
296 // print out the fields
297 for _, field := range fields {
298 fmt.Fprintln(w, field)
301 // generate end of the struct
304 // generate name getter
306 generateTypeNameGetter(w, structName, msgName)
308 generateMessageNameGetter(w, structName, msgName)
311 // generate message type getter method
313 generateMessageTypeGetter(w, structName, msgType)
316 // generate CRC getter
317 crcIf := msg.At(msg.Len() - 1).At("crc").Get()
318 if crc, ok := crcIf.(string); ok {
319 generateCrcGetter(w, structName, crc)
322 // generate message factory
324 generateMessageFactory(w, structName)
327 // if this is a type, save it in the map for later use
329 ctx.types[fmt.Sprintf("vl_api_%s_t", msgName)] = structName
335 // processMessageField process JSON describing one message field into Go code emitted into provided slice of message fields
336 func processMessageField(ctx *context, fields *[]string, fld *jsongo.JSONNode, isType bool) error {
337 if fld.Len() < 2 || fld.At(0).GetType() != jsongo.TypeValue || fld.At(1).GetType() != jsongo.TypeValue {
338 return errors.New("invalid JSON for message field specified")
340 fieldVppType, ok := fld.At(0).Get().(string)
342 return fmt.Errorf("invalid JSON for message specified, field type is %T, not a string", fld.At(0).Get())
344 fieldName, ok := fld.At(1).Get().(string)
346 return fmt.Errorf("invalid JSON for message specified, field name is %T, not a string", fld.At(1).Get())
349 // skip internal fields
350 fieldNameLower := strings.ToLower(fieldName)
351 if fieldNameLower == "crc" || fieldNameLower == "_vl_msg_id" {
354 if !isType && len(*fields) == 0 && (fieldNameLower == "client_index" || fieldNameLower == "context") {
358 fieldName = strings.TrimPrefix(fieldName, "_")
359 fieldName = camelCaseName(strings.Title(fieldName))
365 fieldStr += "\t" + fieldName + " "
368 arraySize = int(fld.At(2).Get().(float64))
372 dataType := translateVppType(ctx, fieldVppType, isArray)
377 // variable sized array
379 // array size is specified by another field
380 arraySizeField := string(fld.At(3).Get().(string))
381 arraySizeField = camelCaseName(strings.Title(arraySizeField))
382 // find & update the field that specifies the array size
383 for i, f := range *fields {
384 if strings.Contains(f, fmt.Sprintf("\t%s ", arraySizeField)) {
385 (*fields)[i] += fmt.Sprintf("\t`struc:\"sizeof=%s\"`", fieldName)
391 fieldStr += fmt.Sprintf("\t`struc:\"[%d]%s\"`", arraySize, dataType)
395 *fields = append(*fields, fieldStr)
399 // generatePackageHeader generates package header into provider writer
400 func generatePackageHeader(ctx *context, w io.Writer, rootNode *jsongo.JSONNode) {
401 fmt.Fprintln(w, "// Code generated by govpp binapi-generator DO NOT EDIT.")
402 fmt.Fprintln(w, "// Package "+ctx.packageName+" represents the VPP binary API of the '"+ctx.packageName+"' VPP module.")
403 fmt.Fprintln(w, "// Generated from '"+ctx.inputFile+"'")
405 fmt.Fprintln(w, "package "+ctx.packageName)
407 fmt.Fprintln(w, "import \""+apiImportPath+"\"")
410 fmt.Fprintln(w, "// VlApiVersion contains version of the API.")
411 vlAPIVersion := rootNode.Map("vl_api_version")
412 if vlAPIVersion != nil {
413 fmt.Fprintln(w, "const VlAPIVersion = ", vlAPIVersion.Get())
418 // generateMessageComment generates comment for a message into provider writer
419 func generateMessageComment(ctx *context, w io.Writer, structName string, msgName string, isType bool) {
422 fmt.Fprintln(w, "// "+structName+" represents the VPP binary API data type '"+msgName+"'.")
424 fmt.Fprintln(w, "// "+structName+" represents the VPP binary API message '"+msgName+"'.")
427 // print out the source of the generated message - the JSON
429 msgTitle := "\"" + msgName + "\","
432 lineBuff, err := ctx.inputBuff.ReadBytes('\n')
437 line := string(lineBuff)
440 msgIndent = strings.Index(line, msgTitle)
442 prefix := line[:msgIndent]
443 suffix := line[msgIndent+len(msgTitle):]
444 // If no other non-whitespace character then we are at the message header.
445 if strings.IndexFunc(prefix, isNotSpace) == -1 && strings.IndexFunc(suffix, isNotSpace) == -1 {
446 fmt.Fprintf(w, "// Generated from '%s', line %d:\n", ctx.inputFile, ctx.inputLine)
447 fmt.Fprintln(w, "//")
448 fmt.Fprint(w, "//", line)
453 if strings.IndexFunc(line, isNotSpace) < msgIndent {
454 break // end of the message in JSON
456 fmt.Fprint(w, "//", line)
459 fmt.Fprintln(w, "//")
462 // generateMessageNameGetter generates getter for original VPP message name into the provider writer
463 func generateMessageNameGetter(w io.Writer, structName string, msgName string) {
464 fmt.Fprintln(w, "func (*"+structName+") GetMessageName() string {")
465 fmt.Fprintln(w, "\treturn \""+msgName+"\"")
469 // generateTypeNameGetter generates getter for original VPP type name into the provider writer
470 func generateTypeNameGetter(w io.Writer, structName string, msgName string) {
471 fmt.Fprintln(w, "func (*"+structName+") GetTypeName() string {")
472 fmt.Fprintln(w, "\treturn \""+msgName+"\"")
476 // generateMessageTypeGetter generates message factory for the generated message into the provider writer
477 func generateMessageTypeGetter(w io.Writer, structName string, msgType messageType) {
478 fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
479 if msgType == requestMessage {
480 fmt.Fprintln(w, "\treturn api.RequestMessage")
481 } else if msgType == replyMessage {
482 fmt.Fprintln(w, "\treturn api.ReplyMessage")
483 } else if msgType == eventMessage {
484 fmt.Fprintln(w, "\treturn api.EventMessage")
486 fmt.Fprintln(w, "\treturn api.OtherMessage")
491 // generateCrcGetter generates getter for CRC checksum of the message definition into the provider writer
492 func generateCrcGetter(w io.Writer, structName string, crc string) {
493 crc = strings.TrimPrefix(crc, "0x")
494 fmt.Fprintln(w, "func (*"+structName+") GetCrcString() string {")
495 fmt.Fprintln(w, "\treturn \""+crc+"\"")
499 // generateMessageFactory generates message factory for the generated message into the provider writer
500 func generateMessageFactory(w io.Writer, structName string) {
501 fmt.Fprintln(w, "func New"+structName+"() api.Message {")
502 fmt.Fprintln(w, "\treturn &"+structName+"{}")
506 // translateVppType translates the VPP data type into Go data type
507 func translateVppType(ctx *context, vppType string, isArray bool) string {
534 typ, ok := ctx.types[vppType]
539 panic(fmt.Sprintf("Unknown VPP type %s", vppType))
542 // camelCaseName returns correct name identifier (camelCase).
543 func camelCaseName(name string) (should string) {
544 // Fast path for simple cases: "_" and all lowercase.
549 for _, r := range name {
550 if !unicode.IsLower(r) {
559 // Split camelCase at any lower->upper transition, and split on underscores.
560 // Check each word for common initialisms.
561 runes := []rune(name)
562 w, i := 0, 0 // index of start of word, scan
563 for i+1 <= len(runes) {
564 eow := false // whether we hit the end of a word
565 if i+1 == len(runes) {
567 } else if runes[i+1] == '_' {
568 // underscore; shift the remainder forward over any run of underscores
571 for i+n+1 < len(runes) && runes[i+n+1] == '_' {
575 // Leave at most one underscore if the underscore is between two digits
576 if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) {
580 copy(runes[i+1:], runes[i+n+1:])
581 runes = runes[:len(runes)-n]
582 } else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) {
592 word := string(runes[w:i])
593 if u := strings.ToUpper(word); commonInitialisms[u] {
594 // Keep consistent case, which is lowercase only at the start.
595 if w == 0 && unicode.IsLower(runes[w]) {
596 u = strings.ToLower(u)
598 // All the common initialisms are ASCII,
599 // so we can replace the bytes exactly.
600 copy(runes[w:], []rune(u))
601 } else if w > 0 && strings.ToLower(word) == word {
602 // already all lowercase, and not the first word, so uppercase the first character.
603 runes[w] = unicode.ToUpper(runes[w])
610 // isNotSpace returns true if the rune is NOT a whitespace character.
611 func isNotSpace(r rune) bool {
612 return !unicode.IsSpace(r)
615 // commonInitialisms is a set of common initialisms that need to stay in upper case.
616 var commonInitialisms = map[string]bool{