4 import ply.yacc as yacc
13 log = logging.getLogger('vppapigen')
15 # Ensure we don't leave temporary files around
16 sys.dont_write_bytecode = True
22 # Global dictionary of new types (including enums)
28 def global_type_add(name, obj):
29 '''Add new type to the dictionary of types '''
30 type_name = 'vl_api_' + name + '_t'
31 if type_name in global_types:
32 raise KeyError("Attempted redefinition of {!r} with {!r}.".format(
34 global_types[type_name] = obj
37 # All your trace are belong to us!
38 def exception_handler(exception_type, exception, traceback):
39 print("%s: %s" % (exception_type.__name__, exception))
45 class VPPAPILexer(object):
46 def __init__(self, filename):
47 self.filename = filename
59 'typeonly': 'TYPEONLY',
60 'manual_print': 'MANUAL_PRINT',
61 'manual_endian': 'MANUAL_ENDIAN',
62 'dont_trace': 'DONT_TRACE',
63 'autoreply': 'AUTOREPLY',
82 tokens = ['STRING_LITERAL',
83 'ID', 'NUM'] + list(reserved.values())
85 t_ignore_LINE_COMMENT = '//.*'
98 r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
99 base = 16 if t.value.startswith('0x') else 10
101 t.value = float(t.value)
103 t.value = int(t.value, base)
107 r'[a-zA-Z_][a-zA-Z_0-9]*'
108 # Check for reserved words
109 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
113 def t_STRING_LITERAL(self, t):
114 r'\"([^\\\n]|(\\.))*?\"'
115 t.value = str(t.value).replace("\"", "")
118 # C or C++ comment (ignore)
119 def t_comment(self, t):
120 r'(/\*(.|\n)*?\*/)|(//.*)'
121 t.lexer.lineno += t.value.count('\n')
123 # Error handling rule
124 def t_error(self, t):
125 raise ParseError("Illegal character '{}' ({})"
126 "in {}: line {}".format(t.value[0],
127 hex(ord(t.value[0])),
132 # Define a rule so we can track line numbers
133 def t_newline(self, t):
135 t.lexer.lineno += len(t.value)
137 literals = ":{}[];=.,"
139 # A string containing ignored characters (spaces and tabs)
143 def crc_block_combine(block, crc):
144 s = str(block).encode()
145 return binascii.crc32(s, crc) & 0xffffffff
148 def vla_is_last_check(name, block):
150 for i, b in enumerate(block):
151 if isinstance(b, Array) and b.vla:
153 if i + 1 < len(block):
155 'VLA field "{}" must be the last field in message "{}"'
156 .format(b.fieldname, name))
157 elif b.fieldtype.startswith('vl_api_'):
158 if global_types[b.fieldtype].vla:
160 if i + 1 < len(block):
162 'VLA field "{}" must be the last '
163 'field in message "{}"'
164 .format(b.fieldname, name))
165 elif b.fieldtype == 'string' and b.length == 0:
167 if i + 1 < len(block):
169 'VLA field "{}" must be the last '
170 'field in message "{}"'
171 .format(b.fieldname, name))
176 def __init__(self, caller, reply, events=None, stream=False):
180 self.events = [] if events is None else events
184 def __init__(self, name, flags, block):
188 self.crc = str(block).encode()
189 self.manual_print = False
190 self.manual_endian = False
192 if f == 'manual_print':
193 self.manual_print = True
194 elif f == 'manual_endian':
195 self.manual_endian = True
197 global_type_add(name, self)
199 self.vla = vla_is_last_check(name, block)
202 return self.name + str(self.flags) + str(self.block)
206 def __init__(self, name, flags, alias):
210 self.manual_print = False
211 self.manual_endian = False
213 if f == 'manual_print':
214 self.manual_print = True
215 elif f == 'manual_endian':
216 self.manual_endian = True
218 if isinstance(alias, Array):
219 a = {'type': alias.fieldtype,
220 'length': alias.length}
222 a = {'type': alias.fieldtype}
224 self.crc = str(alias).encode()
225 global_type_add(name, self)
228 return self.name + str(self.alias)
232 def __init__(self, name, flags, block):
234 self.manual_print = False
235 self.manual_endian = False
239 if f == 'manual_print':
240 self.manual_print = True
241 elif f == 'manual_endian':
242 self.manual_endian = True
245 self.crc = str(block).encode()
246 self.vla = vla_is_last_check(name, block)
248 global_type_add(name, self)
251 return str(self.block)
255 def __init__(self, name, flags, block):
259 self.crc = str(block).encode()
260 self.dont_trace = False
261 self.manual_print = False
262 self.manual_endian = False
263 self.autoreply = False
264 self.singular = False
266 if f == 'dont_trace':
267 self.dont_trace = True
268 elif f == 'manual_print':
269 self.manual_print = True
270 elif f == 'manual_endian':
271 self.manual_endian = True
272 elif f == 'autoreply':
273 self.autoreply = True
276 if isinstance(b, Option):
277 if b[1] == 'singular' and b[2] == 'true':
280 self.vla = vla_is_last_check(name, block)
283 return self.name + str(self.flags) + str(self.block)
287 def __init__(self, name, block, enumtype='u32'):
289 self.enumtype = enumtype
293 for i, b in enumerate(block):
298 block[i] = [b, count]
301 self.crc = str(block).encode()
302 global_type_add(name, self)
305 return self.name + str(self.block)
310 def __new__(cls, *args, **kwargs):
311 if args[0] not in seen_imports:
312 instance = super().__new__(cls)
313 instance._initialized = False
314 seen_imports[args[0]] = instance
316 return seen_imports[args[0]]
318 def __init__(self, filename):
319 if self._initialized:
322 self.filename = filename
324 parser = VPPAPI(filename=filename)
325 dirlist = dirlist_get()
328 f = os.path.join(dir, filename)
329 if os.path.exists(f):
331 if sys.version[0] == '2':
333 self.result = parser.parse_file(fd, None)
335 with open(f, encoding='utf-8') as fd:
336 self.result = parser.parse_file(fd, None)
337 self._initialized = True
344 def __init__(self, option, value):
348 self.crc = str(option).encode()
351 return str(self.option)
353 def __getitem__(self, index):
354 return self.option[index]
358 def __init__(self, fieldtype, name, length, modern_vla=False):
360 self.fieldtype = fieldtype
361 self.fieldname = name
362 self.modern_vla = modern_vla
363 if type(length) is str:
364 self.lengthfield = length
369 self.lengthfield = None
373 return str([self.fieldtype, self.fieldname, self.length,
378 def __init__(self, fieldtype, name, limit=None):
380 self.fieldtype = fieldtype
382 if self.fieldtype == 'string':
383 raise ValueError("The string type {!r} is an "
384 "array type ".format(name))
386 if name in keyword.kwlist:
387 raise ValueError("Fieldname {!r} is a python keyword and is not "
388 "accessible via the python API. ".format(name))
389 self.fieldname = name
393 return str([self.fieldtype, self.fieldname])
397 """ Coordinates of a syntactic element. Consists of:
400 - (optional) column number, for the Lexer
402 __slots__ = ('file', 'line', 'column', '__weakref__')
404 def __init__(self, file, line, column=None):
410 str = "%s:%s" % (self.file, self.line)
412 str += ":%s" % self.column
416 class ParseError(Exception):
423 class VPPAPIParser(object):
424 tokens = VPPAPILexer.tokens
426 def __init__(self, filename, logger):
427 self.filename = filename
431 def _parse_error(self, msg, coord):
432 raise ParseError("%s: %s" % (coord, msg))
434 def _parse_warning(self, msg, coord):
436 self.logger.warning("%s: %s" % (coord, msg))
438 def _coord(self, lineno, column=None):
441 line=lineno, column=column)
443 def _token_coord(self, p, token_idx):
444 """ Returns the coordinates for the YaccProduction object 'p' indexed
445 with 'token_idx'. The coordinate includes the 'lineno' and
446 'column'. Both follow the lex semantic, starting from 1.
448 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
451 column = (p.lexpos(token_idx) - (last_cr))
452 return self._coord(p.lineno(token_idx), column)
454 def p_slist(self, p):
472 def p_import(self, p):
473 '''import : IMPORT STRING_LITERAL ';' '''
476 def p_service(self, p):
477 '''service : SERVICE '{' service_statements '}' ';' '''
480 def p_service_statements(self, p):
481 '''service_statements : service_statement
482 | service_statements service_statement'''
488 def p_service_statement(self, p):
489 '''service_statement : RPC ID RETURNS NULL ';'
490 | RPC ID RETURNS ID ';'
491 | RPC ID RETURNS STREAM ID ';'
492 | RPC ID RETURNS ID EVENTS event_list ';' '''
494 # Verify that caller and reply differ
496 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
497 self._token_coord(p, 1))
499 p[0] = Service(p[2], p[4], p[6])
501 p[0] = Service(p[2], p[5], stream=True)
503 p[0] = Service(p[2], p[4])
505 def p_event_list(self, p):
506 '''event_list : events
507 | event_list events '''
513 def p_event(self, p):
519 '''enum : ENUM ID '{' enum_statements '}' ';' '''
520 p[0] = Enum(p[2], p[4])
522 def p_enum_type(self, p):
523 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
525 p[0] = Enum(p[2], p[6], enumtype=p[4])
527 p[0] = Enum(p[2], p[4])
529 def p_enum_size(self, p):
535 def p_define(self, p):
536 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
538 p[0] = Define(p[2], [], p[4])
540 def p_define_flist(self, p):
541 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
543 if 'typeonly' in p[1]:
544 self._parse_error('legacy typedef. use typedef: {} {}[{}];'
545 .format(p[1], p[2], p[4]),
546 self._token_coord(p, 1))
548 p[0] = Define(p[3], p[1], p[5])
550 def p_flist(self, p):
559 '''flag : MANUAL_PRINT
568 def p_typedef(self, p):
569 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
570 p[0] = Typedef(p[2], [], p[4])
572 def p_typedef_flist(self, p):
573 '''typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';' '''
574 p[0] = Typedef(p[3], p[1], p[5])
576 def p_typedef_alias(self, p):
577 '''typedef : TYPEDEF declaration '''
578 p[0] = Using(p[2].fieldname, [], p[2])
580 def p_typedef_alias_flist(self, p):
581 '''typedef : flist TYPEDEF declaration '''
582 p[0] = Using(p[3].fieldname, p[1], p[3])
584 def p_block_statements_opt(self, p):
585 '''block_statements_opt : block_statements '''
588 def p_block_statements(self, p):
589 '''block_statements : block_statement
590 | block_statements block_statement'''
596 def p_block_statement(self, p):
597 '''block_statement : declaration
601 def p_enum_statements(self, p):
602 '''enum_statements : enum_statement
603 | enum_statements enum_statement'''
609 def p_enum_statement(self, p):
610 '''enum_statement : ID '=' NUM ','
617 def p_field_options(self, p):
618 '''field_options : field_option
619 | field_options field_option'''
623 p[0] = {**p[1], **p[2]}
625 def p_field_option(self, p):
627 | ID '=' assignee ','
636 def p_declaration(self, p):
637 '''declaration : type_specifier ID ';'
638 | type_specifier ID '[' field_options ']' ';' '''
640 p[0] = Field(p[1], p[2], p[4])
642 p[0] = Field(p[1], p[2])
644 self._parse_error('ERROR')
645 self.fields.append(p[2])
647 def p_declaration_array_vla(self, p):
648 '''declaration : type_specifier ID '[' ']' ';' '''
649 p[0] = Array(p[1], p[2], 0, modern_vla=True)
651 def p_declaration_array(self, p):
652 '''declaration : type_specifier ID '[' NUM ']' ';'
653 | type_specifier ID '[' ID ']' ';' '''
656 return self._parse_error(
657 'array: %s' % p.value,
658 self._coord(lineno=p.lineno))
660 # Make this error later
661 if type(p[4]) is int and p[4] == 0:
662 # XXX: Line number is wrong
663 self._parse_warning('Old Style VLA: {} {}[{}];'
664 .format(p[1], p[2], p[4]),
665 self._token_coord(p, 1))
667 if type(p[4]) is str and p[4] not in self.fields:
668 # Verify that length field exists
669 self._parse_error('Missing length field: {} {}[{}];'
670 .format(p[1], p[2], p[4]),
671 self._token_coord(p, 1))
672 p[0] = Array(p[1], p[2], p[4])
674 def p_option(self, p):
675 '''option : OPTION ID '=' assignee ';' '''
676 p[0] = Option(p[2], p[4])
678 def p_assignee(self, p):
685 def p_type_specifier(self, p):
686 '''type_specifier : U8
699 # Do a second pass later to verify that user defined types are defined
700 def p_typedef_specifier(self, p):
701 '''type_specifier : ID '''
702 if p[1] not in global_types:
703 self._parse_error('Undefined type: {}'.format(p[1]),
704 self._token_coord(p, 1))
707 def p_union(self, p):
708 '''union : UNION ID '{' block_statements_opt '}' ';' '''
709 p[0] = Union(p[2], [], p[4])
711 def p_union_flist(self, p):
712 '''union : flist UNION ID '{' block_statements_opt '}' ';' '''
713 p[0] = Union(p[3], p[1], p[5])
715 # Error rule for syntax errors
716 def p_error(self, p):
719 'before: %s' % p.value,
720 self._coord(lineno=p.lineno))
722 self._parse_error('At end of input', self.filename)
725 class VPPAPI(object):
727 def __init__(self, debug=False, filename='', logger=None):
728 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
729 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
730 write_tables=False, debug=debug)
733 def parse_string(self, code, debug=0, lineno=1):
734 self.lexer.lineno = lineno
735 return self.parser.parse(code, lexer=self.lexer, debug=debug)
737 def parse_file(self, fd, debug=0):
739 return self.parse_string(data, debug=debug)
741 def autoreply_block(self, name):
742 block = [Field('u32', 'context'),
743 Field('i32', 'retval')]
744 return Define(name + '_reply', [], block)
746 def process(self, objs):
756 tname = o.__class__.__name__
758 crc = binascii.crc32(o.crc, crc)
759 except AttributeError:
761 if isinstance(o, Define):
764 s[tname].append(self.autoreply_block(o.name))
765 elif isinstance(o, Option):
766 s[tname][o[1]] = o[2]
767 elif type(o) is list:
769 if isinstance(o2, Service):
770 s['Service'].append(o2)
771 elif (isinstance(o, Enum) or
772 isinstance(o, Typedef) or
773 isinstance(o, Union)):
775 elif isinstance(o, Using):
776 s['Alias'][o.name] = o
779 raise ValueError('Unknown class type: {} {}'
783 msgs = {d.name: d for d in s['Define']}
784 svcs = {s.caller: s for s in s['Service']}
785 replies = {s.reply: s for s in s['Service']}
791 if service not in msgs:
793 'Service definition refers to unknown message'
794 ' definition: {}'.format(service))
795 if svcs[service].reply != 'null' and \
796 svcs[service].reply not in msgs:
797 raise ValueError('Service definition refers to unknown message'
798 ' definition in reply: {}'
799 .format(svcs[service].reply))
800 if service in replies:
801 raise ValueError('Service definition refers to message'
802 ' marked as reply: {}'.format(service))
803 for event in svcs[service].events:
804 if event not in msgs:
805 raise ValueError('Service definition refers to unknown '
806 'event: {} in message: {}'
807 .format(event, service))
808 seen_services[event] = True
810 # Create services implicitly
812 if d in seen_services:
814 if msgs[d].singular is True:
816 if d.endswith('_reply'):
819 if d[:-6] not in msgs:
820 raise ValueError('{} missing calling message'
823 if d.endswith('_dump'):
826 if d[:-5]+'_details' in msgs:
827 s['Service'].append(Service(d, d[:-5]+'_details',
830 raise ValueError('{} missing details message'
834 if d.endswith('_details'):
835 if d[:-8]+'_dump' not in msgs:
836 raise ValueError('{} missing dump message'
842 if d+'_reply' in msgs:
843 s['Service'].append(Service(d, d+'_reply'))
846 '{} missing reply message ({}) or service definition'
847 .format(d, d+'_reply'))
851 def process_imports(self, objs, in_import, result):
854 # Only allow the following object types from imported file
855 if in_import and not (isinstance(o, Enum) or
856 isinstance(o, Union) or
857 isinstance(o, Typedef) or
858 isinstance(o, Import) or
859 isinstance(o, Using)):
861 if isinstance(o, Import):
863 result = self.process_imports(o.result, True, result)
869 # Add message ids to each message.
872 o.block.insert(0, Field('u16', '_vl_msg_id'))
879 def dirlist_add(dirs):
882 dirlist = dirlist + dirs
889 def foldup_blocks(block, crc):
891 # Look up CRC in user defined types
892 if b.fieldtype.startswith('vl_api_'):
894 t = global_types[b.fieldtype]
896 crc = crc_block_combine(t.block, crc)
897 return foldup_blocks(t.block, crc)
898 except AttributeError:
905 f.crc = foldup_blocks(f.block,
906 binascii.crc32(f.crc))
913 if sys.version_info < (3, 5,):
914 log.exception('vppapigen requires a supported version of python. '
915 'Please use version 3.5 or greater. '
916 'Using {}'.format(sys.version))
919 cliparser = argparse.ArgumentParser(description='VPP API generator')
920 cliparser.add_argument('--pluginpath', default=""),
921 cliparser.add_argument('--includedir', action='append'),
922 cliparser.add_argument('--input',
923 type=argparse.FileType('r', encoding='UTF-8'),
925 cliparser.add_argument('--output', nargs='?',
926 type=argparse.FileType('w', encoding='UTF-8'),
929 cliparser.add_argument('output_module', nargs='?', default='C')
930 cliparser.add_argument('--debug', action='store_true')
931 cliparser.add_argument('--show-name', nargs=1)
932 args = cliparser.parse_args()
934 dirlist_add(args.includedir)
936 sys.excepthook = exception_handler
940 filename = args.show_name[0]
941 elif args.input != sys.stdin:
942 filename = args.input.name
947 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
949 logging.basicConfig()
951 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
952 parsed_objects = parser.parse_file(args.input, log)
954 # Build a list of objects. Hash of lists.
957 if args.output_module == 'C':
958 s = parser.process(parsed_objects)
960 result = parser.process_imports(parsed_objects, False, result)
961 s = parser.process(result)
964 s['Define'] = add_msg_id(s['Define'])
967 foldup_crcs(s['Define'])
973 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
974 for t in s['Define']:
975 pp.pprint([t.name, t.flags, t.block])
977 pp.pprint([t.name, t.block])
980 # Generate representation
982 from importlib.machinery import SourceFileLoader
986 if not args.pluginpath:
988 cand.append(os.path.dirname(os.path.realpath(__file__)))
989 cand.append(os.path.dirname(os.path.realpath(__file__)) +
993 if os.path.isfile('{}vppapigen_{}.py'
994 .format(c, args.output_module.lower())):
998 pluginpath = args.pluginpath + '/'
1000 log.exception('Output plugin not found')
1002 module_path = '{}vppapigen_{}.py'.format(pluginpath,
1003 args.output_module.lower())
1006 plugin = SourceFileLoader(args.output_module,
1007 module_path).load_module()
1008 except Exception as err:
1009 log.exception('Error importing output plugin: {}, {}'
1010 .format(module_path, err))
1013 result = plugin.run(filename, s)
1015 print(result, file=args.output)
1017 log.exception('Running plugin failed: {} {}'
1018 .format(filename, result))
1023 if __name__ == '__main__':