vppapigen: move import processing logic to individual plugins
[vpp.git] / src / tools / vppapigen / vppapigen_c.py
1 # C generation
2 import datetime
3 import os
4 import time
5 import sys
6 from io import StringIO
7 import shutil
8
9 process_imports = False
10
11 datestring = datetime.datetime.utcfromtimestamp(
12     int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))
13 input_filename = 'inputfil'
14 top_boilerplate = '''\
15 /*
16  * VLIB API definitions {datestring}
17  * Input file: {input_filename}
18  * Automatically generated: please edit the input file NOT this file!
19  */
20
21 #include <stdbool.h>
22 #if defined(vl_msg_id)||defined(vl_union_id) \\
23     || defined(vl_printfun) ||defined(vl_endianfun) \\
24     || defined(vl_api_version)||defined(vl_typedefs) \\
25     || defined(vl_msg_name)||defined(vl_msg_name_crc_list) \\
26     || defined(vl_api_version_tuple)
27 /* ok, something was selected */
28 #else
29 #warning no content included from {input_filename}
30 #endif
31
32 #define VL_API_PACKED(x) x __attribute__ ((packed))
33 '''
34
35 bottom_boilerplate = '''\
36 /****** API CRC (whole file) *****/
37
38 #ifdef vl_api_version
39 vl_api_version({input_filename}, {file_crc:#08x})
40
41 #endif
42 '''
43
44
45 def msg_ids(s):
46     output = '''\
47
48 /****** Message ID / handler enum ******/
49
50 #ifdef vl_msg_id
51 '''
52
53     for t in s['Define']:
54         output += "vl_msg_id(VL_API_%s, vl_api_%s_t_handler)\n" % \
55                   (t.name.upper(), t.name)
56     output += "#endif"
57
58     return output
59
60
61 def msg_names(s):
62     output = '''\
63
64 /****** Message names ******/
65
66 #ifdef vl_msg_name
67 '''
68
69     for t in s['Define']:
70         dont_trace = 0 if t.dont_trace else 1
71         output += "vl_msg_name(vl_api_%s_t, %d)\n" % (t.name, dont_trace)
72     output += "#endif"
73
74     return output
75
76
77 def msg_name_crc_list(s, suffix):
78     output = '''\
79
80 /****** Message name, crc list ******/
81
82 #ifdef vl_msg_name_crc_list
83 '''
84     output += "#define foreach_vl_msg_name_crc_%s " % suffix
85
86     for t in s['Define']:
87         output += "\\\n_(VL_API_%s, %s, %08x) " % \
88                    (t.name.upper(), t.name, t.crc)
89     output += "\n#endif"
90
91     return output
92
93
94 def api2c(fieldtype):
95     mappingtable = {'string': 'vl_api_string_t', }
96     if fieldtype in mappingtable:
97         return mappingtable[fieldtype]
98     return fieldtype
99
100
101 def typedefs(filename):
102
103     output = '''\
104
105 /****** Typedefs ******/
106
107 #ifdef vl_typedefs
108 #include "{include}.api_types.h"
109 #endif
110 '''.format(include=filename)
111     return output
112
113
114 format_strings = {'u8': '%u',
115                   'bool': '%u',
116                   'i8': '%d',
117                   'u16': '%u',
118                   'i16': '%d',
119                   'u32': '%u',
120                   'i32': '%ld',
121                   'u64': '%llu',
122                   'i64': '%lld',
123                   'f64': '%.2f'}
124
125 noprint_fields = {'_vl_msg_id': None,
126                   'client_index': None,
127                   'context': None}
128
129
130 class Printfun():
131     _dispatch = {}
132
133     def __init__(self, stream):
134         self.stream = stream
135
136     def print_string(self, o, stream):
137         write = stream.write
138         if o.modern_vla:
139             write('    if (vl_api_string_len(&a->{f}) > 0) {{\n'
140                   .format(f=o.fieldname))
141             write('        s = format(s, "\\n%U{f}: %U", '
142                   'format_white_space, indent, '
143                   'vl_api_format_string, (&a->{f}));\n'.format(f=o.fieldname))
144             write('    } else {\n')
145             write('        s = format(s, "\\n%U{f}:", '
146                   'format_white_space, indent);\n'.format(f=o.fieldname))
147             write('    }\n')
148         else:
149             write('    s = format(s, "\\n%U{f}: %s", '
150                   'format_white_space, indent, a->{f});\n'
151                   .format(f=o.fieldname))
152
153     def print_field(self, o, stream):
154         write = stream.write
155         if o.fieldname in noprint_fields:
156             return
157         if o.fieldtype in format_strings:
158             f = format_strings[o.fieldtype]
159             write('    s = format(s, "\\n%U{n}: {f}", '
160                   'format_white_space, indent, a->{n});\n'
161                   .format(n=o.fieldname, f=f))
162         else:
163             write('    s = format(s, "\\n%U{n}: %U", '
164                   'format_white_space, indent, '
165                   'format_{t}, &a->{n}, indent);\n'
166                   .format(n=o.fieldname, t=o.fieldtype))
167
168     _dispatch['Field'] = print_field
169
170     def print_array(self, o, stream):
171         write = stream.write
172
173         forloop = '''\
174     for (i = 0; i < {lfield}; i++) {{
175         s = format(s, "\\n%U{n}: %U",
176                    format_white_space, indent, format_{t}, &a->{n}[i], indent);
177     }}
178 '''
179
180         forloop_format = '''\
181     for (i = 0; i < {lfield}; i++) {{
182         s = format(s, "\\n%U{n}: {t}",
183                    format_white_space, indent, a->{n}[i]);
184     }}
185 '''
186
187         if o.fieldtype == 'string':
188             return self.print_string(o, stream)
189
190         if o.fieldtype == 'u8':
191             if o.lengthfield:
192                 write('    s = format(s, "\\n%U{n}: %U", format_white_space, '
193                       'indent, format_hex_bytes, a->{n}, a->{lfield});\n'
194                       .format(n=o.fieldname, lfield=o.lengthfield))
195             else:
196                 write('    s = format(s, "\\n%U{n}: %U", format_white_space, '
197                       'indent, format_hex_bytes, a, {lfield});\n'
198                       .format(n=o.fieldname, lfield=o.length))
199             return
200
201         lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
202         if o.fieldtype in format_strings:
203             write(forloop_format.format(lfield=lfield,
204                                         t=format_strings[o.fieldtype],
205                                         n=o.fieldname))
206         else:
207             write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname))
208
209     _dispatch['Array'] = print_array
210
211     def print_alias(self, k, v, stream):
212         write = stream.write
213         if ('length' in v.alias and v.alias['length'] and
214                 v.alias['type'] == 'u8'):
215             write('    return format(s, "%U", format_hex_bytes, a, {});\n'
216                   .format(v.alias['length']))
217         elif v.alias['type'] in format_strings:
218             write('    return format(s, "{}", *a);\n'
219                   .format(format_strings[v.alias['type']]))
220         else:
221             write('    return format(s, "{} (print not implemented)");\n'
222                   .format(k))
223
224     def print_enum(self, o, stream):
225         write = stream.write
226         write("    switch(*a) {\n")
227         for b in o:
228             write("    case %s:\n" % b[1])
229             write('        return format(s, "{}");\n'.format(b[0]))
230         write('    }\n')
231
232     _dispatch['Enum'] = print_enum
233
234     def print_obj(self, o, stream):
235         write = stream.write
236
237         if o.type in self._dispatch:
238             self._dispatch[o.type](self, o, stream)
239         else:
240             write('    s = format(s, "\\n{} {} {} (print not implemented");\n'
241                   .format(o.type, o.fieldtype, o.fieldname))
242
243
244 def printfun(objs, stream, modulename):
245     write = stream.write
246
247     h = '''\
248 /****** Print functions *****/
249 #ifdef vl_printfun
250 #ifndef included_{module}_printfun
251 #define included_{module}_printfun
252
253 #ifdef LP64
254 #define _uword_fmt \"%lld\"
255 #define _uword_cast (long long)
256 #else
257 #define _uword_fmt \"%ld\"
258 #define _uword_cast long
259 #endif
260
261 '''
262
263     signature = '''\
264 static inline void *vl_api_{name}_t_print (vl_api_{name}_t *a, void *handle)
265 {{
266     u8 *s = 0;
267     u32 indent __attribute__((unused)) = 2;
268     int i __attribute__((unused));
269 '''
270
271     h = h.format(module=modulename)
272     write(h)
273
274     pp = Printfun(stream)
275     for t in objs:
276         if t.manual_print:
277             write("/***** manual: vl_api_%s_t_print  *****/\n\n" % t.name)
278             continue
279         write(signature.format(name=t.name))
280         write('    /* Message definition: vl_api_{}_t: */\n'.format(t.name))
281         write("    s = format(s, \"vl_api_%s_t:\");\n" % t.name)
282         for o in t.block:
283             pp.print_obj(o, stream)
284         write('    vec_add1(s, 0);\n')
285         write('    vl_print (handle, (char *)s);\n')
286         write('    vec_free (s);\n')
287         write('    return handle;\n')
288         write('}\n\n')
289
290     write("\n#endif")
291     write("\n#endif /* vl_printfun */\n")
292
293     return ''
294
295
296 def printfun_types(objs, stream, modulename):
297     write = stream.write
298     pp = Printfun(stream)
299
300     h = '''\
301 /****** Print functions *****/
302 #ifdef vl_printfun
303 #ifndef included_{module}_printfun_types
304 #define included_{module}_printfun_types
305
306 '''
307     h = h.format(module=modulename)
308     write(h)
309
310     signature = '''\
311 static inline u8 *format_vl_api_{name}_t (u8 *s, va_list * args)
312 {{
313     vl_api_{name}_t *a = va_arg (*args, vl_api_{name}_t *);
314     u32 indent __attribute__((unused)) = va_arg (*args, u32);
315     int i __attribute__((unused));
316     indent += 2;
317 '''
318
319     for t in objs:
320         if t.__class__.__name__ == 'Enum':
321             write(signature.format(name=t.name))
322             pp.print_enum(t.block, stream)
323             write('    return s;\n')
324             write('}\n\n')
325             continue
326
327         if t.manual_print:
328             write("/***** manual: vl_api_%s_t_print  *****/\n\n" % t.name)
329             continue
330
331         if t.__class__.__name__ == 'Using':
332             write(signature.format(name=t.name))
333             pp.print_alias(t.name, t, stream)
334             write('}\n\n')
335             continue
336
337         write(signature.format(name=t.name))
338         for o in t.block:
339             pp.print_obj(o, stream)
340
341         write('    return s;\n')
342         write('}\n\n')
343
344     write("\n#endif")
345     write("\n#endif /* vl_printfun_types */\n")
346
347
348 def imports(imports):
349     output = '/* Imported API files */\n'
350     output += '#ifndef vl_api_version\n'
351
352     for i in imports:
353         s = i.filename.replace('plugins/', '')
354         output += '#include <{}.h>\n'.format(s)
355     output += '#endif\n'
356     return output
357
358
359 endian_strings = {
360     'u16': 'clib_net_to_host_u16',
361     'u32': 'clib_net_to_host_u32',
362     'u64': 'clib_net_to_host_u64',
363     'i16': 'clib_net_to_host_i16',
364     'i32': 'clib_net_to_host_i32',
365     'i64': 'clib_net_to_host_i64',
366     'f64': 'clib_net_to_host_f64',
367 }
368
369
370 def endianfun_array(o):
371     forloop = '''\
372     for (i = 0; i < {length}; i++) {{
373         a->{name}[i] = {format}(a->{name}[i]);
374     }}
375 '''
376
377     forloop_format = '''\
378     for (i = 0; i < {length}; i++) {{
379         {type}_endian(&a->{name}[i]);
380     }}
381 '''
382
383     output = ''
384     if o.fieldtype == 'u8' or o.fieldtype == 'string':
385         output += '    /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
386     else:
387         lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
388         if o.fieldtype in endian_strings:
389             output += (forloop
390                        .format(length=lfield,
391                                format=endian_strings[o.fieldtype],
392                                name=o.fieldname))
393         else:
394             output += (forloop_format
395                        .format(length=lfield, type=o.fieldtype,
396                                name=o.fieldname))
397     return output
398
399 no_endian_conversion = {'client_index': None}
400
401 def endianfun_obj(o):
402     output = ''
403     if o.type == 'Array':
404         return endianfun_array(o)
405     elif o.type != 'Field':
406         output += ('    s = format(s, "\\n{} {} {} (print not implemented");\n'
407                    .format(o.type, o.fieldtype, o.fieldname))
408         return output
409     if o.fieldname in no_endian_conversion:
410         output += '    /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
411         return output
412     if o.fieldtype in endian_strings:
413         output += ('    a->{name} = {format}(a->{name});\n'
414                    .format(name=o.fieldname,
415                            format=endian_strings[o.fieldtype]))
416     elif o.fieldtype.startswith('vl_api_'):
417         output += ('    {type}_endian(&a->{name});\n'
418                    .format(type=o.fieldtype, name=o.fieldname))
419     else:
420         output += '    /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
421
422     return output
423
424
425 def endianfun(objs, modulename):
426     output = '''\
427
428 /****** Endian swap functions *****/\n\
429 #ifdef vl_endianfun
430 #ifndef included_{module}_endianfun
431 #define included_{module}_endianfun
432
433 #undef clib_net_to_host_uword
434 #ifdef LP64
435 #define clib_net_to_host_uword clib_net_to_host_u64
436 #else
437 #define clib_net_to_host_uword clib_net_to_host_u32
438 #endif
439
440 '''
441     output = output.format(module=modulename)
442
443     signature = '''\
444 static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
445 {{
446     int i __attribute__((unused));
447 '''
448
449     for t in objs:
450         if t.__class__.__name__ == 'Enum':
451             output += signature.format(name=t.name)
452             if t.enumtype in endian_strings:
453                 output += ('    *a = {}(*a);\n'
454                            .format(endian_strings[t.enumtype]))
455             else:
456                 output += ('    /* a->{name} = a->{name} (no-op) */\n'
457                            .format(name=t.name))
458
459             output += '}\n\n'
460             continue
461
462         if t.manual_endian:
463             output += "/***** manual: vl_api_%s_t_endian  *****/\n\n" % t.name
464             continue
465
466         if t.__class__.__name__ == 'Using':
467             output += signature.format(name=t.name)
468             if ('length' in t.alias and t.alias['length'] and
469                     t.alias['type'] == 'u8'):
470                 output += ('    /* a->{name} = a->{name} (no-op) */\n'
471                            .format(name=t.name))
472             elif t.alias['type'] in format_strings:
473                 output += ('    *a = {}(*a);\n'
474                            .format(endian_strings[t.alias['type']]))
475             else:
476                 output += '    /* Not Implemented yet {} */'.format(t.name)
477             output += '}\n\n'
478             continue
479
480         output += signature.format(name=t.name)
481
482         for o in t.block:
483             output += endianfun_obj(o)
484         output += '}\n\n'
485
486     output += "\n#endif"
487     output += "\n#endif /* vl_endianfun */\n\n"
488
489     return output
490
491
492 def version_tuple(s, module):
493     output = '''\
494 /****** Version tuple *****/
495
496 #ifdef vl_api_version_tuple
497
498 '''
499     if 'version' in s['Option']:
500         v = s['Option']['version']
501         (major, minor, patch) = v.split('.')
502         output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % \
503                   (module, major, minor, patch)
504
505     output += "\n#endif /* vl_api_version_tuple */\n\n"
506
507     return output
508
509
510 def generate_include_enum(s, module, stream):
511     write = stream.write
512
513     if len(s['Define']):
514         write('typedef enum {\n')
515         for t in s['Define']:
516             write('   VL_API_{},\n'.format(t.name.upper()))
517         write('   VL_MSG_{}_LAST\n'.format(module.upper()))
518         write('}} vl_api_{}_enum_t;\n'.format(module))
519
520
521 def generate_include_counters(s, module, stream):
522     write = stream.write
523
524     for counters in s:
525         csetname = counters.name
526         write('typedef enum {\n')
527         for c in counters.block:
528             write('   {}_ERROR_{},\n'
529                   .format(csetname.upper(), c['name'].upper()))
530         write('   {}_N_ERROR\n'.format(csetname.upper()))
531         write('}} vl_counter_{}_enum_t;\n'.format(csetname))
532
533         # write('extern char *{}_error_strings[];\n'.format(csetname))
534         # write('extern char *{}_description_strings[];\n'.format(csetname))
535         write('extern vl_counter_t {}_error_counters[];\n'.format(csetname))
536
537 #
538 # Generate separate API _types file.
539 #
540 def generate_include_types(s, module, stream):
541     write = stream.write
542
543     write('#ifndef included_{module}_api_types_h\n'.format(module=module))
544     write('#define included_{module}_api_types_h\n'.format(module=module))
545
546     if 'version' in s['Option']:
547         v = s['Option']['version']
548         (major, minor, patch) = v.split('.')
549         write('#define VL_API_{m}_API_VERSION_MAJOR {v}\n'.format(m=module.upper(), v=major))
550         write('#define VL_API_{m}_API_VERSION_MINOR {v}\n'.format(m=module.upper(), v=minor))
551         write('#define VL_API_{m}_API_VERSION_PATCH {v}\n'.format(m=module.upper(), v=patch))
552
553     if len(s['Import']):
554         write('/* Imported API files */\n')
555         for i in s['Import']:
556             filename = i.filename.replace('plugins/', '')
557             write('#include <{}_types.h>\n'.format(filename))
558
559     for o in s['types'] + s['Define']:
560         tname = o.__class__.__name__
561         if tname == 'Using':
562             if 'length' in o.alias:
563                 write('typedef %s vl_api_%s_t[%s];\n' % (o.alias['type'], o.name, o.alias['length']))
564             else:
565                 write('typedef %s vl_api_%s_t;\n' % (o.alias['type'], o.name))
566         elif tname == 'Enum':
567             if o.enumtype == 'u32':
568                 write("typedef enum {\n")
569             else:
570                 write("typedef enum __attribute__((packed)) {\n")
571
572             for b in o.block:
573                 write("    %s = %s,\n" % (b[0], b[1]))
574             write('} vl_api_%s_t;\n' % o.name)
575             if o.enumtype != 'u32':
576                 size1 = 'sizeof(vl_api_%s_t)' % o.name
577                 size2 = 'sizeof(%s)' % o.enumtype
578                 err_str = 'size of API enum %s is wrong' % o.name
579                 write('STATIC_ASSERT(%s == %s, "%s");\n'
580                       % (size1, size2, err_str))
581         else:
582             if tname == 'Union':
583                 write("typedef union __attribute__ ((packed)) _vl_api_%s {\n" % o.name)
584             else:
585                 write(("typedef struct __attribute__ ((packed)) _vl_api_%s {\n")
586                            % o.name)
587             for b in o.block:
588                 if b.type == 'Option':
589                     continue
590                 if b.type == 'Field':
591                       write("    %s %s;\n" % (api2c(b.fieldtype),
592                                               b.fieldname))
593                 elif b.type == 'Array':
594                     if b.lengthfield:
595                       write("    %s %s[0];\n" % (api2c(b.fieldtype),
596                                                  b.fieldname))
597                     else:
598                         # Fixed length strings decay to nul terminated u8
599                         if b.fieldtype == 'string':
600                             if b.modern_vla:
601                                 write('    {} {};\n'
602                                       .format(api2c(b.fieldtype),
603                                               b.fieldname))
604                             else:
605                                 write('    u8 {}[{}];\n'
606                                       .format(b.fieldname, b.length))
607                         else:
608                             write("    %s %s[%s];\n" %
609                                   (api2c(b.fieldtype), b.fieldname,
610                                    b.length))
611                 else:
612                     raise ValueError("Error in processing type {} for {}"
613                                      .format(b, o.name))
614
615             write('} vl_api_%s_t;\n' % o.name)
616
617     for t in s['Define']:
618         write('#define VL_API_{ID}_CRC "{n}_{crc:08x}"\n'
619               .format(n=t.name, ID=t.name.upper(), crc=t.crc))
620
621     write("\n#endif\n")
622
623
624 def generate_c_boilerplate(services, defines, counters, file_crc,
625                            module, stream):
626     write = stream.write
627     define_hash = {d.name: d for d in defines}
628
629     hdr = '''\
630 #define vl_endianfun            /* define message structures */
631 #include "{module}.api.h"
632 #undef vl_endianfun
633
634 /* instantiate all the print functions we know about */
635 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
636 #define vl_printfun
637 #include "{module}.api.h"
638 #undef vl_printfun
639
640 '''
641
642     write(hdr.format(module=module))
643     write('static u16\n')
644     write('setup_message_id_table (void) {\n')
645     write('   api_main_t *am = my_api_main;\n')
646     write('   vl_msg_api_msg_config_t c;\n')
647     write('   u16 msg_id_base = vl_msg_api_get_msg_ids ("{}_{crc:08x}", VL_MSG_{m}_LAST);\n'
648           .format(module, crc=file_crc, m=module.upper()))
649
650
651     for d in defines:
652         write('   vl_msg_api_add_msg_name_crc (am, "{n}_{crc:08x}",\n'
653               '                                VL_API_{ID} + msg_id_base);\n'
654               .format(n=d.name, ID=d.name.upper(), crc=d.crc))
655     for s in services:
656         d = define_hash[s.caller]
657         write('   c = (vl_msg_api_msg_config_t) {{.id = VL_API_{ID} + msg_id_base,\n'
658               '                                  .name = "{n}",\n'
659               '                                  .handler = vl_api_{n}_t_handler,\n'
660               '                                  .cleanup = vl_noop_handler,\n'
661               '                                  .endian = vl_api_{n}_t_endian,\n'
662               '                                  .print = vl_api_{n}_t_print,\n'
663               '                                  .is_autoendian = 0}};\n'
664               .format(n=s.caller, ID=s.caller.upper()))
665         write('   vl_msg_api_config (&c);\n')
666         try:
667             d = define_hash[s.reply]
668             write('   c = (vl_msg_api_msg_config_t) {{.id = VL_API_{ID} + msg_id_base,\n'
669                   '                                  .name = "{n}",\n'
670                   '                                  .handler = 0,\n'
671                   '                                  .cleanup = vl_noop_handler,\n'
672                   '                                  .endian = vl_api_{n}_t_endian,\n'
673                   '                                  .print = vl_api_{n}_t_print,\n'
674                   '                                  .is_autoendian = 0}};\n'
675                   .format(n=s.reply, ID=s.reply.upper()))
676             write('   vl_msg_api_config (&c);\n')
677         except KeyError:
678             pass
679
680     write('   return msg_id_base;\n')
681     write('}\n')
682
683     severity = {'error': 'VL_COUNTER_SEVERITY_ERROR',
684                 'info': 'VL_COUNTER_SEVERITY_INFO',
685                 'warn': 'VL_COUNTER_SEVERITY_WARN'}
686
687     for cnt in counters:
688         csetname = cnt.name
689         '''
690         write('char *{}_error_strings[] = {{\n'.format(csetname))
691         for c in cnt.block:
692             write('   "{}",\n'.format(c['name']))
693         write('};\n')
694         write('char *{}_description_strings[] = {{\n'.format(csetname))
695         for c in cnt.block:
696             write('   "{}",\n'.format(c['description']))
697         write('};\n')
698         '''
699         write('vl_counter_t {}_error_counters[] = {{\n'.format(csetname))
700         for c in cnt.block:
701             write('  {\n')
702             write('   .name = "{}",\n'.format(c['name']))
703             write('   .desc = "{}",\n'.format(c['description']))
704             write('   .severity = {},\n'.format(severity[c['severity']]))
705             write('  },\n')
706         write('};\n')
707
708 def generate_c_test_boilerplate(services, defines, file_crc, module, plugin, stream):
709     write = stream.write
710
711     define_hash = {d.name:d for d in defines}
712     replies = {}
713
714     hdr = '''\
715 #define vl_endianfun            /* define message structures */
716 #include "{module}.api.h"
717 #undef vl_endianfun
718
719 /* instantiate all the print functions we know about */
720 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
721 #define vl_printfun
722 #include "{module}.api.h"
723 #undef vl_printfun
724
725 '''
726
727     write(hdr.format(module=module))
728     for s in services:
729         try:
730             d = define_hash[s.reply]
731         except:
732             continue
733         if d.manual_print:
734             write('/* Manual definition requested for: vl_api_{n}_t_handler() */\n'
735                   .format(n=s.reply))
736             continue
737         if not define_hash[s.caller].autoreply:
738             write('/* Only autoreply is supported (vl_api_{n}_t_handler()) */\n'
739                   .format(n=s.reply))
740             continue
741         write('#ifndef VL_API_{n}_T_HANDLER\n'.format(n=s.reply.upper()))
742         write('static void\n')
743         write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=s.reply))
744         write('   vat_main_t * vam = {}_test_main.vat_main;\n'.format(module))
745         write('   i32 retval = ntohl(mp->retval);\n')
746         write('   if (vam->async_mode) {\n')
747         write('      vam->async_errors += (retval < 0);\n')
748         write('   } else {\n')
749         write('      vam->retval = retval;\n')
750         write('      vam->result_ready = 1;\n')
751         write('   }\n')
752         write('}\n')
753         write('#endif\n')
754
755         for e in s.events:
756             if define_hash[e].manual_print:
757                 continue
758             write('static void\n')
759             write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=e))
760             write('    vl_print(0, "{n} event called:");\n'.format(n=e))
761             write('    vl_api_{n}_t_print(mp, 0);\n'.format(n=e))
762             write('}\n')
763
764     write('static void\n')
765     write('setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n')
766     for s in services:
767         write('   vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
768               '                           vl_api_{n}_t_handler, vl_noop_handler,\n'
769               '                           vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
770               '                           sizeof(vl_api_{n}_t), 1);\n'
771               .format(n=s.reply, ID=s.reply.upper()))
772         write('   hash_set_mem (vam->function_by_name, "{n}", api_{n});\n'.format(n=s.caller))
773         try:
774             write('   hash_set_mem (vam->help_by_name, "{n}", "{help}");\n'
775                   .format(n=s.caller, help=define_hash[s.caller].options['vat_help']))
776         except:
777             pass
778
779         # Events
780         for e in s.events:
781             write('   vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "{n}",\n'
782                   '                           vl_api_{n}_t_handler, vl_noop_handler,\n'
783                   '                           vl_api_{n}_t_endian, vl_api_{n}_t_print,\n'
784                   '                           sizeof(vl_api_{n}_t), 1);\n'
785                   .format(n=e, ID=e.upper()))
786
787     write('}\n')
788     if plugin:
789         write('clib_error_t * vat_plugin_register (vat_main_t *vam)\n')
790     else:
791         write('clib_error_t * vat_{}_plugin_register (vat_main_t *vam)\n'.format(module))
792     write('{\n')
793     write('   {n}_test_main_t * mainp = &{n}_test_main;\n'.format(n=module))
794     write('   mainp->vat_main = vam;\n')
795     write('   mainp->msg_id_base = vl_client_get_first_plugin_msg_id ("{n}_{crc:08x}");\n'
796           .format(n=module, crc=file_crc))
797     write('   if (mainp->msg_id_base == (u16) ~0)\n')
798     write('      return clib_error_return (0, "{} plugin not loaded...");\n'.format(module))
799     write('   setup_message_id_table (vam, mainp->msg_id_base);\n')
800     write('#ifdef VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE\n')
801     write('    VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE(vam);\n')
802     write('#endif\n')
803     write('   return 0;\n')
804     write('}\n')
805
806 #
807 # Plugin entry point
808 #
809 def run(args, input_filename, s):
810     stream = StringIO()
811
812     if not args.outputdir:
813         sys.stderr.write('Missing --outputdir argument')
814         return None
815
816     basename = os.path.basename(input_filename)
817     filename, file_extension = os.path.splitext(basename)
818     modulename = filename.replace('.', '_')
819     filename_enum = os.path.join(args.outputdir + '/' + basename + '_enum.h')
820     filename_types = os.path.join(args.outputdir + '/' + basename + '_types.h')
821     filename_c = os.path.join(args.outputdir + '/' + basename + '.c')
822     filename_c_test = os.path.join(args.outputdir + '/' + basename + '_test.c')
823
824     # Generate separate types file
825     st = StringIO()
826     generate_include_types(s, modulename, st)
827     with open (filename_types, 'w') as fd:
828         st.seek (0)
829         shutil.copyfileobj (st, fd)
830     st.close()
831
832     # Generate separate enum file
833     st = StringIO()
834     st.write('#ifndef included_{}_api_enum_h\n'.format(modulename))
835     st.write('#define included_{}_api_enum_h\n'.format(modulename))
836     generate_include_enum(s, modulename, st)
837     generate_include_counters(s['Counters'], modulename, st)
838     st.write('#endif\n')
839     with open (filename_enum, 'w') as fd:
840         st.seek (0)
841         shutil.copyfileobj (st, fd)
842     st.close()
843
844     # Generate separate C file
845     st = StringIO()
846     generate_c_boilerplate(s['Service'], s['Define'], s['Counters'],
847                            s['file_crc'], modulename, st)
848     with open (filename_c, 'w') as fd:
849         st.seek (0)
850         shutil.copyfileobj(st, fd)
851     st.close()
852
853     # Generate separate C test file
854     st = StringIO()
855     plugin = True if 'plugin' in input_filename else False
856     generate_c_test_boilerplate(s['Service'], s['Define'], s['file_crc'],
857                                 modulename, plugin, st)
858     with open (filename_c_test, 'w') as fd:
859         st.seek (0)
860         shutil.copyfileobj(st, fd)
861     st.close()
862
863     output = top_boilerplate.format(datestring=datestring,
864                                     input_filename=basename)
865     output += imports(s['Import'])
866     output += msg_ids(s)
867     output += msg_names(s)
868     output += msg_name_crc_list(s, filename)
869     output += typedefs(modulename)
870     printfun_types(s['types'], stream, modulename)
871     printfun(s['Define'], stream, modulename)
872     output += stream.getvalue()
873     stream.close()
874     output += endianfun(s['types'] + s['Define'], modulename)
875     output += version_tuple(s, basename)
876     output += bottom_boilerplate.format(input_filename=basename,
877                                         file_crc=s['file_crc'])
878
879     return output