4 import ply.yacc as yacc
12 log = logging.getLogger('vppapigen')
14 # Ensure we don't leave temporary files around
15 sys.dont_write_bytecode = True
21 # Global dictionary of new types (including enums)
25 def global_type_add(name, obj):
26 '''Add new type to the dictionary of types '''
27 type_name = 'vl_api_' + name + '_t'
28 global_types[type_name] = obj
31 # All your trace are belong to us!
32 def exception_handler(exception_type, exception, traceback):
33 print("%s: %s" % (exception_type.__name__, exception))
39 class VPPAPILexer(object):
40 def __init__(self, filename):
41 self.filename = filename
53 'typeonly': 'TYPEONLY',
54 'manual_print': 'MANUAL_PRINT',
55 'manual_endian': 'MANUAL_ENDIAN',
56 'dont_trace': 'DONT_TRACE',
57 'autoreply': 'AUTOREPLY',
76 tokens = ['STRING_LITERAL',
77 'ID', 'NUM'] + list(reserved.values())
79 t_ignore_LINE_COMMENT = '//.*'
82 r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
83 base = 16 if t.value.startswith('0x') else 10
85 t.value = float(t.value)
87 t.value = int(t.value, base)
91 r'[a-zA-Z_][a-zA-Z_0-9]*'
92 # Check for reserved words
93 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
97 def t_STRING_LITERAL(self, t):
98 r'\"([^\\\n]|(\\.))*?\"'
99 t.value = str(t.value).replace("\"", "")
102 # C or C++ comment (ignore)
103 def t_comment(self, t):
104 r'(/\*(.|\n)*?\*/)|(//.*)'
105 t.lexer.lineno += t.value.count('\n')
107 # Error handling rule
108 def t_error(self, t):
109 raise ParseError("Illegal character '{}' ({})"
110 "in {}: line {}".format(t.value[0],
111 hex(ord(t.value[0])),
116 # Define a rule so we can track line numbers
117 def t_newline(self, t):
119 t.lexer.lineno += len(t.value)
121 literals = ":{}[];=.,"
123 # A string containing ignored characters (spaces and tabs)
127 def crc_block_combine(block, crc):
128 s = str(block).encode()
129 return binascii.crc32(s, crc) & 0xffffffff
133 def __init__(self, caller, reply, events=None, stream=False):
137 self.events = [] if events is None else events
141 def __init__(self, name, flags, block):
145 self.crc = str(block).encode()
146 self.manual_print = False
147 self.manual_endian = False
149 if f == 'manual_print':
150 self.manual_print = True
151 elif f == 'manual_endian':
152 self.manual_endian = True
153 global_type_add(name, self)
157 for i, b in enumerate(block):
158 if isinstance(b, Array):
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':
168 if i + 1 < len(block):
170 'VLA field "{}" must be the last '
171 'field in message "{}"'
172 .format(b.fieldname, name))
175 return self.name + str(self.flags) + str(self.block)
179 def __init__(self, name, alias):
183 if isinstance(alias, Array):
184 a = {'type': alias.fieldtype,
185 'length': alias.length}
187 a = {'type': alias.fieldtype}
189 self.crc = str(alias).encode()
190 global_type_add(name, self)
193 return self.name + str(self.alias)
197 def __init__(self, name, block):
199 self.manual_print = False
200 self.manual_endian = False
203 self.crc = str(block).encode()
204 global_type_add(name, self)
207 return str(self.block)
211 def __init__(self, name, flags, block):
215 self.crc = str(block).encode()
216 self.dont_trace = False
217 self.manual_print = False
218 self.manual_endian = False
219 self.autoreply = False
220 self.singular = False
222 if f == 'dont_trace':
223 self.dont_trace = True
224 elif f == 'manual_print':
225 self.manual_print = True
226 elif f == 'manual_endian':
227 self.manual_endian = True
228 elif f == 'autoreply':
229 self.autoreply = True
231 for i, b in enumerate(block):
232 if isinstance(b, Option):
233 if b[1] == 'singular' and b[2] == 'true':
237 if isinstance(b, Array) and b.vla and i + 1 < len(block):
239 'VLA field "{}" must be the last field in message "{}"'
240 .format(b.fieldname, name))
241 elif b.fieldtype.startswith('vl_api_'):
242 if (global_types[b.fieldtype].vla and i + 1 < len(block)):
244 'VLA field "{}" must be the last '
245 'field in message "{}"'
246 .format(b.fieldname, name))
247 elif b.fieldtype == 'string' and b.length == 0:
248 if i + 1 < len(block):
250 'VLA field "{}" must be the last '
251 'field in message "{}"'
252 .format(b.fieldname, name))
255 return self.name + str(self.flags) + str(self.block)
259 def __init__(self, name, block, enumtype='u32'):
261 self.enumtype = enumtype
265 for i, b in enumerate(block):
270 block[i] = [b, count]
273 self.crc = str(block).encode()
274 global_type_add(name, self)
277 return self.name + str(self.block)
281 def __init__(self, filename):
282 self.filename = filename
285 parser = VPPAPI(filename=filename)
286 dirlist = dirlist_get()
289 f = os.path.join(dir, filename)
290 if os.path.exists(f):
293 with open(f, encoding='utf-8') as fd:
294 self.result = parser.parse_file(fd, None)
301 def __init__(self, option):
303 self.crc = str(option).encode()
306 return str(self.option)
308 def __getitem__(self, index):
309 return self.option[index]
313 def __init__(self, fieldtype, name, length, modern_vla=False):
315 self.fieldtype = fieldtype
316 self.fieldname = name
317 self.modern_vla = modern_vla
318 if type(length) is str:
319 self.lengthfield = length
324 self.lengthfield = None
328 return str([self.fieldtype, self.fieldname, self.length,
333 def __init__(self, fieldtype, name, limit=None):
335 self.fieldtype = fieldtype
337 if self.fieldtype == 'string':
338 raise ValueError("The string type {!r} is an "
339 "array type ".format(name))
341 if name in keyword.kwlist:
342 raise ValueError("Fieldname {!r} is a python keyword and is not "
343 "accessible via the python API. ".format(name))
344 self.fieldname = name
348 return str([self.fieldtype, self.fieldname])
352 """ Coordinates of a syntactic element. Consists of:
355 - (optional) column number, for the Lexer
357 __slots__ = ('file', 'line', 'column', '__weakref__')
359 def __init__(self, file, line, column=None):
365 str = "%s:%s" % (self.file, self.line)
367 str += ":%s" % self.column
371 class ParseError(Exception):
378 class VPPAPIParser(object):
379 tokens = VPPAPILexer.tokens
381 def __init__(self, filename, logger):
382 self.filename = filename
386 def _parse_error(self, msg, coord):
387 raise ParseError("%s: %s" % (coord, msg))
389 def _parse_warning(self, msg, coord):
391 self.logger.warning("%s: %s" % (coord, msg))
393 def _coord(self, lineno, column=None):
396 line=lineno, column=column)
398 def _token_coord(self, p, token_idx):
399 """ Returns the coordinates for the YaccProduction object 'p' indexed
400 with 'token_idx'. The coordinate includes the 'lineno' and
401 'column'. Both follow the lex semantic, starting from 1.
403 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
406 column = (p.lexpos(token_idx) - (last_cr))
407 return self._coord(p.lineno(token_idx), column)
409 def p_slist(self, p):
427 def p_import(self, p):
428 '''import : IMPORT STRING_LITERAL ';' '''
431 def p_service(self, p):
432 '''service : SERVICE '{' service_statements '}' ';' '''
435 def p_service_statements(self, p):
436 '''service_statements : service_statement
437 | service_statements service_statement'''
443 def p_service_statement(self, p):
444 '''service_statement : RPC ID RETURNS NULL ';'
445 | RPC ID RETURNS ID ';'
446 | RPC ID RETURNS STREAM ID ';'
447 | RPC ID RETURNS ID EVENTS event_list ';' '''
449 # Verify that caller and reply differ
451 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
452 self._token_coord(p, 1))
454 p[0] = Service(p[2], p[4], p[6])
456 p[0] = Service(p[2], p[5], stream=True)
458 p[0] = Service(p[2], p[4])
460 def p_event_list(self, p):
461 '''event_list : events
462 | event_list events '''
468 def p_event(self, p):
474 '''enum : ENUM ID '{' enum_statements '}' ';' '''
475 p[0] = Enum(p[2], p[4])
477 def p_enum_type(self, p):
478 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
480 p[0] = Enum(p[2], p[6], enumtype=p[4])
482 p[0] = Enum(p[2], p[4])
484 def p_enum_size(self, p):
490 def p_define(self, p):
491 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
493 p[0] = Define(p[2], [], p[4])
495 def p_define_flist(self, p):
496 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
498 if 'typeonly' in p[1]:
499 self._parse_error('legacy typedef. use typedef: {} {}[{}];'
500 .format(p[1], p[2], p[4]),
501 self._token_coord(p, 1))
503 p[0] = Define(p[3], p[1], p[5])
505 def p_flist(self, p):
514 '''flag : MANUAL_PRINT
523 def p_typedef(self, p):
524 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
525 p[0] = Typedef(p[2], [], p[4])
527 def p_typedef_alias(self, p):
528 '''typedef : TYPEDEF declaration '''
529 p[0] = Using(p[2].fieldname, p[2])
531 def p_block_statements_opt(self, p):
532 '''block_statements_opt : block_statements '''
535 def p_block_statements(self, p):
536 '''block_statements : block_statement
537 | block_statements block_statement'''
543 def p_block_statement(self, p):
544 '''block_statement : declaration
548 def p_enum_statements(self, p):
549 '''enum_statements : enum_statement
550 | enum_statements enum_statement'''
556 def p_enum_statement(self, p):
557 '''enum_statement : ID '=' NUM ','
564 def p_field_options(self, p):
565 '''field_options : field_option
566 | field_options field_option'''
570 p[0] = {**p[1], **p[2]}
572 def p_field_option(self, p):
574 | ID '=' assignee ','
583 def p_declaration(self, p):
584 '''declaration : type_specifier ID ';'
585 | type_specifier ID '[' field_options ']' ';' '''
587 p[0] = Field(p[1], p[2], p[4])
589 p[0] = Field(p[1], p[2])
591 self._parse_error('ERROR')
592 self.fields.append(p[2])
594 def p_declaration_array_vla(self, p):
595 '''declaration : type_specifier ID '[' ']' ';' '''
596 p[0] = Array(p[1], p[2], 0, modern_vla=True)
598 def p_declaration_array(self, p):
599 '''declaration : type_specifier ID '[' NUM ']' ';'
600 | type_specifier ID '[' ID ']' ';' '''
603 return self._parse_error(
604 'array: %s' % p.value,
605 self._coord(lineno=p.lineno))
607 # Make this error later
608 if type(p[4]) is int and p[4] == 0:
609 # XXX: Line number is wrong
610 self._parse_warning('Old Style VLA: {} {}[{}];'
611 .format(p[1], p[2], p[4]),
612 self._token_coord(p, 1))
614 if type(p[4]) is str and p[4] not in self.fields:
615 # Verify that length field exists
616 self._parse_error('Missing length field: {} {}[{}];'
617 .format(p[1], p[2], p[4]),
618 self._token_coord(p, 1))
619 p[0] = Array(p[1], p[2], p[4])
621 def p_option(self, p):
622 '''option : OPTION ID '=' assignee ';' '''
623 p[0] = Option([p[1], p[2], p[4]])
625 def p_assignee(self, p):
632 def p_type_specifier(self, p):
633 '''type_specifier : U8
646 # Do a second pass later to verify that user defined types are defined
647 def p_typedef_specifier(self, p):
648 '''type_specifier : ID '''
649 if p[1] not in global_types:
650 self._parse_error('Undefined type: {}'.format(p[1]),
651 self._token_coord(p, 1))
654 def p_union(self, p):
655 '''union : UNION ID '{' block_statements_opt '}' ';' '''
656 p[0] = Union(p[2], p[4])
658 # Error rule for syntax errors
659 def p_error(self, p):
662 'before: %s' % p.value,
663 self._coord(lineno=p.lineno))
665 self._parse_error('At end of input', self.filename)
668 class VPPAPI(object):
670 def __init__(self, debug=False, filename='', logger=None):
671 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
672 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
673 write_tables=False, debug=debug)
676 def parse_string(self, code, debug=0, lineno=1):
677 self.lexer.lineno = lineno
678 return self.parser.parse(code, lexer=self.lexer, debug=debug)
680 def parse_file(self, fd, debug=0):
682 return self.parse_string(data, debug=debug)
684 def autoreply_block(self, name):
685 block = [Field('u32', 'context'),
686 Field('i32', 'retval')]
687 return Define(name + '_reply', [], block)
689 def process(self, objs):
699 tname = o.__class__.__name__
701 crc = binascii.crc32(o.crc, crc)
702 except AttributeError:
704 if isinstance(o, Define):
707 s[tname].append(self.autoreply_block(o.name))
708 elif isinstance(o, Option):
709 s[tname][o[1]] = o[2]
710 elif type(o) is list:
712 if isinstance(o2, Service):
713 s['Service'].append(o2)
714 elif (isinstance(o, Enum) or
715 isinstance(o, Typedef) or
716 isinstance(o, Union)):
718 elif isinstance(o, Using):
719 s['Alias'][o.name] = o.alias
722 raise ValueError('Unknown class type: {} {}'
726 msgs = {d.name: d for d in s['Define']}
727 svcs = {s.caller: s for s in s['Service']}
728 replies = {s.reply: s for s in s['Service']}
734 if service not in msgs:
736 'Service definition refers to unknown message'
737 ' definition: {}'.format(service))
738 if svcs[service].reply != 'null' and \
739 svcs[service].reply not in msgs:
740 raise ValueError('Service definition refers to unknown message'
741 ' definition in reply: {}'
742 .format(svcs[service].reply))
743 if service in replies:
744 raise ValueError('Service definition refers to message'
745 ' marked as reply: {}'.format(service))
746 for event in svcs[service].events:
747 if event not in msgs:
748 raise ValueError('Service definition refers to unknown '
749 'event: {} in message: {}'
750 .format(event, service))
751 seen_services[event] = True
753 # Create services implicitly
755 if d in seen_services:
757 if msgs[d].singular is True:
759 if d.endswith('_reply'):
762 if d[:-6] not in msgs:
763 raise ValueError('{} missing calling message'
766 if d.endswith('_dump'):
769 if d[:-5]+'_details' in msgs:
770 s['Service'].append(Service(d, d[:-5]+'_details',
773 raise ValueError('{} missing details message'
777 if d.endswith('_details'):
778 if d[:-8]+'_dump' not in msgs:
779 raise ValueError('{} missing dump message'
785 if d+'_reply' in msgs:
786 s['Service'].append(Service(d, d+'_reply'))
789 '{} missing reply message ({}) or service definition'
790 .format(d, d+'_reply'))
794 def process_imports(self, objs, in_import, result):
797 # Only allow the following object types from imported file
798 if in_import and not (isinstance(o, Enum) or
799 isinstance(o, Union) or
800 isinstance(o, Typedef) or
801 isinstance(o, Import) or
802 isinstance(o, Using)):
804 if isinstance(o, Import):
805 self.process_imports(o.result, True, result)
810 # Add message ids to each message.
813 o.block.insert(0, Field('u16', '_vl_msg_id'))
820 def dirlist_add(dirs):
823 dirlist = dirlist + dirs
830 def foldup_blocks(block, crc):
832 # Look up CRC in user defined types
833 if b.fieldtype.startswith('vl_api_'):
835 t = global_types[b.fieldtype]
837 crc = crc_block_combine(t.block, crc)
838 return foldup_blocks(t.block, crc)
839 except AttributeError:
846 f.crc = foldup_blocks(f.block,
847 binascii.crc32(f.crc))
854 if sys.version_info < (3, 5,):
855 log.exception('vppapigen requires a supported version of python. '
856 'Please use version 3.5 or greater. '
857 'Using {}'.format(sys.version))
860 cliparser = argparse.ArgumentParser(description='VPP API generator')
861 cliparser.add_argument('--pluginpath', default=""),
862 cliparser.add_argument('--includedir', action='append'),
863 cliparser.add_argument('--input',
864 type=argparse.FileType('r', encoding='UTF-8'),
866 cliparser.add_argument('--output', nargs='?',
867 type=argparse.FileType('w', encoding='UTF-8'),
870 cliparser.add_argument('output_module', nargs='?', default='C')
871 cliparser.add_argument('--debug', action='store_true')
872 cliparser.add_argument('--show-name', nargs=1)
873 args = cliparser.parse_args()
875 dirlist_add(args.includedir)
877 sys.excepthook = exception_handler
881 filename = args.show_name[0]
882 elif args.input != sys.stdin:
883 filename = args.input.name
888 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
890 logging.basicConfig()
892 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
893 parsed_objects = parser.parse_file(args.input, log)
895 # Build a list of objects. Hash of lists.
897 parser.process_imports(parsed_objects, False, result)
898 s = parser.process(result)
901 s['Define'] = add_msg_id(s['Define'])
904 foldup_crcs(s['Define'])
910 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
911 for t in s['Define']:
912 pp.pprint([t.name, t.flags, t.block])
914 pp.pprint([t.name, t.block])
917 # Generate representation
919 from importlib.machinery import SourceFileLoader
923 if not args.pluginpath:
925 cand.append(os.path.dirname(os.path.realpath(__file__)))
926 cand.append(os.path.dirname(os.path.realpath(__file__)) +
930 if os.path.isfile('{}vppapigen_{}.py'
931 .format(c, args.output_module.lower())):
935 pluginpath = args.pluginpath + '/'
937 log.exception('Output plugin not found')
939 module_path = '{}vppapigen_{}.py'.format(pluginpath,
940 args.output_module.lower())
943 plugin = SourceFileLoader(args.output_module,
944 module_path).load_module()
945 except Exception as err:
946 log.exception('Error importing output plugin: {}, {}'
947 .format(module_path, err))
950 result = plugin.run(filename, s)
952 print(result, file=args.output)
954 log.exception('Running plugin failed: {} {}'
955 .format(filename, result))
960 if __name__ == '__main__':