feature: Add packet trace API
[vpp.git] / src / tools / vppapigen / vppapigen.py
1 #!/usr/bin/env python3
2
3 import ply.lex as lex
4 import ply.yacc as yacc
5 import sys
6 import argparse
7 import keyword
8 import logging
9 import binascii
10 import os
11 import sys
12 from subprocess import Popen, PIPE
13
14 assert sys.version_info >= (3, 5), \
15     "Not supported Python version: {}".format(sys.version)
16 log = logging.getLogger('vppapigen')
17
18 # Ensure we don't leave temporary files around
19 sys.dont_write_bytecode = True
20
21 #
22 # VPP API language
23 #
24
25 # Global dictionary of new types (including enums)
26 global_types = {}
27
28 seen_imports = {}
29
30
31 def global_type_add(name, obj):
32     '''Add new type to the dictionary of types '''
33     type_name = 'vl_api_' + name + '_t'
34     if type_name in global_types:
35         raise KeyError("Attempted redefinition of {!r} with {!r}.".format(
36             name, obj))
37     global_types[type_name] = obj
38
39
40 # All your trace are belong to us!
41 def exception_handler(exception_type, exception, traceback):
42     print("%s: %s" % (exception_type.__name__, exception))
43
44
45 #
46 # Lexer
47 #
48 class VPPAPILexer(object):
49     def __init__(self, filename):
50         self.filename = filename
51
52     reserved = {
53         'service': 'SERVICE',
54         'rpc': 'RPC',
55         'returns': 'RETURNS',
56         'null': 'NULL',
57         'stream': 'STREAM',
58         'events': 'EVENTS',
59         'define': 'DEFINE',
60         'typedef': 'TYPEDEF',
61         'enum': 'ENUM',
62         'typeonly': 'TYPEONLY',
63         'manual_print': 'MANUAL_PRINT',
64         'manual_endian': 'MANUAL_ENDIAN',
65         'dont_trace': 'DONT_TRACE',
66         'autoreply': 'AUTOREPLY',
67         'option': 'OPTION',
68         'u8': 'U8',
69         'u16': 'U16',
70         'u32': 'U32',
71         'u64': 'U64',
72         'i8': 'I8',
73         'i16': 'I16',
74         'i32': 'I32',
75         'i64': 'I64',
76         'f64': 'F64',
77         'bool': 'BOOL',
78         'string': 'STRING',
79         'import': 'IMPORT',
80         'true': 'TRUE',
81         'false': 'FALSE',
82         'union': 'UNION',
83     }
84
85     tokens = ['STRING_LITERAL',
86               'ID', 'NUM'] + list(reserved.values())
87
88     t_ignore_LINE_COMMENT = '//.*'
89
90     def t_FALSE(self, t):
91         r'false'
92         t.value = False
93         return t
94
95     def t_TRUE(self, t):
96         r'false'
97         t.value = True
98         return t
99
100     def t_NUM(self, t):
101         r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
102         base = 16 if t.value.startswith('0x') else 10
103         if '.' in t.value:
104             t.value = float(t.value)
105         else:
106             t.value = int(t.value, base)
107         return t
108
109     def t_ID(self, t):
110         r'[a-zA-Z_][a-zA-Z_0-9]*'
111         # Check for reserved words
112         t.type = VPPAPILexer.reserved.get(t.value, 'ID')
113         return t
114
115     # C string
116     def t_STRING_LITERAL(self, t):
117         r'\"([^\\\n]|(\\.))*?\"'
118         t.value = str(t.value).replace("\"", "")
119         return t
120
121     # C or C++ comment (ignore)
122     def t_comment(self, t):
123         r'(/\*(.|\n)*?\*/)|(//.*)'
124         t.lexer.lineno += t.value.count('\n')
125
126     # Error handling rule
127     def t_error(self, t):
128         raise ParseError("Illegal character '{}' ({})"
129                          "in {}: line {}".format(t.value[0],
130                                                  hex(ord(t.value[0])),
131                                                  self.filename,
132                                                  t.lexer.lineno))
133
134     # Define a rule so we can track line numbers
135     def t_newline(self, t):
136         r'\n+'
137         t.lexer.lineno += len(t.value)
138
139     literals = ":{}[];=.,"
140
141     # A string containing ignored characters (spaces and tabs)
142     t_ignore = ' \t'
143
144
145 def vla_is_last_check(name, block):
146     vla = False
147     for i, b in enumerate(block):
148         if isinstance(b, Array) and b.vla:
149             vla = True
150             if i + 1 < len(block):
151                 raise ValueError(
152                     'VLA field "{}" must be the last field in message "{}"'
153                     .format(b.fieldname, name))
154         elif b.fieldtype.startswith('vl_api_'):
155             if global_types[b.fieldtype].vla:
156                 vla = True
157                 if i + 1 < len(block):
158                     raise ValueError(
159                         'VLA field "{}" must be the last '
160                         'field in message "{}"'
161                         .format(b.fieldname, name))
162         elif b.fieldtype == 'string' and b.length == 0:
163             vla = True
164             if i + 1 < len(block):
165                 raise ValueError(
166                     'VLA field "{}" must be the last '
167                     'field in message "{}"'
168                     .format(b.fieldname, name))
169     return vla
170
171
172 class Service():
173     def __init__(self, caller, reply, events=None, stream_message=None, stream=False):
174         self.caller = caller
175         self.reply = reply
176         self.stream = stream
177         self.stream_message = stream_message
178         self.events = [] if events is None else events
179
180
181 class Typedef():
182     def __init__(self, name, flags, block):
183         self.name = name
184         self.flags = flags
185         self.block = block
186         self.crc = str(block).encode()
187         self.manual_print = False
188         self.manual_endian = False
189         for f in flags:
190             if f == 'manual_print':
191                 self.manual_print = True
192             elif f == 'manual_endian':
193                 self.manual_endian = True
194
195         global_type_add(name, self)
196
197         self.vla = vla_is_last_check(name, block)
198
199     def __repr__(self):
200         return self.name + str(self.flags) + str(self.block)
201
202
203 class Using():
204     def __init__(self, name, flags, alias):
205         self.name = name
206         self.vla = False
207         self.block = []
208         self.manual_print = True
209         self.manual_endian = True
210
211         self.manual_print = False
212         self.manual_endian = False
213         for f in flags:
214             if f == 'manual_print':
215                 self.manual_print = True
216             elif f == 'manual_endian':
217                 self.manual_endian = True
218
219         if isinstance(alias, Array):
220             a = {'type': alias.fieldtype,
221                  'length': alias.length}
222         else:
223             a = {'type': alias.fieldtype}
224         self.alias = a
225         #
226         # Should have been:
227         #  self.crc = str(alias).encode()
228         # but to be backwards compatible use the block ([])
229         #
230         self.crc = str(self.block).encode()
231         global_type_add(name, self)
232
233     def __repr__(self):
234         return self.name + str(self.alias)
235
236
237 class Union():
238     def __init__(self, name, flags, block):
239         self.type = 'Union'
240         self.manual_print = False
241         self.manual_endian = False
242         self.name = name
243
244         for f in flags:
245             if f == 'manual_print':
246                 self.manual_print = True
247             elif f == 'manual_endian':
248                 self.manual_endian = True
249
250         self.block = block
251         self.crc = str(block).encode()
252         self.vla = vla_is_last_check(name, block)
253
254         global_type_add(name, self)
255
256     def __repr__(self):
257         return str(self.block)
258
259
260 class Define():
261     def __init__(self, name, flags, block):
262         self.name = name
263         self.flags = flags
264         self.block = block
265         self.dont_trace = False
266         self.manual_print = False
267         self.manual_endian = False
268         self.autoreply = False
269         self.singular = False
270         self.options = {}
271         for f in flags:
272             if f == 'dont_trace':
273                 self.dont_trace = True
274             elif f == 'manual_print':
275                 self.manual_print = True
276             elif f == 'manual_endian':
277                 self.manual_endian = True
278             elif f == 'autoreply':
279                 self.autoreply = True
280
281         remove = []
282         for b in block:
283             if isinstance(b, Option):
284                 if b[1] == 'singular' and b[2] == 'true':
285                     self.singular = True
286                 else:
287                     self.options[b.option] = b.value
288                 remove.append(b)
289
290         block = [x for x in block if x not in remove]
291         self.block = block
292         self.vla = vla_is_last_check(name, block)
293         self.crc = str(block).encode()
294
295     def __repr__(self):
296         return self.name + str(self.flags) + str(self.block)
297
298
299 class Enum():
300     def __init__(self, name, block, enumtype='u32'):
301         self.name = name
302         self.enumtype = enumtype
303         self.vla = False
304
305         count = 0
306         block2 = []
307         block3 = []
308         bc_set = False
309
310         for b in block:
311             if 'value' in b:
312                 count = b['value']
313             else:
314                 count += 1
315             block2.append([b['id'], count])
316             try:
317                 if b['option']['backwards_compatible']:
318                     pass
319                 bc_set = True
320             except KeyError:
321                 block3.append([b['id'], count])
322                 if bc_set:
323                     raise ValueError("Backward compatible enum must be last {!r} {!r}"
324                                      .format(name, b['id']))
325         self.block = block2
326         self.crc = str(block3).encode()
327         global_type_add(name, self)
328
329     def __repr__(self):
330         return self.name + str(self.block)
331
332
333 class Import():
334
335     def __new__(cls, *args, **kwargs):
336         if args[0] not in seen_imports:
337             instance = super().__new__(cls)
338             instance._initialized = False
339             seen_imports[args[0]] = instance
340
341         return seen_imports[args[0]]
342
343     def __init__(self, filename, revision):
344         if self._initialized:
345             return
346         else:
347             self.filename = filename
348             # Deal with imports
349             parser = VPPAPI(filename=filename, revision=revision)
350             dirlist = dirlist_get()
351             f = filename
352             for dir in dirlist:
353                 f = os.path.join(dir, filename)
354                 if os.path.exists(f):
355                     break
356             self.result = parser.parse_filename(f, None)
357             self._initialized = True
358
359     def __repr__(self):
360         return self.filename
361
362
363 class Option():
364     def __init__(self, option, value=None):
365         self.type = 'Option'
366         self.option = option
367         self.value = value
368         self.crc = str(option).encode()
369
370     def __repr__(self):
371         return str(self.option)
372
373     def __getitem__(self, index):
374         return self.option[index]
375
376
377 class Array():
378     def __init__(self, fieldtype, name, length, modern_vla=False):
379         self.type = 'Array'
380         self.fieldtype = fieldtype
381         self.fieldname = name
382         self.modern_vla = modern_vla
383         if type(length) is str:
384             self.lengthfield = length
385             self.length = 0
386             self.vla = True
387         else:
388             self.length = length
389             self.lengthfield = None
390             self.vla = False
391
392     def __repr__(self):
393         return str([self.fieldtype, self.fieldname, self.length,
394                     self.lengthfield])
395
396
397 class Field():
398     def __init__(self, fieldtype, name, limit=None):
399         self.type = 'Field'
400         self.fieldtype = fieldtype
401
402         if self.fieldtype == 'string':
403             raise ValueError("The string type {!r} is an "
404                              "array type ".format(name))
405
406         if name in keyword.kwlist:
407             raise ValueError("Fieldname {!r} is a python keyword and is not "
408                              "accessible via the python API. ".format(name))
409         self.fieldname = name
410         self.limit = limit
411
412     def __repr__(self):
413         return str([self.fieldtype, self.fieldname])
414
415
416 class Coord(object):
417     """ Coordinates of a syntactic element. Consists of:
418             - File name
419             - Line number
420             - (optional) column number, for the Lexer
421     """
422     __slots__ = ('file', 'line', 'column', '__weakref__')
423
424     def __init__(self, file, line, column=None):
425         self.file = file
426         self.line = line
427         self.column = column
428
429     def __str__(self):
430         str = "%s:%s" % (self.file, self.line)
431         if self.column:
432             str += ":%s" % self.column
433         return str
434
435
436 class ParseError(Exception):
437     pass
438
439
440 #
441 # Grammar rules
442 #
443 class VPPAPIParser(object):
444     tokens = VPPAPILexer.tokens
445
446     def __init__(self, filename, logger, revision=None):
447         self.filename = filename
448         self.logger = logger
449         self.fields = []
450         self.revision = revision
451
452     def _parse_error(self, msg, coord):
453         raise ParseError("%s: %s" % (coord, msg))
454
455     def _parse_warning(self, msg, coord):
456         if self.logger:
457             self.logger.warning("%s: %s" % (coord, msg))
458
459     def _coord(self, lineno, column=None):
460         return Coord(
461                 file=self.filename,
462                 line=lineno, column=column)
463
464     def _token_coord(self, p, token_idx):
465         """ Returns the coordinates for the YaccProduction object 'p' indexed
466             with 'token_idx'. The coordinate includes the 'lineno' and
467             'column'. Both follow the lex semantic, starting from 1.
468         """
469         last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
470         if last_cr < 0:
471             last_cr = -1
472         column = (p.lexpos(token_idx) - (last_cr))
473         return self._coord(p.lineno(token_idx), column)
474
475     def p_slist(self, p):
476         '''slist : stmt
477                  | slist stmt'''
478         if len(p) == 2:
479             p[0] = [p[1]]
480         else:
481             p[0] = p[1] + [p[2]]
482
483     def p_stmt(self, p):
484         '''stmt : define
485                 | typedef
486                 | option
487                 | import
488                 | enum
489                 | union
490                 | service'''
491         p[0] = p[1]
492
493     def p_import(self, p):
494         '''import : IMPORT STRING_LITERAL ';' '''
495         p[0] = Import(p[2], revision=self.revision)
496
497     def p_service(self, p):
498         '''service : SERVICE '{' service_statements '}' ';' '''
499         p[0] = p[3]
500
501     def p_service_statements(self, p):
502         '''service_statements : service_statement
503                         | service_statements service_statement'''
504         if len(p) == 2:
505             p[0] = [p[1]]
506         else:
507             p[0] = p[1] + [p[2]]
508
509     def p_service_statement(self, p):
510         '''service_statement : RPC ID RETURNS NULL ';'
511                              | RPC ID RETURNS ID ';'
512                              | RPC ID RETURNS STREAM ID ';'
513                              | RPC ID RETURNS ID EVENTS event_list ';' '''
514         if p[2] == p[4]:
515             # Verify that caller and reply differ
516             self._parse_error(
517                 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
518                 self._token_coord(p, 1))
519         if len(p) == 8:
520             p[0] = Service(p[2], p[4], p[6])
521         elif len(p) == 7:
522             p[0] = Service(p[2], p[5], stream=True)
523         else:
524             p[0] = Service(p[2], p[4])
525
526     def p_service_statement2(self, p):
527         '''service_statement : RPC ID RETURNS ID STREAM ID ';' '''
528         p[0] = Service(p[2], p[4], stream_message=p[6], stream=True)
529
530     def p_event_list(self, p):
531         '''event_list : events
532                       | event_list events '''
533         if len(p) == 2:
534             p[0] = [p[1]]
535         else:
536             p[0] = p[1] + [p[2]]
537
538     def p_event(self, p):
539         '''events : ID
540                   | ID ',' '''
541         p[0] = p[1]
542
543     def p_enum(self, p):
544         '''enum : ENUM ID '{' enum_statements '}' ';' '''
545         p[0] = Enum(p[2], p[4])
546
547     def p_enum_type(self, p):
548         ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
549         if len(p) == 9:
550             p[0] = Enum(p[2], p[6], enumtype=p[4])
551         else:
552             p[0] = Enum(p[2], p[4])
553
554     def p_enum_size(self, p):
555         ''' enum_size : U8
556                       | U16
557                       | U32 '''
558         p[0] = p[1]
559
560     def p_define(self, p):
561         '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
562         self.fields = []
563         p[0] = Define(p[2], [], p[4])
564
565     def p_define_flist(self, p):
566         '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
567         # Legacy typedef
568         if 'typeonly' in p[1]:
569             self._parse_error('legacy typedef. use typedef: {} {}[{}];'
570                               .format(p[1], p[2], p[4]),
571                               self._token_coord(p, 1))
572         else:
573             p[0] = Define(p[3], p[1], p[5])
574
575     def p_flist(self, p):
576         '''flist : flag
577                  | flist flag'''
578         if len(p) == 2:
579             p[0] = [p[1]]
580         else:
581             p[0] = p[1] + [p[2]]
582
583     def p_flag(self, p):
584         '''flag : MANUAL_PRINT
585                 | MANUAL_ENDIAN
586                 | DONT_TRACE
587                 | TYPEONLY
588                 | AUTOREPLY'''
589         if len(p) == 1:
590             return
591         p[0] = p[1]
592
593     def p_typedef(self, p):
594         '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
595         p[0] = Typedef(p[2], [], p[4])
596
597     def p_typedef_flist(self, p):
598         '''typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';' '''
599         p[0] = Typedef(p[3], p[1], p[5])
600
601     def p_typedef_alias(self, p):
602         '''typedef : TYPEDEF declaration '''
603         p[0] = Using(p[2].fieldname, [], p[2])
604
605     def p_typedef_alias_flist(self, p):
606         '''typedef : flist TYPEDEF declaration '''
607         p[0] = Using(p[3].fieldname, p[1], p[3])
608
609     def p_block_statements_opt(self, p):
610         '''block_statements_opt : block_statements '''
611         p[0] = p[1]
612
613     def p_block_statements(self, p):
614         '''block_statements : block_statement
615                             | block_statements block_statement'''
616         if len(p) == 2:
617             p[0] = [p[1]]
618         else:
619             p[0] = p[1] + [p[2]]
620
621     def p_block_statement(self, p):
622         '''block_statement : declaration
623                            | option '''
624         p[0] = p[1]
625
626     def p_enum_statements(self, p):
627         '''enum_statements : enum_statement
628                            | enum_statements enum_statement'''
629         if len(p) == 2:
630             p[0] = [p[1]]
631         else:
632             p[0] = p[1] + [p[2]]
633
634     def p_enum_statement(self, p):
635         '''enum_statement : ID '=' NUM ','
636                           | ID ','
637                           | ID '[' field_options ']' ','
638                           | ID '=' NUM '[' field_options ']' ',' '''
639         if len(p) == 3:
640             p[0] = {'id': p[1]}
641         elif len(p) == 5:
642             p[0] = {'id': p[1], 'value': p[3]}
643         elif len(p) == 6:
644             p[0] = {'id': p[1], 'option': p[3]}
645         elif len(p) == 8:
646             p[0] = {'id': p[1], 'value': p[3], 'option': p[5]}
647         else:
648             self._parse_error('ERROR', self._token_coord(p, 1))
649
650     def p_field_options(self, p):
651         '''field_options : field_option
652                            | field_options field_option'''
653         if len(p) == 2:
654             p[0] = p[1]
655         else:
656             p[0] = {**p[1], **p[2]}
657
658     def p_field_option(self, p):
659         '''field_option : ID
660                         | ID '=' assignee ','
661                         | ID '=' assignee
662
663         '''
664         if len(p) == 2:
665             p[0] = {p[1]: None}
666         else:
667             p[0] = {p[1]: p[3]}
668
669     def p_declaration(self, p):
670         '''declaration : type_specifier ID ';'
671                        | type_specifier ID '[' field_options ']' ';' '''
672         if len(p) == 7:
673             p[0] = Field(p[1], p[2], p[4])
674         elif len(p) == 4:
675             p[0] = Field(p[1], p[2])
676         else:
677             self._parse_error('ERROR', self._token_coord(p, 1))
678         self.fields.append(p[2])
679
680     def p_declaration_array_vla(self, p):
681         '''declaration : type_specifier ID '[' ']' ';' '''
682         p[0] = Array(p[1], p[2], 0, modern_vla=True)
683
684     def p_declaration_array(self, p):
685         '''declaration : type_specifier ID '[' NUM ']' ';'
686                        | type_specifier ID '[' ID ']' ';' '''
687
688         if len(p) != 7:
689             return self._parse_error(
690                 'array: %s' % p.value,
691                 self._coord(lineno=p.lineno))
692
693         # Make this error later
694         if type(p[4]) is int and p[4] == 0:
695             # XXX: Line number is wrong
696             self._parse_warning('Old Style VLA: {} {}[{}];'
697                                 .format(p[1], p[2], p[4]),
698                                 self._token_coord(p, 1))
699
700         if type(p[4]) is str and p[4] not in self.fields:
701             # Verify that length field exists
702             self._parse_error('Missing length field: {} {}[{}];'
703                               .format(p[1], p[2], p[4]),
704                               self._token_coord(p, 1))
705         p[0] = Array(p[1], p[2], p[4])
706
707     def p_option(self, p):
708         '''option : OPTION ID '=' assignee ';'
709                   | OPTION ID ';' '''
710         if len(p) == 4:
711             p[0] = Option(p[2])
712         else:
713             p[0] = Option(p[2], p[4])
714
715     def p_assignee(self, p):
716         '''assignee : NUM
717                     | TRUE
718                     | FALSE
719                     | STRING_LITERAL '''
720         p[0] = p[1]
721
722     def p_type_specifier(self, p):
723         '''type_specifier : U8
724                           | U16
725                           | U32
726                           | U64
727                           | I8
728                           | I16
729                           | I32
730                           | I64
731                           | F64
732                           | BOOL
733                           | STRING'''
734         p[0] = p[1]
735
736     # Do a second pass later to verify that user defined types are defined
737     def p_typedef_specifier(self, p):
738         '''type_specifier : ID '''
739         if p[1] not in global_types:
740             self._parse_error('Undefined type: {}'.format(p[1]),
741                               self._token_coord(p, 1))
742         p[0] = p[1]
743
744     def p_union(self, p):
745         '''union : UNION ID '{' block_statements_opt '}' ';' '''
746         p[0] = Union(p[2], [], p[4])
747
748     def p_union_flist(self, p):
749         '''union : flist UNION ID '{' block_statements_opt '}' ';' '''
750         p[0] = Union(p[3], p[1], p[5])
751
752     # Error rule for syntax errors
753     def p_error(self, p):
754         if p:
755             self._parse_error(
756                 'before: %s' % p.value,
757                 self._coord(lineno=p.lineno))
758         else:
759             self._parse_error('At end of input', self.filename)
760
761
762 class VPPAPI(object):
763
764     def __init__(self, debug=False, filename='', logger=None, revision=None):
765         self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
766         self.parser = yacc.yacc(module=VPPAPIParser(filename, logger,
767                                                     revision=revision),
768                                 write_tables=False, debug=debug)
769         self.logger = logger
770         self.revision = revision
771         self.filename = filename
772
773     def parse_string(self, code, debug=0, lineno=1):
774         self.lexer.lineno = lineno
775         return self.parser.parse(code, lexer=self.lexer, debug=debug)
776
777     def parse_fd(self, fd, debug=0):
778         data = fd.read()
779         return self.parse_string(data, debug=debug)
780
781     def parse_filename(self, filename, debug=0):
782         if self.revision:
783             git_show = 'git show {}:{}'.format(self.revision, filename)
784             proc = Popen(git_show.split(), stdout=PIPE, encoding='utf-8')
785             try:
786                 data, errs = proc.communicate()
787                 if proc.returncode != 0:
788                     print('File not found: {}:{}'.format(self.revision,
789                       filename), file=sys.stderr)
790                     sys.exit(2)
791                 return self.parse_string(data, debug=debug)
792             except Exception as e:
793                 sys.exit(3)
794         else:
795             try:
796                 with open(filename, encoding='utf-8') as fd:
797                     return self.parse_fd(fd, None)
798             except FileNotFoundError:
799                 print('File not found: {}'.format(filename), file=sys.stderr)
800                 sys.exit(2)
801
802     def autoreply_block(self, name, parent):
803         block = [Field('u32', 'context'),
804                  Field('i32', 'retval')]
805         # inherhit the parent's options
806         for k, v in parent.options.items():
807             block.append(Option(k, v))
808         return Define(name + '_reply', [], block)
809
810     def process(self, objs):
811         s = {}
812         s['Option'] = {}
813         s['Define'] = []
814         s['Service'] = []
815         s['types'] = []
816         s['Import'] = []
817         crc = 0
818         for o in objs:
819             tname = o.__class__.__name__
820             try:
821                 crc = binascii.crc32(o.crc, crc) & 0xffffffff
822             except AttributeError:
823                 pass
824             if isinstance(o, Define):
825                 s[tname].append(o)
826                 if o.autoreply:
827                     s[tname].append(self.autoreply_block(o.name, o))
828             elif isinstance(o, Option):
829                 s[tname][o.option] = o.value
830             elif type(o) is list:
831                 for o2 in o:
832                     if isinstance(o2, Service):
833                         s['Service'].append(o2)
834             elif (isinstance(o, Enum) or
835                   isinstance(o, Typedef) or
836                   isinstance(o, Using) or
837                   isinstance(o, Union)):
838                 s['types'].append(o)
839             else:
840                 if tname not in s:
841                     raise ValueError('Unknown class type: {} {}'
842                                      .format(tname, o))
843                 s[tname].append(o)
844
845         msgs = {d.name: d for d in s['Define']}
846         svcs = {s.caller: s for s in s['Service']}
847         replies = {s.reply: s for s in s['Service']}
848         seen_services = {}
849
850         s['file_crc'] = crc
851
852         for service in svcs:
853             if service not in msgs:
854                 raise ValueError(
855                     'Service definition refers to unknown message'
856                     ' definition: {}'.format(service))
857             if svcs[service].reply != 'null' and \
858                svcs[service].reply not in msgs:
859                 raise ValueError('Service definition refers to unknown message'
860                                  ' definition in reply: {}'
861                                  .format(svcs[service].reply))
862             if service in replies:
863                 raise ValueError('Service definition refers to message'
864                                  ' marked as reply: {}'.format(service))
865             for event in svcs[service].events:
866                 if event not in msgs:
867                     raise ValueError('Service definition refers to unknown '
868                                      'event: {} in message: {}'
869                                      .format(event, service))
870                 seen_services[event] = True
871
872         # Create services implicitly
873         for d in msgs:
874             if d in seen_services:
875                 continue
876             if msgs[d].singular is True:
877                 continue
878             if d.endswith('_reply'):
879                 if d[:-6] in svcs:
880                     continue
881                 if d[:-6] not in msgs:
882                     raise ValueError('{} missing calling message'
883                                      .format(d))
884                 continue
885             if d.endswith('_dump'):
886                 if d in svcs:
887                     continue
888                 if d[:-5]+'_details' in msgs:
889                     s['Service'].append(Service(d, d[:-5]+'_details',
890                                                 stream=True))
891                 else:
892                     raise ValueError('{} missing details message'
893                                      .format(d))
894                 continue
895
896             if d.endswith('_details'):
897                 if d[:-8]+'_get' in msgs:
898                     if d[:-8]+'_get' in svcs:
899                         continue
900                     else:
901                         raise ValueError('{} should be in a stream service'
902                                          .format(d[:-8]+'_get'))
903                 if d[:-8]+'_dump' in msgs:
904                     continue
905                 raise ValueError('{} missing dump or get message'
906                                  .format(d))
907
908             if d in svcs:
909                 continue
910             if d+'_reply' in msgs:
911                 s['Service'].append(Service(d, d+'_reply'))
912             else:
913                 raise ValueError(
914                     '{} missing reply message ({}) or service definition'
915                     .format(d, d+'_reply'))
916
917         return s
918
919     def process_imports(self, objs, in_import, result):
920         imported_objs = []
921         for o in objs:
922             # Only allow the following object types from imported file
923             if in_import and not (isinstance(o, Enum) or
924                                   isinstance(o, Union) or
925                                   isinstance(o, Typedef) or
926                                   isinstance(o, Import) or
927                                   isinstance(o, Using)):
928                 continue
929             if isinstance(o, Import):
930                 result.append(o)
931                 result = self.process_imports(o.result, True, result)
932             else:
933                 result.append(o)
934         return result
935
936
937 # Add message ids to each message.
938 def add_msg_id(s):
939     for o in s:
940         o.block.insert(0, Field('u16', '_vl_msg_id'))
941     return s
942
943
944 dirlist = []
945
946
947 def dirlist_add(dirs):
948     global dirlist
949     if dirs:
950         dirlist = dirlist + dirs
951
952
953 def dirlist_get():
954     return dirlist
955
956
957 def foldup_blocks(block, crc):
958     for b in block:
959         # Look up CRC in user defined types
960         if b.fieldtype.startswith('vl_api_'):
961             # Recursively
962             t = global_types[b.fieldtype]
963             try:
964                 crc = binascii.crc32(t.crc, crc) & 0xffffffff
965                 crc = foldup_blocks(t.block, crc)
966             except AttributeError:
967                 pass
968     return crc
969
970
971 # keep the CRCs of the existing types of messages compatible with the
972 # old "erroneous" way of calculating the CRC. For that - make a pointed
973 # adjustment of the CRC function.
974 # This is the purpose of the first element of the per-message dictionary.
975 # The second element is there to avoid weakening the duplicate-detecting
976 # properties of crc32. This way, if the new way of calculating the CRC
977 # happens to collide with the old (buggy) way - we will still get
978 # a different result and fail the comparison.
979
980 fixup_crc_dict = {
981         "abf_policy_add_del": { 0xc6131197: 0xee66f93e },
982         "abf_policy_details": { 0xb7487fa4: 0x6769e504 },
983         "acl_add_replace": { 0xee5c2f18: 0x1cabdeab },
984         "acl_details": { 0x95babae0: 0x7a97f21c },
985         "macip_acl_add": { 0xce6fbad0: 0xd648fd0a },
986         "macip_acl_add_replace": { 0x2a461dd4: 0xe34402a7 },
987         "macip_acl_details": { 0x27135b59: 0x57c7482f },
988         "dhcp_proxy_config": { 0x4058a689: 0x6767230e },
989         "dhcp_client_config": { 0x1af013ea: 0x959b80a3 },
990         "dhcp_compl_event": { 0x554a44e5: 0xe908fd1d },
991         "dhcp_client_details": { 0x3c5cd28a: 0xacd82f5a },
992         "dhcp_proxy_details": { 0xdcbaf540: 0xce16f044 },
993         "dhcp6_send_client_message": { 0xf8222476: 0xf6f14ef0 },
994         "dhcp6_pd_send_client_message": { 0x3739fd8d: 0x64badb8 },
995         "dhcp6_reply_event": { 0x85b7b17e: 0x9f3af9e5 },
996         "dhcp6_pd_reply_event": { 0x5e878029: 0xcb3e462b },
997         "ip6_add_del_address_using_prefix": { 0x3982f30a: 0x9b3d11e0 },
998         "gbp_bridge_domain_add": { 0x918e8c01: 0x8454bfdf },
999         "gbp_bridge_domain_details": { 0x51d51be9: 0x2acd15f9 },
1000         "gbp_route_domain_add": { 0x204c79e1: 0x2d0afe38 },
1001         "gbp_route_domain_details": { 0xa78bfbca: 0x8ab11375 },
1002         "gbp_endpoint_add": { 0x7b3af7de: 0x9ce16d5a },
1003         "gbp_endpoint_details": { 0x8dd8fbd3: 0x8aecb60 },
1004         "gbp_endpoint_group_add": { 0x301ddf15: 0x8e0f4054 },
1005         "gbp_endpoint_group_details": { 0xab71d723: 0x8f38292c },
1006         "gbp_subnet_add_del": { 0xa8803c80: 0x888aca35 },
1007         "gbp_subnet_details": { 0xcbc5ca18: 0x4ed84156 },
1008         "gbp_contract_add_del": { 0xaa8d652d: 0x553e275b },
1009         "gbp_contract_details": { 0x65dec325: 0x2a18db6e },
1010         "gbp_ext_itf_add_del": { 0x7606d0e1: 0x12ed5700 },
1011         "gbp_ext_itf_details": { 0x519c3d3c: 0x408a45c0 },
1012         "gtpu_add_del_tunnel": { 0xca983a2b: 0x9a9c0426 },
1013         "gtpu_tunnel_update_tteid": { 0x79f33816: 0x8a2db108 },
1014         "gtpu_tunnel_details": { 0x27f434ae: 0x4535cf95 },
1015         "igmp_listen": { 0x19a49f1e: 0x3f93a51a },
1016         "igmp_details": { 0x38f09929: 0x52f12a89 },
1017         "igmp_event": { 0x85fe93ec: 0xd7696eaf },
1018         "igmp_group_prefix_set": { 0x5b14a5ce: 0xd4f20ac5 },
1019         "igmp_group_prefix_details": { 0x259ccd81: 0xc3b3c526 },
1020         "ikev2_set_responder": { 0xb9aa4d4e: 0xf0d3dc80 },
1021         "vxlan_gpe_ioam_export_enable_disable": { 0xd4c76d3a: 0xe4d4ebfa },
1022         "ioam_export_ip6_enable_disable": { 0xd4c76d3a: 0xe4d4ebfa },
1023         "vxlan_gpe_ioam_vni_enable": { 0xfbb5fb1: 0x997161fb },
1024         "vxlan_gpe_ioam_vni_disable": { 0xfbb5fb1: 0x997161fb },
1025         "vxlan_gpe_ioam_transit_enable": { 0x3d3ec657: 0x553f5b7b },
1026         "vxlan_gpe_ioam_transit_disable": { 0x3d3ec657: 0x553f5b7b },
1027         "udp_ping_add_del": { 0xfa2628fc: 0xc692b188 },
1028         "l3xc_update": { 0xe96aabdf: 0x787b1d3 },
1029         "l3xc_details": { 0xbc5bf852: 0xd4f69627 },
1030         "sw_interface_lacp_details": { 0xd9a83d2f: 0x745ae0ba },
1031         "lb_conf": { 0x56cd3261: 0x22ddb739 },
1032         "lb_add_del_vip": { 0x6fa569c7: 0xd15b7ddc },
1033         "lb_add_del_as": { 0x35d72500: 0x78628987 },
1034         "lb_vip_dump": { 0x56110cb7: 0xc7bcb124 },
1035         "lb_vip_details": { 0x1329ec9b: 0x8f39bed },
1036         "lb_as_details": { 0x8d24c29e: 0x9c39f60e },
1037         "mactime_add_del_range": { 0xcb56e877: 0x101858ef },
1038         "mactime_details": { 0xda25b13a: 0x44921c06 },
1039         "map_add_domain": { 0x249f195c: 0x7a5a18c9 },
1040         "map_domain_details": { 0x796edb50: 0xfc1859dd },
1041         "map_param_add_del_pre_resolve": { 0xdae5af03: 0x17008c66 },
1042         "map_param_get_reply": { 0x26272c90: 0x28092156 },
1043         "memif_details": { 0xda34feb9: 0xd0382c4c },
1044         "dslite_add_del_pool_addr_range": { 0xde2a5b02: 0xc448457a },
1045         "dslite_set_aftr_addr": { 0x78b50fdf: 0x1e955f8d },
1046         "dslite_get_aftr_addr_reply": { 0x8e23608e: 0x38e30db1 },
1047         "dslite_set_b4_addr": { 0x78b50fdf: 0x1e955f8d },
1048         "dslite_get_b4_addr_reply": { 0x8e23608e: 0x38e30db1 },
1049         "nat44_add_del_address_range": { 0x6f2b8055: 0xd4c7568c },
1050         "nat44_address_details": { 0xd1beac1: 0x45410ac4 },
1051         "nat44_add_del_static_mapping": { 0x5ae5f03e: 0xe165e83b },
1052         "nat44_static_mapping_details": { 0x6cb40b2: 0x1a433ef7 },
1053         "nat44_add_del_identity_mapping": { 0x2faaa22: 0x8e12743f },
1054         "nat44_identity_mapping_details": { 0x2a52a030: 0x36d21351 },
1055         "nat44_add_del_interface_addr": { 0x4aed50c0: 0xfc835325 },
1056         "nat44_interface_addr_details": { 0xe4aca9ca: 0x3e687514 },
1057         "nat44_user_session_details": { 0x2cf6e16d: 0x1965fd69 },
1058         "nat44_add_del_lb_static_mapping": { 0x4f68ee9d: 0x53b24611 },
1059         "nat44_lb_static_mapping_add_del_local": { 0x7ca47547: 0x2910a151 },
1060         "nat44_lb_static_mapping_details": { 0xed5ce876: 0x2267b9e8 },
1061         "nat44_del_session": { 0x15a5bf8c: 0x4c49c387 },
1062         "nat_det_add_del_map": { 0x1150a190: 0x112fde05 },
1063         "nat_det_map_details": { 0xad91dc83: 0x88000ee1 },
1064         "nat_det_close_session_out": { 0xf6b259d1: 0xc1b6cbfb },
1065         "nat_det_close_session_in": { 0x3c68e073: 0xa10ef64 },
1066         "nat64_add_del_pool_addr_range": { 0xa3b944e3: 0x21234ef3 },
1067         "nat64_add_del_static_bib": { 0x1c404de5: 0x90fae58a },
1068         "nat64_bib_details": { 0x43bc3ddf: 0x62c8541d },
1069         "nat64_st_details": { 0xdd3361ed: 0xc770d620 },
1070         "nat66_add_del_static_mapping": { 0x3ed88f71: 0xfb64e50b },
1071         "nat66_static_mapping_details": { 0xdf39654b: 0x5c568448 },
1072         "nsh_add_del_map": { 0xa0f42b0: 0x898d857d },
1073         "nsh_map_details": { 0x2fefcf49: 0xb34ac8a1 },
1074         "nsim_cross_connect_enable_disable": { 0x9c3ead86: 0x16f70bdf },
1075         "pppoe_add_del_session": { 0xf6fd759e: 0x46ace853 },
1076         "pppoe_session_details": { 0x4b8e8a4a: 0x332bc742 },
1077         "stn_add_del_rule": { 0x224c6edd: 0x53f751e6 },
1078         "stn_rules_details": { 0xa51935a6: 0xb0f6606c },
1079         "svs_route_add_del": { 0xe49bc63c: 0xd39e31fc },
1080         "svs_details": { 0x6282cd55: 0xb8523d64 },
1081         "vmxnet3_details": { 0x6a1a5498: 0x829ba055 },
1082         "vrrp_vr_add_del": { 0xc5cf15aa: 0x6dc4b881 },
1083         "vrrp_vr_details": { 0x46edcebd: 0x412fa71 },
1084         "vrrp_vr_set_peers": { 0x20bec71f: 0xbaa2e52b },
1085         "vrrp_vr_peer_details": { 0x3d99c108: 0xabd9145e },
1086         "vrrp_vr_track_if_add_del": { 0xd67df299: 0x337f4ba4 },
1087         "vrrp_vr_track_if_details": { 0x73c36f81: 0x99bcca9c },
1088         "proxy_arp_add_del": { 0x1823c3e7: 0x85486cbd },
1089         "proxy_arp_details": { 0x5b948673: 0x9228c150 },
1090         "bfd_udp_get_echo_source_reply": { 0xe3d736a1: 0x1e00cfce },
1091         "bfd_udp_add": { 0x939cd26a: 0x7a6d1185 },
1092         "bfd_udp_mod": { 0x913df085: 0x783a3ff6 },
1093         "bfd_udp_del": { 0xdcb13a89: 0x8096514d },
1094         "bfd_udp_session_details": { 0x9fb2f2d: 0x60653c02 },
1095         "bfd_udp_session_set_flags": { 0x4b4bdfd: 0xcf313851 },
1096         "bfd_udp_auth_activate": { 0x21fd1bdb: 0x493ee0ec },
1097         "bfd_udp_auth_deactivate": { 0x9a05e2e0: 0x99978c32 },
1098         "bier_route_add_del": { 0xfd02f3ea: 0xf29edca0 },
1099         "bier_route_details": { 0x4008caee: 0x39ee6a56 },
1100         "bier_disp_entry_add_del": { 0x9eb80cb4: 0x648323eb },
1101         "bier_disp_entry_details": { 0x84c218f1: 0xe5b039a9 },
1102         "bond_create": { 0xf1dbd4ff: 0x48883c7e },
1103         "bond_enslave": { 0xe7d14948: 0x76ecfa7 },
1104         "sw_interface_bond_details": { 0xbb7c929b: 0xf5ef2106 },
1105         "pipe_create_reply": { 0xb7ce310c: 0xd4c2c2b3 },
1106         "pipe_details": { 0xc52b799d: 0x43ac107a },
1107         "tap_create_v2": { 0x2d0d6570: 0x445835fd },
1108         "sw_interface_tap_v2_details": { 0x1e2b2a47: 0xe53c16de },
1109         "sw_interface_vhost_user_details": { 0xcee1e53: 0x98530df1 },
1110         "virtio_pci_create": { 0x1944f8db: 0xa9f1370c },
1111         "sw_interface_virtio_pci_details": { 0x6ca9c167: 0x16187f3a },
1112         "p2p_ethernet_add": { 0x36a1a6dc: 0xeeb8e717 },
1113         "p2p_ethernet_del": { 0x62f81c8c: 0xb62c386 },
1114         "geneve_add_del_tunnel": { 0x99445831: 0x976693b5 },
1115         "geneve_tunnel_details": { 0x6b16eb24: 0xe27e2748 },
1116         "gre_tunnel_add_del": { 0xa27d7f17: 0x6efc9c22 },
1117         "gre_tunnel_details": { 0x24435433: 0x3bfbf1 },
1118         "sw_interface_set_flags": { 0xf5aec1b8: 0x6a2b491a },
1119         "sw_interface_event": { 0x2d3d95a7: 0xf709f78d },
1120         "sw_interface_details": { 0x6c221fc7: 0x17b69fa2 },
1121         "sw_interface_add_del_address": { 0x5463d73b: 0x5803d5c4 },
1122         "sw_interface_set_unnumbered": { 0x154a6439: 0x938ef33b },
1123         "sw_interface_set_mac_address": { 0xc536e7eb: 0x6aca746a },
1124         "sw_interface_set_rx_mode": { 0xb04d1cfe: 0x780f5cee },
1125         "sw_interface_rx_placement_details": { 0x9e44a7ce: 0xf6d7d024 },
1126         "create_subif": { 0x790ca755: 0xcb371063 },
1127         "ip_neighbor_add_del": { 0x607c257: 0x105518b6 },
1128         "ip_neighbor_dump": { 0xd817a484: 0xcd831298 },
1129         "ip_neighbor_details": { 0xe29d79f0: 0x870e80b9 },
1130         "want_ip_neighbor_events": { 0x73e70a86: 0x1a312870 },
1131         "ip_neighbor_event": { 0xbdb092b2: 0x83933131 },
1132         "ip_route_add_del": { 0xb8ecfe0d: 0xc1ff832d },
1133         "ip_route_details": { 0xbda8f315: 0xd1ffaae1 },
1134         "ip_route_lookup": { 0x710d6471: 0xe2986185 },
1135         "ip_route_lookup_reply": { 0x5d8febcb: 0xae99de8e },
1136         "ip_mroute_add_del": { 0x85d762f3: 0xf6627d17 },
1137         "ip_mroute_details": { 0x99341a45: 0xc1cb4b44 },
1138         "ip_address_details": { 0xee29b797: 0xb1199745 },
1139         "ip_unnumbered_details": { 0xcc59bd42: 0xaa12a483 },
1140         "mfib_signal_details": { 0x6f4a4cfb: 0x64398a9a },
1141         "ip_punt_redirect": { 0x6580f635: 0xa9a5592c },
1142         "ip_punt_redirect_details": { 0x2cef63e7: 0x3924f5d3 },
1143         "ip_container_proxy_add_del": { 0x7df1dff1: 0x91189f40 },
1144         "ip_container_proxy_details": { 0xa8085523: 0xee460e8 },
1145         "ip_source_and_port_range_check_add_del": { 0x92a067e3: 0x8bfc76f2 },
1146         "sw_interface_ip6_set_link_local_address": { 0x1c10f15f: 0x2931d9fa },
1147         "ip_reassembly_enable_disable": { 0xeb77968d: 0x885c85a6 },
1148         "set_punt": { 0xaa83d523: 0x83799618 },
1149         "punt_socket_register": { 0x95268cbf: 0xc8cd10fa },
1150         "punt_socket_details": { 0xde575080: 0x1de0ce75 },
1151         "punt_socket_deregister": { 0x98fc9102: 0x98a444f4 },
1152         "sw_interface_ip6nd_ra_prefix": { 0x82cc1b28: 0xe098785f },
1153         "ip6nd_proxy_add_del": { 0xc2e4a686: 0x3fdf6659 },
1154         "ip6nd_proxy_details": { 0x30b9ff4a: 0xd35be8ff },
1155         "ip6_ra_event": { 0x364c1c5: 0x47e8cfbe },
1156         "set_ipfix_exporter": { 0x5530c8a0: 0x69284e07 },
1157         "ipfix_exporter_details": { 0xdedbfe4: 0x11e07413 },
1158         "ipip_add_tunnel": { 0x2ac399f5: 0xa9decfcd },
1159         "ipip_6rd_add_tunnel": { 0xb9ec1863: 0x56e93cc0 },
1160         "ipip_tunnel_details": { 0xd31cb34e: 0x53236d75 },
1161         "ipsec_spd_entry_add_del": { 0x338b7411: 0x9f384b8d },
1162         "ipsec_spd_details": { 0x5813d7a2: 0xf2222790 },
1163         "ipsec_sad_entry_add_del": { 0xab64b5c6: 0xb8def364 },
1164         "ipsec_tunnel_protect_update": { 0x30d5f133: 0x143f155d },
1165         "ipsec_tunnel_protect_del": { 0xcd239930: 0xddd2ba36 },
1166         "ipsec_tunnel_protect_details": { 0x21663a50: 0xac6c823b },
1167         "ipsec_tunnel_if_add_del": { 0x20e353fa: 0x2b135e68 },
1168         "ipsec_sa_details": { 0x345d14a7: 0xb30c7f41 },
1169         "l2_xconnect_details": { 0x472b6b67: 0xc8aa6b37 },
1170         "l2_fib_table_details": { 0xa44ef6b8: 0xe8d2fc72 },
1171         "l2fib_add_del": { 0xeddda487: 0xf29d796c },
1172         "l2_macs_event": { 0x44b8fd64: 0x2eadfc8b },
1173         "bridge_domain_details": { 0xfa506fd: 0x979f549d },
1174         "l2_interface_pbb_tag_rewrite": { 0x38e802a8: 0x612efa5a },
1175         "l2_patch_add_del": { 0xa1f6a6f3: 0x522f3445 },
1176         "sw_interface_set_l2_xconnect": { 0x4fa28a85: 0x1aaa2dbb },
1177         "sw_interface_set_l2_bridge": { 0xd0678b13: 0x2e483cd0 },
1178         "bd_ip_mac_add_del": { 0x257c869: 0x5f2b84e2 },
1179         "bd_ip_mac_details": { 0x545af86a: 0xa52f8044 },
1180         "l2_arp_term_event": { 0x6963e07a: 0x85ff71ea },
1181         "l2tpv3_create_tunnel": { 0x15bed0c2: 0x596892cb },
1182         "sw_if_l2tpv3_tunnel_details": { 0x50b88993: 0x1dab5c7e },
1183         "lisp_add_del_local_eid": { 0x4e5a83a2: 0x21f573bd },
1184         "lisp_add_del_map_server": { 0xce19e32d: 0x6598ea7c },
1185         "lisp_add_del_map_resolver": { 0xce19e32d: 0x6598ea7c },
1186         "lisp_use_petr": { 0xd87dbad9: 0x9e141831 },
1187         "show_lisp_use_petr_reply": { 0x22b9a4b0: 0xdcad8a81 },
1188         "lisp_add_del_remote_mapping": { 0x6d5c789e: 0xfae8ed77 },
1189         "lisp_add_del_adjacency": { 0x2ce0e6f6: 0xcf5edb61 },
1190         "lisp_locator_details": { 0x2c620ffe: 0xc0c4c2a7 },
1191         "lisp_eid_table_details": { 0x1c29f792: 0x4bc32e3a },
1192         "lisp_eid_table_dump": { 0x629468b5: 0xb959b73b },
1193         "lisp_adjacencies_get_reply": { 0x807257bf: 0x3f97bcdd },
1194         "lisp_map_resolver_details": { 0x3e78fc57: 0x82a09deb },
1195         "lisp_map_server_details": { 0x3e78fc57: 0x82a09deb },
1196         "one_add_del_local_eid": { 0x4e5a83a2: 0x21f573bd },
1197         "one_add_del_map_server": { 0xce19e32d: 0x6598ea7c },
1198         "one_add_del_map_resolver": { 0xce19e32d: 0x6598ea7c },
1199         "one_use_petr": { 0xd87dbad9: 0x9e141831 },
1200         "show_one_use_petr_reply": { 0x84a03528: 0x10e744a6 },
1201         "one_add_del_remote_mapping": { 0x6d5c789e: 0xfae8ed77 },
1202         "one_add_del_l2_arp_entry": { 0x1aa5e8b3: 0x33209078 },
1203         "one_l2_arp_entries_get_reply": { 0xb0dd200f: 0xb0a47bbe },
1204         "one_add_del_ndp_entry": { 0xf8a287c: 0xd1629a2f },
1205         "one_ndp_entries_get_reply": { 0x70719b1a: 0xbd34161 },
1206         "one_add_del_adjacency": { 0x9e830312: 0xe48e7afe },
1207         "one_locator_details": { 0x2c620ffe: 0xc0c4c2a7 },
1208         "one_eid_table_details": { 0x1c29f792: 0x4bc32e3a },
1209         "one_eid_table_dump": { 0xbd190269: 0x95151038 },
1210         "one_adjacencies_get_reply": { 0x85bab89: 0xa8ed89a5 },
1211         "one_map_resolver_details": { 0x3e78fc57: 0x82a09deb },
1212         "one_map_server_details": { 0x3e78fc57: 0x82a09deb },
1213         "one_stats_details": { 0x2eb74678: 0xff6ef238 },
1214         "gpe_add_del_fwd_entry": { 0xf0847644: 0xde6df50f },
1215         "gpe_fwd_entries_get_reply": { 0xc4844876: 0xf9f53f1b },
1216         "gpe_fwd_entry_path_details": { 0x483df51a: 0xee80b19a },
1217         "gpe_add_del_native_fwd_rpath": { 0x43fc8b54: 0x812da2f2 },
1218         "gpe_native_fwd_rpaths_get_reply": { 0x7a1ca5a2: 0x79d54eb9 },
1219         "sw_interface_set_lldp": { 0x57afbcd4: 0xd646ae0f },
1220         "mpls_ip_bind_unbind": { 0xc7533b32: 0x48249a27 },
1221         "mpls_tunnel_add_del": { 0x44350ac1: 0xe57ce61d },
1222         "mpls_tunnel_details": { 0x57118ae3: 0xf3c0928e },
1223         "mpls_route_add_del": { 0x8e1d1e07: 0x343cff54 },
1224         "mpls_route_details": { 0x9b5043dc: 0xd0ac384c },
1225         "policer_add_del": { 0x2b31dd38: 0xcb948f6e },
1226         "policer_details": { 0x72d0e248: 0xa43f781a },
1227         "qos_store_enable_disable": { 0xf3abcc8b: 0x3507235e },
1228         "qos_store_details": { 0x3ee0aad7: 0x38a6d48 },
1229         "qos_record_enable_disable": { 0x2f1a4a38: 0x25b33f88 },
1230         "qos_record_details": { 0xa425d4d3: 0x4956ccdd },
1231         "session_rule_add_del": { 0xe4895422: 0xe31f9443 },
1232         "session_rules_details": { 0x28d71830: 0x304b91f0 },
1233         "sw_interface_span_enable_disable": { 0x23ddd96b: 0xacc8fea1 },
1234         "sw_interface_span_details": { 0x8a20e79f: 0x55643fc },
1235         "sr_mpls_steering_add_del": { 0x64acff63: 0x7d1b0a0b },
1236         "sr_mpls_policy_assign_endpoint_color": { 0xe7eb978: 0x5e1c5c13 },
1237         "sr_localsid_add_del": { 0x5a36c324: 0x26fa3309 },
1238         "sr_policy_add": { 0x44ac92e8: 0xec79ee6a },
1239         "sr_policy_mod": { 0xb97bb56e: 0xe531a102 },
1240         "sr_steering_add_del": { 0xe46b0a0f: 0x3711dace },
1241         "sr_localsids_details": { 0x2e9221b9: 0x6a6c0265 },
1242         "sr_policies_details": { 0xdb6ff2a1: 0x7ec2d93 },
1243         "sr_steering_pol_details": { 0xd41258c9: 0x1c1ee786 },
1244         "syslog_set_sender": { 0xb8011d0b: 0xbb641285 },
1245         "syslog_get_sender_reply": { 0x424cfa4e: 0xd3da60ac },
1246         "tcp_configure_src_addresses": { 0x67eede0d: 0x4b02b946 },
1247         "teib_entry_add_del": { 0x8016cfd2: 0x5aa0a538 },
1248         "teib_details": { 0x981ee1a1: 0xe3b6a503 },
1249         "udp_encap_add": { 0xf74a60b1: 0x61d5fc48 },
1250         "udp_encap_details": { 0x8cfb9c76: 0x87c82821 },
1251         "vxlan_gbp_tunnel_add_del": { 0x6c743427: 0x8c819166 },
1252         "vxlan_gbp_tunnel_details": { 0x66e94a89: 0x1da24016 },
1253         "vxlan_gpe_add_del_tunnel": { 0xa645b2b0: 0x7c6da6ae },
1254         "vxlan_gpe_tunnel_details": { 0x968fc8b: 0x57712346 },
1255         "vxlan_add_del_tunnel": { 0xc09dc80: 0xa35dc8f5 },
1256         "vxlan_tunnel_details": { 0xc3916cb1: 0xe782f70f },
1257         "vxlan_offload_rx": { 0x9cc95087: 0x89a1564b },
1258         "log_details": { 0x3d61cc0: 0x255827a1 },
1259 }
1260
1261
1262 def foldup_crcs(s):
1263     for f in s:
1264         f.crc = foldup_blocks(f.block,
1265                               binascii.crc32(f.crc) & 0xffffffff)
1266
1267         # fixup the CRCs to make the fix seamless
1268         if f.name in fixup_crc_dict:
1269             if f.crc in fixup_crc_dict.get(f.name):
1270                 f.crc = fixup_crc_dict.get(f.name).get(f.crc)
1271
1272 #
1273 # Main
1274 #
1275 def main():
1276     if sys.version_info < (3, 5,):
1277         log.exception('vppapigen requires a supported version of python. '
1278                       'Please use version 3.5 or greater. '
1279                       'Using {}'.format(sys.version))
1280         return 1
1281
1282     cliparser = argparse.ArgumentParser(description='VPP API generator')
1283     cliparser.add_argument('--pluginpath', default=""),
1284     cliparser.add_argument('--includedir', action='append'),
1285     cliparser.add_argument('--outputdir', action='store'),
1286     cliparser.add_argument('--input')
1287     cliparser.add_argument('--output', nargs='?',
1288                            type=argparse.FileType('w', encoding='UTF-8'),
1289                            default=sys.stdout)
1290
1291     cliparser.add_argument('output_module', nargs='?', default='C')
1292     cliparser.add_argument('--debug', action='store_true')
1293     cliparser.add_argument('--show-name', nargs=1)
1294     cliparser.add_argument('--git-revision',
1295                            help="Git revision to use for opening files")
1296     args = cliparser.parse_args()
1297
1298     dirlist_add(args.includedir)
1299     if not args.debug:
1300         sys.excepthook = exception_handler
1301
1302     # Filename
1303     if args.show_name:
1304         filename = args.show_name[0]
1305     elif args.input:
1306         filename = args.input
1307     else:
1308         filename = ''
1309
1310     if args.debug:
1311         logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
1312     else:
1313         logging.basicConfig()
1314
1315     parser = VPPAPI(debug=args.debug, filename=filename, logger=log,
1316                     revision=args.git_revision)
1317
1318     try:
1319         if not args.input:
1320             parsed_objects = parser.parse_fd(sys.stdin, log)
1321         else:
1322             parsed_objects = parser.parse_filename(args.input, log)
1323     except ParseError as e:
1324         print('Parse error: ', e, file=sys.stderr)
1325         sys.exit(1)
1326
1327     # Build a list of objects. Hash of lists.
1328     result = []
1329
1330     if args.output_module == 'C':
1331         s = parser.process(parsed_objects)
1332     else:
1333         result = parser.process_imports(parsed_objects, False, result)
1334         s = parser.process(result)
1335
1336     # Add msg_id field
1337     s['Define'] = add_msg_id(s['Define'])
1338
1339     # Fold up CRCs
1340     foldup_crcs(s['Define'])
1341
1342     #
1343     # Debug
1344     if args.debug:
1345         import pprint
1346         pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
1347         for t in s['Define']:
1348             pp.pprint([t.name, t.flags, t.block])
1349         for t in s['types']:
1350             pp.pprint([t.name, t.block])
1351
1352     #
1353     # Generate representation
1354     #
1355     from importlib.machinery import SourceFileLoader
1356
1357     # Default path
1358     pluginpath = ''
1359     if not args.pluginpath:
1360         cand = []
1361         cand.append(os.path.dirname(os.path.realpath(__file__)))
1362         cand.append(os.path.dirname(os.path.realpath(__file__)) +
1363                     '/../share/vpp/')
1364         for c in cand:
1365             c += '/'
1366             if os.path.isfile('{}vppapigen_{}.py'
1367                               .format(c, args.output_module.lower())):
1368                 pluginpath = c
1369                 break
1370     else:
1371         pluginpath = args.pluginpath + '/'
1372     if pluginpath == '':
1373         log.exception('Output plugin not found')
1374         return 1
1375     module_path = '{}vppapigen_{}.py'.format(pluginpath,
1376                                              args.output_module.lower())
1377
1378     try:
1379         plugin = SourceFileLoader(args.output_module,
1380                                   module_path).load_module()
1381     except Exception as err:
1382         log.exception('Error importing output plugin: {}, {}'
1383                       .format(module_path, err))
1384         return 1
1385
1386     result = plugin.run(args, filename, s)
1387     if result:
1388         print(result, file=args.output)
1389     else:
1390         log.exception('Running plugin failed: {} {}'
1391                       .format(filename, result))
1392         return 1
1393     return 0
1394
1395
1396 if __name__ == '__main__':
1397     sys.exit(main())