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 if type_name in global_types:
27 raise KeyError('Type is already defined: {}'.format(name))
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+'
83 base = 16 if t.value.startswith('0x') else 10
84 t.value = int(t.value, base)
88 r'[a-zA-Z_][a-zA-Z_0-9]*'
89 # Check for reserved words
90 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
94 def t_STRING_LITERAL(self, t):
95 r'\"([^\\\n]|(\\.))*?\"'
96 t.value = str(t.value).replace("\"", "")
99 # C or C++ comment (ignore)
100 def t_comment(self, t):
101 r'(/\*(.|\n)*?\*/)|(//.*)'
102 t.lexer.lineno += t.value.count('\n')
104 # Error handling rule
105 def t_error(self, t):
106 raise ParseError("Illegal character '{}' ({})"
107 "in {}: line {}".format(t.value[0],
108 hex(ord(t.value[0])),
113 # Define a rule so we can track line numbers
114 def t_newline(self, t):
116 t.lexer.lineno += len(t.value)
118 literals = ":{}[];=.,"
120 # A string containing ignored characters (spaces and tabs)
124 def crc_block_combine(block, crc):
125 s = str(block).encode()
126 return binascii.crc32(s, crc) & 0xffffffff
129 def __init__(self, caller, reply, events=None, stream=False):
133 self.events = [] if events is None else events
137 def __init__(self, name, flags, block):
141 self.crc = str(block).encode()
142 self.manual_print = False
143 self.manual_endian = False
145 if f == 'manual_print':
146 self.manual_print = True
147 elif f == 'manual_endian':
148 self.manual_endian = True
149 global_type_add(name, self)
152 return self.name + str(self.flags) + str(self.block)
156 def __init__(self, name, alias):
159 if isinstance(alias, Array):
160 a = { 'type': alias.fieldtype, # noqa: E201
161 'length': alias.length } # noqa: E202
163 a = { 'type': alias.fieldtype } # noqa: E201,E202
165 self.crc = str(alias).encode()
166 global_type_add(name, self)
169 return self.name + str(self.alias)
173 def __init__(self, name, block):
175 self.manual_print = False
176 self.manual_endian = False
179 self.crc = str(block).encode()
180 global_type_add(name, self)
183 return str(self.block)
187 def __init__(self, name, flags, block):
191 self.crc = str(block).encode()
192 self.dont_trace = False
193 self.manual_print = False
194 self.manual_endian = False
195 self.autoreply = False
196 self.singular = False
198 if f == 'dont_trace':
199 self.dont_trace = True
200 elif f == 'manual_print':
201 self.manual_print = True
202 elif f == 'manual_endian':
203 self.manual_endian = True
204 elif f == 'autoreply':
205 self.autoreply = True
208 if isinstance(b, Option):
209 if b[1] == 'singular' and b[2] == 'true':
214 return self.name + str(self.flags) + str(self.block)
218 def __init__(self, name, block, enumtype='u32'):
220 self.enumtype = enumtype
223 for i, b in enumerate(block):
228 block[i] = [b, count]
231 self.crc = str(block).encode()
232 global_type_add(name, self)
235 return self.name + str(self.block)
239 def __init__(self, filename):
240 self.filename = filename
243 parser = VPPAPI(filename=filename)
244 dirlist = dirlist_get()
247 f = os.path.join(dir, filename)
248 if os.path.exists(f):
250 if sys.version[0] == '2':
252 self.result = parser.parse_file(fd, None)
254 with open(f, encoding='utf-8') as fd:
255 self.result = parser.parse_file(fd, None)
262 def __init__(self, option):
264 self.crc = str(option).encode()
267 return str(self.option)
269 def __getitem__(self, index):
270 return self.option[index]
274 def __init__(self, fieldtype, name, length):
276 self.fieldtype = fieldtype
277 self.fieldname = name
278 if type(length) is str:
279 self.lengthfield = length
283 self.lengthfield = None
286 return str([self.fieldtype, self.fieldname, self.length,
291 def __init__(self, fieldtype, name, limit=None):
293 self.fieldtype = fieldtype
294 self.fieldname = name
298 return str([self.fieldtype, self.fieldname])
302 """ Coordinates of a syntactic element. Consists of:
305 - (optional) column number, for the Lexer
307 __slots__ = ('file', 'line', 'column', '__weakref__')
309 def __init__(self, file, line, column=None):
315 str = "%s:%s" % (self.file, self.line)
317 str += ":%s" % self.column
321 class ParseError(Exception):
328 class VPPAPIParser(object):
329 tokens = VPPAPILexer.tokens
331 def __init__(self, filename, logger):
332 self.filename = filename
336 def _parse_error(self, msg, coord):
337 raise ParseError("%s: %s" % (coord, msg))
339 def _parse_warning(self, msg, coord):
341 self.logger.warning("%s: %s" % (coord, msg))
343 def _coord(self, lineno, column=None):
346 line=lineno, column=column)
348 def _token_coord(self, p, token_idx):
349 """ Returns the coordinates for the YaccProduction object 'p' indexed
350 with 'token_idx'. The coordinate includes the 'lineno' and
351 'column'. Both follow the lex semantic, starting from 1.
353 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
356 column = (p.lexpos(token_idx) - (last_cr))
357 return self._coord(p.lineno(token_idx), column)
359 def p_slist(self, p):
377 def p_import(self, p):
378 '''import : IMPORT STRING_LITERAL ';' '''
381 def p_service(self, p):
382 '''service : SERVICE '{' service_statements '}' ';' '''
385 def p_service_statements(self, p):
386 '''service_statements : service_statement
387 | service_statements service_statement'''
393 def p_service_statement(self, p):
394 '''service_statement : RPC ID RETURNS NULL ';'
395 | RPC ID RETURNS ID ';'
396 | RPC ID RETURNS STREAM ID ';'
397 | RPC ID RETURNS ID EVENTS event_list ';' '''
399 # Verify that caller and reply differ
401 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
402 self._token_coord(p, 1))
404 p[0] = Service(p[2], p[4], p[6])
406 p[0] = Service(p[2], p[5], stream=True)
408 p[0] = Service(p[2], p[4])
410 def p_event_list(self, p):
411 '''event_list : events
412 | event_list events '''
418 def p_event(self, p):
424 '''enum : ENUM ID '{' enum_statements '}' ';' '''
425 p[0] = Enum(p[2], p[4])
427 def p_enum_type(self, p):
428 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
430 p[0] = Enum(p[2], p[6], enumtype=p[4])
432 p[0] = Enum(p[2], p[4])
434 def p_enum_size(self, p):
440 def p_define(self, p):
441 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
443 p[0] = Define(p[2], [], p[4])
445 def p_define_flist(self, p):
446 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
448 if 'typeonly' in p[1]:
449 p[0] = Typedef(p[3], p[1], p[5])
451 p[0] = Define(p[3], p[1], p[5])
453 def p_flist(self, p):
462 '''flag : MANUAL_PRINT
471 def p_typedef(self, p):
472 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
473 p[0] = Typedef(p[2], [], p[4])
475 def p_typedef_alias(self, p):
476 '''typedef : TYPEDEF declaration '''
477 p[0] = Using(p[2].fieldname, p[2])
479 def p_block_statements_opt(self, p):
480 '''block_statements_opt : block_statements '''
483 def p_block_statements(self, p):
484 '''block_statements : block_statement
485 | block_statements block_statement'''
491 def p_block_statement(self, p):
492 '''block_statement : declaration
496 def p_enum_statements(self, p):
497 '''enum_statements : enum_statement
498 | enum_statements enum_statement'''
504 def p_enum_statement(self, p):
505 '''enum_statement : ID '=' NUM ','
512 def p_field_options(self, p):
513 '''field_options : field_option
514 | field_options field_option'''
518 p[0] = { **p[1], **p[2] }
520 def p_field_option(self, p):
521 '''field_option : ID '=' assignee ','
524 p[0] = { p[1]: p[3] }
526 def p_declaration(self, p):
527 '''declaration : type_specifier ID ';'
528 | type_specifier ID '[' field_options ']' ';' '''
530 p[0] = Field(p[1], p[2], p[4])
532 p[0] = Field(p[1], p[2])
534 self._parse_error('ERROR')
535 self.fields.append(p[2])
537 def p_declaration_array(self, p):
538 '''declaration : type_specifier ID '[' NUM ']' ';'
539 | type_specifier ID '[' ID ']' ';' '''
541 return self._parse_error(
542 'array: %s' % p.value,
543 self._coord(lineno=p.lineno))
545 # Make this error later
546 if type(p[4]) is int and p[4] == 0:
547 # XXX: Line number is wrong
548 self._parse_warning('Old Style VLA: {} {}[{}];'
549 .format(p[1], p[2], p[4]),
550 self._token_coord(p, 1))
552 if type(p[4]) is str and p[4] not in self.fields:
553 # Verify that length field exists
554 self._parse_error('Missing length field: {} {}[{}];'
555 .format(p[1], p[2], p[4]),
556 self._token_coord(p, 1))
557 p[0] = Array(p[1], p[2], p[4])
559 def p_option(self, p):
560 '''option : OPTION ID '=' assignee ';' '''
561 p[0] = Option([p[1], p[2], p[4]])
563 def p_assignee(self, p):
570 def p_type_specifier(self, p):
571 '''type_specifier : U8
584 # Do a second pass later to verify that user defined types are defined
585 def p_typedef_specifier(self, p):
586 '''type_specifier : ID '''
587 if p[1] not in global_types:
588 self._parse_error('Undefined type: {}'.format(p[1]),
589 self._token_coord(p, 1))
592 def p_union(self, p):
593 '''union : UNION ID '{' block_statements_opt '}' ';' '''
594 p[0] = Union(p[2], p[4])
596 # Error rule for syntax errors
597 def p_error(self, p):
600 'before: %s' % p.value,
601 self._coord(lineno=p.lineno))
603 self._parse_error('At end of input', self.filename)
606 class VPPAPI(object):
608 def __init__(self, debug=False, filename='', logger=None):
609 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
610 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
611 write_tables=False, debug=debug)
614 def parse_string(self, code, debug=0, lineno=1):
615 self.lexer.lineno = lineno
616 return self.parser.parse(code, lexer=self.lexer, debug=debug)
618 def parse_file(self, fd, debug=0):
620 return self.parse_string(data, debug=debug)
622 def autoreply_block(self, name):
623 block = [Field('u32', 'context'),
624 Field('i32', 'retval')]
625 return Define(name + '_reply', [], block)
627 def process(self, objs):
637 tname = o.__class__.__name__
639 crc = binascii.crc32(o.crc, crc)
640 except AttributeError:
642 if isinstance(o, Define):
645 s[tname].append(self.autoreply_block(o.name))
646 elif isinstance(o, Option):
647 s[tname][o[1]] = o[2]
648 elif type(o) is list:
650 if isinstance(o2, Service):
651 s['Service'].append(o2)
652 elif (isinstance(o, Enum) or
653 isinstance(o, Typedef) or
654 isinstance(o, Union)):
656 elif isinstance(o, Using):
657 s['Alias'][o.name] = o.alias
660 raise ValueError('Unknown class type: {} {}'
664 msgs = {d.name: d for d in s['Define']}
665 svcs = {s.caller: s for s in s['Service']}
666 replies = {s.reply: s for s in s['Service']}
672 if service not in msgs:
674 'Service definition refers to unknown message'
675 ' definition: {}'.format(service))
676 if svcs[service].reply != 'null' and \
677 svcs[service].reply not in msgs:
678 raise ValueError('Service definition refers to unknown message'
679 ' definition in reply: {}'
680 .format(svcs[service].reply))
681 if service in replies:
682 raise ValueError('Service definition refers to message'
683 ' marked as reply: {}'.format(service))
684 for event in svcs[service].events:
685 if event not in msgs:
686 raise ValueError('Service definition refers to unknown '
687 'event: {} in message: {}'
688 .format(event, service))
689 seen_services[event] = True
691 # Create services implicitly
693 if d in seen_services:
695 if msgs[d].singular is True:
697 if d.endswith('_reply'):
700 if d[:-6] not in msgs:
701 raise ValueError('{} missing calling message'
704 if d.endswith('_dump'):
707 if d[:-5]+'_details' in msgs:
708 s['Service'].append(Service(d, d[:-5]+'_details',
711 raise ValueError('{} missing details message'
715 if d.endswith('_details'):
716 if d[:-8]+'_dump' not in msgs:
717 raise ValueError('{} missing dump message'
723 if d+'_reply' in msgs:
724 s['Service'].append(Service(d, d+'_reply'))
727 '{} missing reply message ({}) or service definition'
728 .format(d, d+'_reply'))
732 def process_imports(self, objs, in_import, result):
735 # Only allow the following object types from imported file
736 if in_import and not (isinstance(o, Enum) or
737 isinstance(o, Union) or
738 isinstance(o, Typedef) or
739 isinstance(o, Import) or
740 isinstance(o, Using)):
742 if isinstance(o, Import):
743 self.process_imports(o.result, True, result)
748 # Add message ids to each message.
751 o.block.insert(0, Field('u16', '_vl_msg_id'))
758 def dirlist_add(dirs):
761 dirlist = dirlist + dirs
767 def foldup_blocks(block, crc):
769 # Look up CRC in user defined types
770 if b.fieldtype.startswith('vl_api_'):
772 t = global_types[b.fieldtype]
774 crc = crc_block_combine(t.block, crc)
775 return foldup_blocks(t.block, crc)
782 f.crc = foldup_blocks(f.block,
783 binascii.crc32(f.crc))
789 cliparser = argparse.ArgumentParser(description='VPP API generator')
790 cliparser.add_argument('--pluginpath', default=""),
791 cliparser.add_argument('--includedir', action='append'),
792 if sys.version[0] == '2':
793 cliparser.add_argument('--input', type=argparse.FileType('r'),
795 cliparser.add_argument('--output', nargs='?',
796 type=argparse.FileType('w'),
800 cliparser.add_argument('--input',
801 type=argparse.FileType('r', encoding='UTF-8'),
803 cliparser.add_argument('--output', nargs='?',
804 type=argparse.FileType('w', encoding='UTF-8'),
807 cliparser.add_argument('output_module', nargs='?', default='C')
808 cliparser.add_argument('--debug', action='store_true')
809 cliparser.add_argument('--show-name', nargs=1)
810 args = cliparser.parse_args()
812 dirlist_add(args.includedir)
814 sys.excepthook = exception_handler
818 filename = args.show_name[0]
819 elif args.input != sys.stdin:
820 filename = args.input.name
825 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
827 logging.basicConfig()
828 log = logging.getLogger('vppapigen')
830 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
831 parsed_objects = parser.parse_file(args.input, log)
833 # Build a list of objects. Hash of lists.
835 parser.process_imports(parsed_objects, False, result)
836 s = parser.process(result)
839 s['Define'] = add_msg_id(s['Define'])
842 foldup_crcs(s['Define'])
848 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
849 for t in s['Define']:
850 pp.pprint([t.name, t.flags, t.block])
852 pp.pprint([t.name, t.block])
855 # Generate representation
857 from importlib.machinery import SourceFileLoader
861 if not args.pluginpath:
863 cand.append(os.path.dirname(os.path.realpath(__file__)))
864 cand.append(os.path.dirname(os.path.realpath(__file__)) +
868 if os.path.isfile('{}vppapigen_{}.py'
869 .format(c, args.output_module.lower())):
873 pluginpath = args.pluginpath + '/'
875 raise Exception('Output plugin not found')
876 module_path = '{}vppapigen_{}.py'.format(pluginpath,
877 args.output_module.lower())
880 plugin = SourceFileLoader(args.output_module,
881 module_path).load_module()
882 except Exception as err:
883 raise Exception('Error importing output plugin: {}, {}'
884 .format(module_path, err))
886 result = plugin.run(filename, s)
888 print(result, file=args.output)
890 raise Exception('Running plugin failed: {} {}'
891 .format(filename, result))
894 if __name__ == '__main__':