3 from __future__ import print_function
5 import ply.yacc as yacc
12 # Ensure we don't leave temporary files around
13 sys.dont_write_bytecode = True
19 # Global dictionary of new types (including enums)
23 def global_type_add(name, obj):
24 '''Add new type to the dictionary of types '''
25 type_name = 'vl_api_' + name + '_t'
26 global_types[type_name] = obj
29 # All your trace are belong to us!
30 def exception_handler(exception_type, exception, traceback):
31 print("%s: %s" % (exception_type.__name__, exception))
37 class VPPAPILexer(object):
38 def __init__(self, filename):
39 self.filename = filename
51 'typeonly': 'TYPEONLY',
52 'manual_print': 'MANUAL_PRINT',
53 'manual_endian': 'MANUAL_ENDIAN',
54 'dont_trace': 'DONT_TRACE',
55 'autoreply': 'AUTOREPLY',
74 tokens = ['STRING_LITERAL',
75 'ID', 'NUM'] + list(reserved.values())
77 t_ignore_LINE_COMMENT = '//.*'
80 r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
81 base = 16 if t.value.startswith('0x') else 10
83 t.value = float(t.value)
85 t.value = int(t.value, base)
89 r'[a-zA-Z_][a-zA-Z_0-9]*'
90 # Check for reserved words
91 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
95 def t_STRING_LITERAL(self, t):
96 r'\"([^\\\n]|(\\.))*?\"'
97 t.value = str(t.value).replace("\"", "")
100 # C or C++ comment (ignore)
101 def t_comment(self, t):
102 r'(/\*(.|\n)*?\*/)|(//.*)'
103 t.lexer.lineno += t.value.count('\n')
105 # Error handling rule
106 def t_error(self, t):
107 raise ParseError("Illegal character '{}' ({})"
108 "in {}: line {}".format(t.value[0],
109 hex(ord(t.value[0])),
114 # Define a rule so we can track line numbers
115 def t_newline(self, t):
117 t.lexer.lineno += len(t.value)
119 literals = ":{}[];=.,"
121 # A string containing ignored characters (spaces and tabs)
125 def crc_block_combine(block, crc):
126 s = str(block).encode()
127 return binascii.crc32(s, crc) & 0xffffffff
131 def __init__(self, caller, reply, events=None, stream=False):
135 self.events = [] if events is None else events
138 return "Service(caller={!r}, reply={!r}, events={!r}, stream={!r})".\
139 format(self.caller, self.reply, self.events, self.stream)
143 def __init__(self, name, flags, block):
147 self.crc = str(block).encode()
148 self.manual_print = False
149 self.manual_endian = False
151 if f == 'manual_print':
152 self.manual_print = True
153 elif f == 'manual_endian':
154 self.manual_endian = True
155 global_type_add(name, self)
158 return "Typedef(name={!r}, flags={!r}, block={!r})".format(
159 self.name, self.flags, self.block)
163 def __init__(self, name, alias):
166 # save constructor values for repr()
169 if isinstance(alias, Array):
170 a = {'type': alias.fieldtype,
171 'length': alias.length}
173 a = {'type': alias.fieldtype}
175 self.crc = str(alias).encode()
176 global_type_add(name, self)
179 return "Using(name={!r}, alias={!r})".format(self.name, self._alias)
183 def __init__(self, name, block):
185 self.manual_print = False
186 self.manual_endian = False
189 self.crc = str(block).encode()
190 global_type_add(name, self)
193 return "Union(name={!r}, block={!r})".format(self.name, self.block)
197 def __init__(self, name, flags, block):
201 self.crc = str(block).encode()
202 self.dont_trace = False
203 self.manual_print = False
204 self.manual_endian = False
205 self.autoreply = False
206 self.singular = False
208 if f == 'dont_trace':
209 self.dont_trace = True
210 elif f == 'manual_print':
211 self.manual_print = True
212 elif f == 'manual_endian':
213 self.manual_endian = True
214 elif f == 'autoreply':
215 self.autoreply = True
218 if isinstance(b, Option):
219 if b[1] == 'singular' and b[2] == 'true':
224 return "Define(name={!r}, flags={!r}, block={!r})".format(
225 self.name, self.flags, self.block)
229 def __init__(self, name, block, enumtype='u32'):
231 self.enumtype = enumtype
234 for i, b in enumerate(block):
239 block[i] = [b, count]
242 self.crc = str(block).encode()
243 global_type_add(name, self)
246 return "Enum(name={!r}, block={!r}, enumtype={!r})".format(
247 self.name, self.block, self.enumtype)
251 def __init__(self, filename):
252 self.filename = filename
255 parser = VPPAPI(filename=filename)
256 dirlist = dirlist_get()
259 f = os.path.join(dir, filename)
260 if os.path.exists(f):
262 if sys.version[0] == '2':
264 self.result = parser.parse_file(fd, None)
266 with open(f, encoding='utf-8') as fd:
267 self.result = parser.parse_file(fd, None)
270 return "Import(filename={!r})".format(self.filename)
274 def __init__(self, option):
276 self.crc = str(option).encode()
279 return "Option({!r})".format(self.option)
281 def __getitem__(self, index):
282 return self.option[index]
286 def __init__(self, fieldtype, name, length):
288 self.fieldtype = fieldtype
290 # save constructor values for repr()
292 self._length = length
294 self.fieldname = name
295 if type(length) is str:
296 self.lengthfield = length
300 self.lengthfield = None
303 return "Array(fieldtype={!r}, name={!r}, length={!r})".format(
304 self.fieldtype, self._name, self._length)
308 def __init__(self, fieldtype, name, limit=None):
310 self.fieldtype = fieldtype
311 self.fieldname = name
315 return "Field(fieldtype={!r}, name={!r}, limit={!r})".format(
316 self.fieldtype, self.fieldname, self.limit)
320 """ Coordinates of a syntactic element. Consists of:
323 - (optional) column number, for the Lexer
325 __slots__ = ('file', 'line', 'column', '__weakref__')
327 def __init__(self, file, line, column=None):
333 str = "%s:%s" % (self.file, self.line)
335 str += ":%s" % self.column
339 class ParseError(Exception):
346 class VPPAPIParser(object):
347 tokens = VPPAPILexer.tokens
349 def __init__(self, filename, logger):
350 self.filename = filename
354 def _parse_error(self, msg, coord):
355 raise ParseError("%s: %s" % (coord, msg))
357 def _parse_warning(self, msg, coord):
359 self.logger.warning("%s: %s" % (coord, msg))
361 def _coord(self, lineno, column=None):
364 line=lineno, column=column)
366 def _token_coord(self, p, token_idx):
367 """ Returns the coordinates for the YaccProduction object 'p' indexed
368 with 'token_idx'. The coordinate includes the 'lineno' and
369 'column'. Both follow the lex semantic, starting from 1.
371 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
374 column = (p.lexpos(token_idx) - (last_cr))
375 return self._coord(p.lineno(token_idx), column)
377 def p_slist(self, p):
395 def p_import(self, p):
396 '''import : IMPORT STRING_LITERAL ';' '''
399 def p_service(self, p):
400 '''service : SERVICE '{' service_statements '}' ';' '''
403 def p_service_statements(self, p):
404 '''service_statements : service_statement
405 | service_statements service_statement'''
411 def p_service_statement(self, p):
412 '''service_statement : RPC ID RETURNS NULL ';'
413 | RPC ID RETURNS ID ';'
414 | RPC ID RETURNS STREAM ID ';'
415 | RPC ID RETURNS ID EVENTS event_list ';' '''
417 # Verify that caller and reply differ
419 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
420 self._token_coord(p, 1))
422 p[0] = Service(p[2], p[4], p[6])
424 p[0] = Service(p[2], p[5], stream=True)
426 p[0] = Service(p[2], p[4])
428 def p_event_list(self, p):
429 '''event_list : events
430 | event_list events '''
436 def p_event(self, p):
442 '''enum : ENUM ID '{' enum_statements '}' ';' '''
443 p[0] = Enum(p[2], p[4])
445 def p_enum_type(self, p):
446 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
448 p[0] = Enum(p[2], p[6], enumtype=p[4])
450 p[0] = Enum(p[2], p[4])
452 def p_enum_size(self, p):
458 def p_define(self, p):
459 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
461 p[0] = Define(p[2], [], p[4])
463 def p_define_flist(self, p):
464 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
466 if 'typeonly' in p[1]:
467 p[0] = Typedef(p[3], p[1], p[5])
469 p[0] = Define(p[3], p[1], p[5])
471 def p_flist(self, p):
480 '''flag : MANUAL_PRINT
489 def p_typedef(self, p):
490 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
491 p[0] = Typedef(p[2], [], p[4])
493 def p_typedef_alias(self, p):
494 '''typedef : TYPEDEF declaration '''
495 p[0] = Using(p[2].fieldname, p[2])
497 def p_block_statements_opt(self, p):
498 '''block_statements_opt : block_statements '''
501 def p_block_statements(self, p):
502 '''block_statements : block_statement
503 | block_statements block_statement'''
509 def p_block_statement(self, p):
510 '''block_statement : declaration
514 def p_enum_statements(self, p):
515 '''enum_statements : enum_statement
516 | enum_statements enum_statement'''
522 def p_enum_statement(self, p):
523 '''enum_statement : ID '=' NUM ','
530 def p_field_options(self, p):
531 '''field_options : field_option
532 | field_options field_option'''
536 p[0] = {**p[1], **p[2]}
538 def p_field_option(self, p):
539 '''field_option : ID '=' assignee ','
544 def p_declaration(self, p):
545 '''declaration : type_specifier ID ';'
546 | type_specifier ID '[' field_options ']' ';' '''
548 p[0] = Field(p[1], p[2], p[4])
550 p[0] = Field(p[1], p[2])
552 self._parse_error('ERROR')
553 self.fields.append(p[2])
555 def p_declaration_array(self, p):
556 '''declaration : type_specifier ID '[' NUM ']' ';'
557 | type_specifier ID '[' ID ']' ';' '''
559 return self._parse_error(
560 'array: %s' % p.value,
561 self._coord(lineno=p.lineno))
563 # Make this error later
564 if type(p[4]) is int and p[4] == 0:
565 # XXX: Line number is wrong
566 self._parse_warning('Old Style VLA: {} {}[{}];'
567 .format(p[1], p[2], p[4]),
568 self._token_coord(p, 1))
570 if type(p[4]) is str and p[4] not in self.fields:
571 # Verify that length field exists
572 self._parse_error('Missing length field: {} {}[{}];'
573 .format(p[1], p[2], p[4]),
574 self._token_coord(p, 1))
575 p[0] = Array(p[1], p[2], p[4])
577 def p_option(self, p):
578 '''option : OPTION ID '=' assignee ';' '''
579 p[0] = Option([p[1], p[2], p[4]])
581 def p_assignee(self, p):
588 def p_type_specifier(self, p):
589 '''type_specifier : U8
602 # Do a second pass later to verify that user defined types are defined
603 def p_typedef_specifier(self, p):
604 '''type_specifier : ID '''
605 if p[1] not in global_types:
606 self._parse_error('Undefined type: {}'.format(p[1]),
607 self._token_coord(p, 1))
610 def p_union(self, p):
611 '''union : UNION ID '{' block_statements_opt '}' ';' '''
612 p[0] = Union(p[2], p[4])
614 # Error rule for syntax errors
615 def p_error(self, p):
618 'before: %s' % p.value,
619 self._coord(lineno=p.lineno))
621 self._parse_error('At end of input', self.filename)
624 class VPPAPI(object):
626 def __init__(self, debug=False, filename='', logger=None):
627 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
628 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
629 write_tables=False, debug=debug)
632 def parse_string(self, code, debug=0, lineno=1):
633 self.lexer.lineno = lineno
634 return self.parser.parse(code, lexer=self.lexer, debug=debug)
636 def parse_file(self, fd, debug=0):
638 return self.parse_string(data, debug=debug)
640 def autoreply_block(self, name):
641 block = [Field('u32', 'context'),
642 Field('i32', 'retval')]
643 return Define(name + '_reply', [], block)
645 def process(self, objs):
655 tname = o.__class__.__name__
657 crc = binascii.crc32(o.crc, crc)
658 except AttributeError:
660 if isinstance(o, Define):
663 s[tname].append(self.autoreply_block(o.name))
664 elif isinstance(o, Option):
665 s[tname][o[1]] = o[2]
666 elif type(o) is list:
668 if isinstance(o2, Service):
669 s['Service'].append(o2)
670 elif (isinstance(o, Enum) or
671 isinstance(o, Typedef) or
672 isinstance(o, Union)):
674 elif isinstance(o, Using):
675 s['Alias'][o.name] = o.alias
678 raise ValueError('Unknown class type: {} {}'
682 msgs = {d.name: d for d in s['Define']}
683 svcs = {s.caller: s for s in s['Service']}
684 replies = {s.reply: s for s in s['Service']}
690 if service not in msgs:
692 'Service definition refers to unknown message'
693 ' definition: {}'.format(service))
694 if svcs[service].reply != 'null' and \
695 svcs[service].reply not in msgs:
696 raise ValueError('Service definition refers to unknown message'
697 ' definition in reply: {}'
698 .format(svcs[service].reply))
699 if service in replies:
700 raise ValueError('Service definition refers to message'
701 ' marked as reply: {}'.format(service))
702 for event in svcs[service].events:
703 if event not in msgs:
704 raise ValueError('Service definition refers to unknown '
705 'event: {} in message: {}'
706 .format(event, service))
707 seen_services[event] = True
709 # Create services implicitly
711 if d in seen_services:
713 if msgs[d].singular is True:
715 if d.endswith('_reply'):
718 if d[:-6] not in msgs:
719 raise ValueError('{} missing calling message'
722 if d.endswith('_dump'):
725 if d[:-5]+'_details' in msgs:
726 s['Service'].append(Service(d, d[:-5]+'_details',
729 raise ValueError('{} missing details message'
733 if d.endswith('_details'):
734 if d[:-8]+'_dump' not in msgs:
735 raise ValueError('{} missing dump message'
741 if d+'_reply' in msgs:
742 s['Service'].append(Service(d, d+'_reply'))
745 '{} missing reply message ({}) or service definition'
746 .format(d, d+'_reply'))
750 def process_imports(self, objs, in_import, result):
753 # Only allow the following object types from imported file
754 if in_import and not (isinstance(o, Enum) or
755 isinstance(o, Union) or
756 isinstance(o, Typedef) or
757 isinstance(o, Import) or
758 isinstance(o, Using)):
760 if isinstance(o, Import):
761 self.process_imports(o.result, True, result)
766 # Add message ids to each message.
769 o.block.insert(0, Field('u16', '_vl_msg_id'))
776 def dirlist_add(dirs):
779 dirlist = dirlist + dirs
786 def foldup_blocks(block, crc):
788 # Look up CRC in user defined types
789 if b.fieldtype.startswith('vl_api_'):
791 t = global_types[b.fieldtype]
793 crc = crc_block_combine(t.block, crc)
794 return foldup_blocks(t.block, crc)
802 f.crc = foldup_blocks(f.block,
803 binascii.crc32(f.crc))
810 cliparser = argparse.ArgumentParser(description='VPP API generator')
811 cliparser.add_argument('--pluginpath', default=""),
812 cliparser.add_argument('--includedir', action='append'),
813 if sys.version[0] == '2':
814 cliparser.add_argument('--input', type=argparse.FileType('r'),
816 cliparser.add_argument('--output', nargs='?',
817 type=argparse.FileType('w'),
821 cliparser.add_argument('--input',
822 type=argparse.FileType('r', encoding='UTF-8'),
824 cliparser.add_argument('--output', nargs='?',
825 type=argparse.FileType('w', encoding='UTF-8'),
828 cliparser.add_argument('output_module', nargs='?', default='C')
829 cliparser.add_argument('--debug', action='store_true')
830 cliparser.add_argument('--show-name', nargs=1)
831 args = cliparser.parse_args()
833 dirlist_add(args.includedir)
835 sys.excepthook = exception_handler
839 filename = args.show_name[0]
840 elif args.input != sys.stdin:
841 filename = args.input.name
846 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
848 logging.basicConfig()
849 log = logging.getLogger('vppapigen')
851 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
852 parsed_objects = parser.parse_file(args.input, log)
854 # Build a list of objects. Hash of lists.
856 parser.process_imports(parsed_objects, False, result)
857 s = parser.process(result)
860 s['Define'] = add_msg_id(s['Define'])
863 foldup_crcs(s['Define'])
869 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
870 for t in s['Define']:
871 pp.pprint([t.name, t.flags, t.block])
873 pp.pprint([t.name, t.block])
876 # Generate representation
878 from importlib.machinery import SourceFileLoader
882 if not args.pluginpath:
884 cand.append(os.path.dirname(os.path.realpath(__file__)))
885 cand.append(os.path.dirname(os.path.realpath(__file__)) +
889 if os.path.isfile('{}vppapigen_{}.py'
890 .format(c, args.output_module.lower())):
894 pluginpath = args.pluginpath + '/'
896 raise Exception('Output plugin not found')
897 module_path = '{}vppapigen_{}.py'.format(pluginpath,
898 args.output_module.lower())
901 plugin = SourceFileLoader(args.output_module,
902 module_path).load_module()
903 except Exception as err:
904 raise Exception('Error importing output plugin: {}, {}'
905 .format(module_path, err))
907 result = plugin.run(filename, s)
909 print(result, file=args.output)
911 raise Exception('Running plugin failed: {} {}'
912 .format(filename, result))
915 if __name__ == '__main__':