3 from __future__ import print_function
5 import ply.yacc as yacc
12 # Ensure we don't leave temporary files around
13 sys.dont_write_bytecode = True
19 # Global dictionary of new types (including enums)
23 def global_type_add(name, obj):
24 '''Add new type to the dictionary of types '''
25 type_name = 'vl_api_' + name + '_t'
26 if type_name in global_types:
27 raise KeyError('Type is already defined: {}'.format(name))
28 global_types[type_name] = obj
31 # All your trace are belong to us!
32 def exception_handler(exception_type, exception, traceback):
33 print("%s: %s" % (exception_type.__name__, exception))
39 class VPPAPILexer(object):
40 def __init__(self, filename):
41 self.filename = filename
53 'typeonly': 'TYPEONLY',
54 'manual_print': 'MANUAL_PRINT',
55 'manual_endian': 'MANUAL_ENDIAN',
56 'dont_trace': 'DONT_TRACE',
57 'autoreply': 'AUTOREPLY',
76 tokens = ['STRING_LITERAL',
77 'ID', 'NUM'] + list(reserved.values())
79 t_ignore_LINE_COMMENT = '//.*'
82 r'0[xX][0-9a-fA-F]+|\d+'
83 base = 16 if t.value.startswith('0x') else 10
84 t.value = int(t.value, base)
88 r'[a-zA-Z_][a-zA-Z_0-9]*'
89 # Check for reserved words
90 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
94 def t_STRING_LITERAL(self, t):
95 r'\"([^\\\n]|(\\.))*?\"'
96 t.value = str(t.value).replace("\"", "")
99 # C or C++ comment (ignore)
100 def t_comment(self, t):
101 r'(/\*(.|\n)*?\*/)|(//.*)'
102 t.lexer.lineno += t.value.count('\n')
104 # Error handling rule
105 def t_error(self, t):
106 raise ParseError("Illegal character '{}' ({})"
107 "in {}: line {}".format(t.value[0],
108 hex(ord(t.value[0])),
113 # Define a rule so we can track line numbers
114 def t_newline(self, t):
116 t.lexer.lineno += len(t.value)
118 literals = ":{}[];=.,"
120 # A string containing ignored characters (spaces and tabs)
124 def crc_block_combine(block, crc):
125 s = str(block).encode()
126 return binascii.crc32(s, crc) & 0xffffffff
129 def __init__(self, caller, reply, events=None, stream=False):
133 self.events = [] if events is None else events
137 def __init__(self, name, flags, block):
141 self.crc = str(block).encode()
142 self.manual_print = False
143 self.manual_endian = False
145 if f == 'manual_print':
146 self.manual_print = True
147 elif f == 'manual_endian':
148 self.manual_endian = True
149 global_type_add(name, self)
152 return self.name + str(self.flags) + str(self.block)
156 def __init__(self, name, alias):
159 if isinstance(alias, Array):
160 a = { 'type': alias.fieldtype, # noqa: E201
161 'length': alias.length } # noqa: E202
163 a = { 'type': alias.fieldtype } # noqa: E201,E202
165 self.crc = str(alias).encode()
166 global_type_add(name, self)
169 return self.name + str(self.alias)
173 def __init__(self, name, block):
175 self.manual_print = False
176 self.manual_endian = False
179 self.crc = str(block).encode()
180 global_type_add(name, self)
183 return str(self.block)
187 def __init__(self, name, flags, block):
191 self.crc = str(block).encode()
192 self.dont_trace = False
193 self.manual_print = False
194 self.manual_endian = False
195 self.autoreply = False
196 self.singular = False
198 if f == 'dont_trace':
199 self.dont_trace = True
200 elif f == 'manual_print':
201 self.manual_print = True
202 elif f == 'manual_endian':
203 self.manual_endian = True
204 elif f == 'autoreply':
205 self.autoreply = True
208 if isinstance(b, Option):
209 if b[1] == 'singular' and b[2] == 'true':
214 return self.name + str(self.flags) + str(self.block)
218 def __init__(self, name, block, enumtype='u32'):
220 self.enumtype = enumtype
223 for i, b in enumerate(block):
228 block[i] = [b, count]
231 self.crc = str(block).encode()
232 global_type_add(name, self)
235 return self.name + str(self.block)
239 def __init__(self, filename):
240 self.filename = filename
243 parser = VPPAPI(filename=filename)
244 dirlist = dirlist_get()
247 f = os.path.join(dir, filename)
248 if os.path.exists(f):
250 if sys.version[0] == '2':
252 self.result = parser.parse_file(fd, None)
254 with open(f, encoding='utf-8') as fd:
255 self.result = parser.parse_file(fd, None)
262 def __init__(self, option):
264 self.crc = str(option).encode()
267 return str(self.option)
269 def __getitem__(self, index):
270 return self.option[index]
274 def __init__(self, fieldtype, name, length):
276 self.fieldtype = fieldtype
277 self.fieldname = name
278 if type(length) is str:
279 self.lengthfield = length
283 self.lengthfield = None
286 return str([self.fieldtype, self.fieldname, self.length,
291 def __init__(self, fieldtype, name, limit=None):
293 self.fieldtype = fieldtype
294 self.fieldname = name
298 return str([self.fieldtype, self.fieldname])
302 """ Coordinates of a syntactic element. Consists of:
305 - (optional) column number, for the Lexer
307 __slots__ = ('file', 'line', 'column', '__weakref__')
309 def __init__(self, file, line, column=None):
315 str = "%s:%s" % (self.file, self.line)
317 str += ":%s" % self.column
321 class ParseError(Exception):
328 class VPPAPIParser(object):
329 tokens = VPPAPILexer.tokens
331 def __init__(self, filename, logger):
332 self.filename = filename
336 def _parse_error(self, msg, coord):
337 raise ParseError("%s: %s" % (coord, msg))
339 def _parse_warning(self, msg, coord):
341 self.logger.warning("%s: %s" % (coord, msg))
343 def _coord(self, lineno, column=None):
346 line=lineno, column=column)
348 def _token_coord(self, p, token_idx):
349 """ Returns the coordinates for the YaccProduction object 'p' indexed
350 with 'token_idx'. The coordinate includes the 'lineno' and
351 'column'. Both follow the lex semantic, starting from 1.
353 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
356 column = (p.lexpos(token_idx) - (last_cr))
357 return self._coord(p.lineno(token_idx), column)
359 def p_slist(self, p):
377 def p_import(self, p):
378 '''import : IMPORT STRING_LITERAL ';' '''
381 def p_service(self, p):
382 '''service : SERVICE '{' service_statements '}' ';' '''
385 def p_service_statements(self, p):
386 '''service_statements : service_statement
387 | service_statements service_statement'''
393 def p_service_statement(self, p):
394 '''service_statement : RPC ID RETURNS NULL ';'
395 | RPC ID RETURNS ID ';'
396 | RPC ID RETURNS STREAM ID ';'
397 | RPC ID RETURNS ID EVENTS event_list ';' '''
399 # Verify that caller and reply differ
401 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
402 self._token_coord(p, 1))
404 p[0] = Service(p[2], p[4], p[6])
406 p[0] = Service(p[2], p[5], stream=True)
408 p[0] = Service(p[2], p[4])
410 def p_event_list(self, p):
411 '''event_list : events
412 | event_list events '''
418 def p_event(self, p):
424 '''enum : ENUM ID '{' enum_statements '}' ';' '''
425 p[0] = Enum(p[2], p[4])
427 def p_enum_type(self, p):
428 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
430 p[0] = Enum(p[2], p[6], enumtype=p[4])
432 p[0] = Enum(p[2], p[4])
434 def p_enum_size(self, p):
440 def p_define(self, p):
441 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
443 p[0] = Define(p[2], [], p[4])
445 def p_define_flist(self, p):
446 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
448 if 'typeonly' in p[1]:
449 p[0] = Typedef(p[3], p[1], p[5])
451 p[0] = Define(p[3], p[1], p[5])
453 def p_flist(self, p):
462 '''flag : MANUAL_PRINT
471 def p_typedef(self, p):
472 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
473 p[0] = Typedef(p[2], [], p[4])
475 def p_typedef_alias(self, p):
476 '''typedef : TYPEDEF declaration '''
477 p[0] = Using(p[2].fieldname, p[2])
479 def p_block_statements_opt(self, p):
480 '''block_statements_opt : block_statements '''
483 def p_block_statements(self, p):
484 '''block_statements : block_statement
485 | block_statements block_statement'''
491 def p_block_statement(self, p):
492 '''block_statement : declaration
496 def p_enum_statements(self, p):
497 '''enum_statements : enum_statement
498 | enum_statements enum_statement'''
504 def p_enum_statement(self, p):
505 '''enum_statement : ID '=' NUM ','
512 def p_declaration(self, p):
513 '''declaration : type_specifier ID ';'
514 | type_specifier ID '[' ID '=' assignee ']' ';' '''
516 p[0] = Field(p[1], p[2], {p[4]: p[6]})
518 p[0] = Field(p[1], p[2])
520 self._parse_error('ERROR')
521 self.fields.append(p[2])
524 def p_declaration_array(self, p):
525 '''declaration : type_specifier ID '[' NUM ']' ';'
526 | type_specifier ID '[' ID ']' ';' '''
528 return self._parse_error(
529 'array: %s' % p.value,
530 self._coord(lineno=p.lineno))
532 # Make this error later
533 if type(p[4]) is int and p[4] == 0:
534 # XXX: Line number is wrong
535 self._parse_warning('Old Style VLA: {} {}[{}];'
536 .format(p[1], p[2], p[4]),
537 self._token_coord(p, 1))
539 if type(p[4]) is str and p[4] not in self.fields:
540 # Verify that length field exists
541 self._parse_error('Missing length field: {} {}[{}];'
542 .format(p[1], p[2], p[4]),
543 self._token_coord(p, 1))
544 p[0] = Array(p[1], p[2], p[4])
546 def p_option(self, p):
547 '''option : OPTION ID '=' assignee ';' '''
548 p[0] = Option([p[1], p[2], p[4]])
550 def p_assignee(self, p):
557 def p_type_specifier(self, p):
558 '''type_specifier : U8
571 # Do a second pass later to verify that user defined types are defined
572 def p_typedef_specifier(self, p):
573 '''type_specifier : ID '''
574 if p[1] not in global_types:
575 self._parse_error('Undefined type: {}'.format(p[1]),
576 self._token_coord(p, 1))
579 def p_union(self, p):
580 '''union : UNION ID '{' block_statements_opt '}' ';' '''
581 p[0] = Union(p[2], p[4])
583 # Error rule for syntax errors
584 def p_error(self, p):
587 'before: %s' % p.value,
588 self._coord(lineno=p.lineno))
590 self._parse_error('At end of input', self.filename)
593 class VPPAPI(object):
595 def __init__(self, debug=False, filename='', logger=None):
596 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
597 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
598 write_tables=False, debug=debug)
601 def parse_string(self, code, debug=0, lineno=1):
602 self.lexer.lineno = lineno
603 return self.parser.parse(code, lexer=self.lexer, debug=debug)
605 def parse_file(self, fd, debug=0):
607 return self.parse_string(data, debug=debug)
609 def autoreply_block(self, name):
610 block = [Field('u32', 'context'),
611 Field('i32', 'retval')]
612 return Define(name + '_reply', [], block)
614 def process(self, objs):
624 tname = o.__class__.__name__
626 crc = binascii.crc32(o.crc, crc)
627 except AttributeError:
629 if isinstance(o, Define):
632 s[tname].append(self.autoreply_block(o.name))
633 elif isinstance(o, Option):
634 s[tname][o[1]] = o[2]
635 elif type(o) is list:
637 if isinstance(o2, Service):
638 s['Service'].append(o2)
639 elif (isinstance(o, Enum) or
640 isinstance(o, Typedef) or
641 isinstance(o, Union)):
643 elif isinstance(o, Using):
644 s['Alias'][o.name] = o.alias
647 raise ValueError('Unknown class type: {} {}'
651 msgs = {d.name: d for d in s['Define']}
652 svcs = {s.caller: s for s in s['Service']}
653 replies = {s.reply: s for s in s['Service']}
659 if service not in msgs:
661 'Service definition refers to unknown message'
662 ' definition: {}'.format(service))
663 if svcs[service].reply != 'null' and \
664 svcs[service].reply not in msgs:
665 raise ValueError('Service definition refers to unknown message'
666 ' definition in reply: {}'
667 .format(svcs[service].reply))
668 if service in replies:
669 raise ValueError('Service definition refers to message'
670 ' marked as reply: {}'.format(service))
671 for event in svcs[service].events:
672 if event not in msgs:
673 raise ValueError('Service definition refers to unknown '
674 'event: {} in message: {}'
675 .format(event, service))
676 seen_services[event] = True
678 # Create services implicitly
680 if d in seen_services:
682 if msgs[d].singular is True:
684 if d.endswith('_reply'):
687 if d[:-6] not in msgs:
688 raise ValueError('{} missing calling message'
691 if d.endswith('_dump'):
694 if d[:-5]+'_details' in msgs:
695 s['Service'].append(Service(d, d[:-5]+'_details',
698 raise ValueError('{} missing details message'
702 if d.endswith('_details'):
703 if d[:-8]+'_dump' not in msgs:
704 raise ValueError('{} missing dump message'
710 if d+'_reply' in msgs:
711 s['Service'].append(Service(d, d+'_reply'))
714 '{} missing reply message ({}) or service definition'
715 .format(d, d+'_reply'))
719 def process_imports(self, objs, in_import, result):
722 # Only allow the following object types from imported file
723 if in_import and not (isinstance(o, Enum) or
724 isinstance(o, Union) or
725 isinstance(o, Typedef) or
726 isinstance(o, Import) or
727 isinstance(o, Using)):
729 if isinstance(o, Import):
730 self.process_imports(o.result, True, result)
735 # Add message ids to each message.
738 o.block.insert(0, Field('u16', '_vl_msg_id'))
745 def dirlist_add(dirs):
748 dirlist = dirlist + dirs
754 def foldup_blocks(block, crc):
756 # Look up CRC in user defined types
757 if b.fieldtype.startswith('vl_api_'):
759 t = global_types[b.fieldtype]
761 crc = crc_block_combine(t.block, crc)
762 return foldup_blocks(t.block, crc)
769 f.crc = foldup_blocks(f.block,
770 binascii.crc32(f.crc))
776 cliparser = argparse.ArgumentParser(description='VPP API generator')
777 cliparser.add_argument('--pluginpath', default=""),
778 cliparser.add_argument('--includedir', action='append'),
779 if sys.version[0] == '2':
780 cliparser.add_argument('--input', type=argparse.FileType('r'),
782 cliparser.add_argument('--output', nargs='?',
783 type=argparse.FileType('w'),
787 cliparser.add_argument('--input',
788 type=argparse.FileType('r', encoding='UTF-8'),
790 cliparser.add_argument('--output', nargs='?',
791 type=argparse.FileType('w', encoding='UTF-8'),
794 cliparser.add_argument('output_module', nargs='?', default='C')
795 cliparser.add_argument('--debug', action='store_true')
796 cliparser.add_argument('--show-name', nargs=1)
797 args = cliparser.parse_args()
799 dirlist_add(args.includedir)
801 sys.excepthook = exception_handler
805 filename = args.show_name[0]
806 elif args.input != sys.stdin:
807 filename = args.input.name
812 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
814 logging.basicConfig()
815 log = logging.getLogger('vppapigen')
817 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
818 parsed_objects = parser.parse_file(args.input, log)
820 # Build a list of objects. Hash of lists.
822 parser.process_imports(parsed_objects, False, result)
823 s = parser.process(result)
826 s['Define'] = add_msg_id(s['Define'])
829 foldup_crcs(s['Define'])
835 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
836 for t in s['Define']:
837 pp.pprint([t.name, t.flags, t.block])
839 pp.pprint([t.name, t.block])
842 # Generate representation
844 from importlib.machinery import SourceFileLoader
848 if not args.pluginpath:
850 cand.append(os.path.dirname(os.path.realpath(__file__)))
851 cand.append(os.path.dirname(os.path.realpath(__file__)) +
855 if os.path.isfile('{}vppapigen_{}.py'
856 .format(c, args.output_module.lower())):
860 pluginpath = args.pluginpath + '/'
862 raise Exception('Output plugin not found')
863 module_path = '{}vppapigen_{}.py'.format(pluginpath,
864 args.output_module.lower())
867 plugin = SourceFileLoader(args.output_module,
868 module_path).load_module()
869 except Exception as err:
870 raise Exception('Error importing output plugin: {}, {}'
871 .format(module_path, err))
873 result = plugin.run(filename, s)
875 print(result, file=args.output)
877 raise Exception('Running plugin failed: {} {}'
878 .format(filename, result))
881 if __name__ == '__main__':