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 inputFileExt = ".api.json" // file extension of the VPP API files
29 outputFileExt = ".ba.go" // file extension of the Go generated files
31 govppApiImportPath = "git.fd.io/govpp.git/api" // import path of the govpp API package
32 constAPIVersionCrc = "APIVersionCrc" // name for the API version CRC constant
35 // context is a structure storing data for code generation
37 inputFile string // input file with VPP API in JSON
38 outputFile string // output file with generated Go package
40 inputData []byte // contents of the input file
42 includeAPIVersionCrc bool // include constant with API version CRC string
43 includeComments bool // include parts of original source in comments
45 moduleName string // name of the source VPP module
46 packageName string // name of the Go package being generated
48 packageData *Package // parsed package data
51 // getContext returns context details of the code generation task
52 func getContext(inputFile, outputDir string) (*context, error) {
53 if !strings.HasSuffix(inputFile, inputFileExt) {
54 return nil, fmt.Errorf("invalid input file name: %q", inputFile)
62 inputFileName := filepath.Base(inputFile)
63 ctx.moduleName = inputFileName[:strings.Index(inputFileName, ".")]
65 // alter package names for modules that are reserved keywords in Go
66 switch ctx.moduleName {
68 ctx.packageName = "interfaces"
70 ctx.packageName = "maps"
72 ctx.packageName = ctx.moduleName
76 packageDir := filepath.Join(outputDir, ctx.packageName)
77 outputFileName := ctx.packageName + outputFileExt
78 ctx.outputFile = filepath.Join(packageDir, outputFileName)
83 // generatePackage generates code for the parsed package data and writes it into w
84 func generatePackage(ctx *context, w *bufio.Writer) error {
85 logf("generating package %q", ctx.packageName)
87 // generate file header
88 generateHeader(ctx, w)
89 generateImports(ctx, w)
91 if ctx.includeAPIVersionCrc {
92 fmt.Fprintf(w, "// %s defines API version CRC of the VPP binary API module.\n", constAPIVersionCrc)
93 fmt.Fprintf(w, "const %s = %v\n", constAPIVersionCrc, ctx.packageData.APIVersion)
98 if len(ctx.packageData.Services) > 0 {
99 generateServices(ctx, w, ctx.packageData.Services)
101 // TODO: generate implementation for Services interface
105 if len(ctx.packageData.Enums) > 0 {
106 fmt.Fprintf(w, "/* Enums */\n\n")
108 for _, enum := range ctx.packageData.Enums {
109 generateEnum(ctx, w, &enum)
114 if len(ctx.packageData.Aliases) > 0 {
115 fmt.Fprintf(w, "/* Aliases */\n\n")
117 for _, alias := range ctx.packageData.Aliases {
118 generateAlias(ctx, w, &alias)
123 if len(ctx.packageData.Types) > 0 {
124 fmt.Fprintf(w, "/* Types */\n\n")
126 for _, typ := range ctx.packageData.Types {
127 generateType(ctx, w, &typ)
132 if len(ctx.packageData.Unions) > 0 {
133 fmt.Fprintf(w, "/* Unions */\n\n")
135 for _, union := range ctx.packageData.Unions {
136 generateUnion(ctx, w, &union)
141 if len(ctx.packageData.Messages) > 0 {
142 fmt.Fprintf(w, "/* Messages */\n\n")
144 for _, msg := range ctx.packageData.Messages {
145 generateMessage(ctx, w, &msg)
148 // generate message registrations
149 fmt.Fprintln(w, "func init() {")
150 for _, msg := range ctx.packageData.Messages {
151 name := camelCaseName(msg.Name)
152 fmt.Fprintf(w, "\tapi.RegisterMessage((*%s)(nil), \"%s\")\n", name, ctx.moduleName+"."+name)
158 if err := w.Flush(); err != nil {
159 return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
165 // generateHeader writes generated package header into w
166 func generateHeader(ctx *context, w io.Writer) {
167 fmt.Fprintln(w, "// Code generated by GoVPP binapi-generator. DO NOT EDIT.")
168 fmt.Fprintf(w, "// source: %s\n", ctx.inputFile)
171 fmt.Fprintln(w, "/*")
172 fmt.Fprintf(w, " Package %s is a generated from VPP binary API module '%s'.\n", ctx.packageName, ctx.moduleName)
174 fmt.Fprintln(w, " It contains following objects:")
175 var printObjNum = func(obj string, num int) {
178 if strings.HasSuffix(obj, "s") {
184 fmt.Fprintf(w, "\t%3d %s\n", num, obj)
188 printObjNum("service", len(ctx.packageData.Services))
189 printObjNum("enum", len(ctx.packageData.Enums))
190 printObjNum("alias", len(ctx.packageData.Aliases))
191 printObjNum("type", len(ctx.packageData.Types))
192 printObjNum("union", len(ctx.packageData.Unions))
193 printObjNum("message", len(ctx.packageData.Messages))
194 fmt.Fprintln(w, "*/")
195 fmt.Fprintf(w, "package %s\n", ctx.packageName)
199 // generateImports writes generated package imports into w
200 func generateImports(ctx *context, w io.Writer) {
201 fmt.Fprintf(w, "import api \"%s\"\n", govppApiImportPath)
202 fmt.Fprintf(w, "import struc \"%s\"\n", "github.com/lunixbochs/struc")
203 fmt.Fprintf(w, "import bytes \"%s\"\n", "bytes")
206 fmt.Fprintf(w, "// Reference imports to suppress errors if they are not otherwise used.\n")
207 fmt.Fprintf(w, "var _ = api.RegisterMessage\n")
208 fmt.Fprintf(w, "var _ = struc.Pack\n")
209 fmt.Fprintf(w, "var _ = bytes.NewBuffer\n")
212 /*fmt.Fprintln(w, "// This is a compile-time assertion to ensure that this generated file")
213 fmt.Fprintln(w, "// is compatible with the GoVPP api package it is being compiled against.")
214 fmt.Fprintln(w, "// A compilation error at this line likely means your copy of the")
215 fmt.Fprintln(w, "// GoVPP api package needs to be updated.")
216 fmt.Fprintln(w, "const _ = api.GoVppAPIPackageIsVersion1 // please upgrade the GoVPP api package")
220 // generateComment writes generated comment for the object into w
221 func generateComment(ctx *context, w io.Writer, goName string, vppName string, objKind string) {
222 if objKind == "service" {
223 fmt.Fprintf(w, "// %s represents VPP binary API services:\n", goName)
225 fmt.Fprintf(w, "// %s represents VPP binary API %s '%s':\n", goName, objKind, vppName)
228 if !ctx.includeComments {
232 var isNotSpace = func(r rune) bool {
233 return !unicode.IsSpace(r)
236 // print out the source of the generated object
239 objTitle := fmt.Sprintf(`"%s",`, vppName)
241 case "alias", "service":
242 objTitle = fmt.Sprintf(`"%s": {`, vppName)
246 inputBuff := bytes.NewBuffer(ctx.inputData)
249 var trimIndent string
252 line, err := inputBuff.ReadString('\n')
258 noSpaceAt := strings.IndexFunc(line, isNotSpace)
260 indent = strings.Index(line, objTitle)
264 trimIndent = line[:indent]
265 // If no other non-whitespace character then we are at the message header.
266 if trimmed := strings.TrimSpace(line); trimmed == objTitle {
268 fmt.Fprintln(w, "//")
270 } else if noSpaceAt < indent {
271 break // end of the definition in JSON for array types
272 } else if objFound && mapType && noSpaceAt <= indent {
273 fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
274 break // end of the definition in JSON for map types (aliases, services)
276 fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
279 fmt.Fprintln(w, "//")
282 // generateServices writes generated code for the Services interface into w
283 func generateServices(ctx *context, w *bufio.Writer, services []Service) {
284 // generate services comment
285 generateComment(ctx, w, "Services", "services", "service")
287 // generate interface
288 fmt.Fprintf(w, "type %s interface {\n", "Services")
289 for _, svc := range services {
290 generateService(ctx, w, &svc)
297 // generateService writes generated code for the service into w
298 func generateService(ctx *context, w io.Writer, svc *Service) {
299 reqTyp := camelCaseName(svc.RequestType)
301 // method name is same as parameter type name by default
304 // use Dump as prefix instead of suffix for stream services
305 if m := strings.TrimSuffix(method, "Dump"); method != m {
310 params := fmt.Sprintf("*%s", reqTyp)
312 if replyType := camelCaseName(svc.ReplyType); replyType != "" {
313 repTyp := fmt.Sprintf("*%s", replyType)
315 repTyp = fmt.Sprintf("[]%s", repTyp)
317 returns = fmt.Sprintf("(%s, error)", repTyp)
320 fmt.Fprintf(w, "\t%s(%s) %s\n", method, params, returns)
323 // generateEnum writes generated code for the enum into w
324 func generateEnum(ctx *context, w io.Writer, enum *Enum) {
325 name := camelCaseName(enum.Name)
326 typ := binapiTypes[enum.Type]
328 logf(" writing enum %q (%s) with %d entries", enum.Name, name, len(enum.Entries))
330 // generate enum comment
331 generateComment(ctx, w, name, enum.Name, "enum")
333 // generate enum definition
334 fmt.Fprintf(w, "type %s %s\n", name, typ)
337 fmt.Fprintln(w, "const (")
339 // generate enum entries
340 for _, entry := range enum.Entries {
341 fmt.Fprintf(w, "\t%s %s = %v\n", entry.Name, name, entry.Value)
349 // generateAlias writes generated code for the alias into w
350 func generateAlias(ctx *context, w io.Writer, alias *Alias) {
351 name := camelCaseName(alias.Name)
353 logf(" writing type %q (%s), length: %d", alias.Name, name, alias.Length)
355 // generate struct comment
356 generateComment(ctx, w, name, alias.Name, "alias")
358 // generate struct definition
359 fmt.Fprintf(w, "type %s ", name)
361 if alias.Length > 0 {
362 fmt.Fprintf(w, "[%d]", alias.Length)
365 dataType := convertToGoType(ctx, alias.Type)
366 fmt.Fprintf(w, "%s\n", dataType)
371 // generateUnion writes generated code for the union into w
372 func generateUnion(ctx *context, w io.Writer, union *Union) {
373 name := camelCaseName(union.Name)
375 logf(" writing union %q (%s) with %d fields", union.Name, name, len(union.Fields))
377 // generate struct comment
378 generateComment(ctx, w, name, union.Name, "union")
380 // generate struct definition
381 fmt.Fprintln(w, "type", name, "struct {")
383 // maximum size for union
384 maxSize := getUnionSize(ctx, union)
386 // generate data field
387 fieldName := "Union_data"
388 fmt.Fprintf(w, "\t%s [%d]byte\n", fieldName, maxSize)
390 // generate end of the struct
393 // generate name getter
394 generateTypeNameGetter(w, name, union.Name)
396 // generate CRC getter
397 generateCrcGetter(w, name, union.CRC)
399 // generate getters for fields
400 for _, field := range union.Fields {
401 fieldName := camelCaseName(field.Name)
402 fieldType := convertToGoType(ctx, field.Type)
403 generateUnionGetterSetter(w, name, fieldName, fieldType)
406 // generate union methods
407 //generateUnionMethods(w, name)
412 // generateUnionMethods generates methods that implement struc.Custom
413 // interface to allow having Union_data field unexported
414 // TODO: do more testing when unions are actually used in some messages
415 func generateUnionMethods(w io.Writer, structName string) {
416 // generate struc.Custom implementation for union
418 func (u *%[1]s) Pack(p []byte, opt *struc.Options) (int, error) {
419 var b = new(bytes.Buffer)
420 if err := struc.PackWithOptions(b, u.union_data, opt); err != nil {
426 func (u *%[1]s) Unpack(r io.Reader, length int, opt *struc.Options) error {
427 return struc.UnpackWithOptions(r, u.union_data[:], opt)
429 func (u *%[1]s) Size(opt *struc.Options) int {
430 return len(u.union_data)
432 func (u *%[1]s) String() string {
433 return string(u.union_data[:])
438 func generateUnionGetterSetter(w io.Writer, structName string, getterField, getterStruct string) {
440 func %[1]s%[2]s(a %[3]s) (u %[1]s) {
444 func (u *%[1]s) Set%[2]s(a %[3]s) {
445 var b = new(bytes.Buffer)
446 if err := struc.Pack(b, &a); err != nil {
449 copy(u.Union_data[:], b.Bytes())
451 func (u *%[1]s) Get%[2]s() (a %[3]s) {
452 var b = bytes.NewReader(u.Union_data[:])
456 `, structName, getterField, getterStruct)
459 // generateType writes generated code for the type into w
460 func generateType(ctx *context, w io.Writer, typ *Type) {
461 name := camelCaseName(typ.Name)
463 logf(" writing type %q (%s) with %d fields", typ.Name, name, len(typ.Fields))
465 // generate struct comment
466 generateComment(ctx, w, name, typ.Name, "type")
468 // generate struct definition
469 fmt.Fprintf(w, "type %s struct {\n", name)
471 // generate struct fields
472 for i, field := range typ.Fields {
473 // skip internal fields
474 switch strings.ToLower(field.Name) {
475 case crcField, msgIdField:
479 generateField(ctx, w, typ.Fields, i)
482 // generate end of the struct
485 // generate name getter
486 generateTypeNameGetter(w, name, typ.Name)
488 // generate CRC getter
489 generateCrcGetter(w, name, typ.CRC)
494 // generateMessage writes generated code for the message into w
495 func generateMessage(ctx *context, w io.Writer, msg *Message) {
496 name := camelCaseName(msg.Name)
498 logf(" writing message %q (%s) with %d fields", msg.Name, name, len(msg.Fields))
500 // generate struct comment
501 generateComment(ctx, w, name, msg.Name, "message")
503 // generate struct definition
504 fmt.Fprintf(w, "type %s struct {", name)
506 msgType := otherMessage
507 wasClientIndex := false
509 // generate struct fields
511 for i, field := range msg.Fields {
513 if field.Name == clientIndexField {
514 // "client_index" as the second member,
515 // this might be an event message or a request
516 msgType = eventMessage
517 wasClientIndex = true
518 } else if field.Name == contextField {
519 // reply needs "context" as the second member
520 msgType = replyMessage
523 if wasClientIndex && field.Name == contextField {
524 // request needs "client_index" as the second member
525 // and "context" as the third member
526 msgType = requestMessage
530 // skip internal fields
531 switch strings.ToLower(field.Name) {
532 case crcField, msgIdField:
534 case clientIndexField, contextField:
544 generateField(ctx, w, msg.Fields, i)
547 // generate end of the struct
550 // generate name getter
551 generateMessageNameGetter(w, name, msg.Name)
553 // generate CRC getter
554 generateCrcGetter(w, name, msg.CRC)
556 // generate message type getter method
557 generateMessageTypeGetter(w, name, msgType)
562 // generateField writes generated code for the field into w
563 func generateField(ctx *context, w io.Writer, fields []Field, i int) {
566 fieldName := strings.TrimPrefix(field.Name, "_")
567 fieldName = camelCaseName(fieldName)
569 // generate length field for strings
570 if field.Type == "string" {
571 fmt.Fprintf(w, "\tXXX_%sLen uint32 `struc:\"sizeof=%s\"`\n", fieldName, fieldName)
574 dataType := convertToGoType(ctx, field.Type)
575 fieldType := dataType
577 // check if it is array
578 if field.Length > 0 || field.SizeFrom != "" {
579 if dataType == "uint8" {
582 fieldType = "[]" + dataType
584 fmt.Fprintf(w, "\t%s %s", fieldName, fieldType)
586 if field.Length > 0 {
588 fmt.Fprintf(w, "\t`struc:\"[%d]%s\"`", field.Length, dataType)
590 for _, f := range fields {
591 if f.SizeFrom == field.Name {
592 // variable sized array
593 sizeOfName := camelCaseName(f.Name)
594 fmt.Fprintf(w, "\t`struc:\"sizeof=%s\"`", sizeOfName)
602 // generateMessageNameGetter generates getter for original VPP message name into the provider writer
603 func generateMessageNameGetter(w io.Writer, structName, msgName string) {
604 fmt.Fprintf(w, `func (*%s) GetMessageName() string {
607 `, structName, msgName)
610 // generateTypeNameGetter generates getter for original VPP type name into the provider writer
611 func generateTypeNameGetter(w io.Writer, structName, msgName string) {
612 fmt.Fprintf(w, `func (*%s) GetTypeName() string {
615 `, structName, msgName)
618 // generateCrcGetter generates getter for CRC checksum of the message definition into the provider writer
619 func generateCrcGetter(w io.Writer, structName, crc string) {
620 crc = strings.TrimPrefix(crc, "0x")
621 fmt.Fprintf(w, `func (*%s) GetCrcString() string {
627 // generateMessageTypeGetter generates message factory for the generated message into the provider writer
628 func generateMessageTypeGetter(w io.Writer, structName string, msgType MessageType) {
629 fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
630 if msgType == requestMessage {
631 fmt.Fprintln(w, "\treturn api.RequestMessage")
632 } else if msgType == replyMessage {
633 fmt.Fprintln(w, "\treturn api.ReplyMessage")
634 } else if msgType == eventMessage {
635 fmt.Fprintln(w, "\treturn api.EventMessage")
637 fmt.Fprintln(w, "\treturn api.OtherMessage")