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