4 import ply.yacc as yacc
12 from subprocess import Popen, PIPE
14 assert sys.version_info >= (3, 6), \
15 "Not supported Python version: {}".format(sys.version)
16 log = logging.getLogger('vppapigen')
18 # Ensure we don't leave temporary files around
19 sys.dont_write_bytecode = True
25 # Global dictionary of new types (including enums)
31 def global_type_add(name, obj):
32 '''Add new type to the dictionary of types '''
33 type_name = 'vl_api_' + name + '_t'
34 if type_name in global_types:
35 raise KeyError("Attempted redefinition of {!r} with {!r}.".format(
37 global_types[type_name] = obj
40 # All your trace are belong to us!
41 def exception_handler(exception_type, exception, traceback):
42 print("%s: %s" % (exception_type.__name__, exception))
48 class VPPAPILexer(object):
49 def __init__(self, filename):
50 self.filename = filename
62 'typeonly': 'TYPEONLY',
63 'manual_print': 'MANUAL_PRINT',
64 'manual_endian': 'MANUAL_ENDIAN',
65 'dont_trace': 'DONT_TRACE',
66 'autoreply': 'AUTOREPLY',
85 tokens = ['STRING_LITERAL',
86 'ID', 'NUM'] + list(reserved.values())
88 t_ignore_LINE_COMMENT = '//.*'
101 r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
102 base = 16 if t.value.startswith('0x') else 10
104 t.value = float(t.value)
106 t.value = int(t.value, base)
110 r'[a-zA-Z_][a-zA-Z_0-9]*'
111 # Check for reserved words
112 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
116 def t_STRING_LITERAL(self, t):
117 r'\"([^\\\n]|(\\.))*?\"'
118 t.value = str(t.value).replace("\"", "")
121 # C or C++ comment (ignore)
122 def t_comment(self, t):
123 r'(/\*(.|\n)*?\*/)|(//.*)'
124 t.lexer.lineno += t.value.count('\n')
126 # Error handling rule
127 def t_error(self, t):
128 raise ParseError("Illegal character '{}' ({})"
129 "in {}: line {}".format(t.value[0],
130 hex(ord(t.value[0])),
135 # Define a rule so we can track line numbers
136 def t_newline(self, t):
138 t.lexer.lineno += len(t.value)
140 literals = ":{}[];=.,"
142 # A string containing ignored characters (spaces and tabs)
146 def crc_block_combine(block, crc):
147 s = str(block).encode()
148 return binascii.crc32(s, crc) & 0xffffffff
151 def vla_is_last_check(name, block):
153 for i, b in enumerate(block):
154 if isinstance(b, Array) and b.vla:
156 if i + 1 < len(block):
158 'VLA field "{}" must be the last field in message "{}"'
159 .format(b.fieldname, name))
160 elif b.fieldtype.startswith('vl_api_'):
161 if global_types[b.fieldtype].vla:
163 if i + 1 < len(block):
165 'VLA field "{}" must be the last '
166 'field in message "{}"'
167 .format(b.fieldname, name))
168 elif b.fieldtype == 'string' and b.length == 0:
170 if i + 1 < len(block):
172 'VLA field "{}" must be the last '
173 'field in message "{}"'
174 .format(b.fieldname, name))
179 def __init__(self, caller, reply, events=None, stream_message=None, stream=False):
183 self.stream_message = stream_message
184 self.events = [] if events is None else events
188 def __init__(self, name, flags, block):
192 self.crc = str(block).encode()
193 self.manual_print = False
194 self.manual_endian = False
196 if f == 'manual_print':
197 self.manual_print = True
198 elif f == 'manual_endian':
199 self.manual_endian = True
201 global_type_add(name, self)
203 self.vla = vla_is_last_check(name, block)
206 return self.name + str(self.flags) + str(self.block)
210 def __init__(self, name, flags, alias):
214 self.manual_print = True
215 self.manual_endian = True
217 self.manual_print = False
218 self.manual_endian = False
220 if f == 'manual_print':
221 self.manual_print = True
222 elif f == 'manual_endian':
223 self.manual_endian = True
225 if isinstance(alias, Array):
226 a = {'type': alias.fieldtype,
227 'length': alias.length}
229 a = {'type': alias.fieldtype}
231 self.crc = str(alias).encode()
232 global_type_add(name, self)
235 return self.name + str(self.alias)
239 def __init__(self, name, flags, block):
241 self.manual_print = False
242 self.manual_endian = False
246 if f == 'manual_print':
247 self.manual_print = True
248 elif f == 'manual_endian':
249 self.manual_endian = True
252 self.crc = str(block).encode()
253 self.vla = vla_is_last_check(name, block)
255 global_type_add(name, self)
258 return str(self.block)
262 def __init__(self, name, flags, block):
266 self.dont_trace = False
267 self.manual_print = False
268 self.manual_endian = False
269 self.autoreply = False
270 self.singular = False
273 if f == 'dont_trace':
274 self.dont_trace = True
275 elif f == 'manual_print':
276 self.manual_print = True
277 elif f == 'manual_endian':
278 self.manual_endian = True
279 elif f == 'autoreply':
280 self.autoreply = True
284 if isinstance(b, Option):
285 if b[1] == 'singular' and b[2] == 'true':
288 self.options[b.option] = b.value
291 block = [x for x in block if x not in remove]
293 self.vla = vla_is_last_check(name, block)
294 self.crc = str(block).encode()
297 return self.name + str(self.flags) + str(self.block)
301 def __init__(self, name, block, enumtype='u32'):
303 self.enumtype = enumtype
307 for i, b in enumerate(block):
312 block[i] = [b, count]
315 self.crc = str(block).encode()
316 global_type_add(name, self)
319 return self.name + str(self.block)
324 def __new__(cls, *args, **kwargs):
325 if args[0] not in seen_imports:
326 instance = super().__new__(cls)
327 instance._initialized = False
328 seen_imports[args[0]] = instance
330 return seen_imports[args[0]]
332 def __init__(self, filename, revision):
333 if self._initialized:
336 self.filename = filename
338 parser = VPPAPI(filename=filename, revision=revision)
339 dirlist = dirlist_get()
342 f = os.path.join(dir, filename)
343 if os.path.exists(f):
345 self.result = parser.parse_filename(f, None)
346 self._initialized = True
353 def __init__(self, option, value):
357 self.crc = str(option).encode()
360 return str(self.option)
362 def __getitem__(self, index):
363 return self.option[index]
367 def __init__(self, fieldtype, name, length, modern_vla=False):
369 self.fieldtype = fieldtype
370 self.fieldname = name
371 self.modern_vla = modern_vla
372 if type(length) is str:
373 self.lengthfield = length
378 self.lengthfield = None
382 return str([self.fieldtype, self.fieldname, self.length,
387 def __init__(self, fieldtype, name, limit=None):
389 self.fieldtype = fieldtype
391 if self.fieldtype == 'string':
392 raise ValueError("The string type {!r} is an "
393 "array type ".format(name))
395 if name in keyword.kwlist:
396 raise ValueError("Fieldname {!r} is a python keyword and is not "
397 "accessible via the python API. ".format(name))
398 self.fieldname = name
402 return str([self.fieldtype, self.fieldname])
406 """ Coordinates of a syntactic element. Consists of:
409 - (optional) column number, for the Lexer
411 __slots__ = ('file', 'line', 'column', '__weakref__')
413 def __init__(self, file, line, column=None):
419 str = "%s:%s" % (self.file, self.line)
421 str += ":%s" % self.column
425 class ParseError(Exception):
432 class VPPAPIParser(object):
433 tokens = VPPAPILexer.tokens
435 def __init__(self, filename, logger, revision=None):
436 self.filename = filename
439 self.revision = revision
441 def _parse_error(self, msg, coord):
442 raise ParseError("%s: %s" % (coord, msg))
444 def _parse_warning(self, msg, coord):
446 self.logger.warning("%s: %s" % (coord, msg))
448 def _coord(self, lineno, column=None):
451 line=lineno, column=column)
453 def _token_coord(self, p, token_idx):
454 """ Returns the coordinates for the YaccProduction object 'p' indexed
455 with 'token_idx'. The coordinate includes the 'lineno' and
456 'column'. Both follow the lex semantic, starting from 1.
458 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
461 column = (p.lexpos(token_idx) - (last_cr))
462 return self._coord(p.lineno(token_idx), column)
464 def p_slist(self, p):
482 def p_import(self, p):
483 '''import : IMPORT STRING_LITERAL ';' '''
484 p[0] = Import(p[2], revision=self.revision)
486 def p_service(self, p):
487 '''service : SERVICE '{' service_statements '}' ';' '''
490 def p_service_statements(self, p):
491 '''service_statements : service_statement
492 | service_statements service_statement'''
498 def p_service_statement(self, p):
499 '''service_statement : RPC ID RETURNS NULL ';'
500 | RPC ID RETURNS ID ';'
501 | RPC ID RETURNS STREAM ID ';'
502 | RPC ID RETURNS ID EVENTS event_list ';' '''
504 # Verify that caller and reply differ
506 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
507 self._token_coord(p, 1))
509 p[0] = Service(p[2], p[4], p[6])
511 p[0] = Service(p[2], p[5], stream=True)
513 p[0] = Service(p[2], p[4])
515 def p_service_statement2(self, p):
516 '''service_statement : RPC ID RETURNS ID STREAM ID ';' '''
517 p[0] = Service(p[2], p[4], stream_message=p[6], stream=True)
519 def p_event_list(self, p):
520 '''event_list : events
521 | event_list events '''
527 def p_event(self, p):
533 '''enum : ENUM ID '{' enum_statements '}' ';' '''
534 p[0] = Enum(p[2], p[4])
536 def p_enum_type(self, p):
537 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
539 p[0] = Enum(p[2], p[6], enumtype=p[4])
541 p[0] = Enum(p[2], p[4])
543 def p_enum_size(self, p):
549 def p_define(self, p):
550 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
552 p[0] = Define(p[2], [], p[4])
554 def p_define_flist(self, p):
555 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
557 if 'typeonly' in p[1]:
558 self._parse_error('legacy typedef. use typedef: {} {}[{}];'
559 .format(p[1], p[2], p[4]),
560 self._token_coord(p, 1))
562 p[0] = Define(p[3], p[1], p[5])
564 def p_flist(self, p):
573 '''flag : MANUAL_PRINT
582 def p_typedef(self, p):
583 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
584 p[0] = Typedef(p[2], [], p[4])
586 def p_typedef_flist(self, p):
587 '''typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';' '''
588 p[0] = Typedef(p[3], p[1], p[5])
590 def p_typedef_alias(self, p):
591 '''typedef : TYPEDEF declaration '''
592 p[0] = Using(p[2].fieldname, [], p[2])
594 def p_typedef_alias_flist(self, p):
595 '''typedef : flist TYPEDEF declaration '''
596 p[0] = Using(p[3].fieldname, p[1], p[3])
598 def p_block_statements_opt(self, p):
599 '''block_statements_opt : block_statements '''
602 def p_block_statements(self, p):
603 '''block_statements : block_statement
604 | block_statements block_statement'''
610 def p_block_statement(self, p):
611 '''block_statement : declaration
615 def p_enum_statements(self, p):
616 '''enum_statements : enum_statement
617 | enum_statements enum_statement'''
623 def p_enum_statement(self, p):
624 '''enum_statement : ID '=' NUM ','
631 def p_field_options(self, p):
632 '''field_options : field_option
633 | field_options field_option'''
637 p[0] = {**p[1], **p[2]}
639 def p_field_option(self, p):
641 | ID '=' assignee ','
650 def p_declaration(self, p):
651 '''declaration : type_specifier ID ';'
652 | type_specifier ID '[' field_options ']' ';' '''
654 p[0] = Field(p[1], p[2], p[4])
656 p[0] = Field(p[1], p[2])
658 self._parse_error('ERROR', self._token_coord(p, 1))
659 self.fields.append(p[2])
661 def p_declaration_array_vla(self, p):
662 '''declaration : type_specifier ID '[' ']' ';' '''
663 p[0] = Array(p[1], p[2], 0, modern_vla=True)
665 def p_declaration_array(self, p):
666 '''declaration : type_specifier ID '[' NUM ']' ';'
667 | type_specifier ID '[' ID ']' ';' '''
670 return self._parse_error(
671 'array: %s' % p.value,
672 self._coord(lineno=p.lineno))
674 # Make this error later
675 if type(p[4]) is int and p[4] == 0:
676 # XXX: Line number is wrong
677 self._parse_warning('Old Style VLA: {} {}[{}];'
678 .format(p[1], p[2], p[4]),
679 self._token_coord(p, 1))
681 if type(p[4]) is str and p[4] not in self.fields:
682 # Verify that length field exists
683 self._parse_error('Missing length field: {} {}[{}];'
684 .format(p[1], p[2], p[4]),
685 self._token_coord(p, 1))
686 p[0] = Array(p[1], p[2], p[4])
688 def p_option(self, p):
689 '''option : OPTION ID '=' assignee ';' '''
690 p[0] = Option(p[2], p[4])
692 def p_assignee(self, p):
699 def p_type_specifier(self, p):
700 '''type_specifier : U8
713 # Do a second pass later to verify that user defined types are defined
714 def p_typedef_specifier(self, p):
715 '''type_specifier : ID '''
716 if p[1] not in global_types:
717 self._parse_error('Undefined type: {}'.format(p[1]),
718 self._token_coord(p, 1))
721 def p_union(self, p):
722 '''union : UNION ID '{' block_statements_opt '}' ';' '''
723 p[0] = Union(p[2], [], p[4])
725 def p_union_flist(self, p):
726 '''union : flist UNION ID '{' block_statements_opt '}' ';' '''
727 p[0] = Union(p[3], p[1], p[5])
729 # Error rule for syntax errors
730 def p_error(self, p):
733 'before: %s' % p.value,
734 self._coord(lineno=p.lineno))
736 self._parse_error('At end of input', self.filename)
739 class VPPAPI(object):
741 def __init__(self, debug=False, filename='', logger=None, revision=None):
742 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
743 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger,
745 write_tables=False, debug=debug)
747 self.revision = revision
748 self.filename = filename
750 def parse_string(self, code, debug=0, lineno=1):
751 self.lexer.lineno = lineno
752 return self.parser.parse(code, lexer=self.lexer, debug=debug)
754 def parse_fd(self, fd, debug=0):
756 return self.parse_string(data, debug=debug)
758 def parse_filename(self, filename, debug=0):
760 git_show = f'git show {self.revision}:{filename}'
761 proc = Popen(git_show.split(), stdout=PIPE, encoding='utf-8')
763 data, errs = proc.communicate()
764 if proc.returncode != 0:
765 print(f'File not found: {self.revision}:{filename}', file=sys.stderr)
767 return self.parse_string(data, debug=debug)
768 except Exception as e:
772 with open(filename, encoding='utf-8') as fd:
773 return self.parse_fd(fd, None)
774 except FileNotFoundError:
775 print(f'File not found: {filename}', file=sys.stderr)
778 def autoreply_block(self, name, parent):
779 block = [Field('u32', 'context'),
780 Field('i32', 'retval')]
781 # inherhit the parent's options
782 for k, v in parent.options.items():
783 block.append(Option(k, v))
784 return Define(name + '_reply', [], block)
786 def process(self, objs):
795 tname = o.__class__.__name__
797 crc = binascii.crc32(o.crc, crc) & 0xffffffff
798 except AttributeError:
800 if isinstance(o, Define):
803 s[tname].append(self.autoreply_block(o.name, o))
804 elif isinstance(o, Option):
805 s[tname][o.option] = o.value
806 elif type(o) is list:
808 if isinstance(o2, Service):
809 s['Service'].append(o2)
810 elif (isinstance(o, Enum) or
811 isinstance(o, Typedef) or
812 isinstance(o, Using) or
813 isinstance(o, Union)):
817 raise ValueError('Unknown class type: {} {}'
821 msgs = {d.name: d for d in s['Define']}
822 svcs = {s.caller: s for s in s['Service']}
823 replies = {s.reply: s for s in s['Service']}
829 if service not in msgs:
831 'Service definition refers to unknown message'
832 ' definition: {}'.format(service))
833 if svcs[service].reply != 'null' and \
834 svcs[service].reply not in msgs:
835 raise ValueError('Service definition refers to unknown message'
836 ' definition in reply: {}'
837 .format(svcs[service].reply))
838 if service in replies:
839 raise ValueError('Service definition refers to message'
840 ' marked as reply: {}'.format(service))
841 for event in svcs[service].events:
842 if event not in msgs:
843 raise ValueError('Service definition refers to unknown '
844 'event: {} in message: {}'
845 .format(event, service))
846 seen_services[event] = True
848 # Create services implicitly
850 if d in seen_services:
852 if msgs[d].singular is True:
854 if d.endswith('_reply'):
857 if d[:-6] not in msgs:
858 raise ValueError('{} missing calling message'
861 if d.endswith('_dump'):
864 if d[:-5]+'_details' in msgs:
865 s['Service'].append(Service(d, d[:-5]+'_details',
868 raise ValueError('{} missing details message'
872 if d.endswith('_details'):
873 if d[:-8]+'_dump' not in msgs:
874 raise ValueError('{} missing dump message'
880 if d+'_reply' in msgs:
881 s['Service'].append(Service(d, d+'_reply'))
884 '{} missing reply message ({}) or service definition'
885 .format(d, d+'_reply'))
889 def process_imports(self, objs, in_import, result):
892 # Only allow the following object types from imported file
893 if in_import and not (isinstance(o, Enum) or
894 isinstance(o, Union) or
895 isinstance(o, Typedef) or
896 isinstance(o, Import) or
897 isinstance(o, Using)):
899 if isinstance(o, Import):
901 result = self.process_imports(o.result, True, result)
907 # Add message ids to each message.
910 o.block.insert(0, Field('u16', '_vl_msg_id'))
917 def dirlist_add(dirs):
920 dirlist = dirlist + dirs
927 def foldup_blocks(block, crc):
929 # Look up CRC in user defined types
930 if b.fieldtype.startswith('vl_api_'):
932 t = global_types[b.fieldtype]
934 crc = crc_block_combine(t.block, crc)
935 return foldup_blocks(t.block, crc)
936 except AttributeError:
943 f.crc = foldup_blocks(f.block,
944 binascii.crc32(f.crc) & 0xffffffff)
951 if sys.version_info < (3, 5,):
952 log.exception('vppapigen requires a supported version of python. '
953 'Please use version 3.5 or greater. '
954 'Using {}'.format(sys.version))
957 cliparser = argparse.ArgumentParser(description='VPP API generator')
958 cliparser.add_argument('--pluginpath', default=""),
959 cliparser.add_argument('--includedir', action='append'),
960 cliparser.add_argument('--outputdir', action='store'),
961 cliparser.add_argument('--input')
962 cliparser.add_argument('--output', nargs='?',
963 type=argparse.FileType('w', encoding='UTF-8'),
966 cliparser.add_argument('output_module', nargs='?', default='C')
967 cliparser.add_argument('--debug', action='store_true')
968 cliparser.add_argument('--show-name', nargs=1)
969 cliparser.add_argument('--git-revision',
970 help="Git revision to use for opening files")
971 args = cliparser.parse_args()
973 dirlist_add(args.includedir)
975 sys.excepthook = exception_handler
979 filename = args.show_name[0]
981 filename = args.input
986 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
988 logging.basicConfig()
990 parser = VPPAPI(debug=args.debug, filename=filename, logger=log,
991 revision=args.git_revision)
995 parsed_objects = parser.parse_fd(sys.stdin, log)
997 parsed_objects = parser.parse_filename(args.input, log)
998 except ParseError as e:
999 print('Parse error: ', e, file=sys.stderr)
1002 # Build a list of objects. Hash of lists.
1005 if args.output_module == 'C':
1006 s = parser.process(parsed_objects)
1008 result = parser.process_imports(parsed_objects, False, result)
1009 s = parser.process(result)
1012 s['Define'] = add_msg_id(s['Define'])
1015 foldup_crcs(s['Define'])
1021 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
1022 for t in s['Define']:
1023 pp.pprint([t.name, t.flags, t.block])
1024 for t in s['types']:
1025 pp.pprint([t.name, t.block])
1028 # Generate representation
1030 from importlib.machinery import SourceFileLoader
1034 if not args.pluginpath:
1036 cand.append(os.path.dirname(os.path.realpath(__file__)))
1037 cand.append(os.path.dirname(os.path.realpath(__file__)) +
1041 if os.path.isfile('{}vppapigen_{}.py'
1042 .format(c, args.output_module.lower())):
1046 pluginpath = args.pluginpath + '/'
1047 if pluginpath == '':
1048 log.exception('Output plugin not found')
1050 module_path = '{}vppapigen_{}.py'.format(pluginpath,
1051 args.output_module.lower())
1054 plugin = SourceFileLoader(args.output_module,
1055 module_path).load_module()
1056 except Exception as err:
1057 log.exception('Error importing output plugin: {}, {}'
1058 .format(module_path, err))
1061 result = plugin.run(args, filename, s)
1063 print(result, file=args.output)
1065 log.exception('Running plugin failed: {} {}'
1066 .format(filename, result))
1071 if __name__ == '__main__':