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