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 fmt.Fprintf(w, "type %s interface {\n", "Services")
144 ctx.inputBuff = bytes.NewBuffer(ctx.inputData)
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 _ = struc.Pack\n")
213 fmt.Fprintf(w, "var _ = bytes.NewBuffer\n")
217 // generateComment writes generated comment for the object into w
218 func generateComment(ctx *context, w io.Writer, goName string, vppName string, objKind string) {
219 fmt.Fprintf(w, "// %s represents the VPP binary API %s '%s'.\n", goName, objKind, vppName)
221 var isNotSpace = func(r rune) bool {
222 return !unicode.IsSpace(r)
225 // print out the source of the generated object
227 objTitle := fmt.Sprintf(`"%s",`, vppName)
230 line, err := ctx.inputBuff.ReadString('\n')
237 indent = strings.Index(line, objTitle)
241 // If no other non-whitespace character then we are at the message header.
242 if trimmed := strings.TrimSpace(line); trimmed == objTitle {
244 fmt.Fprintf(w, "// Generated from '%s', line %d:\n", filepath.Base(ctx.inputFile), ctx.inputLine)
245 fmt.Fprintln(w, "//")
248 if strings.IndexFunc(line, isNotSpace) < indent {
249 break // end of the object definition in JSON
252 fmt.Fprint(w, "//", line)
255 fmt.Fprintln(w, "//")
258 // generateEnum writes generated code for the enum into w
259 func generateEnum(ctx *context, w io.Writer, enum *Enum) {
260 name := camelCaseName(enum.Name)
261 typ := binapiTypes[enum.Type]
263 logf(" writing enum %q (%s) with %d entries", enum.Name, name, len(enum.Entries))
265 // generate enum comment
266 generateComment(ctx, w, name, enum.Name, "enum")
268 // generate enum definition
269 fmt.Fprintf(w, "type %s %s\n", name, typ)
272 fmt.Fprintln(w, "const (")
274 // generate enum entries
275 for _, entry := range enum.Entries {
276 fmt.Fprintf(w, "\t%s %s = %v\n", entry.Name, name, entry.Value)
284 // generateType writes generated code for the type into w
285 func generateType(ctx *context, w io.Writer, typ *Type) {
286 name := camelCaseName(typ.Name)
288 logf(" writing type %q (%s) with %d fields", typ.Name, name, len(typ.Fields))
290 // generate struct comment
291 generateComment(ctx, w, name, typ.Name, "type")
293 // generate struct definition
294 fmt.Fprintf(w, "type %s struct {\n", name)
296 // generate struct fields
297 for i, field := range typ.Fields {
298 // skip internal fields
299 switch strings.ToLower(field.Name) {
300 case "crc", "_vl_msg_id":
304 generateField(ctx, w, typ.Fields, i)
307 // generate end of the struct
310 // generate name getter
311 generateTypeNameGetter(w, name, typ.Name)
313 // generate CRC getter
314 generateCrcGetter(w, name, typ.CRC)
319 // generateUnion writes generated code for the union into w
320 func generateUnion(ctx *context, w io.Writer, union *Union) {
321 name := camelCaseName(union.Name)
323 logf(" writing union %q (%s) with %d fields", union.Name, name, len(union.Fields))
325 // generate struct comment
326 generateComment(ctx, w, name, union.Name, "union")
328 // generate struct definition
329 fmt.Fprintln(w, "type", name, "struct {")
331 // maximum size for union
332 maxSize := getUnionSize(ctx, union)
334 // generate data field
335 fieldName := "Union_data"
336 fmt.Fprintf(w, "\t%s [%d]byte\n", fieldName, maxSize)
338 // generate end of the struct
341 // generate name getter
342 generateTypeNameGetter(w, name, union.Name)
344 // generate CRC getter
345 generateCrcGetter(w, name, union.CRC)
347 // generate getters for fields
348 for _, field := range union.Fields {
349 fieldName := camelCaseName(field.Name)
350 fieldType := convertToGoType(ctx, field.Type)
351 generateUnionGetterSetter(w, name, fieldName, fieldType)
354 // generate union methods
355 //generateUnionMethods(w, name)
360 // generateUnionMethods generates methods that implement struc.Custom
361 // interface to allow having Union_data field unexported
362 // TODO: do more testing when unions are actually used in some messages
363 func generateUnionMethods(w io.Writer, structName string) {
364 // generate struc.Custom implementation for union
366 func (u *%[1]s) Pack(p []byte, opt *struc.Options) (int, error) {
367 var b = new(bytes.Buffer)
368 if err := struc.PackWithOptions(b, u.union_data, opt); err != nil {
374 func (u *%[1]s) Unpack(r io.Reader, length int, opt *struc.Options) error {
375 return struc.UnpackWithOptions(r, u.union_data[:], opt)
377 func (u *%[1]s) Size(opt *struc.Options) int {
378 return len(u.union_data)
380 func (u *%[1]s) String() string {
381 return string(u.union_data[:])
386 func generateUnionGetterSetter(w io.Writer, structName string, getterField, getterStruct string) {
388 func (u *%[1]s) Set%[2]s(a %[3]s) {
389 var b = new(bytes.Buffer)
390 if err := struc.Pack(b, &a); err != nil {
393 copy(u.Union_data[:], b.Bytes())
395 func (u *%[1]s) Get%[2]s() (a %[3]s) {
396 var b = bytes.NewReader(u.Union_data[:])
400 `, structName, getterField, getterStruct)
403 // generateMessage writes generated code for the message into w
404 func generateMessage(ctx *context, w io.Writer, msg *Message) {
405 name := camelCaseName(msg.Name)
407 logf(" writing message %q (%s) with %d fields", msg.Name, name, len(msg.Fields))
409 // generate struct comment
410 generateComment(ctx, w, name, msg.Name, "message")
412 // generate struct definition
413 fmt.Fprintf(w, "type %s struct {", name)
415 msgType := otherMessage
416 wasClientIndex := false
418 // generate struct fields
420 for i, field := range msg.Fields {
422 if field.Name == "client_index" {
423 // "client_index" as the second member, this might be an event message or a request
424 msgType = eventMessage
425 wasClientIndex = true
426 } else if field.Name == "context" {
427 // reply needs "context" as the second member
428 msgType = replyMessage
431 if wasClientIndex && field.Name == "context" {
432 // request needs "client_index" as the second member and "context" as the third member
433 msgType = requestMessage
437 // skip internal fields
438 switch strings.ToLower(field.Name) {
439 case "crc", "_vl_msg_id":
441 case "client_index", "context":
451 generateField(ctx, w, msg.Fields, i)
454 // generate end of the struct
457 // generate name getter
458 generateMessageNameGetter(w, name, msg.Name)
460 // generate CRC getter
461 generateCrcGetter(w, name, msg.CRC)
463 // generate message type getter method
464 generateMessageTypeGetter(w, name, msgType)
466 // generate message factory
467 generateMessageFactory(w, name)
470 // generateField writes generated code for the field into w
471 func generateField(ctx *context, w io.Writer, fields []Field, i int) {
474 fieldName := strings.TrimPrefix(field.Name, "_")
475 fieldName = camelCaseName(fieldName)
477 dataType := convertToGoType(ctx, field.Type)
479 fieldType := dataType
481 if dataType == "uint8" {
484 fieldType = "[]" + dataType
486 fmt.Fprintf(w, "\t%s %s", fieldName, fieldType)
488 if field.Length > 0 {
490 fmt.Fprintf(w, "\t`struc:\"[%d]%s\"`", field.Length, dataType)
492 for _, f := range fields {
493 if f.SizeFrom == field.Name {
494 // variable sized array
495 sizeOfName := camelCaseName(f.Name)
496 fmt.Fprintf(w, "\t`struc:\"sizeof=%s\"`", sizeOfName)
504 // generateService writes generated code for the service into w
505 func generateService(ctx *context, w io.Writer, svc *Service) {
506 reqTyp := camelCaseName(svc.RequestType)
508 // method name is same as parameter type name by default
509 method := svc.MethodName()
510 params := fmt.Sprintf("*%s", reqTyp)
512 if replyTyp := camelCaseName(svc.ReplyType); replyTyp != "" {
513 returns = fmt.Sprintf("(*%s, error)", replyTyp)
516 fmt.Fprintf(w, "\t%s(%s) %s\n", method, params, returns)
519 // generateMessageNameGetter generates getter for original VPP message name into the provider writer
520 func generateMessageNameGetter(w io.Writer, structName, msgName string) {
521 fmt.Fprintf(w, `func (*%s) GetMessageName() string {
524 `, structName, msgName)
527 // generateTypeNameGetter generates getter for original VPP type name into the provider writer
528 func generateTypeNameGetter(w io.Writer, structName, msgName string) {
529 fmt.Fprintf(w, `func (*%s) GetTypeName() string {
532 `, structName, msgName)
535 // generateCrcGetter generates getter for CRC checksum of the message definition into the provider writer
536 func generateCrcGetter(w io.Writer, structName, crc string) {
537 crc = strings.TrimPrefix(crc, "0x")
538 fmt.Fprintf(w, `func (*%s) GetCrcString() string {
544 // generateMessageTypeGetter generates message factory for the generated message into the provider writer
545 func generateMessageTypeGetter(w io.Writer, structName string, msgType MessageType) {
546 fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
547 if msgType == requestMessage {
548 fmt.Fprintln(w, "\treturn api.RequestMessage")
549 } else if msgType == replyMessage {
550 fmt.Fprintln(w, "\treturn api.ReplyMessage")
551 } else if msgType == eventMessage {
552 fmt.Fprintln(w, "\treturn api.EventMessage")
554 fmt.Fprintln(w, "\treturn api.OtherMessage")
559 // generateMessageFactory generates message factory for the generated message into the provider writer
560 func generateMessageFactory(w io.Writer, structName string) {
561 fmt.Fprintln(w, "func New"+structName+"() api.Message {")
562 fmt.Fprintln(w, "\treturn &"+structName+"{}")