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',
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)
125 def __init__(self, caller, reply, events=[], stream=False):
133 def __init__(self, name, flags, block):
138 self.crc = binascii.crc32(str(block)) & 0xffffffff
139 global_crc = binascii.crc32(str(block), global_crc)
140 global_type_add(name)
143 return self.name + str(self.flags) + str(self.block)
147 def __init__(self, name, flags, block):
152 self.crc = binascii.crc32(str(block)) & 0xffffffff
153 global_crc = binascii.crc32(str(block), global_crc)
154 self.typeonly = False
155 self.dont_trace = False
156 self.manual_print = False
157 self.manual_endian = False
158 self.autoreply = False
159 self.singular = False
163 global_type_add(name)
164 elif f == 'dont_trace':
165 self.dont_trace = True
166 elif f == 'manual_print':
167 self.manual_print = True
168 elif f == 'manual_endian':
169 self.manual_endian = True
170 elif f == 'autoreply':
171 self.autoreply = True
174 if isinstance(b, Option):
175 if b[1] == 'singular' and b[2] == 'true':
180 return self.name + str(self.flags) + str(self.block)
184 def __init__(self, name, block, enumtype='u32'):
187 self.enumtype = enumtype
189 for i, b in enumerate(block):
194 block[i] = [b, count]
197 self.crc = binascii.crc32(str(block)) & 0xffffffff
198 global_crc = binascii.crc32(str(block), global_crc)
199 global_type_add(name)
202 return self.name + str(self.block)
206 def __init__(self, filename):
207 self.filename = filename
210 parser = VPPAPI(filename=filename)
211 dirlist = dirlist_get()
214 f = os.path.join(dir, filename)
215 if os.path.exists(f):
218 self.result = parser.parse_file(fd, None)
225 def __init__(self, option):
228 self.crc = binascii.crc32(str(option)) & 0xffffffff
229 global_crc = binascii.crc32(str(option), global_crc)
232 return str(self.option)
234 def __getitem__(self, index):
235 return self.option[index]
239 def __init__(self, fieldtype, name, length):
241 self.fieldtype = fieldtype
242 self.fieldname = name
243 if type(length) is str:
244 self.lengthfield = length
248 self.lengthfield = None
251 return str([self.fieldtype, self.fieldname, self.length,
256 def __init__(self, fieldtype, name):
258 self.fieldtype = fieldtype
259 self.fieldname = name
262 return str([self.fieldtype, self.fieldname])
266 """ Coordinates of a syntactic element. Consists of:
269 - (optional) column number, for the Lexer
271 __slots__ = ('file', 'line', 'column', '__weakref__')
273 def __init__(self, file, line, column=None):
279 str = "%s:%s" % (self.file, self.line)
281 str += ":%s" % self.column
285 class ParseError(Exception):
292 class VPPAPIParser(object):
293 tokens = VPPAPILexer.tokens
295 def __init__(self, filename, logger):
296 self.filename = filename
300 def _parse_error(self, msg, coord):
301 raise ParseError("%s: %s" % (coord, msg))
303 def _parse_warning(self, msg, coord):
305 self.logger.warning("%s: %s" % (coord, msg))
307 def _coord(self, lineno, column=None):
310 line=lineno, column=column)
312 def _token_coord(self, p, token_idx):
313 """ Returns the coordinates for the YaccProduction object 'p' indexed
314 with 'token_idx'. The coordinate includes the 'lineno' and
315 'column'. Both follow the lex semantic, starting from 1.
317 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
320 column = (p.lexpos(token_idx) - (last_cr))
321 return self._coord(p.lineno(token_idx), column)
323 def p_slist(self, p):
340 def p_import(self, p):
341 '''import : IMPORT STRING_LITERAL ';' '''
344 def p_service(self, p):
345 '''service : SERVICE '{' service_statements '}' ';' '''
348 def p_service_statements(self, p):
349 '''service_statements : service_statement
350 | service_statements service_statement'''
356 def p_service_statement(self, p):
357 '''service_statement : RPC ID RETURNS NULL ';'
358 | RPC ID RETURNS ID ';'
359 | RPC ID RETURNS STREAM ID ';'
360 | RPC ID RETURNS ID EVENTS event_list ';' '''
362 # Verify that caller and reply differ
364 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
365 self._token_coord(p, 1))
367 p[0] = Service(p[2], p[4], p[6])
369 p[0] = Service(p[2], p[5], stream=True)
371 p[0] = Service(p[2], p[4])
373 def p_event_list(self, p):
374 '''event_list : events
375 | event_list events '''
381 def p_event(self, p):
387 '''enum : ENUM ID '{' enum_statements '}' ';' '''
388 p[0] = Enum(p[2], p[4])
390 def p_enum_type(self, p):
391 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
393 p[0] = Enum(p[2], p[6], enumtype=p[4])
395 p[0] = Enum(p[2], p[4])
397 def p_enum_size(self, p):
403 def p_define(self, p):
404 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
406 p[0] = Define(p[2], [], p[4])
408 def p_define_flist(self, p):
409 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
410 p[0] = Define(p[3], p[1], p[5])
412 def p_flist(self, p):
421 '''flag : MANUAL_PRINT
430 def p_typedef(self, p):
431 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
432 p[0] = Typedef(p[2], [], p[4])
434 def p_block_statements_opt(self, p):
435 '''block_statements_opt : block_statements'''
438 def p_block_statements(self, p):
439 '''block_statements : block_statement
440 | block_statements block_statement'''
446 def p_block_statement(self, p):
447 '''block_statement : declaration
451 def p_enum_statements(self, p):
452 '''enum_statements : enum_statement
453 | enum_statements enum_statement'''
459 def p_enum_statement(self, p):
460 '''enum_statement : ID '=' NUM ','
467 def p_declaration(self, p):
468 '''declaration : type_specifier ID ';' '''
470 self._parse_error('ERROR')
471 self.fields.append(p[2])
472 p[0] = Field(p[1], p[2])
474 def p_declaration_array(self, p):
475 '''declaration : type_specifier ID '[' NUM ']' ';'
476 | type_specifier ID '[' ID ']' ';' '''
478 return self._parse_error(
479 'array: %s' % p.value,
480 self._coord(lineno=p.lineno))
482 # Make this error later
483 if type(p[4]) is int and p[4] == 0:
484 # XXX: Line number is wrong
485 self._parse_warning('Old Style VLA: {} {}[{}];'
486 .format(p[1], p[2], p[4]),
487 self._token_coord(p, 1))
489 if type(p[4]) is str and p[4] not in self.fields:
490 # Verify that length field exists
491 self._parse_error('Missing length field: {} {}[{}];'
492 .format(p[1], p[2], p[4]),
493 self._token_coord(p, 1))
494 p[0] = Array(p[1], p[2], p[4])
496 def p_option(self, p):
497 '''option : OPTION ID '=' assignee ';' '''
498 p[0] = Option([p[1], p[2], p[4]])
500 def p_assignee(self, p):
507 def p_type_specifier(self, p):
508 '''type_specifier : U8
521 # Do a second pass later to verify that user defined types are defined
522 def p_typedef_specifier(self, p):
523 '''type_specifier : ID '''
524 if p[1] not in global_types:
525 self._parse_error('Undefined type: {}'.format(p[1]),
526 self._token_coord(p, 1))
529 # Error rule for syntax errors
530 def p_error(self, p):
533 'before: %s' % p.value,
534 self._coord(lineno=p.lineno))
536 self._parse_error('At end of input', self.filename)
539 class VPPAPI(object):
541 def __init__(self, debug=False, filename='', logger=None):
542 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
543 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
544 write_tables=False, debug=debug)
547 def parse_string(self, code, debug=0, lineno=1):
548 self.lexer.lineno = lineno
549 return self.parser.parse(code, lexer=self.lexer, debug=debug)
551 def parse_file(self, fd, debug=0):
553 return self.parse_string(data, debug=debug)
555 def autoreply_block(self, name):
556 block = [Field('u32', 'context'),
557 Field('i32', 'retval')]
558 return Define(name + '_reply', [], block)
560 def process(self, objs):
570 if isinstance(o, Define):
572 s['typedefs'].append(o)
574 s['defines'].append(o)
576 s['defines'].append(self.autoreply_block(o.name))
577 elif isinstance(o, Option):
578 s['options'][o[1]] = o[2]
579 elif isinstance(o, Enum):
581 elif isinstance(o, Typedef):
582 s['typedefs'].append(o)
583 elif type(o) is list:
585 if isinstance(o2, Service):
586 s['services'].append(o2)
588 msgs = {d.name: d for d in s['defines']}
589 svcs = {s.caller: s for s in s['services']}
590 replies = {s.reply: s for s in s['services']}
594 if service not in msgs:
596 'Service definition refers to unknown message'
597 ' definition: {}'.format(service))
598 if svcs[service].reply != 'null' and \
599 svcs[service].reply not in msgs:
600 raise ValueError('Service definition refers to unknown message'
601 ' definition in reply: {}'
602 .format(svcs[service].reply))
603 if service in replies:
604 raise ValueError('Service definition refers to message'
605 ' marked as reply: {}'.format(service))
606 for event in svcs[service].events:
607 if event not in msgs:
608 raise ValueError('Service definition refers to unknown '
609 'event: {} in message: {}'
610 .format(event, service))
611 seen_services[event] = True
613 # Create services implicitly
615 if d in seen_services:
617 if msgs[d].singular is True:
619 if d.endswith('_reply'):
622 if d[:-6] not in msgs:
623 raise ValueError('{} missing calling message'
626 if d.endswith('_dump'):
629 if d[:-5]+'_details' in msgs:
630 s['services'].append(Service(d, d[:-5]+'_details',
633 raise ValueError('{} missing details message'
637 if d.endswith('_details'):
638 if d[:-8]+'_dump' not in msgs:
639 raise ValueError('{} missing dump message'
645 if d+'_reply' in msgs:
646 s['services'].append(Service(d, d+'_reply'))
649 '{} missing reply message ({}) or service definition'
650 .format(d, d+'_reply'))
654 def process_imports(self, objs, in_import):
657 if isinstance(o, Import):
658 return self.process_imports(o.result, True) + objs
660 if isinstance(o, Define) and o.typeonly:
661 imported_objs.append(o)
667 # Add message ids to each message.
670 o.block.insert(0, Field('u16', '_vl_msg_id'))
677 def dirlist_add(dirs):
680 dirlist = dirlist + dirs
691 cliparser = argparse.ArgumentParser(description='VPP API generator')
692 cliparser.add_argument('--pluginpath', default=""),
693 cliparser.add_argument('--includedir', action='append'),
694 cliparser.add_argument('--input', type=argparse.FileType('r'),
696 cliparser.add_argument('--output', nargs='?', type=argparse.FileType('w'),
699 cliparser.add_argument('output_module', nargs='?', default='C')
700 cliparser.add_argument('--debug', action='store_true')
701 cliparser.add_argument('--show-name', nargs=1)
702 args = cliparser.parse_args()
704 dirlist_add(args.includedir)
706 sys.excepthook = exception_handler
710 filename = args.show_name[0]
711 elif args.input != sys.stdin:
712 filename = args.input.name
717 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
719 logging.basicConfig()
720 log = logging.getLogger('vppapigen')
722 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
723 result = parser.parse_file(args.input, log)
725 # Build a list of objects. Hash of lists.
726 result = parser.process_imports(result, False)
727 s = parser.process(result)
730 s['defines'] = add_msg_id(s['defines'])
732 file_crc = global_crc & 0xffffffff
738 pp = pprint.PrettyPrinter(indent=4)
739 for t in s['defines']:
740 pp.pprint([t.name, t.flags, t.block])
741 for t in s['typedefs']:
742 pp.pprint([t.name, t.flags, t.block])
745 # Generate representation
751 if not args.pluginpath:
753 cand.append(os.path.dirname(os.path.realpath(__file__)))
754 cand.append(os.path.dirname(os.path.realpath(__file__)) +
758 if os.path.isfile(c + args.output_module + '.py'):
762 pluginpath = args.pluginpath + '/'
764 raise Exception('Output plugin not found')
765 module_path = pluginpath + args.output_module + '.py'
768 plugin = imp.load_source(args.output_module, module_path)
769 except Exception, err:
770 raise Exception('Error importing output plugin: {}, {}'
771 .format(module_path, err))
773 result = plugin.run(filename, s, file_crc)
775 print(result, file=args.output)
777 raise Exception('Running plugin failed: {} {}'
778 .format(filename, result))
781 if __name__ == '__main__':