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)
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
32 # All your trace are belong to us!
33 def exception_handler(exception_type, exception, traceback):
34 print("%s: %s" % (exception_type.__name__, exception))
40 class VPPAPILexer(object):
41 def __init__(self, filename):
42 self.filename = filename
54 'typeonly': 'TYPEONLY',
55 'manual_print': 'MANUAL_PRINT',
56 'manual_endian': 'MANUAL_ENDIAN',
57 'dont_trace': 'DONT_TRACE',
58 'autoreply': 'AUTOREPLY',
77 tokens = ['STRING_LITERAL',
78 'ID', 'NUM'] + list(reserved.values())
80 t_ignore_LINE_COMMENT = '//.*'
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)
89 r'[a-zA-Z_][a-zA-Z_0-9]*'
90 # Check for reserved words
91 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
95 def t_STRING_LITERAL(self, t):
96 r'\"([^\\\n]|(\\.))*?\"'
97 t.value = str(t.value).replace("\"", "")
100 # C or C++ comment (ignore)
101 def t_comment(self, t):
102 r'(/\*(.|\n)*?\*/)|(//.*)'
103 t.lexer.lineno += t.value.count('\n')
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])),
114 # Define a rule so we can track line numbers
115 def t_newline(self, t):
117 t.lexer.lineno += len(t.value)
119 literals = ":{}[];=.,"
121 # A string containing ignored characters (spaces and tabs)
126 def __init__(self, caller, reply, events=[], stream=False):
134 def __init__(self, name, flags, block):
139 self.crc = binascii.crc32(str(block)) & 0xffffffff
140 global_crc = binascii.crc32(str(block), global_crc)
141 self.manual_print = False
142 self.manual_endian = False
144 if f == 'manual_print':
145 self.manual_print = True
146 elif f == 'manual_endian':
147 self.manual_endian = True
148 global_type_add(name)
151 return self.name + str(self.flags) + str(self.block)
155 def __init__(self, name, block):
157 self.manual_print = False
158 self.manual_endian = False
162 self.crc = binascii.crc32(str(block)) & 0xffffffff
163 global_crc = binascii.crc32(str(block), global_crc)
164 global_type_add(name)
167 return str(self.block)
171 def __init__(self, name, flags, block):
176 self.crc = binascii.crc32(str(block)) & 0xffffffff
177 global_crc = binascii.crc32(str(block), global_crc)
178 self.dont_trace = False
179 self.manual_print = False
180 self.manual_endian = False
181 self.autoreply = False
182 self.singular = False
184 if f == 'dont_trace':
185 self.dont_trace = True
186 elif f == 'manual_print':
187 self.manual_print = True
188 elif f == 'manual_endian':
189 self.manual_endian = True
190 elif f == 'autoreply':
191 self.autoreply = True
194 if isinstance(b, Option):
195 if b[1] == 'singular' and b[2] == 'true':
200 return self.name + str(self.flags) + str(self.block)
204 def __init__(self, name, block, enumtype='u32'):
207 self.enumtype = enumtype
210 for i, b in enumerate(block):
215 block[i] = [b, count]
218 self.crc = binascii.crc32(str(block)) & 0xffffffff
219 global_crc = binascii.crc32(str(block), global_crc)
220 global_type_add(name)
223 return self.name + str(self.block)
227 def __init__(self, filename):
228 self.filename = filename
231 parser = VPPAPI(filename=filename)
232 dirlist = dirlist_get()
235 f = os.path.join(dir, filename)
236 if os.path.exists(f):
239 self.result = parser.parse_file(fd, None)
246 def __init__(self, option):
249 self.crc = binascii.crc32(str(option)) & 0xffffffff
250 global_crc = binascii.crc32(str(option), global_crc)
253 return str(self.option)
255 def __getitem__(self, index):
256 return self.option[index]
260 def __init__(self, fieldtype, name, length):
262 self.fieldtype = fieldtype
263 self.fieldname = name
264 if type(length) is str:
265 self.lengthfield = length
269 self.lengthfield = None
272 return str([self.fieldtype, self.fieldname, self.length,
277 def __init__(self, fieldtype, name):
279 self.fieldtype = fieldtype
280 self.fieldname = name
283 return str([self.fieldtype, self.fieldname])
287 """ Coordinates of a syntactic element. Consists of:
290 - (optional) column number, for the Lexer
292 __slots__ = ('file', 'line', 'column', '__weakref__')
294 def __init__(self, file, line, column=None):
300 str = "%s:%s" % (self.file, self.line)
302 str += ":%s" % self.column
306 class ParseError(Exception):
313 class VPPAPIParser(object):
314 tokens = VPPAPILexer.tokens
316 def __init__(self, filename, logger):
317 self.filename = filename
321 def _parse_error(self, msg, coord):
322 raise ParseError("%s: %s" % (coord, msg))
324 def _parse_warning(self, msg, coord):
326 self.logger.warning("%s: %s" % (coord, msg))
328 def _coord(self, lineno, column=None):
331 line=lineno, column=column)
333 def _token_coord(self, p, token_idx):
334 """ Returns the coordinates for the YaccProduction object 'p' indexed
335 with 'token_idx'. The coordinate includes the 'lineno' and
336 'column'. Both follow the lex semantic, starting from 1.
338 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
341 column = (p.lexpos(token_idx) - (last_cr))
342 return self._coord(p.lineno(token_idx), column)
344 def p_slist(self, p):
362 def p_import(self, p):
363 '''import : IMPORT STRING_LITERAL ';' '''
366 def p_service(self, p):
367 '''service : SERVICE '{' service_statements '}' ';' '''
370 def p_service_statements(self, p):
371 '''service_statements : service_statement
372 | service_statements service_statement'''
378 def p_service_statement(self, p):
379 '''service_statement : RPC ID RETURNS NULL ';'
380 | RPC ID RETURNS ID ';'
381 | RPC ID RETURNS STREAM ID ';'
382 | RPC ID RETURNS ID EVENTS event_list ';' '''
384 # Verify that caller and reply differ
386 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
387 self._token_coord(p, 1))
389 p[0] = Service(p[2], p[4], p[6])
391 p[0] = Service(p[2], p[5], stream=True)
393 p[0] = Service(p[2], p[4])
395 def p_event_list(self, p):
396 '''event_list : events
397 | event_list events '''
403 def p_event(self, p):
409 '''enum : ENUM ID '{' enum_statements '}' ';' '''
410 p[0] = Enum(p[2], p[4])
412 def p_enum_type(self, p):
413 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
415 p[0] = Enum(p[2], p[6], enumtype=p[4])
417 p[0] = Enum(p[2], p[4])
419 def p_enum_size(self, p):
425 def p_define(self, p):
426 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
428 p[0] = Define(p[2], [], p[4])
430 def p_define_flist(self, p):
431 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
433 if 'typeonly' in p[1]:
434 p[0] = Typedef(p[3], p[1], p[5])
436 p[0] = Define(p[3], p[1], p[5])
438 def p_flist(self, p):
447 '''flag : MANUAL_PRINT
456 def p_typedef(self, p):
457 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
458 p[0] = Typedef(p[2], [], p[4])
460 def p_block_statements_opt(self, p):
461 '''block_statements_opt : block_statements '''
464 def p_block_statements(self, p):
465 '''block_statements : block_statement
466 | block_statements block_statement'''
472 def p_block_statement(self, p):
473 '''block_statement : declaration
477 def p_enum_statements(self, p):
478 '''enum_statements : enum_statement
479 | enum_statements enum_statement'''
485 def p_enum_statement(self, p):
486 '''enum_statement : ID '=' NUM ','
493 def p_declaration(self, p):
494 '''declaration : type_specifier ID ';' '''
496 self._parse_error('ERROR')
497 self.fields.append(p[2])
498 p[0] = Field(p[1], p[2])
500 def p_declaration_array(self, p):
501 '''declaration : type_specifier ID '[' NUM ']' ';'
502 | type_specifier ID '[' ID ']' ';' '''
504 return self._parse_error(
505 'array: %s' % p.value,
506 self._coord(lineno=p.lineno))
508 # Make this error later
509 if type(p[4]) is int and p[4] == 0:
510 # XXX: Line number is wrong
511 self._parse_warning('Old Style VLA: {} {}[{}];'
512 .format(p[1], p[2], p[4]),
513 self._token_coord(p, 1))
515 if type(p[4]) is str and p[4] not in self.fields:
516 # Verify that length field exists
517 self._parse_error('Missing length field: {} {}[{}];'
518 .format(p[1], p[2], p[4]),
519 self._token_coord(p, 1))
520 p[0] = Array(p[1], p[2], p[4])
522 def p_option(self, p):
523 '''option : OPTION ID '=' assignee ';' '''
524 p[0] = Option([p[1], p[2], p[4]])
526 def p_assignee(self, p):
533 def p_type_specifier(self, p):
534 '''type_specifier : U8
547 # Do a second pass later to verify that user defined types are defined
548 def p_typedef_specifier(self, p):
549 '''type_specifier : ID '''
550 if p[1] not in global_types:
551 self._parse_error('Undefined type: {}'.format(p[1]),
552 self._token_coord(p, 1))
555 def p_union(self, p):
556 '''union : UNION ID '{' block_statements_opt '}' ';' '''
557 p[0] = Union(p[2], p[4])
559 # Error rule for syntax errors
560 def p_error(self, p):
563 'before: %s' % p.value,
564 self._coord(lineno=p.lineno))
566 self._parse_error('At end of input', self.filename)
569 class VPPAPI(object):
571 def __init__(self, debug=False, filename='', logger=None):
572 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
573 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
574 write_tables=False, debug=debug)
577 def parse_string(self, code, debug=0, lineno=1):
578 self.lexer.lineno = lineno
579 return self.parser.parse(code, lexer=self.lexer, debug=debug)
581 def parse_file(self, fd, debug=0):
583 return self.parse_string(data, debug=debug)
585 def autoreply_block(self, name):
586 block = [Field('u32', 'context'),
587 Field('i32', 'retval')]
588 return Define(name + '_reply', [], block)
590 def process(self, objs):
598 tname = o.__class__.__name__
599 if isinstance(o, Define):
602 s[tname].append(self.autoreply_block(o.name))
603 elif isinstance(o, Option):
604 s[tname][o[1]] = o[2]
605 elif type(o) is list:
607 if isinstance(o2, Service):
608 s['Service'].append(o2)
609 elif isinstance(o, Enum) or isinstance(o, Typedef) or isinstance(o, Union):
613 raise ValueError('Unknown class type: {} {}'.format(tname, o))
616 msgs = {d.name: d for d in s['Define']}
617 svcs = {s.caller: s for s in s['Service']}
618 replies = {s.reply: s for s in s['Service']}
622 if service not in msgs:
624 'Service definition refers to unknown message'
625 ' definition: {}'.format(service))
626 if svcs[service].reply != 'null' and \
627 svcs[service].reply not in msgs:
628 raise ValueError('Service definition refers to unknown message'
629 ' definition in reply: {}'
630 .format(svcs[service].reply))
631 if service in replies:
632 raise ValueError('Service definition refers to message'
633 ' marked as reply: {}'.format(service))
634 for event in svcs[service].events:
635 if event not in msgs:
636 raise ValueError('Service definition refers to unknown '
637 'event: {} in message: {}'
638 .format(event, service))
639 seen_services[event] = True
641 # Create services implicitly
643 if d in seen_services:
645 if msgs[d].singular is True:
647 if d.endswith('_reply'):
650 if d[:-6] not in msgs:
651 raise ValueError('{} missing calling message'
654 if d.endswith('_dump'):
657 if d[:-5]+'_details' in msgs:
658 s['Service'].append(Service(d, d[:-5]+'_details',
661 raise ValueError('{} missing details message'
665 if d.endswith('_details'):
666 if d[:-8]+'_dump' not in msgs:
667 raise ValueError('{} missing dump message'
673 if d+'_reply' in msgs:
674 s['Service'].append(Service(d, d+'_reply'))
677 '{} missing reply message ({}) or service definition'
678 .format(d, d+'_reply'))
682 def process_imports(self, objs, in_import, result):
685 # Only allow the following object types from imported file
686 if in_import and not (isinstance(o, Enum) or
687 isinstance(o, Union) or
688 isinstance(o, Typedef) or
689 isinstance(o, Import)):
691 if isinstance(o, Import):
692 self.process_imports(o.result, True, result)
696 # Add message ids to each message.
699 o.block.insert(0, Field('u16', '_vl_msg_id'))
706 def dirlist_add(dirs):
709 dirlist = dirlist + dirs
720 cliparser = argparse.ArgumentParser(description='VPP API generator')
721 cliparser.add_argument('--pluginpath', default=""),
722 cliparser.add_argument('--includedir', action='append'),
723 cliparser.add_argument('--input', type=argparse.FileType('r'),
725 cliparser.add_argument('--output', nargs='?', type=argparse.FileType('w'),
728 cliparser.add_argument('output_module', nargs='?', default='C')
729 cliparser.add_argument('--debug', action='store_true')
730 cliparser.add_argument('--show-name', nargs=1)
731 args = cliparser.parse_args()
733 dirlist_add(args.includedir)
735 sys.excepthook = exception_handler
739 filename = args.show_name[0]
740 elif args.input != sys.stdin:
741 filename = args.input.name
746 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
748 logging.basicConfig()
749 log = logging.getLogger('vppapigen')
751 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
752 parsed_objects = parser.parse_file(args.input, log)
754 # Build a list of objects. Hash of lists.
756 parser.process_imports(parsed_objects, False, result)
757 s = parser.process(result)
760 s['Define'] = add_msg_id(s['Define'])
762 file_crc = global_crc & 0xffffffff
768 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
769 for t in s['Define']:
770 pp.pprint([t.name, t.flags, t.block])
772 pp.pprint([t.name, t.block])
775 # Generate representation
781 if not args.pluginpath:
783 cand.append(os.path.dirname(os.path.realpath(__file__)))
784 cand.append(os.path.dirname(os.path.realpath(__file__)) +
788 if os.path.isfile('{}vppapigen_{}.py'.format(c, args.output_module.lower())):
792 pluginpath = args.pluginpath + '/'
794 raise Exception('Output plugin not found')
795 module_path = '{}vppapigen_{}.py'.format(pluginpath, args.output_module.lower())
798 plugin = imp.load_source(args.output_module, module_path)
799 except Exception, err:
800 raise Exception('Error importing output plugin: {}, {}'
801 .format(module_path, err))
803 result = plugin.run(filename, s, file_crc)
805 print(result, file=args.output)
807 raise Exception('Running plugin failed: {} {}'
808 .format(filename, result))
811 if __name__ == '__main__':