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 = True
211 self.manual_endian = True
213 self.manual_print = False
214 self.manual_endian = False
216 if f == 'manual_print':
217 self.manual_print = True
218 elif f == 'manual_endian':
219 self.manual_endian = True
221 if isinstance(alias, Array):
222 a = {'type': alias.fieldtype,
223 'length': alias.length}
225 a = {'type': alias.fieldtype}
227 self.crc = str(alias).encode()
228 global_type_add(name, self)
231 return self.name + str(self.alias)
235 def __init__(self, name, flags, block):
237 self.manual_print = False
238 self.manual_endian = False
242 if f == 'manual_print':
243 self.manual_print = True
244 elif f == 'manual_endian':
245 self.manual_endian = True
248 self.crc = str(block).encode()
249 self.vla = vla_is_last_check(name, block)
251 global_type_add(name, self)
254 return str(self.block)
258 def __init__(self, name, flags, block):
262 self.crc = str(block).encode()
263 self.dont_trace = False
264 self.manual_print = False
265 self.manual_endian = False
266 self.autoreply = False
267 self.singular = False
269 if f == 'dont_trace':
270 self.dont_trace = True
271 elif f == 'manual_print':
272 self.manual_print = True
273 elif f == 'manual_endian':
274 self.manual_endian = True
275 elif f == 'autoreply':
276 self.autoreply = True
279 if isinstance(b, Option):
280 if b[1] == 'singular' and b[2] == 'true':
283 self.vla = vla_is_last_check(name, block)
286 return self.name + str(self.flags) + str(self.block)
290 def __init__(self, name, block, enumtype='u32'):
292 self.enumtype = enumtype
296 for i, b in enumerate(block):
301 block[i] = [b, count]
304 self.crc = str(block).encode()
305 global_type_add(name, self)
308 return self.name + str(self.block)
313 def __new__(cls, *args, **kwargs):
314 if args[0] not in seen_imports:
315 instance = super().__new__(cls)
316 instance._initialized = False
317 seen_imports[args[0]] = instance
319 return seen_imports[args[0]]
321 def __init__(self, filename):
322 if self._initialized:
325 self.filename = filename
327 parser = VPPAPI(filename=filename)
328 dirlist = dirlist_get()
331 f = os.path.join(dir, filename)
332 if os.path.exists(f):
334 if sys.version[0] == '2':
336 self.result = parser.parse_file(fd, None)
338 with open(f, encoding='utf-8') as fd:
339 self.result = parser.parse_file(fd, None)
340 self._initialized = True
347 def __init__(self, option, value):
351 self.crc = str(option).encode()
354 return str(self.option)
356 def __getitem__(self, index):
357 return self.option[index]
361 def __init__(self, fieldtype, name, length, modern_vla=False):
363 self.fieldtype = fieldtype
364 self.fieldname = name
365 self.modern_vla = modern_vla
366 if type(length) is str:
367 self.lengthfield = length
372 self.lengthfield = None
376 return str([self.fieldtype, self.fieldname, self.length,
381 def __init__(self, fieldtype, name, limit=None):
383 self.fieldtype = fieldtype
385 if self.fieldtype == 'string':
386 raise ValueError("The string type {!r} is an "
387 "array type ".format(name))
389 if name in keyword.kwlist:
390 raise ValueError("Fieldname {!r} is a python keyword and is not "
391 "accessible via the python API. ".format(name))
392 self.fieldname = name
396 return str([self.fieldtype, self.fieldname])
400 """ Coordinates of a syntactic element. Consists of:
403 - (optional) column number, for the Lexer
405 __slots__ = ('file', 'line', 'column', '__weakref__')
407 def __init__(self, file, line, column=None):
413 str = "%s:%s" % (self.file, self.line)
415 str += ":%s" % self.column
419 class ParseError(Exception):
426 class VPPAPIParser(object):
427 tokens = VPPAPILexer.tokens
429 def __init__(self, filename, logger):
430 self.filename = filename
434 def _parse_error(self, msg, coord):
435 raise ParseError("%s: %s" % (coord, msg))
437 def _parse_warning(self, msg, coord):
439 self.logger.warning("%s: %s" % (coord, msg))
441 def _coord(self, lineno, column=None):
444 line=lineno, column=column)
446 def _token_coord(self, p, token_idx):
447 """ Returns the coordinates for the YaccProduction object 'p' indexed
448 with 'token_idx'. The coordinate includes the 'lineno' and
449 'column'. Both follow the lex semantic, starting from 1.
451 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
454 column = (p.lexpos(token_idx) - (last_cr))
455 return self._coord(p.lineno(token_idx), column)
457 def p_slist(self, p):
475 def p_import(self, p):
476 '''import : IMPORT STRING_LITERAL ';' '''
479 def p_service(self, p):
480 '''service : SERVICE '{' service_statements '}' ';' '''
483 def p_service_statements(self, p):
484 '''service_statements : service_statement
485 | service_statements service_statement'''
491 def p_service_statement(self, p):
492 '''service_statement : RPC ID RETURNS NULL ';'
493 | RPC ID RETURNS ID ';'
494 | RPC ID RETURNS STREAM ID ';'
495 | RPC ID RETURNS ID EVENTS event_list ';' '''
497 # Verify that caller and reply differ
499 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
500 self._token_coord(p, 1))
502 p[0] = Service(p[2], p[4], p[6])
504 p[0] = Service(p[2], p[5], stream=True)
506 p[0] = Service(p[2], p[4])
508 def p_event_list(self, p):
509 '''event_list : events
510 | event_list events '''
516 def p_event(self, p):
522 '''enum : ENUM ID '{' enum_statements '}' ';' '''
523 p[0] = Enum(p[2], p[4])
525 def p_enum_type(self, p):
526 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
528 p[0] = Enum(p[2], p[6], enumtype=p[4])
530 p[0] = Enum(p[2], p[4])
532 def p_enum_size(self, p):
538 def p_define(self, p):
539 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
541 p[0] = Define(p[2], [], p[4])
543 def p_define_flist(self, p):
544 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
546 if 'typeonly' in p[1]:
547 self._parse_error('legacy typedef. use typedef: {} {}[{}];'
548 .format(p[1], p[2], p[4]),
549 self._token_coord(p, 1))
551 p[0] = Define(p[3], p[1], p[5])
553 def p_flist(self, p):
562 '''flag : MANUAL_PRINT
571 def p_typedef(self, p):
572 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
573 p[0] = Typedef(p[2], [], p[4])
575 def p_typedef_flist(self, p):
576 '''typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';' '''
577 p[0] = Typedef(p[3], p[1], p[5])
579 def p_typedef_alias(self, p):
580 '''typedef : TYPEDEF declaration '''
581 p[0] = Using(p[2].fieldname, [], p[2])
583 def p_typedef_alias_flist(self, p):
584 '''typedef : flist TYPEDEF declaration '''
585 p[0] = Using(p[3].fieldname, p[1], p[3])
587 def p_block_statements_opt(self, p):
588 '''block_statements_opt : block_statements '''
591 def p_block_statements(self, p):
592 '''block_statements : block_statement
593 | block_statements block_statement'''
599 def p_block_statement(self, p):
600 '''block_statement : declaration
604 def p_enum_statements(self, p):
605 '''enum_statements : enum_statement
606 | enum_statements enum_statement'''
612 def p_enum_statement(self, p):
613 '''enum_statement : ID '=' NUM ','
620 def p_field_options(self, p):
621 '''field_options : field_option
622 | field_options field_option'''
626 p[0] = {**p[1], **p[2]}
628 def p_field_option(self, p):
630 | ID '=' assignee ','
639 def p_declaration(self, p):
640 '''declaration : type_specifier ID ';'
641 | type_specifier ID '[' field_options ']' ';' '''
643 p[0] = Field(p[1], p[2], p[4])
645 p[0] = Field(p[1], p[2])
647 self._parse_error('ERROR')
648 self.fields.append(p[2])
650 def p_declaration_array_vla(self, p):
651 '''declaration : type_specifier ID '[' ']' ';' '''
652 p[0] = Array(p[1], p[2], 0, modern_vla=True)
654 def p_declaration_array(self, p):
655 '''declaration : type_specifier ID '[' NUM ']' ';'
656 | type_specifier ID '[' ID ']' ';' '''
659 return self._parse_error(
660 'array: %s' % p.value,
661 self._coord(lineno=p.lineno))
663 # Make this error later
664 if type(p[4]) is int and p[4] == 0:
665 # XXX: Line number is wrong
666 self._parse_warning('Old Style VLA: {} {}[{}];'
667 .format(p[1], p[2], p[4]),
668 self._token_coord(p, 1))
670 if type(p[4]) is str and p[4] not in self.fields:
671 # Verify that length field exists
672 self._parse_error('Missing length field: {} {}[{}];'
673 .format(p[1], p[2], p[4]),
674 self._token_coord(p, 1))
675 p[0] = Array(p[1], p[2], p[4])
677 def p_option(self, p):
678 '''option : OPTION ID '=' assignee ';' '''
679 p[0] = Option(p[2], p[4])
681 def p_assignee(self, p):
688 def p_type_specifier(self, p):
689 '''type_specifier : U8
702 # Do a second pass later to verify that user defined types are defined
703 def p_typedef_specifier(self, p):
704 '''type_specifier : ID '''
705 if p[1] not in global_types:
706 self._parse_error('Undefined type: {}'.format(p[1]),
707 self._token_coord(p, 1))
710 def p_union(self, p):
711 '''union : UNION ID '{' block_statements_opt '}' ';' '''
712 p[0] = Union(p[2], [], p[4])
714 def p_union_flist(self, p):
715 '''union : flist UNION ID '{' block_statements_opt '}' ';' '''
716 p[0] = Union(p[3], p[1], p[5])
718 # Error rule for syntax errors
719 def p_error(self, p):
722 'before: %s' % p.value,
723 self._coord(lineno=p.lineno))
725 self._parse_error('At end of input', self.filename)
728 class VPPAPI(object):
730 def __init__(self, debug=False, filename='', logger=None):
731 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
732 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
733 write_tables=False, debug=debug)
736 def parse_string(self, code, debug=0, lineno=1):
737 self.lexer.lineno = lineno
738 return self.parser.parse(code, lexer=self.lexer, debug=debug)
740 def parse_file(self, fd, debug=0):
742 return self.parse_string(data, debug=debug)
744 def autoreply_block(self, name):
745 block = [Field('u32', 'context'),
746 Field('i32', 'retval')]
747 return Define(name + '_reply', [], block)
749 def process(self, objs):
758 tname = o.__class__.__name__
760 crc = binascii.crc32(o.crc, crc)
761 except AttributeError:
763 if isinstance(o, Define):
766 s[tname].append(self.autoreply_block(o.name))
767 elif isinstance(o, Option):
768 s[tname][o[1]] = o[2]
769 elif type(o) is list:
771 if isinstance(o2, Service):
772 s['Service'].append(o2)
773 elif (isinstance(o, Enum) or
774 isinstance(o, Typedef) or
775 isinstance(o, Using) or
776 isinstance(o, Union)):
780 raise ValueError('Unknown class type: {} {}'
784 msgs = {d.name: d for d in s['Define']}
785 svcs = {s.caller: s for s in s['Service']}
786 replies = {s.reply: s for s in s['Service']}
792 if service not in msgs:
794 'Service definition refers to unknown message'
795 ' definition: {}'.format(service))
796 if svcs[service].reply != 'null' and \
797 svcs[service].reply not in msgs:
798 raise ValueError('Service definition refers to unknown message'
799 ' definition in reply: {}'
800 .format(svcs[service].reply))
801 if service in replies:
802 raise ValueError('Service definition refers to message'
803 ' marked as reply: {}'.format(service))
804 for event in svcs[service].events:
805 if event not in msgs:
806 raise ValueError('Service definition refers to unknown '
807 'event: {} in message: {}'
808 .format(event, service))
809 seen_services[event] = True
811 # Create services implicitly
813 if d in seen_services:
815 if msgs[d].singular is True:
817 if d.endswith('_reply'):
820 if d[:-6] not in msgs:
821 raise ValueError('{} missing calling message'
824 if d.endswith('_dump'):
827 if d[:-5]+'_details' in msgs:
828 s['Service'].append(Service(d, d[:-5]+'_details',
831 raise ValueError('{} missing details message'
835 if d.endswith('_details'):
836 if d[:-8]+'_dump' not in msgs:
837 raise ValueError('{} missing dump message'
843 if d+'_reply' in msgs:
844 s['Service'].append(Service(d, d+'_reply'))
847 '{} missing reply message ({}) or service definition'
848 .format(d, d+'_reply'))
852 def process_imports(self, objs, in_import, result):
855 # Only allow the following object types from imported file
856 if in_import and not (isinstance(o, Enum) or
857 isinstance(o, Union) or
858 isinstance(o, Typedef) or
859 isinstance(o, Import) or
860 isinstance(o, Using)):
862 if isinstance(o, Import):
864 result = self.process_imports(o.result, True, result)
870 # Add message ids to each message.
873 o.block.insert(0, Field('u16', '_vl_msg_id'))
880 def dirlist_add(dirs):
883 dirlist = dirlist + dirs
890 def foldup_blocks(block, crc):
892 # Look up CRC in user defined types
893 if b.fieldtype.startswith('vl_api_'):
895 t = global_types[b.fieldtype]
897 crc = crc_block_combine(t.block, crc)
898 return foldup_blocks(t.block, crc)
899 except AttributeError:
906 f.crc = foldup_blocks(f.block,
907 binascii.crc32(f.crc))
914 if sys.version_info < (3, 5,):
915 log.exception('vppapigen requires a supported version of python. '
916 'Please use version 3.5 or greater. '
917 'Using {}'.format(sys.version))
920 cliparser = argparse.ArgumentParser(description='VPP API generator')
921 cliparser.add_argument('--pluginpath', default=""),
922 cliparser.add_argument('--includedir', action='append'),
923 cliparser.add_argument('--input',
924 type=argparse.FileType('r', encoding='UTF-8'),
926 cliparser.add_argument('--output', nargs='?',
927 type=argparse.FileType('w', encoding='UTF-8'),
930 cliparser.add_argument('output_module', nargs='?', default='C')
931 cliparser.add_argument('--debug', action='store_true')
932 cliparser.add_argument('--show-name', nargs=1)
933 args = cliparser.parse_args()
935 dirlist_add(args.includedir)
937 sys.excepthook = exception_handler
941 filename = args.show_name[0]
942 elif args.input != sys.stdin:
943 filename = args.input.name
948 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
950 logging.basicConfig()
952 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
953 parsed_objects = parser.parse_file(args.input, log)
955 # Build a list of objects. Hash of lists.
958 if args.output_module == 'C':
959 s = parser.process(parsed_objects)
961 result = parser.process_imports(parsed_objects, False, result)
962 s = parser.process(result)
965 s['Define'] = add_msg_id(s['Define'])
968 foldup_crcs(s['Define'])
974 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
975 for t in s['Define']:
976 pp.pprint([t.name, t.flags, t.block])
978 pp.pprint([t.name, t.block])
981 # Generate representation
983 from importlib.machinery import SourceFileLoader
987 if not args.pluginpath:
989 cand.append(os.path.dirname(os.path.realpath(__file__)))
990 cand.append(os.path.dirname(os.path.realpath(__file__)) +
994 if os.path.isfile('{}vppapigen_{}.py'
995 .format(c, args.output_module.lower())):
999 pluginpath = args.pluginpath + '/'
1000 if pluginpath == '':
1001 log.exception('Output plugin not found')
1003 module_path = '{}vppapigen_{}.py'.format(pluginpath,
1004 args.output_module.lower())
1007 plugin = SourceFileLoader(args.output_module,
1008 module_path).load_module()
1009 except Exception as err:
1010 log.exception('Error importing output plugin: {}, {}'
1011 .format(module_path, err))
1014 result = plugin.run(filename, s)
1016 print(result, file=args.output)
1018 log.exception('Running plugin failed: {} {}'
1019 .format(filename, result))
1024 if __name__ == '__main__':