6 from io import StringIO
8 datestring = datetime.datetime.utcfromtimestamp(
9 int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))
10 input_filename = 'inputfil'
11 top_boilerplate = '''\
13 * VLIB API definitions {datestring}
14 * Input file: {input_filename}
15 * Automatically generated: please edit the input file NOT this file!
19 #if defined(vl_msg_id)||defined(vl_union_id) \\
20 || defined(vl_printfun) ||defined(vl_endianfun) \\
21 || defined(vl_api_version)||defined(vl_typedefs) \\
22 || defined(vl_msg_name)||defined(vl_msg_name_crc_list) \\
23 || defined(vl_api_version_tuple)
24 /* ok, something was selected */
26 #warning no content included from {input_filename}
29 #define VL_API_PACKED(x) x __attribute__ ((packed))
32 bottom_boilerplate = '''\
33 /****** API CRC (whole file) *****/
36 vl_api_version({input_filename}, {file_crc:#08x})
45 /****** Message ID / handler enum ******/
51 output += "vl_msg_id(VL_API_%s, vl_api_%s_t_handler)\n" % \
52 (t.name.upper(), t.name)
61 /****** Message names ******/
67 dont_trace = 0 if t.dont_trace else 1
68 output += "vl_msg_name(vl_api_%s_t, %d)\n" % (t.name, dont_trace)
74 def msg_name_crc_list(s, suffix):
77 /****** Message name, crc list ******/
79 #ifdef vl_msg_name_crc_list
81 output += "#define foreach_vl_msg_name_crc_%s " % suffix
84 output += "\\\n_(VL_API_%s, %s, %08x) " % \
85 (t.name.upper(), t.name, t.crc)
92 mappingtable = {'string': 'vl_api_string_t', }
93 if fieldtype in mappingtable:
94 return mappingtable[fieldtype]
98 def typedefs(objs, filename):
99 name = filename.replace('.', '_')
103 /****** Typedefs ******/
106 #ifndef included_{module}_typedef
107 #define included_{module}_typedef
109 output = output.format(module=name)
112 tname = o.__class__.__name__
114 if 'length' in o.alias:
115 output += 'typedef %s vl_api_%s_t[%s];\n' % (o.alias['type'], o.name, o.alias['length'])
117 output += 'typedef %s vl_api_%s_t;\n' % (o.alias['type'], o.name)
118 elif tname == 'Enum':
119 if o.enumtype == 'u32':
120 output += "typedef enum {\n"
122 output += "typedef enum __attribute__((__packed__)) {\n"
125 output += " %s = %s,\n" % (b[0], b[1])
126 output += '} vl_api_%s_t;\n' % o.name
127 if o.enumtype != 'u32':
128 size1 = 'sizeof(vl_api_%s_t)' % o.name
129 size2 = 'sizeof(%s)' % o.enumtype
130 err_str = 'size of API enum %s is wrong' % o.name
131 output += ('STATIC_ASSERT(%s == %s, "%s");\n'
132 % (size1, size2, err_str))
135 output += "typedef VL_API_PACKED(union _vl_api_%s {\n" % o.name
137 output += ("typedef VL_API_PACKED(struct _vl_api_%s {\n"
140 if b.type == 'Option':
142 if b.type == 'Field':
143 output += " %s %s;\n" % (api2c(b.fieldtype),
145 elif b.type == 'Array':
147 output += " %s %s[0];\n" % (api2c(b.fieldtype),
150 # Fixed length strings decay to nul terminated u8
151 if b.fieldtype == 'string':
153 output += (' {} {};\n'
154 .format(api2c(b.fieldtype),
157 output += (' u8 {}[{}];\n'
158 .format(b.fieldname, b.length))
160 output += (" %s %s[%s];\n" %
161 (api2c(b.fieldtype), b.fieldname,
164 raise ValueError("Error in processing type {} for {}"
167 output += '}) vl_api_%s_t;\n' % o.name
170 output += "\n#endif\n\n"
175 format_strings = {'u8': '%u',
186 noprint_fields = {'_vl_msg_id': None,
187 'client_index': None,
194 def __init__(self, stream):
197 def print_string(self, o, stream):
200 write(' if (vl_api_string_len(&a->{f}) > 0) {{\n'
201 .format(f=o.fieldname))
202 write(' s = format(s, "\\n%U{f}: %.*s", '
203 'format_white_space, indent, '
204 'vl_api_string_len(&a->{f}) - 1, '
205 'vl_api_from_api_string(&a->{f}));\n'.format(f=o.fieldname))
207 write(' s = format(s, "\\n%U{f}:", '
208 'format_white_space, indent);\n'.format(f=o.fieldname))
211 write(' s = format(s, "\\n%U{f}: %s", '
212 'format_white_space, indent, a->{f});\n'
213 .format(f=o.fieldname))
215 def print_field(self, o, stream):
217 if o.fieldname in noprint_fields:
219 if o.fieldtype in format_strings:
220 f = format_strings[o.fieldtype]
221 write(' s = format(s, "\\n%U{n}: {f}", '
222 'format_white_space, indent, a->{n});\n'
223 .format(n=o.fieldname, f=f))
225 write(' s = format(s, "\\n%U{n}: %U", '
226 'format_white_space, indent, '
227 'format_{t}, &a->{n}, indent);\n'
228 .format(n=o.fieldname, t=o.fieldtype))
230 _dispatch['Field'] = print_field
232 def print_array(self, o, stream):
236 for (i = 0; i < {lfield}; i++) {{
237 s = format(s, "\\n%U{n}: %U",
238 format_white_space, indent, format_{t}, &a->{n}[i], indent);
242 forloop_format = '''\
243 for (i = 0; i < {lfield}; i++) {{
244 s = format(s, "\\n%U{n}: {t}",
245 format_white_space, indent, a->{n}[i]);
249 if o.fieldtype == 'string':
250 return self.print_string(o, stream)
252 if o.fieldtype == 'u8':
254 write(' s = format(s, "\\n%U{n}: %U", format_white_space, '
255 'indent, format_hex_bytes, a->{n}, a->{lfield});\n'
256 .format(n=o.fieldname, lfield=o.lengthfield))
258 write(' s = format(s, "\\n%U{n}: %U", format_white_space, '
259 'indent, format_hex_bytes, a, {lfield});\n'
260 .format(n=o.fieldname, lfield=o.length))
263 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
264 if o.fieldtype in format_strings:
265 write(forloop_format.format(lfield=lfield,
266 t=format_strings[o.fieldtype],
269 write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname))
271 _dispatch['Array'] = print_array
273 def print_alias(self, k, v, stream):
275 if ('length' in v.alias and v.alias['length'] and
276 v.alias['type'] == 'u8'):
277 write(' return format(s, "%U", format_hex_bytes, a, {});\n'
278 .format(v.alias['length']))
279 elif v.alias['type'] in format_strings:
280 write(' return format(s, "{}", *a);\n'
281 .format(format_strings[v.alias['type']]))
283 write(' return format(s, "{} (print not implemented)");\n'
286 def print_enum(self, o, stream):
288 write(" switch(*a) {\n")
290 write(" case %s:\n" % b[1])
291 write(' return format(s, "{}");\n'.format(b[0]))
294 _dispatch['Enum'] = print_enum
296 def print_obj(self, o, stream):
299 if o.type in self._dispatch:
300 self._dispatch[o.type](self, o, stream)
302 write(' s = format(s, "\\n{} {} {} (print not implemented");\n'
303 .format(o.type, o.fieldtype, o.fieldname))
306 def printfun(objs, stream, modulename):
310 /****** Print functions *****/
312 #ifndef included_{module}_printfun
313 #define included_{module}_printfun
316 #define _uword_fmt \"%lld\"
317 #define _uword_cast (long long)
319 #define _uword_fmt \"%ld\"
320 #define _uword_cast long
326 static inline void *vl_api_{name}_t_print (vl_api_{name}_t *a, void *handle)
329 u32 indent __attribute__((unused)) = 2;
330 int i __attribute__((unused));
333 h = h.format(module=modulename)
336 pp = Printfun(stream)
339 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
341 write(signature.format(name=t.name))
342 write(' /* Message definition: vl_api_{}_t: */\n'.format(t.name))
343 write(" s = format(s, \"vl_api_%s_t:\");\n" % t.name)
345 pp.print_obj(o, stream)
346 write(' vec_add1(s, 0);\n')
347 write(' vl_print (handle, (char *)s);\n')
348 write(' vec_free (s);\n')
349 write(' return handle;\n')
353 write("\n#endif /* vl_printfun */\n")
358 def printfun_types(objs, stream, modulename):
360 pp = Printfun(stream)
363 /****** Print functions *****/
365 #ifndef included_{module}_printfun_types
366 #define included_{module}_printfun_types
369 h = h.format(module=modulename)
373 static inline u8 *format_vl_api_{name}_t (u8 *s, va_list * args)
375 vl_api_{name}_t *a = va_arg (*args, vl_api_{name}_t *);
376 u32 indent __attribute__((unused)) = va_arg (*args, u32);
377 int i __attribute__((unused));
382 if t.__class__.__name__ == 'Enum':
383 write(signature.format(name=t.name))
384 pp.print_enum(t.block, stream)
385 write(' return s;\n')
390 write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
393 if t.__class__.__name__ == 'Using':
394 write(signature.format(name=t.name))
395 pp.print_alias(t.name, t, stream)
399 write(signature.format(name=t.name))
401 pp.print_obj(o, stream)
403 write(' return s;\n')
407 write("\n#endif /* vl_printfun_types */\n")
410 def imports(imports):
411 output = '/* Imported API files */\n'
412 output += '#ifndef vl_api_version\n'
415 s = i.filename.replace('plugins/', '')
416 output += '#include <{}.h>\n'.format(s)
422 'u16': 'clib_net_to_host_u16',
423 'u32': 'clib_net_to_host_u32',
424 'u64': 'clib_net_to_host_u64',
425 'i16': 'clib_net_to_host_u16',
426 'i32': 'clib_net_to_host_u32',
427 'i64': 'clib_net_to_host_u64',
428 'f64': 'clib_net_to_host_u64',
432 def endianfun_array(o):
434 for (i = 0; i < {length}; i++) {{
435 a->{name}[i] = {format}(a->{name}[i]);
439 forloop_format = '''\
440 for (i = 0; i < {length}; i++) {{
441 {type}_endian(&a->{name}[i]);
446 if o.fieldtype == 'u8' or o.fieldtype == 'string':
447 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
449 lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
450 if o.fieldtype in endian_strings:
452 .format(length=lfield,
453 format=endian_strings[o.fieldtype],
456 output += (forloop_format
457 .format(length=lfield, type=o.fieldtype,
462 def endianfun_obj(o):
464 if o.type == 'Array':
465 return endianfun_array(o)
466 elif o.type != 'Field':
467 output += (' s = format(s, "\\n{} {} {} (print not implemented");\n'
468 .format(o.type, o.fieldtype, o.fieldname))
470 if o.fieldtype in endian_strings:
471 output += (' a->{name} = {format}(a->{name});\n'
472 .format(name=o.fieldname,
473 format=endian_strings[o.fieldtype]))
474 elif o.fieldtype.startswith('vl_api_'):
475 output += (' {type}_endian(&a->{name});\n'
476 .format(type=o.fieldtype, name=o.fieldname))
478 output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
483 def endianfun(objs, modulename):
486 /****** Endian swap functions *****/\n\
488 #ifndef included_{module}_endianfun
489 #define included_{module}_endianfun
491 #undef clib_net_to_host_uword
493 #define clib_net_to_host_uword clib_net_to_host_u64
495 #define clib_net_to_host_uword clib_net_to_host_u32
499 output = output.format(module=modulename)
502 static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
504 int i __attribute__((unused));
508 if t.__class__.__name__ == 'Enum':
509 output += signature.format(name=t.name)
510 if t.enumtype in endian_strings:
511 output += (' *a = {}(*a);\n'
512 .format(endian_strings[t.enumtype]))
514 output += (' /* a->{name} = a->{name} (no-op) */\n'
515 .format(name=t.name))
521 output += "/***** manual: vl_api_%s_t_endian *****/\n\n" % t.name
525 if t.__class__.__name__ == 'Using':
526 output += signature.format(name=t.name)
527 if ('length' in t.alias and t.alias['length'] and
528 t.alias['type'] == 'u8'):
529 output += (' /* a->{name} = a->{name} (no-op) */\n'
530 .format(name=t.name))
531 elif t.alias['type'] in format_strings:
532 output += (' *a = {}(*a);\n'
533 .format(endian_strings[t.alias['type']]))
535 output += ' /* Not Implemented yet {} */'.format(t.name)
539 output += signature.format(name=t.name)
542 output += endianfun_obj(o)
546 output += "\n#endif /* vl_endianfun */\n\n"
551 def version_tuple(s, module):
553 /****** Version tuple *****/
555 #ifdef vl_api_version_tuple
558 if 'version' in s['Option']:
559 v = s['Option']['version']
560 (major, minor, patch) = v.split('.')
561 output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % \
562 (module, major, minor, patch)
564 output += "\n#endif /* vl_api_version_tuple */\n\n"
572 def run(input_filename, s):
574 basename = os.path.basename(input_filename)
575 filename, file_extension = os.path.splitext(basename)
576 modulename = filename.replace('.', '_')
578 output = top_boilerplate.format(datestring=datestring,
579 input_filename=basename)
580 output += imports(s['Import'])
582 output += msg_names(s)
583 output += msg_name_crc_list(s, filename)
584 output += typedefs(s['types'] + s['Define'], filename + file_extension)
585 printfun_types(s['types'], stream, modulename)
586 printfun(s['Define'], stream, modulename)
587 output += stream.getvalue()
588 output += endianfun(s['types'] + s['Define'], modulename)
589 output += version_tuple(s, basename)
590 output += bottom_boilerplate.format(input_filename=basename,
591 file_crc=s['file_crc'])