4 import ply.yacc as yacc
12 from subprocess import Popen, PIPE
14 log = logging.getLogger('vppapigen')
16 # Ensure we don't leave temporary files around
17 sys.dont_write_bytecode = True
23 # Global dictionary of new types (including enums)
29 def global_type_add(name, obj):
30 '''Add new type to the dictionary of types '''
31 type_name = 'vl_api_' + name + '_t'
32 if type_name in global_types:
33 raise KeyError("Attempted redefinition of {!r} with {!r}.".format(
35 global_types[type_name] = obj
38 # All your trace are belong to us!
39 def exception_handler(exception_type, exception, traceback):
40 print("%s: %s" % (exception_type.__name__, exception))
46 class VPPAPILexer(object):
47 def __init__(self, filename):
48 self.filename = filename
60 'typeonly': 'TYPEONLY',
61 'manual_print': 'MANUAL_PRINT',
62 'manual_endian': 'MANUAL_ENDIAN',
63 'dont_trace': 'DONT_TRACE',
64 'autoreply': 'AUTOREPLY',
83 tokens = ['STRING_LITERAL',
84 'ID', 'NUM'] + list(reserved.values())
86 t_ignore_LINE_COMMENT = '//.*'
99 r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
100 base = 16 if t.value.startswith('0x') else 10
102 t.value = float(t.value)
104 t.value = int(t.value, base)
108 r'[a-zA-Z_][a-zA-Z_0-9]*'
109 # Check for reserved words
110 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
114 def t_STRING_LITERAL(self, t):
115 r'\"([^\\\n]|(\\.))*?\"'
116 t.value = str(t.value).replace("\"", "")
119 # C or C++ comment (ignore)
120 def t_comment(self, t):
121 r'(/\*(.|\n)*?\*/)|(//.*)'
122 t.lexer.lineno += t.value.count('\n')
124 # Error handling rule
125 def t_error(self, t):
126 raise ParseError("Illegal character '{}' ({})"
127 "in {}: line {}".format(t.value[0],
128 hex(ord(t.value[0])),
133 # Define a rule so we can track line numbers
134 def t_newline(self, t):
136 t.lexer.lineno += len(t.value)
138 literals = ":{}[];=.,"
140 # A string containing ignored characters (spaces and tabs)
144 def crc_block_combine(block, crc):
145 s = str(block).encode()
146 return binascii.crc32(s, crc) & 0xffffffff
149 def vla_is_last_check(name, block):
151 for i, b in enumerate(block):
152 if isinstance(b, Array) and b.vla:
154 if i + 1 < len(block):
156 'VLA field "{}" must be the last field in message "{}"'
157 .format(b.fieldname, name))
158 elif b.fieldtype.startswith('vl_api_'):
159 if global_types[b.fieldtype].vla:
161 if i + 1 < len(block):
163 'VLA field "{}" must be the last '
164 'field in message "{}"'
165 .format(b.fieldname, name))
166 elif b.fieldtype == 'string' and b.length == 0:
168 if i + 1 < len(block):
170 'VLA field "{}" must be the last '
171 'field in message "{}"'
172 .format(b.fieldname, name))
177 def __init__(self, caller, reply, events=None, stream=False):
181 self.events = [] if events is None else events
185 def __init__(self, name, flags, block):
189 self.crc = str(block).encode()
190 self.manual_print = False
191 self.manual_endian = False
193 if f == 'manual_print':
194 self.manual_print = True
195 elif f == 'manual_endian':
196 self.manual_endian = True
198 global_type_add(name, self)
200 self.vla = vla_is_last_check(name, block)
203 return self.name + str(self.flags) + str(self.block)
207 def __init__(self, name, flags, alias):
211 self.manual_print = True
212 self.manual_endian = True
214 self.manual_print = False
215 self.manual_endian = False
217 if f == 'manual_print':
218 self.manual_print = True
219 elif f == 'manual_endian':
220 self.manual_endian = True
222 if isinstance(alias, Array):
223 a = {'type': alias.fieldtype,
224 'length': alias.length}
226 a = {'type': alias.fieldtype}
228 self.crc = str(alias).encode()
229 global_type_add(name, self)
232 return self.name + str(self.alias)
236 def __init__(self, name, flags, block):
238 self.manual_print = False
239 self.manual_endian = False
243 if f == 'manual_print':
244 self.manual_print = True
245 elif f == 'manual_endian':
246 self.manual_endian = True
249 self.crc = str(block).encode()
250 self.vla = vla_is_last_check(name, block)
252 global_type_add(name, self)
255 return str(self.block)
259 def __init__(self, name, flags, block):
263 self.dont_trace = False
264 self.manual_print = False
265 self.manual_endian = False
266 self.autoreply = False
267 self.singular = False
270 if f == 'dont_trace':
271 self.dont_trace = True
272 elif f == 'manual_print':
273 self.manual_print = True
274 elif f == 'manual_endian':
275 self.manual_endian = True
276 elif f == 'autoreply':
277 self.autoreply = True
281 if isinstance(b, Option):
282 if b[1] == 'singular' and b[2] == 'true':
285 self.options[b.option] = b.value
288 block = [x for x in block if not x in remove]
290 self.vla = vla_is_last_check(name, block)
291 self.crc = str(block).encode()
294 return self.name + str(self.flags) + str(self.block)
298 def __init__(self, name, block, enumtype='u32'):
300 self.enumtype = enumtype
304 for i, b in enumerate(block):
309 block[i] = [b, count]
312 self.crc = str(block).encode()
313 global_type_add(name, self)
316 return self.name + str(self.block)
321 def __new__(cls, *args, **kwargs):
322 if args[0] not in seen_imports:
323 instance = super().__new__(cls)
324 instance._initialized = False
325 seen_imports[args[0]] = instance
327 return seen_imports[args[0]]
329 def __init__(self, filename, revision):
330 if self._initialized:
333 self.filename = filename
335 parser = VPPAPI(filename=filename, revision=revision)
336 dirlist = dirlist_get()
339 f = os.path.join(dir, filename)
340 if os.path.exists(f):
342 self.result = parser.parse_filename(f, None)
343 self._initialized = True
350 def __init__(self, option, value):
354 self.crc = str(option).encode()
357 return str(self.option)
359 def __getitem__(self, index):
360 return self.option[index]
364 def __init__(self, fieldtype, name, length, modern_vla=False):
366 self.fieldtype = fieldtype
367 self.fieldname = name
368 self.modern_vla = modern_vla
369 if type(length) is str:
370 self.lengthfield = length
375 self.lengthfield = None
379 return str([self.fieldtype, self.fieldname, self.length,
384 def __init__(self, fieldtype, name, limit=None):
386 self.fieldtype = fieldtype
388 if self.fieldtype == 'string':
389 raise ValueError("The string type {!r} is an "
390 "array type ".format(name))
392 if name in keyword.kwlist:
393 raise ValueError("Fieldname {!r} is a python keyword and is not "
394 "accessible via the python API. ".format(name))
395 self.fieldname = name
399 return str([self.fieldtype, self.fieldname])
403 """ Coordinates of a syntactic element. Consists of:
406 - (optional) column number, for the Lexer
408 __slots__ = ('file', 'line', 'column', '__weakref__')
410 def __init__(self, file, line, column=None):
416 str = "%s:%s" % (self.file, self.line)
418 str += ":%s" % self.column
422 class ParseError(Exception):
429 class VPPAPIParser(object):
430 tokens = VPPAPILexer.tokens
432 def __init__(self, filename, logger, revision=None):
433 self.filename = filename
436 self.revision = revision
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 ';' '''
481 p[0] = Import(p[2], revision=self.revision)
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', self._token_coord(p, 1))
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, revision=None):
735 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
736 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger,
738 write_tables=False, debug=debug)
740 self.revision = revision
741 self.filename = filename
743 def parse_string(self, code, debug=0, lineno=1):
744 self.lexer.lineno = lineno
745 return self.parser.parse(code, lexer=self.lexer, debug=debug)
747 def parse_fd(self, fd, debug=0):
749 return self.parse_string(data, debug=debug)
751 def parse_filename(self, filename, debug=0):
753 git_show = f'git show {self.revision}:{filename}'
754 with Popen(git_show.split(), stdout=PIPE, encoding='utf-8') as git:
755 return self.parse_fd(git.stdout, None)
758 with open(filename, encoding='utf-8') as fd:
759 return self.parse_fd(fd, None)
760 except FileNotFoundError:
761 print(f'File not found: {filename}', file=sys.stderr)
764 def autoreply_block(self, name, parent):
765 block = [Field('u32', 'context'),
766 Field('i32', 'retval')]
767 # inherhit the parent's options
768 for k,v in parent.options.items():
769 block.append(Option(k, v))
770 return Define(name + '_reply', [], block)
772 def process(self, objs):
781 tname = o.__class__.__name__
783 crc = binascii.crc32(o.crc, crc) & 0xffffffff
784 except AttributeError:
786 if isinstance(o, Define):
789 s[tname].append(self.autoreply_block(o.name, o))
790 elif isinstance(o, Option):
791 s[tname][o.option] = o.value
792 elif type(o) is list:
794 if isinstance(o2, Service):
795 s['Service'].append(o2)
796 elif (isinstance(o, Enum) or
797 isinstance(o, Typedef) or
798 isinstance(o, Using) or
799 isinstance(o, Union)):
803 raise ValueError('Unknown class type: {} {}'
807 msgs = {d.name: d for d in s['Define']}
808 svcs = {s.caller: s for s in s['Service']}
809 replies = {s.reply: s for s in s['Service']}
815 if service not in msgs:
817 'Service definition refers to unknown message'
818 ' definition: {}'.format(service))
819 if svcs[service].reply != 'null' and \
820 svcs[service].reply not in msgs:
821 raise ValueError('Service definition refers to unknown message'
822 ' definition in reply: {}'
823 .format(svcs[service].reply))
824 if service in replies:
825 raise ValueError('Service definition refers to message'
826 ' marked as reply: {}'.format(service))
827 for event in svcs[service].events:
828 if event not in msgs:
829 raise ValueError('Service definition refers to unknown '
830 'event: {} in message: {}'
831 .format(event, service))
832 seen_services[event] = True
834 # Create services implicitly
836 if d in seen_services:
838 if msgs[d].singular is True:
840 if d.endswith('_reply'):
843 if d[:-6] not in msgs:
844 raise ValueError('{} missing calling message'
847 if d.endswith('_dump'):
850 if d[:-5]+'_details' in msgs:
851 s['Service'].append(Service(d, d[:-5]+'_details',
854 raise ValueError('{} missing details message'
858 if d.endswith('_details'):
859 if d[:-8]+'_dump' not in msgs:
860 raise ValueError('{} missing dump message'
866 if d+'_reply' in msgs:
867 s['Service'].append(Service(d, d+'_reply'))
870 '{} missing reply message ({}) or service definition'
871 .format(d, d+'_reply'))
875 def process_imports(self, objs, in_import, result):
878 # Only allow the following object types from imported file
879 if in_import and not (isinstance(o, Enum) or
880 isinstance(o, Union) or
881 isinstance(o, Typedef) or
882 isinstance(o, Import) or
883 isinstance(o, Using)):
885 if isinstance(o, Import):
887 result = self.process_imports(o.result, True, result)
893 # Add message ids to each message.
896 o.block.insert(0, Field('u16', '_vl_msg_id'))
903 def dirlist_add(dirs):
906 dirlist = dirlist + dirs
913 def foldup_blocks(block, crc):
915 # Look up CRC in user defined types
916 if b.fieldtype.startswith('vl_api_'):
918 t = global_types[b.fieldtype]
920 crc = crc_block_combine(t.block, crc)
921 return foldup_blocks(t.block, crc)
922 except AttributeError:
929 f.crc = foldup_blocks(f.block,
930 binascii.crc32(f.crc) & 0xffffffff)
937 if sys.version_info < (3, 5,):
938 log.exception('vppapigen requires a supported version of python. '
939 'Please use version 3.5 or greater. '
940 'Using {}'.format(sys.version))
943 cliparser = argparse.ArgumentParser(description='VPP API generator')
944 cliparser.add_argument('--pluginpath', default=""),
945 cliparser.add_argument('--includedir', action='append'),
946 cliparser.add_argument('--outputdir', action='store'),
947 cliparser.add_argument('--input')
948 cliparser.add_argument('--output', nargs='?',
949 type=argparse.FileType('w', encoding='UTF-8'),
952 cliparser.add_argument('output_module', nargs='?', default='C')
953 cliparser.add_argument('--debug', action='store_true')
954 cliparser.add_argument('--show-name', nargs=1)
955 cliparser.add_argument('--git-revision',
956 help="Git revision to use for opening files")
957 args = cliparser.parse_args()
959 dirlist_add(args.includedir)
961 sys.excepthook = exception_handler
965 filename = args.show_name[0]
967 filename = args.input
972 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
974 logging.basicConfig()
976 parser = VPPAPI(debug=args.debug, filename=filename, logger=log,
977 revision=args.git_revision)
981 parsed_objects = parser.parse_fd(sys.stdin, log)
983 parsed_objects = parser.parse_filename(args.input, log)
984 except ParseError as e:
985 print('Parse error: ', e, file=sys.stderr)
988 # Build a list of objects. Hash of lists.
991 if args.output_module == 'C':
992 s = parser.process(parsed_objects)
994 result = parser.process_imports(parsed_objects, False, result)
995 s = parser.process(result)
998 s['Define'] = add_msg_id(s['Define'])
1001 foldup_crcs(s['Define'])
1007 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
1008 for t in s['Define']:
1009 pp.pprint([t.name, t.flags, t.block])
1010 for t in s['types']:
1011 pp.pprint([t.name, t.block])
1014 # Generate representation
1016 from importlib.machinery import SourceFileLoader
1020 if not args.pluginpath:
1022 cand.append(os.path.dirname(os.path.realpath(__file__)))
1023 cand.append(os.path.dirname(os.path.realpath(__file__)) +
1027 if os.path.isfile('{}vppapigen_{}.py'
1028 .format(c, args.output_module.lower())):
1032 pluginpath = args.pluginpath + '/'
1033 if pluginpath == '':
1034 log.exception('Output plugin not found')
1036 module_path = '{}vppapigen_{}.py'.format(pluginpath,
1037 args.output_module.lower())
1040 plugin = SourceFileLoader(args.output_module,
1041 module_path).load_module()
1042 except Exception as err:
1043 log.exception('Error importing output plugin: {}, {}'
1044 .format(module_path, err))
1047 result = plugin.run(args, filename, s)
1049 print(result, file=args.output)
1051 log.exception('Running plugin failed: {} {}'
1052 .format(filename, result))
1057 if __name__ == '__main__':