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