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 # Side-effect: Sets global_crc
128 def crc_block(block):
130 s = str(block).encode()
131 global_crc = binascii.crc32(s, global_crc)
132 return binascii.crc32(s) & 0xffffffff
136 def __init__(self, caller, reply, events=[], stream=False):
144 def __init__(self, name, flags, block):
148 self.crc = crc_block(block)
149 self.manual_print = False
150 self.manual_endian = False
152 if f == 'manual_print':
153 self.manual_print = True
154 elif f == 'manual_endian':
155 self.manual_endian = True
156 global_type_add(name)
159 return self.name + str(self.flags) + str(self.block)
163 def __init__(self, name, alias):
167 if isinstance(alias, Array):
168 a = { 'type': alias.fieldtype,
169 'length': alias.length }
171 a = { 'type': alias.fieldtype }
173 self.crc = binascii.crc32(str(alias)) & 0xffffffff
174 global_crc = binascii.crc32(str(alias), global_crc)
175 global_type_add(name)
178 return self.name + str(self.alias)
182 def __init__(self, name, block):
184 self.manual_print = False
185 self.manual_endian = False
189 self.crc = crc_block(block)
190 global_type_add(name)
193 return str(self.block)
197 def __init__(self, name, flags, block):
201 self.crc = crc_block(block)
202 self.dont_trace = False
203 self.manual_print = False
204 self.manual_endian = False
205 self.autoreply = False
206 self.singular = False
208 if f == 'dont_trace':
209 self.dont_trace = True
210 elif f == 'manual_print':
211 self.manual_print = True
212 elif f == 'manual_endian':
213 self.manual_endian = True
214 elif f == 'autoreply':
215 self.autoreply = True
218 if isinstance(b, Option):
219 if b[1] == 'singular' and b[2] == 'true':
224 return self.name + str(self.flags) + str(self.block)
228 def __init__(self, name, block, enumtype='u32'):
230 self.enumtype = enumtype
233 for i, b in enumerate(block):
238 block[i] = [b, count]
241 self.crc = crc_block(block)
242 global_type_add(name)
245 return self.name + str(self.block)
249 def __init__(self, filename):
250 self.filename = filename
253 parser = VPPAPI(filename=filename)
254 dirlist = dirlist_get()
257 f = os.path.join(dir, filename)
258 if os.path.exists(f):
260 if sys.version[0] == '2':
262 self.result = parser.parse_file(fd, None)
264 with open(f, encoding='utf-8') as fd:
265 self.result = parser.parse_file(fd, None)
272 def __init__(self, option):
274 self.crc = crc_block(option)
277 return str(self.option)
279 def __getitem__(self, index):
280 return self.option[index]
284 def __init__(self, fieldtype, name, length):
286 self.fieldtype = fieldtype
287 self.fieldname = name
288 if type(length) is str:
289 self.lengthfield = length
293 self.lengthfield = None
296 return str([self.fieldtype, self.fieldname, self.length,
301 def __init__(self, fieldtype, name):
303 self.fieldtype = fieldtype
304 self.fieldname = name
307 return str([self.fieldtype, self.fieldname])
311 """ Coordinates of a syntactic element. Consists of:
314 - (optional) column number, for the Lexer
316 __slots__ = ('file', 'line', 'column', '__weakref__')
318 def __init__(self, file, line, column=None):
324 str = "%s:%s" % (self.file, self.line)
326 str += ":%s" % self.column
330 class ParseError(Exception):
337 class VPPAPIParser(object):
338 tokens = VPPAPILexer.tokens
340 def __init__(self, filename, logger):
341 self.filename = filename
345 def _parse_error(self, msg, coord):
346 raise ParseError("%s: %s" % (coord, msg))
348 def _parse_warning(self, msg, coord):
350 self.logger.warning("%s: %s" % (coord, msg))
352 def _coord(self, lineno, column=None):
355 line=lineno, column=column)
357 def _token_coord(self, p, token_idx):
358 """ Returns the coordinates for the YaccProduction object 'p' indexed
359 with 'token_idx'. The coordinate includes the 'lineno' and
360 'column'. Both follow the lex semantic, starting from 1.
362 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
365 column = (p.lexpos(token_idx) - (last_cr))
366 return self._coord(p.lineno(token_idx), column)
368 def p_slist(self, p):
386 def p_import(self, p):
387 '''import : IMPORT STRING_LITERAL ';' '''
390 def p_service(self, p):
391 '''service : SERVICE '{' service_statements '}' ';' '''
394 def p_service_statements(self, p):
395 '''service_statements : service_statement
396 | service_statements service_statement'''
402 def p_service_statement(self, p):
403 '''service_statement : RPC ID RETURNS NULL ';'
404 | RPC ID RETURNS ID ';'
405 | RPC ID RETURNS STREAM ID ';'
406 | RPC ID RETURNS ID EVENTS event_list ';' '''
408 # Verify that caller and reply differ
410 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
411 self._token_coord(p, 1))
413 p[0] = Service(p[2], p[4], p[6])
415 p[0] = Service(p[2], p[5], stream=True)
417 p[0] = Service(p[2], p[4])
419 def p_event_list(self, p):
420 '''event_list : events
421 | event_list events '''
427 def p_event(self, p):
433 '''enum : ENUM ID '{' enum_statements '}' ';' '''
434 p[0] = Enum(p[2], p[4])
436 def p_enum_type(self, p):
437 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
439 p[0] = Enum(p[2], p[6], enumtype=p[4])
441 p[0] = Enum(p[2], p[4])
443 def p_enum_size(self, p):
449 def p_define(self, p):
450 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
452 p[0] = Define(p[2], [], p[4])
454 def p_define_flist(self, p):
455 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
457 if 'typeonly' in p[1]:
458 p[0] = Typedef(p[3], p[1], p[5])
460 p[0] = Define(p[3], p[1], p[5])
462 def p_flist(self, p):
471 '''flag : MANUAL_PRINT
480 def p_typedef(self, p):
481 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
482 p[0] = Typedef(p[2], [], p[4])
484 def p_typedef_alias(self, p):
485 '''typedef : TYPEDEF declaration '''
486 p[0] = Using(p[2].fieldname, p[2])
488 def p_block_statements_opt(self, p):
489 '''block_statements_opt : block_statements '''
492 def p_block_statements(self, p):
493 '''block_statements : block_statement
494 | block_statements block_statement'''
500 def p_block_statement(self, p):
501 '''block_statement : declaration
505 def p_enum_statements(self, p):
506 '''enum_statements : enum_statement
507 | enum_statements enum_statement'''
513 def p_enum_statement(self, p):
514 '''enum_statement : ID '=' NUM ','
521 def p_declaration(self, p):
522 '''declaration : type_specifier ID ';' '''
524 self._parse_error('ERROR')
525 self.fields.append(p[2])
526 p[0] = Field(p[1], p[2])
528 def p_declaration_array(self, p):
529 '''declaration : type_specifier ID '[' NUM ']' ';'
530 | type_specifier ID '[' ID ']' ';' '''
532 return self._parse_error(
533 'array: %s' % p.value,
534 self._coord(lineno=p.lineno))
536 # Make this error later
537 if type(p[4]) is int and p[4] == 0:
538 # XXX: Line number is wrong
539 self._parse_warning('Old Style VLA: {} {}[{}];'
540 .format(p[1], p[2], p[4]),
541 self._token_coord(p, 1))
543 if type(p[4]) is str and p[4] not in self.fields:
544 # Verify that length field exists
545 self._parse_error('Missing length field: {} {}[{}];'
546 .format(p[1], p[2], p[4]),
547 self._token_coord(p, 1))
548 p[0] = Array(p[1], p[2], p[4])
550 def p_option(self, p):
551 '''option : OPTION ID '=' assignee ';' '''
552 p[0] = Option([p[1], p[2], p[4]])
554 def p_assignee(self, p):
561 def p_type_specifier(self, p):
562 '''type_specifier : U8
575 # Do a second pass later to verify that user defined types are defined
576 def p_typedef_specifier(self, p):
577 '''type_specifier : ID '''
578 if p[1] not in global_types:
579 self._parse_error('Undefined type: {}'.format(p[1]),
580 self._token_coord(p, 1))
583 def p_union(self, p):
584 '''union : UNION ID '{' block_statements_opt '}' ';' '''
585 p[0] = Union(p[2], p[4])
587 # Error rule for syntax errors
588 def p_error(self, p):
591 'before: %s' % p.value,
592 self._coord(lineno=p.lineno))
594 self._parse_error('At end of input', self.filename)
597 class VPPAPI(object):
599 def __init__(self, debug=False, filename='', logger=None):
600 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
601 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
602 write_tables=False, debug=debug)
605 def parse_string(self, code, debug=0, lineno=1):
606 self.lexer.lineno = lineno
607 return self.parser.parse(code, lexer=self.lexer, debug=debug)
609 def parse_file(self, fd, debug=0):
611 return self.parse_string(data, debug=debug)
613 def autoreply_block(self, name):
614 block = [Field('u32', 'context'),
615 Field('i32', 'retval')]
616 return Define(name + '_reply', [], block)
618 def process(self, objs):
627 tname = o.__class__.__name__
628 if isinstance(o, Define):
631 s[tname].append(self.autoreply_block(o.name))
632 elif isinstance(o, Option):
633 s[tname][o[1]] = o[2]
634 elif type(o) is list:
636 if isinstance(o2, Service):
637 s['Service'].append(o2)
638 elif (isinstance(o, Enum) or
639 isinstance(o, Typedef) or
640 isinstance(o, Union)):
642 elif isinstance(o, Using):
643 s['Alias'][o.name] = o.alias
646 raise ValueError('Unknown class type: {} {}'
650 msgs = {d.name: d for d in s['Define']}
651 svcs = {s.caller: s for s in s['Service']}
652 replies = {s.reply: s for s in s['Service']}
656 if service not in msgs:
658 'Service definition refers to unknown message'
659 ' definition: {}'.format(service))
660 if svcs[service].reply != 'null' and \
661 svcs[service].reply not in msgs:
662 raise ValueError('Service definition refers to unknown message'
663 ' definition in reply: {}'
664 .format(svcs[service].reply))
665 if service in replies:
666 raise ValueError('Service definition refers to message'
667 ' marked as reply: {}'.format(service))
668 for event in svcs[service].events:
669 if event not in msgs:
670 raise ValueError('Service definition refers to unknown '
671 'event: {} in message: {}'
672 .format(event, service))
673 seen_services[event] = True
675 # Create services implicitly
677 if d in seen_services:
679 if msgs[d].singular is True:
681 if d.endswith('_reply'):
684 if d[:-6] not in msgs:
685 raise ValueError('{} missing calling message'
688 if d.endswith('_dump'):
691 if d[:-5]+'_details' in msgs:
692 s['Service'].append(Service(d, d[:-5]+'_details',
695 raise ValueError('{} missing details message'
699 if d.endswith('_details'):
700 if d[:-8]+'_dump' not in msgs:
701 raise ValueError('{} missing dump message'
707 if d+'_reply' in msgs:
708 s['Service'].append(Service(d, d+'_reply'))
711 '{} missing reply message ({}) or service definition'
712 .format(d, d+'_reply'))
716 def process_imports(self, objs, in_import, result):
719 # Only allow the following object types from imported file
720 if in_import and not (isinstance(o, Enum) or
721 isinstance(o, Union) or
722 isinstance(o, Typedef) or
723 isinstance(o, Import) or
724 isinstance(o, Using)):
726 if isinstance(o, Import):
727 self.process_imports(o.result, True, result)
732 # Add message ids to each message.
735 o.block.insert(0, Field('u16', '_vl_msg_id'))
742 def dirlist_add(dirs):
745 dirlist = dirlist + dirs
756 cliparser = argparse.ArgumentParser(description='VPP API generator')
757 cliparser.add_argument('--pluginpath', default=""),
758 cliparser.add_argument('--includedir', action='append'),
759 if sys.version[0] == '2':
760 cliparser.add_argument('--input', type=argparse.FileType('r'),
763 cliparser.add_argument('--input',
764 type=argparse.FileType('r', encoding='UTF-8'),
766 cliparser.add_argument('--output', nargs='?', type=argparse.FileType('w'),
769 cliparser.add_argument('output_module', nargs='?', default='C')
770 cliparser.add_argument('--debug', action='store_true')
771 cliparser.add_argument('--show-name', nargs=1)
772 args = cliparser.parse_args()
774 dirlist_add(args.includedir)
776 sys.excepthook = exception_handler
780 filename = args.show_name[0]
781 elif args.input != sys.stdin:
782 filename = args.input.name
787 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
789 logging.basicConfig()
790 log = logging.getLogger('vppapigen')
792 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
793 parsed_objects = parser.parse_file(args.input, log)
795 # Build a list of objects. Hash of lists.
797 parser.process_imports(parsed_objects, False, result)
798 s = parser.process(result)
801 s['Define'] = add_msg_id(s['Define'])
803 file_crc = global_crc & 0xffffffff
809 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
810 for t in s['Define']:
811 pp.pprint([t.name, t.flags, t.block])
813 pp.pprint([t.name, t.block])
816 # Generate representation
822 if not args.pluginpath:
824 cand.append(os.path.dirname(os.path.realpath(__file__)))
825 cand.append(os.path.dirname(os.path.realpath(__file__)) +
829 if os.path.isfile('{}vppapigen_{}.py'
830 .format(c, args.output_module.lower())):
834 pluginpath = args.pluginpath + '/'
836 raise Exception('Output plugin not found')
837 module_path = '{}vppapigen_{}.py'.format(pluginpath,
838 args.output_module.lower())
841 plugin = imp.load_source(args.output_module, module_path)
842 except Exception as err:
843 raise Exception('Error importing output plugin: {}, {}'
844 .format(module_path, err))
846 result = plugin.run(filename, s, file_crc)
848 print(result, file=args.output)
850 raise Exception('Running plugin failed: {} {}'
851 .format(filename, result))
854 if __name__ == '__main__':