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
149 def __init__(self, caller, reply, events=None, stream=False):
153 self.events = [] if events is None else events
157 def __init__(self, name, flags, block):
161 self.crc = str(block).encode()
162 self.manual_print = False
163 self.manual_endian = False
165 if f == 'manual_print':
166 self.manual_print = True
167 elif f == 'manual_endian':
168 self.manual_endian = True
170 # Tag length field of a VLA
171 if isinstance(b, Array):
174 if b2.fieldname == b.lengthfield:
177 global_type_add(name, self)
181 for i, b in enumerate(block):
182 if isinstance(b, Array):
185 if i + 1 < len(block):
187 'VLA field "{}" must be the last '
188 'field in message "{}"'
189 .format(b.fieldname, name))
190 elif b.fieldtype == 'string':
192 if i + 1 < len(block):
194 'VLA field "{}" must be the last '
195 'field in message "{}"'
196 .format(b.fieldname, name))
199 return self.name + str(self.flags) + str(self.block)
203 def __init__(self, name, flags, alias):
207 self.manual_print = False
208 self.manual_endian = False
210 if f == 'manual_print':
211 self.manual_print = True
212 elif f == 'manual_endian':
213 self.manual_endian = True
215 if isinstance(alias, Array):
216 a = {'type': alias.fieldtype,
217 'length': alias.length}
219 a = {'type': alias.fieldtype}
221 self.crc = str(alias).encode()
222 global_type_add(name, self)
225 return self.name + str(self.alias)
229 def __init__(self, name, flags, block):
231 self.manual_print = False
232 self.manual_endian = False
235 self.manual_print = False
236 self.manual_endian = False
238 if f == 'manual_print':
239 self.manual_print = True
240 elif f == 'manual_endian':
241 self.manual_endian = True
244 self.crc = str(block).encode()
245 global_type_add(name, self)
248 return str(self.block)
252 def __init__(self, name, flags, block):
256 self.crc = str(block).encode()
257 self.dont_trace = False
258 self.manual_print = False
259 self.manual_endian = False
260 self.autoreply = False
261 self.singular = False
263 if f == 'dont_trace':
264 self.dont_trace = True
265 elif f == 'manual_print':
266 self.manual_print = True
267 elif f == 'manual_endian':
268 self.manual_endian = True
269 elif f == 'autoreply':
270 self.autoreply = True
272 for i, b in enumerate(block):
273 if isinstance(b, Option):
274 if b[1] == 'singular' and b[2] == 'true':
278 if isinstance(b, Array) and b.vla and i + 1 < len(block):
280 'VLA field "{}" must be the last field in message "{}"'
281 .format(b.fieldname, name))
282 elif b.fieldtype.startswith('vl_api_'):
283 if (global_types[b.fieldtype].vla and i + 1 < len(block)):
285 'VLA field "{}" must be the last '
286 'field in message "{}"'
287 .format(b.fieldname, name))
288 elif b.fieldtype == 'string' and b.length == 0:
289 if i + 1 < len(block):
291 'VLA field "{}" must be the last '
292 'field in message "{}"'
293 .format(b.fieldname, name))
294 # Tag length field of a VLA
295 if isinstance(b, Array):
298 if b2.fieldname == b.lengthfield:
302 return self.name + str(self.flags) + str(self.block)
306 def __init__(self, name, block, enumtype='u32'):
308 self.enumtype = enumtype
312 for i, b in enumerate(block):
317 block[i] = [b, count]
320 self.crc = str(block).encode()
321 global_type_add(name, self)
324 return self.name + str(self.block)
329 def __new__(cls, *args, **kwargs):
330 if args[0] not in seen_imports:
331 instance = super().__new__(cls)
332 instance._initialized = False
333 seen_imports[args[0]] = instance
335 return seen_imports[args[0]]
337 def __init__(self, filename):
338 if self._initialized:
341 self.filename = filename
343 parser = VPPAPI(filename=filename)
344 dirlist = dirlist_get()
347 f = os.path.join(dir, filename)
348 if os.path.exists(f):
350 if sys.version[0] == '2':
352 self.result = parser.parse_file(fd, None)
354 with open(f, encoding='utf-8') as fd:
355 self.result = parser.parse_file(fd, None)
356 self._initialized = True
363 def __init__(self, option, value):
367 self.crc = str(option).encode()
370 return str(self.option)
372 def __getitem__(self, index):
373 return self.option[index]
377 def __init__(self, fieldtype, name, length, modern_vla=False):
379 self.fieldtype = fieldtype
380 self.fieldname = name
381 self.modern_vla = modern_vla
382 if type(length) is str:
383 self.lengthfield = length
388 self.lengthfield = None
392 return str([self.fieldtype, self.fieldname, self.length,
397 def __init__(self, fieldtype, name, limit=None):
399 self.fieldtype = fieldtype
401 if self.fieldtype == 'string':
402 raise ValueError("The string type {!r} is an "
403 "array type ".format(name))
405 if name in keyword.kwlist:
406 raise ValueError("Fieldname {!r} is a python keyword and is not "
407 "accessible via the python API. ".format(name))
408 self.fieldname = name
412 return str([self.fieldtype, self.fieldname])
416 """ Coordinates of a syntactic element. Consists of:
419 - (optional) column number, for the Lexer
421 __slots__ = ('file', 'line', 'column', '__weakref__')
423 def __init__(self, file, line, column=None):
429 str = "%s:%s" % (self.file, self.line)
431 str += ":%s" % self.column
435 class ParseError(Exception):
442 class VPPAPIParser(object):
443 tokens = VPPAPILexer.tokens
445 def __init__(self, filename, logger):
446 self.filename = filename
450 def _parse_error(self, msg, coord):
451 raise ParseError("%s: %s" % (coord, msg))
453 def _parse_warning(self, msg, coord):
455 self.logger.warning("%s: %s" % (coord, msg))
457 def _coord(self, lineno, column=None):
460 line=lineno, column=column)
462 def _token_coord(self, p, token_idx):
463 """ Returns the coordinates for the YaccProduction object 'p' indexed
464 with 'token_idx'. The coordinate includes the 'lineno' and
465 'column'. Both follow the lex semantic, starting from 1.
467 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
470 column = (p.lexpos(token_idx) - (last_cr))
471 return self._coord(p.lineno(token_idx), column)
473 def p_slist(self, p):
491 def p_import(self, p):
492 '''import : IMPORT STRING_LITERAL ';' '''
495 def p_service(self, p):
496 '''service : SERVICE '{' service_statements '}' ';' '''
499 def p_service_statements(self, p):
500 '''service_statements : service_statement
501 | service_statements service_statement'''
507 def p_service_statement(self, p):
508 '''service_statement : RPC ID RETURNS NULL ';'
509 | RPC ID RETURNS ID ';'
510 | RPC ID RETURNS STREAM ID ';'
511 | RPC ID RETURNS ID EVENTS event_list ';' '''
513 # Verify that caller and reply differ
515 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
516 self._token_coord(p, 1))
518 p[0] = Service(p[2], p[4], p[6])
520 p[0] = Service(p[2], p[5], stream=True)
522 p[0] = Service(p[2], p[4])
524 def p_event_list(self, p):
525 '''event_list : events
526 | event_list events '''
532 def p_event(self, p):
538 '''enum : ENUM ID '{' enum_statements '}' ';' '''
539 p[0] = Enum(p[2], p[4])
541 def p_enum_type(self, p):
542 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
544 p[0] = Enum(p[2], p[6], enumtype=p[4])
546 p[0] = Enum(p[2], p[4])
548 def p_enum_size(self, p):
554 def p_define(self, p):
555 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
557 p[0] = Define(p[2], [], p[4])
559 def p_define_flist(self, p):
560 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
562 if 'typeonly' in p[1]:
563 self._parse_error('legacy typedef. use typedef: {} {}[{}];'
564 .format(p[1], p[2], p[4]),
565 self._token_coord(p, 1))
567 p[0] = Define(p[3], p[1], p[5])
569 def p_flist(self, p):
578 '''flag : MANUAL_PRINT
587 def p_typedef(self, p):
588 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
589 p[0] = Typedef(p[2], [], p[4])
591 def p_typedef_flist(self, p):
592 '''typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';' '''
593 p[0] = Typedef(p[3], p[1], p[5])
595 def p_typedef_alias(self, p):
596 '''typedef : TYPEDEF declaration '''
597 p[0] = Using(p[2].fieldname, [], p[2])
599 def p_typedef_alias_flist(self, p):
600 '''typedef : flist TYPEDEF declaration '''
601 p[0] = Using(p[3].fieldname, p[1], p[3])
603 def p_block_statements_opt(self, p):
604 '''block_statements_opt : block_statements '''
607 def p_block_statements(self, p):
608 '''block_statements : block_statement
609 | block_statements block_statement'''
615 def p_block_statement(self, p):
616 '''block_statement : declaration
620 def p_enum_statements(self, p):
621 '''enum_statements : enum_statement
622 | enum_statements enum_statement'''
628 def p_enum_statement(self, p):
629 '''enum_statement : ID '=' NUM ','
636 def p_field_options(self, p):
637 '''field_options : field_option
638 | field_options field_option'''
642 p[0] = {**p[1], **p[2]}
644 def p_field_option(self, p):
646 | ID '=' assignee ','
655 def p_declaration(self, p):
656 '''declaration : type_specifier ID ';'
657 | type_specifier ID '[' field_options ']' ';' '''
659 p[0] = Field(p[1], p[2], p[4])
661 p[0] = Field(p[1], p[2])
663 self._parse_error('ERROR')
664 self.fields.append(p[2])
666 def p_declaration_array_vla(self, p):
667 '''declaration : type_specifier ID '[' ']' ';' '''
668 p[0] = Array(p[1], p[2], 0, modern_vla=True)
670 def p_declaration_array(self, p):
671 '''declaration : type_specifier ID '[' NUM ']' ';'
672 | type_specifier ID '[' ID ']' ';' '''
675 return self._parse_error(
676 'array: %s' % p.value,
677 self._coord(lineno=p.lineno))
679 # Make this error later
680 if type(p[4]) is int and p[4] == 0:
681 # XXX: Line number is wrong
682 self._parse_warning('Old Style VLA: {} {}[{}];'
683 .format(p[1], p[2], p[4]),
684 self._token_coord(p, 1))
686 if type(p[4]) is str and p[4] not in self.fields:
687 # Verify that length field exists
688 self._parse_error('Missing length field: {} {}[{}];'
689 .format(p[1], p[2], p[4]),
690 self._token_coord(p, 1))
691 p[0] = Array(p[1], p[2], p[4])
693 def p_option(self, p):
694 '''option : OPTION ID '=' assignee ';' '''
695 p[0] = Option(p[2], p[4])
697 def p_assignee(self, p):
704 def p_type_specifier(self, p):
705 '''type_specifier : U8
718 # Do a second pass later to verify that user defined types are defined
719 def p_typedef_specifier(self, p):
720 '''type_specifier : ID '''
721 if p[1] not in global_types:
722 self._parse_error('Undefined type: {}'.format(p[1]),
723 self._token_coord(p, 1))
726 def p_union(self, p):
727 '''union : UNION ID '{' block_statements_opt '}' ';' '''
728 p[0] = Union(p[2], [], p[4])
730 def p_union_flist(self, p):
731 '''union : flist UNION ID '{' block_statements_opt '}' ';' '''
732 p[0] = Union(p[3], p[1], p[5])
734 # Error rule for syntax errors
735 def p_error(self, p):
738 'before: %s' % p.value,
739 self._coord(lineno=p.lineno))
741 self._parse_error('At end of input', self.filename)
744 class VPPAPI(object):
746 def __init__(self, debug=False, filename='', logger=None):
747 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
748 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
749 write_tables=False, debug=debug)
752 def parse_string(self, code, debug=0, lineno=1):
753 self.lexer.lineno = lineno
754 return self.parser.parse(code, lexer=self.lexer, debug=debug)
756 def parse_file(self, fd, debug=0):
758 return self.parse_string(data, debug=debug)
760 def autoreply_block(self, name):
761 block = [Field('u32', 'context'),
762 Field('i32', 'retval')]
763 return Define(name + '_reply', [], block)
765 def process(self, objs):
775 tname = o.__class__.__name__
777 crc = binascii.crc32(o.crc, crc)
778 except AttributeError:
780 if isinstance(o, Define):
783 s[tname].append(self.autoreply_block(o.name))
784 elif isinstance(o, Option):
785 s[tname][o[1]] = o[2]
786 elif type(o) is list:
788 if isinstance(o2, Service):
789 s['Service'].append(o2)
790 elif (isinstance(o, Enum) or
791 isinstance(o, Typedef) or
792 isinstance(o, Union)):
794 elif isinstance(o, Using):
795 s['Alias'][o.name] = o
798 raise ValueError('Unknown class type: {} {}'
802 msgs = {d.name: d for d in s['Define']}
803 svcs = {s.caller: s for s in s['Service']}
804 replies = {s.reply: s for s in s['Service']}
810 if service not in msgs:
812 'Service definition refers to unknown message'
813 ' definition: {}'.format(service))
814 if svcs[service].reply != 'null' and \
815 svcs[service].reply not in msgs:
816 raise ValueError('Service definition refers to unknown message'
817 ' definition in reply: {}'
818 .format(svcs[service].reply))
819 if service in replies:
820 raise ValueError('Service definition refers to message'
821 ' marked as reply: {}'.format(service))
822 for event in svcs[service].events:
823 if event not in msgs:
824 raise ValueError('Service definition refers to unknown '
825 'event: {} in message: {}'
826 .format(event, service))
827 seen_services[event] = True
829 # Create services implicitly
831 if d in seen_services:
833 if msgs[d].singular is True:
835 if d.endswith('_reply'):
838 if d[:-6] not in msgs:
839 raise ValueError('{} missing calling message'
842 if d.endswith('_dump'):
845 if d[:-5]+'_details' in msgs:
846 s['Service'].append(Service(d, d[:-5]+'_details',
849 raise ValueError('{} missing details message'
853 if d.endswith('_details'):
854 if d[:-8]+'_dump' not in msgs:
855 raise ValueError('{} missing dump message'
861 if d+'_reply' in msgs:
862 s['Service'].append(Service(d, d+'_reply'))
865 '{} missing reply message ({}) or service definition'
866 .format(d, d+'_reply'))
870 def process_imports(self, objs, in_import, result):
873 # Only allow the following object types from imported file
874 if in_import and not (isinstance(o, Enum) or
875 isinstance(o, Union) or
876 isinstance(o, Typedef) or
877 isinstance(o, Import) or
878 isinstance(o, Using)):
880 if isinstance(o, Import):
882 result = self.process_imports(o.result, True, result)
888 # Add message ids to each message.
891 o.block.insert(0, Field('u16', '_vl_msg_id'))
898 def dirlist_add(dirs):
901 dirlist = dirlist + dirs
908 def foldup_blocks(block, crc):
910 # Look up CRC in user defined types
911 if b.fieldtype.startswith('vl_api_'):
913 t = global_types[b.fieldtype]
915 crc = crc_block_combine(t.block, crc)
916 return foldup_blocks(t.block, crc)
917 except AttributeError:
924 f.crc = foldup_blocks(f.block,
925 binascii.crc32(f.crc))
932 if sys.version_info < (3, 5,):
933 log.exception('vppapigen requires a supported version of python. '
934 'Please use version 3.5 or greater. '
935 'Using {}'.format(sys.version))
938 cliparser = argparse.ArgumentParser(description='VPP API generator')
939 cliparser.add_argument('--pluginpath', default=""),
940 cliparser.add_argument('--includedir', action='append'),
941 cliparser.add_argument('--input',
942 type=argparse.FileType('r', encoding='UTF-8'),
944 cliparser.add_argument('--output', nargs='?',
945 type=argparse.FileType('w', encoding='UTF-8'),
948 cliparser.add_argument('output_module', nargs='?', default='C')
949 cliparser.add_argument('--debug', action='store_true')
950 cliparser.add_argument('--show-name', nargs=1)
951 args = cliparser.parse_args()
953 dirlist_add(args.includedir)
955 sys.excepthook = exception_handler
959 filename = args.show_name[0]
960 elif args.input != sys.stdin:
961 filename = args.input.name
966 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
968 logging.basicConfig()
970 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
971 parsed_objects = parser.parse_file(args.input, log)
973 # Build a list of objects. Hash of lists.
976 if args.output_module == 'C':
977 s = parser.process(parsed_objects)
979 result = parser.process_imports(parsed_objects, False, result)
980 s = parser.process(result)
983 s['Define'] = add_msg_id(s['Define'])
986 foldup_crcs(s['Define'])
992 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
993 for t in s['Define']:
994 pp.pprint([t.name, t.flags, t.block])
996 pp.pprint([t.name, t.block])
999 # Generate representation
1001 from importlib.machinery import SourceFileLoader
1005 if not args.pluginpath:
1007 cand.append(os.path.dirname(os.path.realpath(__file__)))
1008 cand.append(os.path.dirname(os.path.realpath(__file__)) +
1012 if os.path.isfile('{}vppapigen_{}.py'
1013 .format(c, args.output_module.lower())):
1017 pluginpath = args.pluginpath + '/'
1018 if pluginpath == '':
1019 log.exception('Output plugin not found')
1021 module_path = '{}vppapigen_{}.py'.format(pluginpath,
1022 args.output_module.lower())
1025 plugin = SourceFileLoader(args.output_module,
1026 module_path).load_module()
1027 except Exception as err:
1028 log.exception('Error importing output plugin: {}, {}'
1029 .format(module_path, err))
1032 result = plugin.run(filename, s)
1034 print(result, file=args.output)
1036 log.exception('Running plugin failed: {} {}'
1037 .format(filename, result))
1042 if __name__ == '__main__':