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