c01fa40c1691b709de842d875c9bee390d806f38
[vpp.git] / src / tools / vppapigen / vppapigen.py
1 #!/usr/bin/python3
2
3 import ply.lex as lex
4 import ply.yacc as yacc
5 import sys
6 import argparse
7 import keyword
8 import logging
9 import binascii
10 import os
11
12 log = logging.getLogger('vppapigen')
13
14 # Ensure we don't leave temporary files around
15 sys.dont_write_bytecode = True
16
17 #
18 # VPP API language
19 #
20
21 # Global dictionary of new types (including enums)
22 global_types = {}
23
24
25 def global_type_add(name, obj):
26     '''Add new type to the dictionary of types '''
27     type_name = 'vl_api_' + name + '_t'
28     global_types[type_name] = obj
29
30
31 # All your trace are belong to us!
32 def exception_handler(exception_type, exception, traceback):
33     print("%s: %s" % (exception_type.__name__, exception))
34
35
36 #
37 # Lexer
38 #
39 class VPPAPILexer(object):
40     def __init__(self, filename):
41         self.filename = filename
42
43     reserved = {
44         'service': 'SERVICE',
45         'rpc': 'RPC',
46         'returns': 'RETURNS',
47         'null': 'NULL',
48         'stream': 'STREAM',
49         'events': 'EVENTS',
50         'define': 'DEFINE',
51         'typedef': 'TYPEDEF',
52         'enum': 'ENUM',
53         'typeonly': 'TYPEONLY',
54         'manual_print': 'MANUAL_PRINT',
55         'manual_endian': 'MANUAL_ENDIAN',
56         'dont_trace': 'DONT_TRACE',
57         'autoreply': 'AUTOREPLY',
58         'option': 'OPTION',
59         'u8': 'U8',
60         'u16': 'U16',
61         'u32': 'U32',
62         'u64': 'U64',
63         'i8': 'I8',
64         'i16': 'I16',
65         'i32': 'I32',
66         'i64': 'I64',
67         'f64': 'F64',
68         'bool': 'BOOL',
69         'string': 'STRING',
70         'import': 'IMPORT',
71         'true': 'TRUE',
72         'false': 'FALSE',
73         'union': 'UNION',
74     }
75
76     tokens = ['STRING_LITERAL',
77               'ID', 'NUM'] + list(reserved.values())
78
79     t_ignore_LINE_COMMENT = '//.*'
80
81     def t_NUM(self, t):
82         r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
83         base = 16 if t.value.startswith('0x') else 10
84         if '.' in t.value:
85             t.value = float(t.value)
86         else:
87             t.value = int(t.value, base)
88         return t
89
90     def t_ID(self, t):
91         r'[a-zA-Z_][a-zA-Z_0-9]*'
92         # Check for reserved words
93         t.type = VPPAPILexer.reserved.get(t.value, 'ID')
94         return t
95
96     # C string
97     def t_STRING_LITERAL(self, t):
98         r'\"([^\\\n]|(\\.))*?\"'
99         t.value = str(t.value).replace("\"", "")
100         return t
101
102     # C or C++ comment (ignore)
103     def t_comment(self, t):
104         r'(/\*(.|\n)*?\*/)|(//.*)'
105         t.lexer.lineno += t.value.count('\n')
106
107     # Error handling rule
108     def t_error(self, t):
109         raise ParseError("Illegal character '{}' ({})"
110                          "in {}: line {}".format(t.value[0],
111                                                  hex(ord(t.value[0])),
112                                                  self.filename,
113                                                  t.lexer.lineno))
114         t.lexer.skip(1)
115
116     # Define a rule so we can track line numbers
117     def t_newline(self, t):
118         r'\n+'
119         t.lexer.lineno += len(t.value)
120
121     literals = ":{}[];=.,"
122
123     # A string containing ignored characters (spaces and tabs)
124     t_ignore = ' \t'
125
126
127 def crc_block_combine(block, crc):
128     s = str(block).encode()
129     return binascii.crc32(s, crc) & 0xffffffff
130
131
132 class Service():
133     def __init__(self, caller, reply, events=None, stream=False):
134         self.caller = caller
135         self.reply = reply
136         self.stream = stream
137         self.events = [] if events is None else events
138
139
140 class Typedef():
141     def __init__(self, name, flags, block):
142         self.name = name
143         self.flags = flags
144         self.block = block
145         self.crc = str(block).encode()
146         self.manual_print = False
147         self.manual_endian = False
148         for f in flags:
149             if f == 'manual_print':
150                 self.manual_print = True
151             elif f == 'manual_endian':
152                 self.manual_endian = True
153         global_type_add(name, self)
154
155     def __repr__(self):
156         return self.name + str(self.flags) + str(self.block)
157
158
159 class Using():
160     def __init__(self, name, alias):
161         self.name = name
162
163         if isinstance(alias, Array):
164             a = { 'type': alias.fieldtype,  # noqa: E201
165                   'length': alias.length }  # noqa: E202
166         else:
167             a = { 'type': alias.fieldtype }  # noqa: E201,E202
168         self.alias = a
169         self.crc = str(alias).encode()
170         global_type_add(name, self)
171
172     def __repr__(self):
173         return self.name + str(self.alias)
174
175
176 class Union():
177     def __init__(self, name, block):
178         self.type = 'Union'
179         self.manual_print = False
180         self.manual_endian = False
181         self.name = name
182         self.block = block
183         self.crc = str(block).encode()
184         global_type_add(name, self)
185
186     def __repr__(self):
187         return str(self.block)
188
189
190 class Define():
191     def __init__(self, name, flags, block):
192         self.name = name
193         self.flags = flags
194         self.block = block
195         self.crc = str(block).encode()
196         self.dont_trace = False
197         self.manual_print = False
198         self.manual_endian = False
199         self.autoreply = False
200         self.singular = False
201         for f in flags:
202             if f == 'dont_trace':
203                 self.dont_trace = True
204             elif f == 'manual_print':
205                 self.manual_print = True
206             elif f == 'manual_endian':
207                 self.manual_endian = True
208             elif f == 'autoreply':
209                 self.autoreply = True
210
211         for b in block:
212             if isinstance(b, Option):
213                 if b[1] == 'singular' and b[2] == 'true':
214                     self.singular = True
215                 block.remove(b)
216
217     def __repr__(self):
218         return self.name + str(self.flags) + str(self.block)
219
220
221 class Enum():
222     def __init__(self, name, block, enumtype='u32'):
223         self.name = name
224         self.enumtype = enumtype
225
226         count = 0
227         for i, b in enumerate(block):
228             if type(b) is list:
229                 count = b[1]
230             else:
231                 count += 1
232                 block[i] = [b, count]
233
234         self.block = block
235         self.crc = str(block).encode()
236         global_type_add(name, self)
237
238     def __repr__(self):
239         return self.name + str(self.block)
240
241
242 class Import():
243     def __init__(self, filename):
244         self.filename = filename
245
246         # Deal with imports
247         parser = VPPAPI(filename=filename)
248         dirlist = dirlist_get()
249         f = filename
250         for dir in dirlist:
251             f = os.path.join(dir, filename)
252             if os.path.exists(f):
253                 break
254
255         with open(f, encoding='utf-8') as fd:
256             self.result = parser.parse_file(fd, None)
257
258     def __repr__(self):
259         return self.filename
260
261
262 class Option():
263     def __init__(self, option):
264         self.option = option
265         self.crc = str(option).encode()
266
267     def __repr__(self):
268         return str(self.option)
269
270     def __getitem__(self, index):
271         return self.option[index]
272
273
274 class Array():
275     def __init__(self, fieldtype, name, length):
276         self.type = 'Array'
277         self.fieldtype = fieldtype
278         self.fieldname = name
279         if type(length) is str:
280             self.lengthfield = length
281             self.length = 0
282         else:
283             self.length = length
284             self.lengthfield = None
285
286     def __repr__(self):
287         return str([self.fieldtype, self.fieldname, self.length,
288                     self.lengthfield])
289
290
291 class Field():
292     def __init__(self, fieldtype, name, limit=None):
293         self.type = 'Field'
294         self.fieldtype = fieldtype
295         if name in keyword.kwlist:
296             raise ValueError("Fieldname {!r} is a python keyword and is not "
297                              "accessible via the python API. ".format(name))
298         self.fieldname = name
299         self.limit = limit
300
301     def __repr__(self):
302         return str([self.fieldtype, self.fieldname])
303
304
305 class Coord(object):
306     """ Coordinates of a syntactic element. Consists of:
307             - File name
308             - Line number
309             - (optional) column number, for the Lexer
310     """
311     __slots__ = ('file', 'line', 'column', '__weakref__')
312
313     def __init__(self, file, line, column=None):
314         self.file = file
315         self.line = line
316         self.column = column
317
318     def __str__(self):
319         str = "%s:%s" % (self.file, self.line)
320         if self.column:
321             str += ":%s" % self.column
322         return str
323
324
325 class ParseError(Exception):
326     pass
327
328
329 #
330 # Grammar rules
331 #
332 class VPPAPIParser(object):
333     tokens = VPPAPILexer.tokens
334
335     def __init__(self, filename, logger):
336         self.filename = filename
337         self.logger = logger
338         self.fields = []
339
340     def _parse_error(self, msg, coord):
341         raise ParseError("%s: %s" % (coord, msg))
342
343     def _parse_warning(self, msg, coord):
344         if self.logger:
345             self.logger.warning("%s: %s" % (coord, msg))
346
347     def _coord(self, lineno, column=None):
348         return Coord(
349                 file=self.filename,
350                 line=lineno, column=column)
351
352     def _token_coord(self, p, token_idx):
353         """ Returns the coordinates for the YaccProduction object 'p' indexed
354             with 'token_idx'. The coordinate includes the 'lineno' and
355             'column'. Both follow the lex semantic, starting from 1.
356         """
357         last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
358         if last_cr < 0:
359             last_cr = -1
360         column = (p.lexpos(token_idx) - (last_cr))
361         return self._coord(p.lineno(token_idx), column)
362
363     def p_slist(self, p):
364         '''slist : stmt
365                  | slist stmt'''
366         if len(p) == 2:
367             p[0] = [p[1]]
368         else:
369             p[0] = p[1] + [p[2]]
370
371     def p_stmt(self, p):
372         '''stmt : define
373                 | typedef
374                 | option
375                 | import
376                 | enum
377                 | union
378                 | service'''
379         p[0] = p[1]
380
381     def p_import(self, p):
382         '''import : IMPORT STRING_LITERAL ';' '''
383         p[0] = Import(p[2])
384
385     def p_service(self, p):
386         '''service : SERVICE '{' service_statements '}' ';' '''
387         p[0] = p[3]
388
389     def p_service_statements(self, p):
390         '''service_statements : service_statement
391                         | service_statements service_statement'''
392         if len(p) == 2:
393             p[0] = [p[1]]
394         else:
395             p[0] = p[1] + [p[2]]
396
397     def p_service_statement(self, p):
398         '''service_statement : RPC ID RETURNS NULL ';'
399                              | RPC ID RETURNS ID ';'
400                              | RPC ID RETURNS STREAM ID ';'
401                              | RPC ID RETURNS ID EVENTS event_list ';' '''
402         if p[2] == p[4]:
403             # Verify that caller and reply differ
404             self._parse_error(
405                 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
406                 self._token_coord(p, 1))
407         if len(p) == 8:
408             p[0] = Service(p[2], p[4], p[6])
409         elif len(p) == 7:
410             p[0] = Service(p[2], p[5], stream=True)
411         else:
412             p[0] = Service(p[2], p[4])
413
414     def p_event_list(self, p):
415         '''event_list : events
416                       | event_list events '''
417         if len(p) == 2:
418             p[0] = [p[1]]
419         else:
420             p[0] = p[1] + [p[2]]
421
422     def p_event(self, p):
423         '''events : ID
424                   | ID ',' '''
425         p[0] = p[1]
426
427     def p_enum(self, p):
428         '''enum : ENUM ID '{' enum_statements '}' ';' '''
429         p[0] = Enum(p[2], p[4])
430
431     def p_enum_type(self, p):
432         ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
433         if len(p) == 9:
434             p[0] = Enum(p[2], p[6], enumtype=p[4])
435         else:
436             p[0] = Enum(p[2], p[4])
437
438     def p_enum_size(self, p):
439         ''' enum_size : U8
440                       | U16
441                       | U32 '''
442         p[0] = p[1]
443
444     def p_define(self, p):
445         '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
446         self.fields = []
447         p[0] = Define(p[2], [], p[4])
448
449     def p_define_flist(self, p):
450         '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
451         # Legacy typedef
452         if 'typeonly' in p[1]:
453             self._parse_error('legacy typedef. use typedef: {} {}[{}];'
454                               .format(p[1], p[2], p[4]),
455                               self._token_coord(p, 1))
456         else:
457             p[0] = Define(p[3], p[1], p[5])
458
459     def p_flist(self, p):
460         '''flist : flag
461                  | flist flag'''
462         if len(p) == 2:
463             p[0] = [p[1]]
464         else:
465             p[0] = p[1] + [p[2]]
466
467     def p_flag(self, p):
468         '''flag : MANUAL_PRINT
469                 | MANUAL_ENDIAN
470                 | DONT_TRACE
471                 | TYPEONLY
472                 | AUTOREPLY'''
473         if len(p) == 1:
474             return
475         p[0] = p[1]
476
477     def p_typedef(self, p):
478         '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
479         p[0] = Typedef(p[2], [], p[4])
480
481     def p_typedef_alias(self, p):
482         '''typedef : TYPEDEF declaration '''
483         p[0] = Using(p[2].fieldname, p[2])
484
485     def p_block_statements_opt(self, p):
486         '''block_statements_opt : block_statements '''
487         p[0] = p[1]
488
489     def p_block_statements(self, p):
490         '''block_statements : block_statement
491                             | block_statements block_statement'''
492         if len(p) == 2:
493             p[0] = [p[1]]
494         else:
495             p[0] = p[1] + [p[2]]
496
497     def p_block_statement(self, p):
498         '''block_statement : declaration
499                            | option '''
500         p[0] = p[1]
501
502     def p_enum_statements(self, p):
503         '''enum_statements : enum_statement
504                            | enum_statements enum_statement'''
505         if len(p) == 2:
506             p[0] = [p[1]]
507         else:
508             p[0] = p[1] + [p[2]]
509
510     def p_enum_statement(self, p):
511         '''enum_statement : ID '=' NUM ','
512                           | ID ',' '''
513         if len(p) == 5:
514             p[0] = [p[1], p[3]]
515         else:
516             p[0] = p[1]
517
518     def p_field_options(self, p):
519         '''field_options : field_option
520                            | field_options field_option'''
521         if len(p) == 2:
522             p[0] = p[1]
523         else:
524             p[0] = { **p[1], **p[2] }
525
526     def p_field_option(self, p):
527         '''field_option : ID '=' assignee ','
528                         | ID '=' assignee
529         '''
530         p[0] = { p[1]: p[3] }
531
532     def p_declaration(self, p):
533         '''declaration : type_specifier ID ';'
534                        | type_specifier ID '[' field_options ']' ';' '''
535         if len(p) == 7:
536             p[0] = Field(p[1], p[2], p[4])
537         elif len(p) == 4:
538             p[0] = Field(p[1], p[2])
539         else:
540             self._parse_error('ERROR')
541         self.fields.append(p[2])
542
543     def p_declaration_array(self, p):
544         '''declaration : type_specifier ID '[' NUM ']' ';'
545                        | type_specifier ID '[' ID ']' ';' '''
546         if len(p) != 7:
547             return self._parse_error(
548                 'array: %s' % p.value,
549                 self._coord(lineno=p.lineno))
550
551         # Make this error later
552         if type(p[4]) is int and p[4] == 0:
553             # XXX: Line number is wrong
554             self._parse_warning('Old Style VLA: {} {}[{}];'
555                                 .format(p[1], p[2], p[4]),
556                                 self._token_coord(p, 1))
557
558         if type(p[4]) is str and p[4] not in self.fields:
559             # Verify that length field exists
560             self._parse_error('Missing length field: {} {}[{}];'
561                               .format(p[1], p[2], p[4]),
562                               self._token_coord(p, 1))
563         p[0] = Array(p[1], p[2], p[4])
564
565     def p_option(self, p):
566         '''option : OPTION ID '=' assignee ';' '''
567         p[0] = Option([p[1], p[2], p[4]])
568
569     def p_assignee(self, p):
570         '''assignee : NUM
571                     | TRUE
572                     | FALSE
573                     | STRING_LITERAL '''
574         p[0] = p[1]
575
576     def p_type_specifier(self, p):
577         '''type_specifier : U8
578                           | U16
579                           | U32
580                           | U64
581                           | I8
582                           | I16
583                           | I32
584                           | I64
585                           | F64
586                           | BOOL
587                           | STRING'''
588         p[0] = p[1]
589
590     # Do a second pass later to verify that user defined types are defined
591     def p_typedef_specifier(self, p):
592         '''type_specifier : ID '''
593         if p[1] not in global_types:
594             self._parse_error('Undefined type: {}'.format(p[1]),
595                               self._token_coord(p, 1))
596         p[0] = p[1]
597
598     def p_union(self, p):
599         '''union : UNION ID '{' block_statements_opt '}' ';' '''
600         p[0] = Union(p[2], p[4])
601
602     # Error rule for syntax errors
603     def p_error(self, p):
604         if p:
605             self._parse_error(
606                 'before: %s' % p.value,
607                 self._coord(lineno=p.lineno))
608         else:
609             self._parse_error('At end of input', self.filename)
610
611
612 class VPPAPI(object):
613
614     def __init__(self, debug=False, filename='', logger=None):
615         self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
616         self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
617                                 write_tables=False, debug=debug)
618         self.logger = logger
619
620     def parse_string(self, code, debug=0, lineno=1):
621         self.lexer.lineno = lineno
622         return self.parser.parse(code, lexer=self.lexer, debug=debug)
623
624     def parse_file(self, fd, debug=0):
625         data = fd.read()
626         return self.parse_string(data, debug=debug)
627
628     def autoreply_block(self, name):
629         block = [Field('u32', 'context'),
630                  Field('i32', 'retval')]
631         return Define(name + '_reply', [], block)
632
633     def process(self, objs):
634         s = {}
635         s['Option'] = {}
636         s['Define'] = []
637         s['Service'] = []
638         s['types'] = []
639         s['Import'] = []
640         s['Alias'] = {}
641         crc = 0
642         for o in objs:
643             tname = o.__class__.__name__
644             try:
645                 crc = binascii.crc32(o.crc, crc)
646             except AttributeError:
647                 pass
648             if isinstance(o, Define):
649                 s[tname].append(o)
650                 if o.autoreply:
651                     s[tname].append(self.autoreply_block(o.name))
652             elif isinstance(o, Option):
653                 s[tname][o[1]] = o[2]
654             elif type(o) is list:
655                 for o2 in o:
656                     if isinstance(o2, Service):
657                         s['Service'].append(o2)
658             elif (isinstance(o, Enum) or
659                   isinstance(o, Typedef) or
660                   isinstance(o, Union)):
661                 s['types'].append(o)
662             elif isinstance(o, Using):
663                 s['Alias'][o.name] = o.alias
664             else:
665                 if tname not in s:
666                     raise ValueError('Unknown class type: {} {}'
667                                      .format(tname, o))
668                 s[tname].append(o)
669
670         msgs = {d.name: d for d in s['Define']}
671         svcs = {s.caller: s for s in s['Service']}
672         replies = {s.reply: s for s in s['Service']}
673         seen_services = {}
674
675         s['file_crc'] = crc
676
677         for service in svcs:
678             if service not in msgs:
679                 raise ValueError(
680                     'Service definition refers to unknown message'
681                     ' definition: {}'.format(service))
682             if svcs[service].reply != 'null' and \
683                svcs[service].reply not in msgs:
684                 raise ValueError('Service definition refers to unknown message'
685                                  ' definition in reply: {}'
686                                  .format(svcs[service].reply))
687             if service in replies:
688                 raise ValueError('Service definition refers to message'
689                                  ' marked as reply: {}'.format(service))
690             for event in svcs[service].events:
691                 if event not in msgs:
692                     raise ValueError('Service definition refers to unknown '
693                                      'event: {} in message: {}'
694                                      .format(event, service))
695                 seen_services[event] = True
696
697         # Create services implicitly
698         for d in msgs:
699             if d in seen_services:
700                 continue
701             if msgs[d].singular is True:
702                 continue
703             if d.endswith('_reply'):
704                 if d[:-6] in svcs:
705                     continue
706                 if d[:-6] not in msgs:
707                     raise ValueError('{} missing calling message'
708                                      .format(d))
709                 continue
710             if d.endswith('_dump'):
711                 if d in svcs:
712                     continue
713                 if d[:-5]+'_details' in msgs:
714                     s['Service'].append(Service(d, d[:-5]+'_details',
715                                                 stream=True))
716                 else:
717                     raise ValueError('{} missing details message'
718                                      .format(d))
719                 continue
720
721             if d.endswith('_details'):
722                 if d[:-8]+'_dump' not in msgs:
723                     raise ValueError('{} missing dump message'
724                                      .format(d))
725                 continue
726
727             if d in svcs:
728                 continue
729             if d+'_reply' in msgs:
730                 s['Service'].append(Service(d, d+'_reply'))
731             else:
732                 raise ValueError(
733                     '{} missing reply message ({}) or service definition'
734                     .format(d, d+'_reply'))
735
736         return s
737
738     def process_imports(self, objs, in_import, result):
739         imported_objs = []
740         for o in objs:
741             # Only allow the following object types from imported file
742             if in_import and not (isinstance(o, Enum) or
743                                   isinstance(o, Union) or
744                                   isinstance(o, Typedef) or
745                                   isinstance(o, Import) or
746                                   isinstance(o, Using)):
747                 continue
748             if isinstance(o, Import):
749                 self.process_imports(o.result, True, result)
750             else:
751                 result.append(o)
752
753
754 # Add message ids to each message.
755 def add_msg_id(s):
756     for o in s:
757         o.block.insert(0, Field('u16', '_vl_msg_id'))
758     return s
759
760
761 dirlist = []
762
763
764 def dirlist_add(dirs):
765     global dirlist
766     if dirs:
767         dirlist = dirlist + dirs
768
769
770 def dirlist_get():
771     return dirlist
772
773
774 def foldup_blocks(block, crc):
775     for b in block:
776         # Look up CRC in user defined types
777         if b.fieldtype.startswith('vl_api_'):
778             # Recursively
779             t = global_types[b.fieldtype]
780             try:
781                 crc = crc_block_combine(t.block, crc)
782                 return foldup_blocks(t.block, crc)
783             except:
784                 pass
785     return crc
786
787
788 def foldup_crcs(s):
789     for f in s:
790         f.crc = foldup_blocks(f.block,
791                               binascii.crc32(f.crc))
792
793
794 #
795 # Main
796 #
797 def main():
798     if sys.version_info < (3, 5,):
799         log.exception('vppapigen requires a supported version of python. '
800                       'Please use version 3.5 or greater. '
801                       'Using {}'.format(sys.version))
802         return 1
803
804     cliparser = argparse.ArgumentParser(description='VPP API generator')
805     cliparser.add_argument('--pluginpath', default=""),
806     cliparser.add_argument('--includedir', action='append'),
807     cliparser.add_argument('--input',
808                            type=argparse.FileType('r', encoding='UTF-8'),
809                            default=sys.stdin)
810     cliparser.add_argument('--output', nargs='?',
811                            type=argparse.FileType('w', encoding='UTF-8'),
812                            default=sys.stdout)
813
814     cliparser.add_argument('output_module', nargs='?', default='C')
815     cliparser.add_argument('--debug', action='store_true')
816     cliparser.add_argument('--show-name', nargs=1)
817     args = cliparser.parse_args()
818
819     dirlist_add(args.includedir)
820     if not args.debug:
821         sys.excepthook = exception_handler
822
823     # Filename
824     if args.show_name:
825         filename = args.show_name[0]
826     elif args.input != sys.stdin:
827         filename = args.input.name
828     else:
829         filename = ''
830
831     if args.debug:
832         logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
833     else:
834         logging.basicConfig()
835
836     parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
837     parsed_objects = parser.parse_file(args.input, log)
838
839     # Build a list of objects. Hash of lists.
840     result = []
841     parser.process_imports(parsed_objects, False, result)
842     s = parser.process(result)
843
844     # Add msg_id field
845     s['Define'] = add_msg_id(s['Define'])
846
847     # Fold up CRCs
848     foldup_crcs(s['Define'])
849
850     #
851     # Debug
852     if args.debug:
853         import pprint
854         pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
855         for t in s['Define']:
856             pp.pprint([t.name, t.flags, t.block])
857         for t in s['types']:
858             pp.pprint([t.name, t.block])
859
860     #
861     # Generate representation
862     #
863     from importlib.machinery import SourceFileLoader
864
865     # Default path
866     pluginpath = ''
867     if not args.pluginpath:
868         cand = []
869         cand.append(os.path.dirname(os.path.realpath(__file__)))
870         cand.append(os.path.dirname(os.path.realpath(__file__)) +
871                     '/../share/vpp/')
872         for c in cand:
873             c += '/'
874             if os.path.isfile('{}vppapigen_{}.py'
875                               .format(c, args.output_module.lower())):
876                 pluginpath = c
877                 break
878     else:
879         pluginpath = args.pluginpath + '/'
880     if pluginpath == '':
881         log.exception('Output plugin not found')
882         return 1
883     module_path = '{}vppapigen_{}.py'.format(pluginpath,
884                                              args.output_module.lower())
885
886     try:
887         plugin = SourceFileLoader(args.output_module,
888                                   module_path).load_module()
889     except Exception as err:
890         log.exception('Error importing output plugin: {}, {}'
891                       .format(module_path, err))
892         return 1
893
894     result = plugin.run(filename, s)
895     if result:
896         print(result, file=args.output)
897     else:
898         log.exception('Running plugin failed: {} {}'
899                       .format(filename, result))
900         return 1
901     return 0
902
903
904 if __name__ == '__main__':
905     sys.exit(main())