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
39 inputBuff *bytes.Buffer // contents of the input file currently being read
40 inputLine int // currently processed line in the input file
42 moduleName string // name of the source VPP module
43 packageName string // name of the Go package being generated
45 packageData *Package // parsed package data
48 // getContext returns context details of the code generation task
49 func getContext(inputFile, outputDir string) (*context, error) {
50 if !strings.HasSuffix(inputFile, inputFileExt) {
51 return nil, fmt.Errorf("invalid input file name: %q", inputFile)
59 inputFileName := filepath.Base(inputFile)
60 ctx.moduleName = inputFileName[:strings.Index(inputFileName, ".")]
62 // alter package names for modules that are reserved keywords in Go
63 switch ctx.moduleName {
65 ctx.packageName = "interfaces"
67 ctx.packageName = "maps"
69 ctx.packageName = ctx.moduleName
73 packageDir := filepath.Join(outputDir, ctx.packageName)
74 outputFileName := ctx.packageName + outputFileExt
75 ctx.outputFile = filepath.Join(packageDir, outputFileName)
80 // generatePackage generates code for the parsed package data and writes it into w
81 func generatePackage(ctx *context, w *bufio.Writer) error {
82 logf("generating package %q", ctx.packageName)
84 // generate file header
85 generateHeader(ctx, w)
86 generateImports(ctx, w)
89 const APIVerConstName = "VlAPIVersion"
90 fmt.Fprintf(w, "// %s represents version of the API.\n", APIVerConstName)
91 fmt.Fprintf(w, "const %s = %v\n", APIVerConstName, ctx.packageData.APIVersion)
96 if len(ctx.packageData.Enums) > 0 {
97 fmt.Fprintf(w, "/* Enums */\n\n")
99 ctx.inputBuff = bytes.NewBuffer(ctx.inputData)
101 for _, enum := range ctx.packageData.Enums {
102 generateEnum(ctx, w, &enum)
107 if len(ctx.packageData.Types) > 0 {
108 fmt.Fprintf(w, "/* Types */\n\n")
110 ctx.inputBuff = bytes.NewBuffer(ctx.inputData)
112 for _, typ := range ctx.packageData.Types {
113 generateType(ctx, w, &typ)
118 if len(ctx.packageData.Unions) > 0 {
119 fmt.Fprintf(w, "/* Unions */\n\n")
121 ctx.inputBuff = bytes.NewBuffer(ctx.inputData)
123 for _, union := range ctx.packageData.Unions {
124 generateUnion(ctx, w, &union)
129 if len(ctx.packageData.Messages) > 0 {
130 fmt.Fprintf(w, "/* Messages */\n\n")
132 ctx.inputBuff = bytes.NewBuffer(ctx.inputData)
134 for _, msg := range ctx.packageData.Messages {
135 generateMessage(ctx, w, &msg)
140 if len(ctx.packageData.Services) > 0 {
141 fmt.Fprintf(w, "/* Services */\n\n")
143 ctx.inputBuff = bytes.NewBuffer(ctx.inputData)
145 fmt.Fprintf(w, "type %s interface {\n", "Services")
146 for _, svc := range ctx.packageData.Services {
147 generateService(ctx, w, &svc)
152 // TODO: generate implementation for Services interface
154 // generate message registrations
156 fmt.Fprintln(w, "func init() {")
157 for _, msg := range ctx.packageData.Messages {
158 name := camelCaseName(msg.Name)
159 fmt.Fprintf(w, "\tapi.RegisterMessage((*%s)(nil), \"%s\")\n", name, ctx.moduleName+"."+name)
164 if err := w.Flush(); err != nil {
165 return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
171 // generateHeader writes generated package header into w
172 func generateHeader(ctx *context, w io.Writer) {
173 fmt.Fprintln(w, "// Code generated by GoVPP binapi-generator. DO NOT EDIT.")
174 fmt.Fprintf(w, "// source: %s\n", ctx.inputFile)
177 fmt.Fprintln(w, "/*")
178 fmt.Fprintf(w, "Package %s is a generated VPP binary API of the '%s' VPP module.\n", ctx.packageName, ctx.moduleName)
180 fmt.Fprintln(w, "It is generated from this file:")
181 fmt.Fprintf(w, "\t%s\n", filepath.Base(ctx.inputFile))
183 fmt.Fprintln(w, "It contains these VPP binary API objects:")
185 var printObjNum = func(obj string, num int) {
190 fmt.Fprintf(w, "\t%d %s\n", num, obj)
193 printObjNum("message", len(ctx.packageData.Messages))
194 printObjNum("type", len(ctx.packageData.Types))
195 printObjNum("enum", len(ctx.packageData.Enums))
196 printObjNum("union", len(ctx.packageData.Unions))
197 printObjNum("service", len(ctx.packageData.Services))
199 fmt.Fprintln(w, "*/")
200 fmt.Fprintf(w, "package %s\n", ctx.packageName)
204 // generateImports writes generated package imports into w
205 func generateImports(ctx *context, w io.Writer) {
206 fmt.Fprintf(w, "import \"%s\"\n", govppApiImportPath)
207 fmt.Fprintf(w, "import \"%s\"\n", "github.com/lunixbochs/struc")
208 fmt.Fprintf(w, "import \"%s\"\n", "bytes")
211 fmt.Fprintf(w, "// Reference imports to suppress errors if they are not otherwise used.\n")
212 fmt.Fprintf(w, "var _ = api.RegisterMessage\n")
213 fmt.Fprintf(w, "var _ = struc.Pack\n")
214 fmt.Fprintf(w, "var _ = bytes.NewBuffer\n")
218 // generateComment writes generated comment for the object into w
219 func generateComment(ctx *context, w io.Writer, goName string, vppName string, objKind string) {
220 fmt.Fprintf(w, "// %s represents the VPP binary API %s '%s'.\n", goName, objKind, vppName)
222 var isNotSpace = func(r rune) bool {
223 return !unicode.IsSpace(r)
226 // print out the source of the generated object
228 objTitle := fmt.Sprintf(`"%s",`, vppName)
231 line, err := ctx.inputBuff.ReadString('\n')
238 indent = strings.Index(line, objTitle)
242 // If no other non-whitespace character then we are at the message header.
243 if trimmed := strings.TrimSpace(line); trimmed == objTitle {
245 fmt.Fprintf(w, "// Generated from '%s', line %d:\n", filepath.Base(ctx.inputFile), ctx.inputLine)
246 fmt.Fprintln(w, "//")
249 if strings.IndexFunc(line, isNotSpace) < indent {
250 break // end of the object definition in JSON
253 fmt.Fprint(w, "//", line)
256 fmt.Fprintln(w, "//")
259 // generateEnum writes generated code for the enum into w
260 func generateEnum(ctx *context, w io.Writer, enum *Enum) {
261 name := camelCaseName(enum.Name)
262 typ := binapiTypes[enum.Type]
264 logf(" writing enum %q (%s) with %d entries", enum.Name, name, len(enum.Entries))
266 // generate enum comment
267 generateComment(ctx, w, name, enum.Name, "enum")
269 // generate enum definition
270 fmt.Fprintf(w, "type %s %s\n", name, typ)
273 fmt.Fprintln(w, "const (")
275 // generate enum entries
276 for _, entry := range enum.Entries {
277 fmt.Fprintf(w, "\t%s %s = %v\n", entry.Name, name, entry.Value)
285 // generateType writes generated code for the type into w
286 func generateType(ctx *context, w io.Writer, typ *Type) {
287 name := camelCaseName(typ.Name)
289 logf(" writing type %q (%s) with %d fields", typ.Name, name, len(typ.Fields))
291 // generate struct comment
292 generateComment(ctx, w, name, typ.Name, "type")
294 // generate struct definition
295 fmt.Fprintf(w, "type %s struct {\n", name)
297 // generate struct fields
298 for i, field := range typ.Fields {
299 // skip internal fields
300 switch strings.ToLower(field.Name) {
301 case "crc", "_vl_msg_id":
305 generateField(ctx, w, typ.Fields, i)
308 // generate end of the struct
311 // generate name getter
312 generateTypeNameGetter(w, name, typ.Name)
314 // generate CRC getter
315 generateCrcGetter(w, name, typ.CRC)
320 // generateUnion writes generated code for the union into w
321 func generateUnion(ctx *context, w io.Writer, union *Union) {
322 name := camelCaseName(union.Name)
324 logf(" writing union %q (%s) with %d fields", union.Name, name, len(union.Fields))
326 // generate struct comment
327 generateComment(ctx, w, name, union.Name, "union")
329 // generate struct definition
330 fmt.Fprintln(w, "type", name, "struct {")
332 // maximum size for union
333 maxSize := getUnionSize(ctx, union)
335 // generate data field
336 fieldName := "Union_data"
337 fmt.Fprintf(w, "\t%s [%d]byte\n", fieldName, maxSize)
339 // generate end of the struct
342 // generate name getter
343 generateTypeNameGetter(w, name, union.Name)
345 // generate CRC getter
346 generateCrcGetter(w, name, union.CRC)
348 // generate getters for fields
349 for _, field := range union.Fields {
350 fieldName := camelCaseName(field.Name)
351 fieldType := convertToGoType(ctx, field.Type)
352 generateUnionGetterSetter(w, name, fieldName, fieldType)
355 // generate union methods
356 //generateUnionMethods(w, name)
361 // generateUnionMethods generates methods that implement struc.Custom
362 // interface to allow having Union_data field unexported
363 // TODO: do more testing when unions are actually used in some messages
364 func generateUnionMethods(w io.Writer, structName string) {
365 // generate struc.Custom implementation for union
367 func (u *%[1]s) Pack(p []byte, opt *struc.Options) (int, error) {
368 var b = new(bytes.Buffer)
369 if err := struc.PackWithOptions(b, u.union_data, opt); err != nil {
375 func (u *%[1]s) Unpack(r io.Reader, length int, opt *struc.Options) error {
376 return struc.UnpackWithOptions(r, u.union_data[:], opt)
378 func (u *%[1]s) Size(opt *struc.Options) int {
379 return len(u.union_data)
381 func (u *%[1]s) String() string {
382 return string(u.union_data[:])
387 func generateUnionGetterSetter(w io.Writer, structName string, getterField, getterStruct string) {
389 func (u *%[1]s) Set%[2]s(a %[3]s) {
390 var b = new(bytes.Buffer)
391 if err := struc.Pack(b, &a); err != nil {
394 copy(u.Union_data[:], b.Bytes())
396 func (u *%[1]s) Get%[2]s() (a %[3]s) {
397 var b = bytes.NewReader(u.Union_data[:])
401 `, structName, getterField, getterStruct)
404 // generateMessage writes generated code for the message into w
405 func generateMessage(ctx *context, w io.Writer, msg *Message) {
406 name := camelCaseName(msg.Name)
408 logf(" writing message %q (%s) with %d fields", msg.Name, name, len(msg.Fields))
410 // generate struct comment
411 generateComment(ctx, w, name, msg.Name, "message")
413 // generate struct definition
414 fmt.Fprintf(w, "type %s struct {", name)
416 msgType := otherMessage
417 wasClientIndex := false
419 // generate struct fields
421 for i, field := range msg.Fields {
423 if field.Name == "client_index" {
424 // "client_index" as the second member, this might be an event message or a request
425 msgType = eventMessage
426 wasClientIndex = true
427 } else if field.Name == "context" {
428 // reply needs "context" as the second member
429 msgType = replyMessage
432 if wasClientIndex && field.Name == "context" {
433 // request needs "client_index" as the second member and "context" as the third member
434 msgType = requestMessage
438 // skip internal fields
439 switch strings.ToLower(field.Name) {
440 case "crc", "_vl_msg_id":
442 case "client_index", "context":
452 generateField(ctx, w, msg.Fields, i)
455 // generate end of the struct
458 // generate name getter
459 generateMessageNameGetter(w, name, msg.Name)
461 // generate CRC getter
462 generateCrcGetter(w, name, msg.CRC)
464 // generate message type getter method
465 generateMessageTypeGetter(w, name, msgType)
467 // generate message factory
468 generateMessageFactory(w, name)
471 // generateField writes generated code for the field into w
472 func generateField(ctx *context, w io.Writer, fields []Field, i int) {
475 fieldName := strings.TrimPrefix(field.Name, "_")
476 fieldName = camelCaseName(fieldName)
478 dataType := convertToGoType(ctx, field.Type)
480 fieldType := dataType
482 if dataType == "uint8" {
485 fieldType = "[]" + dataType
487 fmt.Fprintf(w, "\t%s %s", fieldName, fieldType)
489 if field.Length > 0 {
491 fmt.Fprintf(w, "\t`struc:\"[%d]%s\"`", field.Length, dataType)
493 for _, f := range fields {
494 if f.SizeFrom == field.Name {
495 // variable sized array
496 sizeOfName := camelCaseName(f.Name)
497 fmt.Fprintf(w, "\t`struc:\"sizeof=%s\"`", sizeOfName)
505 // generateService writes generated code for the service into w
506 func generateService(ctx *context, w io.Writer, svc *Service) {
507 reqTyp := camelCaseName(svc.RequestType)
509 // method name is same as parameter type name by default
510 method := svc.MethodName()
511 params := fmt.Sprintf("*%s", reqTyp)
513 if replyTyp := camelCaseName(svc.ReplyType); replyTyp != "" {
514 returns = fmt.Sprintf("(*%s, error)", replyTyp)
517 fmt.Fprintf(w, "\t%s(%s) %s\n", method, params, returns)
520 // generateMessageNameGetter generates getter for original VPP message name into the provider writer
521 func generateMessageNameGetter(w io.Writer, structName, msgName string) {
522 fmt.Fprintf(w, `func (*%s) GetMessageName() string {
525 `, structName, msgName)
528 // generateTypeNameGetter generates getter for original VPP type name into the provider writer
529 func generateTypeNameGetter(w io.Writer, structName, msgName string) {
530 fmt.Fprintf(w, `func (*%s) GetTypeName() string {
533 `, structName, msgName)
536 // generateCrcGetter generates getter for CRC checksum of the message definition into the provider writer
537 func generateCrcGetter(w io.Writer, structName, crc string) {
538 crc = strings.TrimPrefix(crc, "0x")
539 fmt.Fprintf(w, `func (*%s) GetCrcString() string {
545 // generateMessageTypeGetter generates message factory for the generated message into the provider writer
546 func generateMessageTypeGetter(w io.Writer, structName string, msgType MessageType) {
547 fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
548 if msgType == requestMessage {
549 fmt.Fprintln(w, "\treturn api.RequestMessage")
550 } else if msgType == replyMessage {
551 fmt.Fprintln(w, "\treturn api.ReplyMessage")
552 } else if msgType == eventMessage {
553 fmt.Fprintln(w, "\treturn api.EventMessage")
555 fmt.Fprintln(w, "\treturn api.OtherMessage")
560 // generateMessageFactory generates message factory for the generated message into the provider writer
561 func generateMessageFactory(w io.Writer, structName string) {
562 fmt.Fprintln(w, "func New"+structName+"() api.Message {")
563 fmt.Fprintln(w, "\treturn &"+structName+"{}")