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.
28 govppApiImportPath = "git.fd.io/govpp.git/api" // import path of the govpp API package
29 inputFileExt = ".api.json" // file extension of the VPP binary API files
30 outputFileExt = ".ba.go" // file extension of the Go generated files
33 // context is a structure storing data for code generation
35 inputFile string // input file with VPP API in JSON
36 outputFile string // output file with generated Go package
38 inputData []byte // contents of the input file
40 moduleName string // name of the source VPP module
41 packageName string // name of the Go package being generated
43 packageData *Package // parsed package data
46 // getContext returns context details of the code generation task
47 func getContext(inputFile, outputDir string) (*context, error) {
48 if !strings.HasSuffix(inputFile, inputFileExt) {
49 return nil, fmt.Errorf("invalid input file name: %q", inputFile)
57 inputFileName := filepath.Base(inputFile)
58 ctx.moduleName = inputFileName[:strings.Index(inputFileName, ".")]
60 // alter package names for modules that are reserved keywords in Go
61 switch ctx.moduleName {
63 ctx.packageName = "interfaces"
65 ctx.packageName = "maps"
67 ctx.packageName = ctx.moduleName
71 packageDir := filepath.Join(outputDir, ctx.packageName)
72 outputFileName := ctx.packageName + outputFileExt
73 ctx.outputFile = filepath.Join(packageDir, outputFileName)
78 // generatePackage generates code for the parsed package data and writes it into w
79 func generatePackage(ctx *context, w *bufio.Writer) error {
80 logf("generating package %q", ctx.packageName)
82 // generate file header
83 generateHeader(ctx, w)
84 generateImports(ctx, w)
87 const APIVerConstName = "VlAPIVersion"
88 fmt.Fprintf(w, "// %s represents version of the binary API module.\n", APIVerConstName)
89 fmt.Fprintf(w, "const %s = %v\n", APIVerConstName, ctx.packageData.APIVersion)
94 if len(ctx.packageData.Services) > 0 {
95 generateServices(ctx, w, ctx.packageData.Services)
98 // TODO: generate implementation for Services interface
101 if len(ctx.packageData.Enums) > 0 {
102 fmt.Fprintf(w, "/* Enums */\n\n")
104 for _, enum := range ctx.packageData.Enums {
105 generateEnum(ctx, w, &enum)
110 if len(ctx.packageData.Aliases) > 0 {
111 fmt.Fprintf(w, "/* Aliases */\n\n")
113 for _, alias := range ctx.packageData.Aliases {
114 generateAlias(ctx, w, &alias)
119 if len(ctx.packageData.Types) > 0 {
120 fmt.Fprintf(w, "/* Types */\n\n")
122 for _, typ := range ctx.packageData.Types {
123 generateType(ctx, w, &typ)
128 if len(ctx.packageData.Unions) > 0 {
129 fmt.Fprintf(w, "/* Unions */\n\n")
131 for _, union := range ctx.packageData.Unions {
132 generateUnion(ctx, w, &union)
137 if len(ctx.packageData.Messages) > 0 {
138 fmt.Fprintf(w, "/* Messages */\n\n")
140 for _, msg := range ctx.packageData.Messages {
141 generateMessage(ctx, w, &msg)
145 // generate message registrations
147 fmt.Fprintln(w, "func init() {")
148 for _, msg := range ctx.packageData.Messages {
149 name := camelCaseName(msg.Name)
150 fmt.Fprintf(w, "\tapi.RegisterMessage((*%s)(nil), \"%s\")\n", name, ctx.moduleName+"."+name)
155 if err := w.Flush(); err != nil {
156 return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
162 // generateHeader writes generated package header into w
163 func generateHeader(ctx *context, w io.Writer) {
164 fmt.Fprintln(w, "// Code generated by GoVPP binapi-generator. DO NOT EDIT.")
165 fmt.Fprintf(w, "// source: %s\n", ctx.inputFile)
168 fmt.Fprintln(w, "/*")
169 fmt.Fprintf(w, " Package %s is a generated from VPP binary API module '%s'.\n", ctx.packageName, ctx.moduleName)
171 fmt.Fprintln(w, " It contains following objects:")
172 var printObjNum = func(obj string, num int) {
175 if strings.HasSuffix(obj, "s") {
181 fmt.Fprintf(w, "\t%3d %s\n", num, obj)
184 printObjNum("message", len(ctx.packageData.Messages))
185 printObjNum("type", len(ctx.packageData.Types))
186 printObjNum("alias", len(ctx.packageData.Aliases))
187 printObjNum("enum", len(ctx.packageData.Enums))
188 printObjNum("union", len(ctx.packageData.Unions))
189 printObjNum("service", len(ctx.packageData.Services))
191 fmt.Fprintln(w, "*/")
192 fmt.Fprintf(w, "package %s\n", ctx.packageName)
196 // generateImports writes generated package imports into w
197 func generateImports(ctx *context, w io.Writer) {
198 fmt.Fprintf(w, "import \"%s\"\n", govppApiImportPath)
199 fmt.Fprintf(w, "import \"%s\"\n", "github.com/lunixbochs/struc")
200 fmt.Fprintf(w, "import \"%s\"\n", "bytes")
203 fmt.Fprintf(w, "// Reference imports to suppress errors if they are not otherwise used.\n")
204 fmt.Fprintf(w, "var _ = api.RegisterMessage\n")
205 fmt.Fprintf(w, "var _ = struc.Pack\n")
206 fmt.Fprintf(w, "var _ = bytes.NewBuffer\n")
210 // generateComment writes generated comment for the object into w
211 func generateComment(ctx *context, w io.Writer, goName string, vppName string, objKind string) {
212 if objKind == "service" {
213 fmt.Fprintf(w, "// %s represents VPP binary API services:\n", goName)
215 fmt.Fprintf(w, "// %s represents VPP binary API %s '%s':\n", goName, objKind, vppName)
218 var isNotSpace = func(r rune) bool {
219 return !unicode.IsSpace(r)
222 // print out the source of the generated object
225 objTitle := fmt.Sprintf(`"%s",`, vppName)
227 case "alias", "service":
228 objTitle = fmt.Sprintf(`"%s": {`, vppName)
232 inputBuff := bytes.NewBuffer(ctx.inputData)
235 var trimIndent string
238 line, err := inputBuff.ReadString('\n')
244 noSpaceAt := strings.IndexFunc(line, isNotSpace)
246 indent = strings.Index(line, objTitle)
250 trimIndent = line[:indent]
251 // If no other non-whitespace character then we are at the message header.
252 if trimmed := strings.TrimSpace(line); trimmed == objTitle {
254 fmt.Fprintln(w, "//")
256 } else if noSpaceAt < indent {
257 break // end of the definition in JSON for array types
258 } else if objFound && mapType && noSpaceAt <= indent {
259 fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
260 break // end of the definition in JSON for map types (aliases, services)
262 fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
265 fmt.Fprintln(w, "//")
268 // generateServices writes generated code for the Services interface into w
269 func generateServices(ctx *context, w *bufio.Writer, services []Service) {
270 // generate services comment
271 generateComment(ctx, w, "Services", "services", "service")
273 // generate interface
274 fmt.Fprintf(w, "type %s interface {\n", "Services")
275 for _, svc := range ctx.packageData.Services {
276 generateService(ctx, w, &svc)
283 // generateService writes generated code for the service into w
284 func generateService(ctx *context, w io.Writer, svc *Service) {
285 reqTyp := camelCaseName(svc.RequestType)
287 // method name is same as parameter type name by default
288 method := svc.MethodName()
289 params := fmt.Sprintf("*%s", reqTyp)
291 if replyType := camelCaseName(svc.ReplyType); replyType != "" {
292 repTyp := fmt.Sprintf("*%s", replyType)
294 repTyp = fmt.Sprintf("[]%s", repTyp)
296 returns = fmt.Sprintf("(%s, error)", repTyp)
299 fmt.Fprintf(w, "\t%s(%s) %s\n", method, params, returns)
302 // generateEnum writes generated code for the enum into w
303 func generateEnum(ctx *context, w io.Writer, enum *Enum) {
304 name := camelCaseName(enum.Name)
305 typ := binapiTypes[enum.Type]
307 logf(" writing enum %q (%s) with %d entries", enum.Name, name, len(enum.Entries))
309 // generate enum comment
310 generateComment(ctx, w, name, enum.Name, "enum")
312 // generate enum definition
313 fmt.Fprintf(w, "type %s %s\n", name, typ)
316 fmt.Fprintln(w, "const (")
318 // generate enum entries
319 for _, entry := range enum.Entries {
320 fmt.Fprintf(w, "\t%s %s = %v\n", entry.Name, name, entry.Value)
328 // generateAlias writes generated code for the alias into w
329 func generateAlias(ctx *context, w io.Writer, alias *Alias) {
330 name := camelCaseName(alias.Name)
332 logf(" writing type %q (%s), length: %d", alias.Name, name, alias.Length)
334 // generate struct comment
335 generateComment(ctx, w, name, alias.Name, "alias")
337 // generate struct definition
338 fmt.Fprintf(w, "type %s ", name)
340 if alias.Length > 0 {
341 fmt.Fprintf(w, "[%d]", alias.Length)
344 dataType := convertToGoType(ctx, alias.Type)
345 fmt.Fprintf(w, "%s\n", dataType)
350 // generateUnion writes generated code for the union into w
351 func generateUnion(ctx *context, w io.Writer, union *Union) {
352 name := camelCaseName(union.Name)
354 logf(" writing union %q (%s) with %d fields", union.Name, name, len(union.Fields))
356 // generate struct comment
357 generateComment(ctx, w, name, union.Name, "union")
359 // generate struct definition
360 fmt.Fprintln(w, "type", name, "struct {")
362 // maximum size for union
363 maxSize := getUnionSize(ctx, union)
365 // generate data field
366 fieldName := "Union_data"
367 fmt.Fprintf(w, "\t%s [%d]byte\n", fieldName, maxSize)
369 // generate end of the struct
372 // generate name getter
373 generateTypeNameGetter(w, name, union.Name)
375 // generate CRC getter
376 generateCrcGetter(w, name, union.CRC)
378 // generate getters for fields
379 for _, field := range union.Fields {
380 fieldName := camelCaseName(field.Name)
381 fieldType := convertToGoType(ctx, field.Type)
382 generateUnionGetterSetter(w, name, fieldName, fieldType)
385 // generate union methods
386 //generateUnionMethods(w, name)
391 // generateUnionMethods generates methods that implement struc.Custom
392 // interface to allow having Union_data field unexported
393 // TODO: do more testing when unions are actually used in some messages
394 func generateUnionMethods(w io.Writer, structName string) {
395 // generate struc.Custom implementation for union
397 func (u *%[1]s) Pack(p []byte, opt *struc.Options) (int, error) {
398 var b = new(bytes.Buffer)
399 if err := struc.PackWithOptions(b, u.union_data, opt); err != nil {
405 func (u *%[1]s) Unpack(r io.Reader, length int, opt *struc.Options) error {
406 return struc.UnpackWithOptions(r, u.union_data[:], opt)
408 func (u *%[1]s) Size(opt *struc.Options) int {
409 return len(u.union_data)
411 func (u *%[1]s) String() string {
412 return string(u.union_data[:])
417 func generateUnionGetterSetter(w io.Writer, structName string, getterField, getterStruct string) {
419 func (u *%[1]s) Set%[2]s(a %[3]s) {
420 var b = new(bytes.Buffer)
421 if err := struc.Pack(b, &a); err != nil {
424 copy(u.Union_data[:], b.Bytes())
426 func (u *%[1]s) Get%[2]s() (a %[3]s) {
427 var b = bytes.NewReader(u.Union_data[:])
431 `, structName, getterField, getterStruct)
434 // generateType writes generated code for the type into w
435 func generateType(ctx *context, w io.Writer, typ *Type) {
436 name := camelCaseName(typ.Name)
438 logf(" writing type %q (%s) with %d fields", typ.Name, name, len(typ.Fields))
440 // generate struct comment
441 generateComment(ctx, w, name, typ.Name, "type")
443 // generate struct definition
444 fmt.Fprintf(w, "type %s struct {\n", name)
446 // generate struct fields
447 for i, field := range typ.Fields {
448 // skip internal fields
449 switch strings.ToLower(field.Name) {
450 case "crc", "_vl_msg_id":
454 generateField(ctx, w, typ.Fields, i)
457 // generate end of the struct
460 // generate name getter
461 generateTypeNameGetter(w, name, typ.Name)
463 // generate CRC getter
464 generateCrcGetter(w, name, typ.CRC)
469 // generateMessage writes generated code for the message into w
470 func generateMessage(ctx *context, w io.Writer, msg *Message) {
471 name := camelCaseName(msg.Name)
473 logf(" writing message %q (%s) with %d fields", msg.Name, name, len(msg.Fields))
475 // generate struct comment
476 generateComment(ctx, w, name, msg.Name, "message")
478 // generate struct definition
479 fmt.Fprintf(w, "type %s struct {", name)
481 msgType := otherMessage
482 wasClientIndex := false
484 // generate struct fields
486 for i, field := range msg.Fields {
488 if field.Name == "client_index" {
489 // "client_index" as the second member,
490 // this might be an event message or a request
491 msgType = eventMessage
492 wasClientIndex = true
493 } else if field.Name == "context" {
494 // reply needs "context" as the second member
495 msgType = replyMessage
498 if wasClientIndex && field.Name == "context" {
499 // request needs "client_index" as the second member
500 // and "context" as the third member
501 msgType = requestMessage
505 // skip internal fields
506 switch strings.ToLower(field.Name) {
507 case "crc", "_vl_msg_id":
509 case "client_index", "context":
519 generateField(ctx, w, msg.Fields, i)
522 // generate end of the struct
525 // generate name getter
526 generateMessageNameGetter(w, name, msg.Name)
528 // generate CRC getter
529 generateCrcGetter(w, name, msg.CRC)
531 // generate message type getter method
532 generateMessageTypeGetter(w, name, msgType)
535 // generateField writes generated code for the field into w
536 func generateField(ctx *context, w io.Writer, fields []Field, i int) {
539 fieldName := strings.TrimPrefix(field.Name, "_")
540 fieldName = camelCaseName(fieldName)
542 // generate length field for strings
543 if field.Type == "string" {
544 fmt.Fprintf(w, "\tXXX_%sLen uint32 `struc:\"sizeof=%s\"`\n", fieldName, fieldName)
547 dataType := convertToGoType(ctx, field.Type)
549 fieldType := dataType
551 if dataType == "uint8" {
554 fieldType = "[]" + dataType
556 fmt.Fprintf(w, "\t%s %s", fieldName, fieldType)
558 if field.Length > 0 {
560 fmt.Fprintf(w, "\t`struc:\"[%d]%s\"`", field.Length, dataType)
562 for _, f := range fields {
563 if f.SizeFrom == field.Name {
564 // variable sized array
565 sizeOfName := camelCaseName(f.Name)
566 fmt.Fprintf(w, "\t`struc:\"sizeof=%s\"`", sizeOfName)
574 // generateMessageNameGetter generates getter for original VPP message name into the provider writer
575 func generateMessageNameGetter(w io.Writer, structName, msgName string) {
576 fmt.Fprintf(w, `func (*%s) GetMessageName() string {
579 `, structName, msgName)
582 // generateTypeNameGetter generates getter for original VPP type name into the provider writer
583 func generateTypeNameGetter(w io.Writer, structName, msgName string) {
584 fmt.Fprintf(w, `func (*%s) GetTypeName() string {
587 `, structName, msgName)
590 // generateCrcGetter generates getter for CRC checksum of the message definition into the provider writer
591 func generateCrcGetter(w io.Writer, structName, crc string) {
592 crc = strings.TrimPrefix(crc, "0x")
593 fmt.Fprintf(w, `func (*%s) GetCrcString() string {
599 // generateMessageTypeGetter generates message factory for the generated message into the provider writer
600 func generateMessageTypeGetter(w io.Writer, structName string, msgType MessageType) {
601 fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
602 if msgType == requestMessage {
603 fmt.Fprintln(w, "\treturn api.RequestMessage")
604 } else if msgType == replyMessage {
605 fmt.Fprintln(w, "\treturn api.ReplyMessage")
606 } else if msgType == eventMessage {
607 fmt.Fprintln(w, "\treturn api.EventMessage")
609 fmt.Fprintln(w, "\treturn api.OtherMessage")