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)
26 def global_type_add(name, obj):
27 '''Add new type to the dictionary of types '''
28 type_name = 'vl_api_' + name + '_t'
29 global_types[type_name] = obj
32 # All your trace are belong to us!
33 def exception_handler(exception_type, exception, traceback):
34 print("%s: %s" % (exception_type.__name__, exception))
40 class VPPAPILexer(object):
41 def __init__(self, filename):
42 self.filename = filename
54 'typeonly': 'TYPEONLY',
55 'manual_print': 'MANUAL_PRINT',
56 'manual_endian': 'MANUAL_ENDIAN',
57 'dont_trace': 'DONT_TRACE',
58 'autoreply': 'AUTOREPLY',
77 tokens = ['STRING_LITERAL',
78 'ID', 'NUM'] + list(reserved.values())
80 t_ignore_LINE_COMMENT = '//.*'
93 r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
94 base = 16 if t.value.startswith('0x') else 10
96 t.value = float(t.value)
98 t.value = int(t.value, base)
102 r'[a-zA-Z_][a-zA-Z_0-9]*'
103 # Check for reserved words
104 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
108 def t_STRING_LITERAL(self, t):
109 r'\"([^\\\n]|(\\.))*?\"'
110 t.value = str(t.value).replace("\"", "")
113 # C or C++ comment (ignore)
114 def t_comment(self, t):
115 r'(/\*(.|\n)*?\*/)|(//.*)'
116 t.lexer.lineno += t.value.count('\n')
118 # Error handling rule
119 def t_error(self, t):
120 raise ParseError("Illegal character '{}' ({})"
121 "in {}: line {}".format(t.value[0],
122 hex(ord(t.value[0])),
127 # Define a rule so we can track line numbers
128 def t_newline(self, t):
130 t.lexer.lineno += len(t.value)
132 literals = ":{}[];=.,"
134 # A string containing ignored characters (spaces and tabs)
138 def crc_block_combine(block, crc):
139 s = str(block).encode()
140 return binascii.crc32(s, crc) & 0xffffffff
144 def __init__(self, caller, reply, events=None, stream=False):
148 self.events = [] if events is None else events
152 def __init__(self, name, flags, block):
156 self.crc = str(block).encode()
157 self.manual_print = False
158 self.manual_endian = False
160 if f == 'manual_print':
161 self.manual_print = True
162 elif f == 'manual_endian':
163 self.manual_endian = True
165 # Tag length field of a VLA
166 if isinstance(b, Array):
169 if b2.fieldname == b.lengthfield:
172 global_type_add(name, self)
176 for i, b in enumerate(block):
177 if isinstance(b, Array):
180 if i + 1 < len(block):
182 'VLA field "{}" must be the last '
183 'field in message "{}"'
184 .format(b.fieldname, name))
185 elif b.fieldtype == 'string':
187 if i + 1 < len(block):
189 'VLA field "{}" must be the last '
190 'field in message "{}"'
191 .format(b.fieldname, name))
194 return self.name + str(self.flags) + str(self.block)
198 def __init__(self, name, flags, alias):
202 self.manual_print = False
203 self.manual_endian = False
205 if f == 'manual_print':
206 self.manual_print = True
207 elif f == 'manual_endian':
208 self.manual_endian = True
210 if isinstance(alias, Array):
211 a = {'type': alias.fieldtype,
212 'length': alias.length}
214 a = {'type': alias.fieldtype}
216 self.crc = str(alias).encode()
217 global_type_add(name, self)
220 return self.name + str(self.alias)
224 def __init__(self, name, flags, block):
226 self.manual_print = False
227 self.manual_endian = False
230 self.manual_print = False
231 self.manual_endian = False
233 if f == 'manual_print':
234 self.manual_print = True
235 elif f == 'manual_endian':
236 self.manual_endian = True
239 self.crc = str(block).encode()
240 global_type_add(name, self)
243 return str(self.block)
247 def __init__(self, name, flags, block):
251 self.crc = str(block).encode()
252 self.dont_trace = False
253 self.manual_print = False
254 self.manual_endian = False
255 self.autoreply = False
256 self.singular = False
258 if f == 'dont_trace':
259 self.dont_trace = True
260 elif f == 'manual_print':
261 self.manual_print = True
262 elif f == 'manual_endian':
263 self.manual_endian = True
264 elif f == 'autoreply':
265 self.autoreply = True
267 for i, b in enumerate(block):
268 if isinstance(b, Option):
269 if b[1] == 'singular' and b[2] == 'true':
273 if isinstance(b, Array) and b.vla and i + 1 < len(block):
275 'VLA field "{}" must be the last field in message "{}"'
276 .format(b.fieldname, name))
277 elif b.fieldtype.startswith('vl_api_'):
278 if (global_types[b.fieldtype].vla and i + 1 < len(block)):
280 'VLA field "{}" must be the last '
281 'field in message "{}"'
282 .format(b.fieldname, name))
283 elif b.fieldtype == 'string' and b.length == 0:
284 if i + 1 < len(block):
286 'VLA field "{}" must be the last '
287 'field in message "{}"'
288 .format(b.fieldname, name))
289 # Tag length field of a VLA
290 if isinstance(b, Array):
293 if b2.fieldname == b.lengthfield:
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)
323 def __init__(self, filename):
324 self.filename = filename
327 parser = VPPAPI(filename=filename)
328 dirlist = dirlist_get()
331 f = os.path.join(dir, filename)
332 if os.path.exists(f):
335 with open(f, encoding='utf-8') as fd:
336 self.result = parser.parse_file(fd, None)
343 def __init__(self, option, value):
347 self.crc = str(option).encode()
350 return str(self.option)
352 def __getitem__(self, index):
353 return self.option[index]
357 def __init__(self, fieldtype, name, length, modern_vla=False):
359 self.fieldtype = fieldtype
360 self.fieldname = name
361 self.modern_vla = modern_vla
362 if type(length) is str:
363 self.lengthfield = length
368 self.lengthfield = None
372 return str([self.fieldtype, self.fieldname, self.length,
377 def __init__(self, fieldtype, name, limit=None):
379 self.fieldtype = fieldtype
381 if self.fieldtype == 'string':
382 raise ValueError("The string type {!r} is an "
383 "array type ".format(name))
385 if name in keyword.kwlist:
386 raise ValueError("Fieldname {!r} is a python keyword and is not "
387 "accessible via the python API. ".format(name))
388 self.fieldname = name
392 return str([self.fieldtype, self.fieldname])
396 """ Coordinates of a syntactic element. Consists of:
399 - (optional) column number, for the Lexer
401 __slots__ = ('file', 'line', 'column', '__weakref__')
403 def __init__(self, file, line, column=None):
409 str = "%s:%s" % (self.file, self.line)
411 str += ":%s" % self.column
415 class ParseError(Exception):
422 class VPPAPIParser(object):
423 tokens = VPPAPILexer.tokens
425 def __init__(self, filename, logger):
426 self.filename = filename
430 def _parse_error(self, msg, coord):
431 raise ParseError("%s: %s" % (coord, msg))
433 def _parse_warning(self, msg, coord):
435 self.logger.warning("%s: %s" % (coord, msg))
437 def _coord(self, lineno, column=None):
440 line=lineno, column=column)
442 def _token_coord(self, p, token_idx):
443 """ Returns the coordinates for the YaccProduction object 'p' indexed
444 with 'token_idx'. The coordinate includes the 'lineno' and
445 'column'. Both follow the lex semantic, starting from 1.
447 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
450 column = (p.lexpos(token_idx) - (last_cr))
451 return self._coord(p.lineno(token_idx), column)
453 def p_slist(self, p):
471 def p_import(self, p):
472 '''import : IMPORT STRING_LITERAL ';' '''
475 def p_service(self, p):
476 '''service : SERVICE '{' service_statements '}' ';' '''
479 def p_service_statements(self, p):
480 '''service_statements : service_statement
481 | service_statements service_statement'''
487 def p_service_statement(self, p):
488 '''service_statement : RPC ID RETURNS NULL ';'
489 | RPC ID RETURNS ID ';'
490 | RPC ID RETURNS STREAM ID ';'
491 | RPC ID RETURNS ID EVENTS event_list ';' '''
493 # Verify that caller and reply differ
495 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
496 self._token_coord(p, 1))
498 p[0] = Service(p[2], p[4], p[6])
500 p[0] = Service(p[2], p[5], stream=True)
502 p[0] = Service(p[2], p[4])
504 def p_event_list(self, p):
505 '''event_list : events
506 | event_list events '''
512 def p_event(self, p):
518 '''enum : ENUM ID '{' enum_statements '}' ';' '''
519 p[0] = Enum(p[2], p[4])
521 def p_enum_type(self, p):
522 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
524 p[0] = Enum(p[2], p[6], enumtype=p[4])
526 p[0] = Enum(p[2], p[4])
528 def p_enum_size(self, p):
534 def p_define(self, p):
535 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
537 p[0] = Define(p[2], [], p[4])
539 def p_define_flist(self, p):
540 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
542 if 'typeonly' in p[1]:
543 self._parse_error('legacy typedef. use typedef: {} {}[{}];'
544 .format(p[1], p[2], p[4]),
545 self._token_coord(p, 1))
547 p[0] = Define(p[3], p[1], p[5])
549 def p_flist(self, p):
558 '''flag : MANUAL_PRINT
567 def p_typedef(self, p):
568 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
569 p[0] = Typedef(p[2], [], p[4])
571 def p_typedef_flist(self, p):
572 '''typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';' '''
573 p[0] = Typedef(p[3], p[1], p[5])
575 def p_typedef_alias(self, p):
576 '''typedef : TYPEDEF declaration '''
577 p[0] = Using(p[2].fieldname, [], p[2])
579 def p_typedef_alias_flist(self, p):
580 '''typedef : flist TYPEDEF declaration '''
581 p[0] = Using(p[3].fieldname, p[1], p[3])
583 def p_block_statements_opt(self, p):
584 '''block_statements_opt : block_statements '''
587 def p_block_statements(self, p):
588 '''block_statements : block_statement
589 | block_statements block_statement'''
595 def p_block_statement(self, p):
596 '''block_statement : declaration
600 def p_enum_statements(self, p):
601 '''enum_statements : enum_statement
602 | enum_statements enum_statement'''
608 def p_enum_statement(self, p):
609 '''enum_statement : ID '=' NUM ','
616 def p_field_options(self, p):
617 '''field_options : field_option
618 | field_options field_option'''
622 p[0] = {**p[1], **p[2]}
624 def p_field_option(self, p):
626 | ID '=' assignee ','
635 def p_declaration(self, p):
636 '''declaration : type_specifier ID ';'
637 | type_specifier ID '[' field_options ']' ';' '''
639 p[0] = Field(p[1], p[2], p[4])
641 p[0] = Field(p[1], p[2])
643 self._parse_error('ERROR')
644 self.fields.append(p[2])
646 def p_declaration_array_vla(self, p):
647 '''declaration : type_specifier ID '[' ']' ';' '''
648 p[0] = Array(p[1], p[2], 0, modern_vla=True)
650 def p_declaration_array(self, p):
651 '''declaration : type_specifier ID '[' NUM ']' ';'
652 | type_specifier ID '[' ID ']' ';' '''
655 return self._parse_error(
656 'array: %s' % p.value,
657 self._coord(lineno=p.lineno))
659 # Make this error later
660 if type(p[4]) is int and p[4] == 0:
661 # XXX: Line number is wrong
662 self._parse_warning('Old Style VLA: {} {}[{}];'
663 .format(p[1], p[2], p[4]),
664 self._token_coord(p, 1))
666 if type(p[4]) is str and p[4] not in self.fields:
667 # Verify that length field exists
668 self._parse_error('Missing length field: {} {}[{}];'
669 .format(p[1], p[2], p[4]),
670 self._token_coord(p, 1))
671 p[0] = Array(p[1], p[2], p[4])
673 def p_option(self, p):
674 '''option : OPTION ID '=' assignee ';' '''
675 p[0] = Option(p[2], p[4])
677 def p_assignee(self, p):
684 def p_type_specifier(self, p):
685 '''type_specifier : U8
698 # Do a second pass later to verify that user defined types are defined
699 def p_typedef_specifier(self, p):
700 '''type_specifier : ID '''
701 if p[1] not in global_types:
702 self._parse_error('Undefined type: {}'.format(p[1]),
703 self._token_coord(p, 1))
706 def p_union(self, p):
707 '''union : UNION ID '{' block_statements_opt '}' ';' '''
708 p[0] = Union(p[2], [], p[4])
710 def p_union_flist(self, p):
711 '''union : flist UNION ID '{' block_statements_opt '}' ';' '''
712 p[0] = Union(p[3], p[1], p[5])
714 # Error rule for syntax errors
715 def p_error(self, p):
718 'before: %s' % p.value,
719 self._coord(lineno=p.lineno))
721 self._parse_error('At end of input', self.filename)
724 class VPPAPI(object):
726 def __init__(self, debug=False, filename='', logger=None):
727 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
728 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
729 write_tables=False, debug=debug)
732 def parse_string(self, code, debug=0, lineno=1):
733 self.lexer.lineno = lineno
734 return self.parser.parse(code, lexer=self.lexer, debug=debug)
736 def parse_file(self, fd, debug=0):
738 return self.parse_string(data, debug=debug)
740 def autoreply_block(self, name):
741 block = [Field('u32', 'context'),
742 Field('i32', 'retval')]
743 return Define(name + '_reply', [], block)
745 def process(self, objs):
755 tname = o.__class__.__name__
757 crc = binascii.crc32(o.crc, crc)
758 except AttributeError:
760 if isinstance(o, Define):
763 s[tname].append(self.autoreply_block(o.name))
764 elif isinstance(o, Option):
765 s[tname][o[1]] = o[2]
766 elif type(o) is list:
768 if isinstance(o2, Service):
769 s['Service'].append(o2)
770 elif (isinstance(o, Enum) or
771 isinstance(o, Typedef) or
772 isinstance(o, Union)):
774 elif isinstance(o, Using):
775 s['Alias'][o.name] = o
778 raise ValueError('Unknown class type: {} {}'
782 msgs = {d.name: d for d in s['Define']}
783 svcs = {s.caller: s for s in s['Service']}
784 replies = {s.reply: s for s in s['Service']}
790 if service not in msgs:
792 'Service definition refers to unknown message'
793 ' definition: {}'.format(service))
794 if svcs[service].reply != 'null' and \
795 svcs[service].reply not in msgs:
796 raise ValueError('Service definition refers to unknown message'
797 ' definition in reply: {}'
798 .format(svcs[service].reply))
799 if service in replies:
800 raise ValueError('Service definition refers to message'
801 ' marked as reply: {}'.format(service))
802 for event in svcs[service].events:
803 if event not in msgs:
804 raise ValueError('Service definition refers to unknown '
805 'event: {} in message: {}'
806 .format(event, service))
807 seen_services[event] = True
809 # Create services implicitly
811 if d in seen_services:
813 if msgs[d].singular is True:
815 if d.endswith('_reply'):
818 if d[:-6] not in msgs:
819 raise ValueError('{} missing calling message'
822 if d.endswith('_dump'):
825 if d[:-5]+'_details' in msgs:
826 s['Service'].append(Service(d, d[:-5]+'_details',
829 raise ValueError('{} missing details message'
833 if d.endswith('_details'):
834 if d[:-8]+'_dump' not in msgs:
835 raise ValueError('{} missing dump message'
841 if d+'_reply' in msgs:
842 s['Service'].append(Service(d, d+'_reply'))
845 '{} missing reply message ({}) or service definition'
846 .format(d, d+'_reply'))
850 def process_imports(self, objs, in_import, result):
853 # Only allow the following object types from imported file
854 if in_import and not (isinstance(o, Enum) or
855 isinstance(o, Union) or
856 isinstance(o, Typedef) or
857 isinstance(o, Import) or
858 isinstance(o, Using)):
860 if isinstance(o, Import):
862 self.process_imports(o.result, True, result)
867 # Add message ids to each message.
870 o.block.insert(0, Field('u16', '_vl_msg_id'))
877 def dirlist_add(dirs):
880 dirlist = dirlist + dirs
887 def foldup_blocks(block, crc):
889 # Look up CRC in user defined types
890 if b.fieldtype.startswith('vl_api_'):
892 t = global_types[b.fieldtype]
894 crc = crc_block_combine(t.block, crc)
895 return foldup_blocks(t.block, crc)
896 except AttributeError:
903 f.crc = foldup_blocks(f.block,
904 binascii.crc32(f.crc))
911 if sys.version_info < (3, 5,):
912 log.exception('vppapigen requires a supported version of python. '
913 'Please use version 3.5 or greater. '
914 'Using {}'.format(sys.version))
917 cliparser = argparse.ArgumentParser(description='VPP API generator')
918 cliparser.add_argument('--pluginpath', default=""),
919 cliparser.add_argument('--includedir', action='append'),
920 cliparser.add_argument('--input',
921 type=argparse.FileType('r', encoding='UTF-8'),
923 cliparser.add_argument('--output', nargs='?',
924 type=argparse.FileType('w', encoding='UTF-8'),
927 cliparser.add_argument('output_module', nargs='?', default='C')
928 cliparser.add_argument('--debug', action='store_true')
929 cliparser.add_argument('--show-name', nargs=1)
930 args = cliparser.parse_args()
932 dirlist_add(args.includedir)
934 sys.excepthook = exception_handler
938 filename = args.show_name[0]
939 elif args.input != sys.stdin:
940 filename = args.input.name
945 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
947 logging.basicConfig()
949 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
950 parsed_objects = parser.parse_file(args.input, log)
952 # Build a list of objects. Hash of lists.
955 if args.output_module == 'C':
956 s = parser.process(parsed_objects)
958 parser.process_imports(parsed_objects, False, result)
959 s = parser.process(result)
962 s['Define'] = add_msg_id(s['Define'])
965 foldup_crcs(s['Define'])
971 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
972 for t in s['Define']:
973 pp.pprint([t.name, t.flags, t.block])
975 pp.pprint([t.name, t.block])
978 # Generate representation
980 from importlib.machinery import SourceFileLoader
984 if not args.pluginpath:
986 cand.append(os.path.dirname(os.path.realpath(__file__)))
987 cand.append(os.path.dirname(os.path.realpath(__file__)) +
991 if os.path.isfile('{}vppapigen_{}.py'
992 .format(c, args.output_module.lower())):
996 pluginpath = args.pluginpath + '/'
998 log.exception('Output plugin not found')
1000 module_path = '{}vppapigen_{}.py'.format(pluginpath,
1001 args.output_module.lower())
1004 plugin = SourceFileLoader(args.output_module,
1005 module_path).load_module()
1006 except Exception as err:
1007 log.exception('Error importing output plugin: {}, {}'
1008 .format(module_path, err))
1011 result = plugin.run(filename, s)
1013 print(result, file=args.output)
1015 log.exception('Running plugin failed: {} {}'
1016 .format(filename, result))
1021 if __name__ == '__main__':