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.dont_trace = False
263 self.manual_print = False
264 self.manual_endian = False
265 self.autoreply = False
266 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.options[b.option] = b.value
286 self.vla = vla_is_last_check(name, block)
287 self.crc = str(block).encode()
290 return self.name + str(self.flags) + str(self.block)
294 def __init__(self, name, block, enumtype='u32'):
296 self.enumtype = enumtype
300 for i, b in enumerate(block):
305 block[i] = [b, count]
308 self.crc = str(block).encode()
309 global_type_add(name, self)
312 return self.name + str(self.block)
317 def __new__(cls, *args, **kwargs):
318 if args[0] not in seen_imports:
319 instance = super().__new__(cls)
320 instance._initialized = False
321 seen_imports[args[0]] = instance
323 return seen_imports[args[0]]
325 def __init__(self, filename):
326 if self._initialized:
329 self.filename = filename
331 parser = VPPAPI(filename=filename)
332 dirlist = dirlist_get()
335 f = os.path.join(dir, filename)
336 if os.path.exists(f):
338 if sys.version[0] == '2':
340 self.result = parser.parse_file(fd, None)
342 with open(f, encoding='utf-8') as fd:
343 self.result = parser.parse_file(fd, None)
344 self._initialized = True
351 def __init__(self, option, value):
355 self.crc = str(option).encode()
358 return str(self.option)
360 def __getitem__(self, index):
361 return self.option[index]
365 def __init__(self, fieldtype, name, length, modern_vla=False):
367 self.fieldtype = fieldtype
368 self.fieldname = name
369 self.modern_vla = modern_vla
370 if type(length) is str:
371 self.lengthfield = length
376 self.lengthfield = None
380 return str([self.fieldtype, self.fieldname, self.length,
385 def __init__(self, fieldtype, name, limit=None):
387 self.fieldtype = fieldtype
389 if self.fieldtype == 'string':
390 raise ValueError("The string type {!r} is an "
391 "array type ".format(name))
393 if name in keyword.kwlist:
394 raise ValueError("Fieldname {!r} is a python keyword and is not "
395 "accessible via the python API. ".format(name))
396 self.fieldname = name
400 return str([self.fieldtype, self.fieldname])
404 """ Coordinates of a syntactic element. Consists of:
407 - (optional) column number, for the Lexer
409 __slots__ = ('file', 'line', 'column', '__weakref__')
411 def __init__(self, file, line, column=None):
417 str = "%s:%s" % (self.file, self.line)
419 str += ":%s" % self.column
423 class ParseError(Exception):
430 class VPPAPIParser(object):
431 tokens = VPPAPILexer.tokens
433 def __init__(self, filename, logger):
434 self.filename = filename
438 def _parse_error(self, msg, coord):
439 raise ParseError("%s: %s" % (coord, msg))
441 def _parse_warning(self, msg, coord):
443 self.logger.warning("%s: %s" % (coord, msg))
445 def _coord(self, lineno, column=None):
448 line=lineno, column=column)
450 def _token_coord(self, p, token_idx):
451 """ Returns the coordinates for the YaccProduction object 'p' indexed
452 with 'token_idx'. The coordinate includes the 'lineno' and
453 'column'. Both follow the lex semantic, starting from 1.
455 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
458 column = (p.lexpos(token_idx) - (last_cr))
459 return self._coord(p.lineno(token_idx), column)
461 def p_slist(self, p):
479 def p_import(self, p):
480 '''import : IMPORT STRING_LITERAL ';' '''
483 def p_service(self, p):
484 '''service : SERVICE '{' service_statements '}' ';' '''
487 def p_service_statements(self, p):
488 '''service_statements : service_statement
489 | service_statements service_statement'''
495 def p_service_statement(self, p):
496 '''service_statement : RPC ID RETURNS NULL ';'
497 | RPC ID RETURNS ID ';'
498 | RPC ID RETURNS STREAM ID ';'
499 | RPC ID RETURNS ID EVENTS event_list ';' '''
501 # Verify that caller and reply differ
503 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
504 self._token_coord(p, 1))
506 p[0] = Service(p[2], p[4], p[6])
508 p[0] = Service(p[2], p[5], stream=True)
510 p[0] = Service(p[2], p[4])
512 def p_event_list(self, p):
513 '''event_list : events
514 | event_list events '''
520 def p_event(self, p):
526 '''enum : ENUM ID '{' enum_statements '}' ';' '''
527 p[0] = Enum(p[2], p[4])
529 def p_enum_type(self, p):
530 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
532 p[0] = Enum(p[2], p[6], enumtype=p[4])
534 p[0] = Enum(p[2], p[4])
536 def p_enum_size(self, p):
542 def p_define(self, p):
543 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
545 p[0] = Define(p[2], [], p[4])
547 def p_define_flist(self, p):
548 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
550 if 'typeonly' in p[1]:
551 self._parse_error('legacy typedef. use typedef: {} {}[{}];'
552 .format(p[1], p[2], p[4]),
553 self._token_coord(p, 1))
555 p[0] = Define(p[3], p[1], p[5])
557 def p_flist(self, p):
566 '''flag : MANUAL_PRINT
575 def p_typedef(self, p):
576 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
577 p[0] = Typedef(p[2], [], p[4])
579 def p_typedef_flist(self, p):
580 '''typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';' '''
581 p[0] = Typedef(p[3], p[1], p[5])
583 def p_typedef_alias(self, p):
584 '''typedef : TYPEDEF declaration '''
585 p[0] = Using(p[2].fieldname, [], p[2])
587 def p_typedef_alias_flist(self, p):
588 '''typedef : flist TYPEDEF declaration '''
589 p[0] = Using(p[3].fieldname, p[1], p[3])
591 def p_block_statements_opt(self, p):
592 '''block_statements_opt : block_statements '''
595 def p_block_statements(self, p):
596 '''block_statements : block_statement
597 | block_statements block_statement'''
603 def p_block_statement(self, p):
604 '''block_statement : declaration
608 def p_enum_statements(self, p):
609 '''enum_statements : enum_statement
610 | enum_statements enum_statement'''
616 def p_enum_statement(self, p):
617 '''enum_statement : ID '=' NUM ','
624 def p_field_options(self, p):
625 '''field_options : field_option
626 | field_options field_option'''
630 p[0] = {**p[1], **p[2]}
632 def p_field_option(self, p):
634 | ID '=' assignee ','
643 def p_declaration(self, p):
644 '''declaration : type_specifier ID ';'
645 | type_specifier ID '[' field_options ']' ';' '''
647 p[0] = Field(p[1], p[2], p[4])
649 p[0] = Field(p[1], p[2])
651 self._parse_error('ERROR')
652 self.fields.append(p[2])
654 def p_declaration_array_vla(self, p):
655 '''declaration : type_specifier ID '[' ']' ';' '''
656 p[0] = Array(p[1], p[2], 0, modern_vla=True)
658 def p_declaration_array(self, p):
659 '''declaration : type_specifier ID '[' NUM ']' ';'
660 | type_specifier ID '[' ID ']' ';' '''
663 return self._parse_error(
664 'array: %s' % p.value,
665 self._coord(lineno=p.lineno))
667 # Make this error later
668 if type(p[4]) is int and p[4] == 0:
669 # XXX: Line number is wrong
670 self._parse_warning('Old Style VLA: {} {}[{}];'
671 .format(p[1], p[2], p[4]),
672 self._token_coord(p, 1))
674 if type(p[4]) is str and p[4] not in self.fields:
675 # Verify that length field exists
676 self._parse_error('Missing length field: {} {}[{}];'
677 .format(p[1], p[2], p[4]),
678 self._token_coord(p, 1))
679 p[0] = Array(p[1], p[2], p[4])
681 def p_option(self, p):
682 '''option : OPTION ID '=' assignee ';' '''
683 p[0] = Option(p[2], p[4])
685 def p_assignee(self, p):
692 def p_type_specifier(self, p):
693 '''type_specifier : U8
706 # Do a second pass later to verify that user defined types are defined
707 def p_typedef_specifier(self, p):
708 '''type_specifier : ID '''
709 if p[1] not in global_types:
710 self._parse_error('Undefined type: {}'.format(p[1]),
711 self._token_coord(p, 1))
714 def p_union(self, p):
715 '''union : UNION ID '{' block_statements_opt '}' ';' '''
716 p[0] = Union(p[2], [], p[4])
718 def p_union_flist(self, p):
719 '''union : flist UNION ID '{' block_statements_opt '}' ';' '''
720 p[0] = Union(p[3], p[1], p[5])
722 # Error rule for syntax errors
723 def p_error(self, p):
726 'before: %s' % p.value,
727 self._coord(lineno=p.lineno))
729 self._parse_error('At end of input', self.filename)
732 class VPPAPI(object):
734 def __init__(self, debug=False, filename='', logger=None):
735 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
736 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
737 write_tables=False, debug=debug)
740 def parse_string(self, code, debug=0, lineno=1):
741 self.lexer.lineno = lineno
742 return self.parser.parse(code, lexer=self.lexer, debug=debug)
744 def parse_file(self, fd, debug=0):
746 return self.parse_string(data, debug=debug)
748 def autoreply_block(self, name):
749 block = [Field('u32', 'context'),
750 Field('i32', 'retval')]
751 return Define(name + '_reply', [], block)
753 def process(self, objs):
762 tname = o.__class__.__name__
764 crc = binascii.crc32(o.crc, crc)
765 except AttributeError:
767 if isinstance(o, Define):
770 s[tname].append(self.autoreply_block(o.name))
771 elif isinstance(o, Option):
772 s[tname][o.option] = o.value
773 elif type(o) is list:
775 if isinstance(o2, Service):
776 s['Service'].append(o2)
777 elif (isinstance(o, Enum) or
778 isinstance(o, Typedef) or
779 isinstance(o, Using) or
780 isinstance(o, Union)):
784 raise ValueError('Unknown class type: {} {}'
788 msgs = {d.name: d for d in s['Define']}
789 svcs = {s.caller: s for s in s['Service']}
790 replies = {s.reply: s for s in s['Service']}
796 if service not in msgs:
798 'Service definition refers to unknown message'
799 ' definition: {}'.format(service))
800 if svcs[service].reply != 'null' and \
801 svcs[service].reply not in msgs:
802 raise ValueError('Service definition refers to unknown message'
803 ' definition in reply: {}'
804 .format(svcs[service].reply))
805 if service in replies:
806 raise ValueError('Service definition refers to message'
807 ' marked as reply: {}'.format(service))
808 for event in svcs[service].events:
809 if event not in msgs:
810 raise ValueError('Service definition refers to unknown '
811 'event: {} in message: {}'
812 .format(event, service))
813 seen_services[event] = True
815 # Create services implicitly
817 if d in seen_services:
819 if msgs[d].singular is True:
821 if d.endswith('_reply'):
824 if d[:-6] not in msgs:
825 raise ValueError('{} missing calling message'
828 if d.endswith('_dump'):
831 if d[:-5]+'_details' in msgs:
832 s['Service'].append(Service(d, d[:-5]+'_details',
835 raise ValueError('{} missing details message'
839 if d.endswith('_details'):
840 if d[:-8]+'_dump' not in msgs:
841 raise ValueError('{} missing dump message'
847 if d+'_reply' in msgs:
848 s['Service'].append(Service(d, d+'_reply'))
851 '{} missing reply message ({}) or service definition'
852 .format(d, d+'_reply'))
856 def process_imports(self, objs, in_import, result):
859 # Only allow the following object types from imported file
860 if in_import and not (isinstance(o, Enum) or
861 isinstance(o, Union) or
862 isinstance(o, Typedef) or
863 isinstance(o, Import) or
864 isinstance(o, Using)):
866 if isinstance(o, Import):
868 result = self.process_imports(o.result, True, result)
874 # Add message ids to each message.
877 o.block.insert(0, Field('u16', '_vl_msg_id'))
884 def dirlist_add(dirs):
887 dirlist = dirlist + dirs
894 def foldup_blocks(block, crc):
896 # Look up CRC in user defined types
897 if b.fieldtype.startswith('vl_api_'):
899 t = global_types[b.fieldtype]
901 crc = crc_block_combine(t.block, crc)
902 return foldup_blocks(t.block, crc)
903 except AttributeError:
910 f.crc = foldup_blocks(f.block,
911 binascii.crc32(f.crc))
918 if sys.version_info < (3, 5,):
919 log.exception('vppapigen requires a supported version of python. '
920 'Please use version 3.5 or greater. '
921 'Using {}'.format(sys.version))
924 cliparser = argparse.ArgumentParser(description='VPP API generator')
925 cliparser.add_argument('--pluginpath', default=""),
926 cliparser.add_argument('--includedir', action='append'),
927 cliparser.add_argument('--outputdir', action='store'),
928 cliparser.add_argument('--input',
929 type=argparse.FileType('r', encoding='UTF-8'),
931 cliparser.add_argument('--output', nargs='?',
932 type=argparse.FileType('w', encoding='UTF-8'),
935 cliparser.add_argument('output_module', nargs='?', default='C')
936 cliparser.add_argument('--debug', action='store_true')
937 cliparser.add_argument('--show-name', nargs=1)
938 args = cliparser.parse_args()
940 dirlist_add(args.includedir)
942 sys.excepthook = exception_handler
946 filename = args.show_name[0]
947 elif args.input != sys.stdin:
948 filename = args.input.name
953 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
955 logging.basicConfig()
957 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
958 parsed_objects = parser.parse_file(args.input, log)
960 # Build a list of objects. Hash of lists.
963 if args.output_module == 'C':
964 s = parser.process(parsed_objects)
966 result = parser.process_imports(parsed_objects, False, result)
967 s = parser.process(result)
970 s['Define'] = add_msg_id(s['Define'])
973 foldup_crcs(s['Define'])
979 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
980 for t in s['Define']:
981 pp.pprint([t.name, t.flags, t.block])
983 pp.pprint([t.name, t.block])
986 # Generate representation
988 from importlib.machinery import SourceFileLoader
992 if not args.pluginpath:
994 cand.append(os.path.dirname(os.path.realpath(__file__)))
995 cand.append(os.path.dirname(os.path.realpath(__file__)) +
999 if os.path.isfile('{}vppapigen_{}.py'
1000 .format(c, args.output_module.lower())):
1004 pluginpath = args.pluginpath + '/'
1005 if pluginpath == '':
1006 log.exception('Output plugin not found')
1008 module_path = '{}vppapigen_{}.py'.format(pluginpath,
1009 args.output_module.lower())
1012 plugin = SourceFileLoader(args.output_module,
1013 module_path).load_module()
1014 except Exception as err:
1015 log.exception('Error importing output plugin: {}, {}'
1016 .format(module_path, err))
1019 result = plugin.run(args, filename, s)
1021 print(result, file=args.output)
1023 log.exception('Running plugin failed: {} {}'
1024 .format(filename, result))
1029 if __name__ == '__main__':