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=False):
183 self.events = [] if events is None else events
187 def __init__(self, name, flags, block):
191 self.crc = str(block).encode()
192 self.manual_print = False
193 self.manual_endian = False
195 if f == 'manual_print':
196 self.manual_print = True
197 elif f == 'manual_endian':
198 self.manual_endian = True
200 global_type_add(name, self)
202 self.vla = vla_is_last_check(name, block)
205 return self.name + str(self.flags) + str(self.block)
209 def __init__(self, name, flags, alias):
213 self.manual_print = True
214 self.manual_endian = True
216 self.manual_print = False
217 self.manual_endian = False
219 if f == 'manual_print':
220 self.manual_print = True
221 elif f == 'manual_endian':
222 self.manual_endian = True
224 if isinstance(alias, Array):
225 a = {'type': alias.fieldtype,
226 'length': alias.length}
228 a = {'type': alias.fieldtype}
230 self.crc = str(alias).encode()
231 global_type_add(name, self)
234 return self.name + str(self.alias)
238 def __init__(self, name, flags, block):
240 self.manual_print = False
241 self.manual_endian = False
245 if f == 'manual_print':
246 self.manual_print = True
247 elif f == 'manual_endian':
248 self.manual_endian = True
251 self.crc = str(block).encode()
252 self.vla = vla_is_last_check(name, block)
254 global_type_add(name, self)
257 return str(self.block)
261 def __init__(self, name, flags, block):
265 self.dont_trace = False
266 self.manual_print = False
267 self.manual_endian = False
268 self.autoreply = False
269 self.singular = False
272 if f == 'dont_trace':
273 self.dont_trace = True
274 elif f == 'manual_print':
275 self.manual_print = True
276 elif f == 'manual_endian':
277 self.manual_endian = True
278 elif f == 'autoreply':
279 self.autoreply = True
283 if isinstance(b, Option):
284 if b[1] == 'singular' and b[2] == 'true':
287 self.options[b.option] = b.value
290 block = [x for x in block if x not in remove]
292 self.vla = vla_is_last_check(name, block)
293 self.crc = str(block).encode()
296 return self.name + str(self.flags) + str(self.block)
300 def __init__(self, name, block, enumtype='u32'):
302 self.enumtype = enumtype
306 for i, b in enumerate(block):
311 block[i] = [b, count]
314 self.crc = str(block).encode()
315 global_type_add(name, self)
318 return self.name + str(self.block)
323 def __new__(cls, *args, **kwargs):
324 if args[0] not in seen_imports:
325 instance = super().__new__(cls)
326 instance._initialized = False
327 seen_imports[args[0]] = instance
329 return seen_imports[args[0]]
331 def __init__(self, filename, revision):
332 if self._initialized:
335 self.filename = filename
337 parser = VPPAPI(filename=filename, revision=revision)
338 dirlist = dirlist_get()
341 f = os.path.join(dir, filename)
342 if os.path.exists(f):
344 self.result = parser.parse_filename(f, None)
345 self._initialized = True
352 def __init__(self, option, value):
356 self.crc = str(option).encode()
359 return str(self.option)
361 def __getitem__(self, index):
362 return self.option[index]
366 def __init__(self, fieldtype, name, length, modern_vla=False):
368 self.fieldtype = fieldtype
369 self.fieldname = name
370 self.modern_vla = modern_vla
371 if type(length) is str:
372 self.lengthfield = length
377 self.lengthfield = None
381 return str([self.fieldtype, self.fieldname, self.length,
386 def __init__(self, fieldtype, name, limit=None):
388 self.fieldtype = fieldtype
390 if self.fieldtype == 'string':
391 raise ValueError("The string type {!r} is an "
392 "array type ".format(name))
394 if name in keyword.kwlist:
395 raise ValueError("Fieldname {!r} is a python keyword and is not "
396 "accessible via the python API. ".format(name))
397 self.fieldname = name
401 return str([self.fieldtype, self.fieldname])
405 """ Coordinates of a syntactic element. Consists of:
408 - (optional) column number, for the Lexer
410 __slots__ = ('file', 'line', 'column', '__weakref__')
412 def __init__(self, file, line, column=None):
418 str = "%s:%s" % (self.file, self.line)
420 str += ":%s" % self.column
424 class ParseError(Exception):
431 class VPPAPIParser(object):
432 tokens = VPPAPILexer.tokens
434 def __init__(self, filename, logger, revision=None):
435 self.filename = filename
438 self.revision = revision
440 def _parse_error(self, msg, coord):
441 raise ParseError("%s: %s" % (coord, msg))
443 def _parse_warning(self, msg, coord):
445 self.logger.warning("%s: %s" % (coord, msg))
447 def _coord(self, lineno, column=None):
450 line=lineno, column=column)
452 def _token_coord(self, p, token_idx):
453 """ Returns the coordinates for the YaccProduction object 'p' indexed
454 with 'token_idx'. The coordinate includes the 'lineno' and
455 'column'. Both follow the lex semantic, starting from 1.
457 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
460 column = (p.lexpos(token_idx) - (last_cr))
461 return self._coord(p.lineno(token_idx), column)
463 def p_slist(self, p):
481 def p_import(self, p):
482 '''import : IMPORT STRING_LITERAL ';' '''
483 p[0] = Import(p[2], revision=self.revision)
485 def p_service(self, p):
486 '''service : SERVICE '{' service_statements '}' ';' '''
489 def p_service_statements(self, p):
490 '''service_statements : service_statement
491 | service_statements service_statement'''
497 def p_service_statement(self, p):
498 '''service_statement : RPC ID RETURNS NULL ';'
499 | RPC ID RETURNS ID ';'
500 | RPC ID RETURNS STREAM ID ';'
501 | RPC ID RETURNS ID EVENTS event_list ';' '''
503 # Verify that caller and reply differ
505 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
506 self._token_coord(p, 1))
508 p[0] = Service(p[2], p[4], p[6])
510 p[0] = Service(p[2], p[5], stream=True)
512 p[0] = Service(p[2], p[4])
514 def p_event_list(self, p):
515 '''event_list : events
516 | event_list events '''
522 def p_event(self, p):
528 '''enum : ENUM ID '{' enum_statements '}' ';' '''
529 p[0] = Enum(p[2], p[4])
531 def p_enum_type(self, p):
532 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
534 p[0] = Enum(p[2], p[6], enumtype=p[4])
536 p[0] = Enum(p[2], p[4])
538 def p_enum_size(self, p):
544 def p_define(self, p):
545 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
547 p[0] = Define(p[2], [], p[4])
549 def p_define_flist(self, p):
550 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
552 if 'typeonly' in p[1]:
553 self._parse_error('legacy typedef. use typedef: {} {}[{}];'
554 .format(p[1], p[2], p[4]),
555 self._token_coord(p, 1))
557 p[0] = Define(p[3], p[1], p[5])
559 def p_flist(self, p):
568 '''flag : MANUAL_PRINT
577 def p_typedef(self, p):
578 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
579 p[0] = Typedef(p[2], [], p[4])
581 def p_typedef_flist(self, p):
582 '''typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';' '''
583 p[0] = Typedef(p[3], p[1], p[5])
585 def p_typedef_alias(self, p):
586 '''typedef : TYPEDEF declaration '''
587 p[0] = Using(p[2].fieldname, [], p[2])
589 def p_typedef_alias_flist(self, p):
590 '''typedef : flist TYPEDEF declaration '''
591 p[0] = Using(p[3].fieldname, p[1], p[3])
593 def p_block_statements_opt(self, p):
594 '''block_statements_opt : block_statements '''
597 def p_block_statements(self, p):
598 '''block_statements : block_statement
599 | block_statements block_statement'''
605 def p_block_statement(self, p):
606 '''block_statement : declaration
610 def p_enum_statements(self, p):
611 '''enum_statements : enum_statement
612 | enum_statements enum_statement'''
618 def p_enum_statement(self, p):
619 '''enum_statement : ID '=' NUM ','
626 def p_field_options(self, p):
627 '''field_options : field_option
628 | field_options field_option'''
632 p[0] = {**p[1], **p[2]}
634 def p_field_option(self, p):
636 | ID '=' assignee ','
645 def p_declaration(self, p):
646 '''declaration : type_specifier ID ';'
647 | type_specifier ID '[' field_options ']' ';' '''
649 p[0] = Field(p[1], p[2], p[4])
651 p[0] = Field(p[1], p[2])
653 self._parse_error('ERROR', self._token_coord(p, 1))
654 self.fields.append(p[2])
656 def p_declaration_array_vla(self, p):
657 '''declaration : type_specifier ID '[' ']' ';' '''
658 p[0] = Array(p[1], p[2], 0, modern_vla=True)
660 def p_declaration_array(self, p):
661 '''declaration : type_specifier ID '[' NUM ']' ';'
662 | type_specifier ID '[' ID ']' ';' '''
665 return self._parse_error(
666 'array: %s' % p.value,
667 self._coord(lineno=p.lineno))
669 # Make this error later
670 if type(p[4]) is int and p[4] == 0:
671 # XXX: Line number is wrong
672 self._parse_warning('Old Style VLA: {} {}[{}];'
673 .format(p[1], p[2], p[4]),
674 self._token_coord(p, 1))
676 if type(p[4]) is str and p[4] not in self.fields:
677 # Verify that length field exists
678 self._parse_error('Missing length field: {} {}[{}];'
679 .format(p[1], p[2], p[4]),
680 self._token_coord(p, 1))
681 p[0] = Array(p[1], p[2], p[4])
683 def p_option(self, p):
684 '''option : OPTION ID '=' assignee ';' '''
685 p[0] = Option(p[2], p[4])
687 def p_assignee(self, p):
694 def p_type_specifier(self, p):
695 '''type_specifier : U8
708 # Do a second pass later to verify that user defined types are defined
709 def p_typedef_specifier(self, p):
710 '''type_specifier : ID '''
711 if p[1] not in global_types:
712 self._parse_error('Undefined type: {}'.format(p[1]),
713 self._token_coord(p, 1))
716 def p_union(self, p):
717 '''union : UNION ID '{' block_statements_opt '}' ';' '''
718 p[0] = Union(p[2], [], p[4])
720 def p_union_flist(self, p):
721 '''union : flist UNION ID '{' block_statements_opt '}' ';' '''
722 p[0] = Union(p[3], p[1], p[5])
724 # Error rule for syntax errors
725 def p_error(self, p):
728 'before: %s' % p.value,
729 self._coord(lineno=p.lineno))
731 self._parse_error('At end of input', self.filename)
734 class VPPAPI(object):
736 def __init__(self, debug=False, filename='', logger=None, revision=None):
737 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
738 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger,
740 write_tables=False, debug=debug)
742 self.revision = revision
743 self.filename = filename
745 def parse_string(self, code, debug=0, lineno=1):
746 self.lexer.lineno = lineno
747 return self.parser.parse(code, lexer=self.lexer, debug=debug)
749 def parse_fd(self, fd, debug=0):
751 return self.parse_string(data, debug=debug)
753 def parse_filename(self, filename, debug=0):
755 git_show = f'git show {self.revision}:{filename}'
756 proc = Popen(git_show.split(), stdout=PIPE, encoding='utf-8')
758 data, errs = proc.communicate()
759 if proc.returncode != 0:
760 print(f'File not found: {self.revision}:{filename}', file=sys.stderr)
762 return self.parse_string(data, debug=debug)
763 except Exception as e:
767 with open(filename, encoding='utf-8') as fd:
768 return self.parse_fd(fd, None)
769 except FileNotFoundError:
770 print(f'File not found: {filename}', file=sys.stderr)
773 def autoreply_block(self, name, parent):
774 block = [Field('u32', 'context'),
775 Field('i32', 'retval')]
776 # inherhit the parent's options
777 for k, v in parent.options.items():
778 block.append(Option(k, v))
779 return Define(name + '_reply', [], block)
781 def process(self, objs):
790 tname = o.__class__.__name__
792 crc = binascii.crc32(o.crc, crc) & 0xffffffff
793 except AttributeError:
795 if isinstance(o, Define):
798 s[tname].append(self.autoreply_block(o.name, o))
799 elif isinstance(o, Option):
800 s[tname][o.option] = o.value
801 elif type(o) is list:
803 if isinstance(o2, Service):
804 s['Service'].append(o2)
805 elif (isinstance(o, Enum) or
806 isinstance(o, Typedef) or
807 isinstance(o, Using) or
808 isinstance(o, Union)):
812 raise ValueError('Unknown class type: {} {}'
816 msgs = {d.name: d for d in s['Define']}
817 svcs = {s.caller: s for s in s['Service']}
818 replies = {s.reply: s for s in s['Service']}
824 if service not in msgs:
826 'Service definition refers to unknown message'
827 ' definition: {}'.format(service))
828 if svcs[service].reply != 'null' and \
829 svcs[service].reply not in msgs:
830 raise ValueError('Service definition refers to unknown message'
831 ' definition in reply: {}'
832 .format(svcs[service].reply))
833 if service in replies:
834 raise ValueError('Service definition refers to message'
835 ' marked as reply: {}'.format(service))
836 for event in svcs[service].events:
837 if event not in msgs:
838 raise ValueError('Service definition refers to unknown '
839 'event: {} in message: {}'
840 .format(event, service))
841 seen_services[event] = True
843 # Create services implicitly
845 if d in seen_services:
847 if msgs[d].singular is True:
849 if d.endswith('_reply'):
852 if d[:-6] not in msgs:
853 raise ValueError('{} missing calling message'
856 if d.endswith('_dump'):
859 if d[:-5]+'_details' in msgs:
860 s['Service'].append(Service(d, d[:-5]+'_details',
863 raise ValueError('{} missing details message'
867 if d.endswith('_details'):
868 if d[:-8]+'_dump' not in msgs:
869 raise ValueError('{} missing dump message'
875 if d+'_reply' in msgs:
876 s['Service'].append(Service(d, d+'_reply'))
879 '{} missing reply message ({}) or service definition'
880 .format(d, d+'_reply'))
884 def process_imports(self, objs, in_import, result):
887 # Only allow the following object types from imported file
888 if in_import and not (isinstance(o, Enum) or
889 isinstance(o, Union) or
890 isinstance(o, Typedef) or
891 isinstance(o, Import) or
892 isinstance(o, Using)):
894 if isinstance(o, Import):
896 result = self.process_imports(o.result, True, result)
902 # Add message ids to each message.
905 o.block.insert(0, Field('u16', '_vl_msg_id'))
912 def dirlist_add(dirs):
915 dirlist = dirlist + dirs
922 def foldup_blocks(block, crc):
924 # Look up CRC in user defined types
925 if b.fieldtype.startswith('vl_api_'):
927 t = global_types[b.fieldtype]
929 crc = crc_block_combine(t.block, crc)
930 return foldup_blocks(t.block, crc)
931 except AttributeError:
938 f.crc = foldup_blocks(f.block,
939 binascii.crc32(f.crc) & 0xffffffff)
946 if sys.version_info < (3, 5,):
947 log.exception('vppapigen requires a supported version of python. '
948 'Please use version 3.5 or greater. '
949 'Using {}'.format(sys.version))
952 cliparser = argparse.ArgumentParser(description='VPP API generator')
953 cliparser.add_argument('--pluginpath', default=""),
954 cliparser.add_argument('--includedir', action='append'),
955 cliparser.add_argument('--outputdir', action='store'),
956 cliparser.add_argument('--input')
957 cliparser.add_argument('--output', nargs='?',
958 type=argparse.FileType('w', encoding='UTF-8'),
961 cliparser.add_argument('output_module', nargs='?', default='C')
962 cliparser.add_argument('--debug', action='store_true')
963 cliparser.add_argument('--show-name', nargs=1)
964 cliparser.add_argument('--git-revision',
965 help="Git revision to use for opening files")
966 args = cliparser.parse_args()
968 dirlist_add(args.includedir)
970 sys.excepthook = exception_handler
974 filename = args.show_name[0]
976 filename = args.input
981 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
983 logging.basicConfig()
985 parser = VPPAPI(debug=args.debug, filename=filename, logger=log,
986 revision=args.git_revision)
990 parsed_objects = parser.parse_fd(sys.stdin, log)
992 parsed_objects = parser.parse_filename(args.input, log)
993 except ParseError as e:
994 print('Parse error: ', e, file=sys.stderr)
997 # Build a list of objects. Hash of lists.
1000 if args.output_module == 'C':
1001 s = parser.process(parsed_objects)
1003 result = parser.process_imports(parsed_objects, False, result)
1004 s = parser.process(result)
1007 s['Define'] = add_msg_id(s['Define'])
1010 foldup_crcs(s['Define'])
1016 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
1017 for t in s['Define']:
1018 pp.pprint([t.name, t.flags, t.block])
1019 for t in s['types']:
1020 pp.pprint([t.name, t.block])
1023 # Generate representation
1025 from importlib.machinery import SourceFileLoader
1029 if not args.pluginpath:
1031 cand.append(os.path.dirname(os.path.realpath(__file__)))
1032 cand.append(os.path.dirname(os.path.realpath(__file__)) +
1036 if os.path.isfile('{}vppapigen_{}.py'
1037 .format(c, args.output_module.lower())):
1041 pluginpath = args.pluginpath + '/'
1042 if pluginpath == '':
1043 log.exception('Output plugin not found')
1045 module_path = '{}vppapigen_{}.py'.format(pluginpath,
1046 args.output_module.lower())
1049 plugin = SourceFileLoader(args.output_module,
1050 module_path).load_module()
1051 except Exception as err:
1052 log.exception('Error importing output plugin: {}, {}'
1053 .format(module_path, err))
1056 result = plugin.run(args, filename, s)
1058 print(result, file=args.output)
1060 log.exception('Running plugin failed: {} {}'
1061 .format(filename, result))
1066 if __name__ == '__main__':