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, alias):
159 if isinstance(alias, Array):
160 a = { 'type': alias.fieldtype,
161 'length': alias.length }
163 a = { 'type': alias.fieldtype }
165 self.crc = binascii.crc32(str(alias)) & 0xffffffff
166 global_crc = binascii.crc32(str(alias), global_crc)
167 global_type_add(name)
170 return self.name + str(self.alias)
174 def __init__(self, name, block):
176 self.manual_print = False
177 self.manual_endian = False
181 self.crc = binascii.crc32(str(block)) & 0xffffffff
182 global_crc = binascii.crc32(str(block), global_crc)
183 global_type_add(name)
186 return str(self.block)
190 def __init__(self, name, flags, block):
195 self.crc = binascii.crc32(str(block)) & 0xffffffff
196 global_crc = binascii.crc32(str(block), global_crc)
197 self.dont_trace = False
198 self.manual_print = False
199 self.manual_endian = False
200 self.autoreply = False
201 self.singular = False
203 if f == 'dont_trace':
204 self.dont_trace = True
205 elif f == 'manual_print':
206 self.manual_print = True
207 elif f == 'manual_endian':
208 self.manual_endian = True
209 elif f == 'autoreply':
210 self.autoreply = True
213 if isinstance(b, Option):
214 if b[1] == 'singular' and b[2] == 'true':
219 return self.name + str(self.flags) + str(self.block)
223 def __init__(self, name, block, enumtype='u32'):
226 self.enumtype = enumtype
229 for i, b in enumerate(block):
234 block[i] = [b, count]
237 self.crc = binascii.crc32(str(block)) & 0xffffffff
238 global_crc = binascii.crc32(str(block), global_crc)
239 global_type_add(name)
242 return self.name + str(self.block)
246 def __init__(self, filename):
247 self.filename = filename
250 parser = VPPAPI(filename=filename)
251 dirlist = dirlist_get()
254 f = os.path.join(dir, filename)
255 if os.path.exists(f):
258 self.result = parser.parse_file(fd, None)
265 def __init__(self, option):
268 self.crc = binascii.crc32(str(option)) & 0xffffffff
269 global_crc = binascii.crc32(str(option), global_crc)
272 return str(self.option)
274 def __getitem__(self, index):
275 return self.option[index]
279 def __init__(self, fieldtype, name, length):
281 self.fieldtype = fieldtype
282 self.fieldname = name
283 if type(length) is str:
284 self.lengthfield = length
288 self.lengthfield = None
291 return str([self.fieldtype, self.fieldname, self.length,
296 def __init__(self, fieldtype, name):
298 self.fieldtype = fieldtype
299 self.fieldname = name
302 return str([self.fieldtype, self.fieldname])
306 """ Coordinates of a syntactic element. Consists of:
309 - (optional) column number, for the Lexer
311 __slots__ = ('file', 'line', 'column', '__weakref__')
313 def __init__(self, file, line, column=None):
319 str = "%s:%s" % (self.file, self.line)
321 str += ":%s" % self.column
325 class ParseError(Exception):
332 class VPPAPIParser(object):
333 tokens = VPPAPILexer.tokens
335 def __init__(self, filename, logger):
336 self.filename = filename
340 def _parse_error(self, msg, coord):
341 raise ParseError("%s: %s" % (coord, msg))
343 def _parse_warning(self, msg, coord):
345 self.logger.warning("%s: %s" % (coord, msg))
347 def _coord(self, lineno, column=None):
350 line=lineno, column=column)
352 def _token_coord(self, p, token_idx):
353 """ Returns the coordinates for the YaccProduction object 'p' indexed
354 with 'token_idx'. The coordinate includes the 'lineno' and
355 'column'. Both follow the lex semantic, starting from 1.
357 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
360 column = (p.lexpos(token_idx) - (last_cr))
361 return self._coord(p.lineno(token_idx), column)
363 def p_slist(self, p):
381 def p_import(self, p):
382 '''import : IMPORT STRING_LITERAL ';' '''
385 def p_service(self, p):
386 '''service : SERVICE '{' service_statements '}' ';' '''
389 def p_service_statements(self, p):
390 '''service_statements : service_statement
391 | service_statements service_statement'''
397 def p_service_statement(self, p):
398 '''service_statement : RPC ID RETURNS NULL ';'
399 | RPC ID RETURNS ID ';'
400 | RPC ID RETURNS STREAM ID ';'
401 | RPC ID RETURNS ID EVENTS event_list ';' '''
403 # Verify that caller and reply differ
405 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
406 self._token_coord(p, 1))
408 p[0] = Service(p[2], p[4], p[6])
410 p[0] = Service(p[2], p[5], stream=True)
412 p[0] = Service(p[2], p[4])
414 def p_event_list(self, p):
415 '''event_list : events
416 | event_list events '''
422 def p_event(self, p):
428 '''enum : ENUM ID '{' enum_statements '}' ';' '''
429 p[0] = Enum(p[2], p[4])
431 def p_enum_type(self, p):
432 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
434 p[0] = Enum(p[2], p[6], enumtype=p[4])
436 p[0] = Enum(p[2], p[4])
438 def p_enum_size(self, p):
444 def p_define(self, p):
445 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
447 p[0] = Define(p[2], [], p[4])
449 def p_define_flist(self, p):
450 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
452 if 'typeonly' in p[1]:
453 p[0] = Typedef(p[3], p[1], p[5])
455 p[0] = Define(p[3], p[1], p[5])
457 def p_flist(self, p):
466 '''flag : MANUAL_PRINT
475 def p_typedef(self, p):
476 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
477 p[0] = Typedef(p[2], [], p[4])
479 def p_typedef_alias(self, p):
480 '''typedef : TYPEDEF declaration '''
481 p[0] = Using(p[2].fieldname, p[2])
483 def p_block_statements_opt(self, p):
484 '''block_statements_opt : block_statements '''
487 def p_block_statements(self, p):
488 '''block_statements : block_statement
489 | block_statements block_statement'''
495 def p_block_statement(self, p):
496 '''block_statement : declaration
500 def p_enum_statements(self, p):
501 '''enum_statements : enum_statement
502 | enum_statements enum_statement'''
508 def p_enum_statement(self, p):
509 '''enum_statement : ID '=' NUM ','
516 def p_declaration(self, p):
517 '''declaration : type_specifier ID ';' '''
519 self._parse_error('ERROR')
520 self.fields.append(p[2])
521 p[0] = Field(p[1], p[2])
523 def p_declaration_array(self, p):
524 '''declaration : type_specifier ID '[' NUM ']' ';'
525 | type_specifier ID '[' ID ']' ';' '''
527 return self._parse_error(
528 'array: %s' % p.value,
529 self._coord(lineno=p.lineno))
531 # Make this error later
532 if type(p[4]) is int and p[4] == 0:
533 # XXX: Line number is wrong
534 self._parse_warning('Old Style VLA: {} {}[{}];'
535 .format(p[1], p[2], p[4]),
536 self._token_coord(p, 1))
538 if type(p[4]) is str and p[4] not in self.fields:
539 # Verify that length field exists
540 self._parse_error('Missing length field: {} {}[{}];'
541 .format(p[1], p[2], p[4]),
542 self._token_coord(p, 1))
543 p[0] = Array(p[1], p[2], p[4])
545 def p_option(self, p):
546 '''option : OPTION ID '=' assignee ';' '''
547 p[0] = Option([p[1], p[2], p[4]])
549 def p_assignee(self, p):
556 def p_type_specifier(self, p):
557 '''type_specifier : U8
570 # Do a second pass later to verify that user defined types are defined
571 def p_typedef_specifier(self, p):
572 '''type_specifier : ID '''
573 if p[1] not in global_types:
574 self._parse_error('Undefined type: {}'.format(p[1]),
575 self._token_coord(p, 1))
578 def p_union(self, p):
579 '''union : UNION ID '{' block_statements_opt '}' ';' '''
580 p[0] = Union(p[2], p[4])
582 # Error rule for syntax errors
583 def p_error(self, p):
586 'before: %s' % p.value,
587 self._coord(lineno=p.lineno))
589 self._parse_error('At end of input', self.filename)
592 class VPPAPI(object):
594 def __init__(self, debug=False, filename='', logger=None):
595 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
596 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
597 write_tables=False, debug=debug)
600 def parse_string(self, code, debug=0, lineno=1):
601 self.lexer.lineno = lineno
602 return self.parser.parse(code, lexer=self.lexer, debug=debug)
604 def parse_file(self, fd, debug=0):
606 return self.parse_string(data, debug=debug)
608 def autoreply_block(self, name):
609 block = [Field('u32', 'context'),
610 Field('i32', 'retval')]
611 return Define(name + '_reply', [], block)
613 def process(self, objs):
622 tname = o.__class__.__name__
623 if isinstance(o, Define):
626 s[tname].append(self.autoreply_block(o.name))
627 elif isinstance(o, Option):
628 s[tname][o[1]] = o[2]
629 elif type(o) is list:
631 if isinstance(o2, Service):
632 s['Service'].append(o2)
633 elif isinstance(o, Enum) or isinstance(o, Typedef) or isinstance(o, Union):
635 elif isinstance(o, Using):
636 s['Alias'][o.name] = o.alias
639 raise ValueError('Unknown class type: {} {}'.format(tname, o))
642 msgs = {d.name: d for d in s['Define']}
643 svcs = {s.caller: s for s in s['Service']}
644 replies = {s.reply: s for s in s['Service']}
648 if service not in msgs:
650 'Service definition refers to unknown message'
651 ' definition: {}'.format(service))
652 if svcs[service].reply != 'null' and \
653 svcs[service].reply not in msgs:
654 raise ValueError('Service definition refers to unknown message'
655 ' definition in reply: {}'
656 .format(svcs[service].reply))
657 if service in replies:
658 raise ValueError('Service definition refers to message'
659 ' marked as reply: {}'.format(service))
660 for event in svcs[service].events:
661 if event not in msgs:
662 raise ValueError('Service definition refers to unknown '
663 'event: {} in message: {}'
664 .format(event, service))
665 seen_services[event] = True
667 # Create services implicitly
669 if d in seen_services:
671 if msgs[d].singular is True:
673 if d.endswith('_reply'):
676 if d[:-6] not in msgs:
677 raise ValueError('{} missing calling message'
680 if d.endswith('_dump'):
683 if d[:-5]+'_details' in msgs:
684 s['Service'].append(Service(d, d[:-5]+'_details',
687 raise ValueError('{} missing details message'
691 if d.endswith('_details'):
692 if d[:-8]+'_dump' not in msgs:
693 raise ValueError('{} missing dump message'
699 if d+'_reply' in msgs:
700 s['Service'].append(Service(d, d+'_reply'))
703 '{} missing reply message ({}) or service definition'
704 .format(d, d+'_reply'))
708 def process_imports(self, objs, in_import, result):
711 # Only allow the following object types from imported file
712 if in_import and not (isinstance(o, Enum) or
713 isinstance(o, Union) or
714 isinstance(o, Typedef) or
715 isinstance(o, Import) or
716 isinstance(o, Using)):
718 if isinstance(o, Import):
719 self.process_imports(o.result, True, result)
723 # Add message ids to each message.
726 o.block.insert(0, Field('u16', '_vl_msg_id'))
733 def dirlist_add(dirs):
736 dirlist = dirlist + dirs
747 cliparser = argparse.ArgumentParser(description='VPP API generator')
748 cliparser.add_argument('--pluginpath', default=""),
749 cliparser.add_argument('--includedir', action='append'),
750 cliparser.add_argument('--input', type=argparse.FileType('r'),
752 cliparser.add_argument('--output', nargs='?', type=argparse.FileType('w'),
755 cliparser.add_argument('output_module', nargs='?', default='C')
756 cliparser.add_argument('--debug', action='store_true')
757 cliparser.add_argument('--show-name', nargs=1)
758 args = cliparser.parse_args()
760 dirlist_add(args.includedir)
762 sys.excepthook = exception_handler
766 filename = args.show_name[0]
767 elif args.input != sys.stdin:
768 filename = args.input.name
773 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
775 logging.basicConfig()
776 log = logging.getLogger('vppapigen')
778 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
779 parsed_objects = parser.parse_file(args.input, log)
781 # Build a list of objects. Hash of lists.
783 parser.process_imports(parsed_objects, False, result)
784 s = parser.process(result)
787 s['Define'] = add_msg_id(s['Define'])
789 file_crc = global_crc & 0xffffffff
795 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
796 for t in s['Define']:
797 pp.pprint([t.name, t.flags, t.block])
799 pp.pprint([t.name, t.block])
802 # Generate representation
808 if not args.pluginpath:
810 cand.append(os.path.dirname(os.path.realpath(__file__)))
811 cand.append(os.path.dirname(os.path.realpath(__file__)) +
815 if os.path.isfile('{}vppapigen_{}.py'.format(c, args.output_module.lower())):
819 pluginpath = args.pluginpath + '/'
821 raise Exception('Output plugin not found')
822 module_path = '{}vppapigen_{}.py'.format(pluginpath, args.output_module.lower())
825 plugin = imp.load_source(args.output_module, module_path)
826 except Exception, err:
827 raise Exception('Error importing output plugin: {}, {}'
828 .format(module_path, err))
830 result = plugin.run(filename, s, file_crc)
832 print(result, file=args.output)
834 raise Exception('Running plugin failed: {} {}'
835 .format(filename, result))
838 if __name__ == '__main__':