3 from __future__ import print_function
5 import ply.yacc as yacc
13 # Ensure we don't leave temporary files around
14 sys.dont_write_bytecode = True
20 # Global dictionary of new types (including enums)
24 def global_type_add(name, obj):
25 '''Add new type to the dictionary of types '''
26 type_name = 'vl_api_' + name + '_t'
27 global_types[type_name] = obj
30 # All your trace are belong to us!
31 def exception_handler(exception_type, exception, traceback):
32 print("%s: %s" % (exception_type.__name__, exception))
38 class VPPAPILexer(object):
39 def __init__(self, filename):
40 self.filename = filename
52 'typeonly': 'TYPEONLY',
53 'manual_print': 'MANUAL_PRINT',
54 'manual_endian': 'MANUAL_ENDIAN',
55 'dont_trace': 'DONT_TRACE',
56 'autoreply': 'AUTOREPLY',
75 tokens = ['STRING_LITERAL',
76 'ID', 'NUM'] + list(reserved.values())
78 t_ignore_LINE_COMMENT = '//.*'
81 r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
82 base = 16 if t.value.startswith('0x') else 10
84 t.value = float(t.value)
86 t.value = int(t.value, base)
90 r'[a-zA-Z_][a-zA-Z_0-9]*'
91 # Check for reserved words
92 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
96 def t_STRING_LITERAL(self, t):
97 r'\"([^\\\n]|(\\.))*?\"'
98 t.value = str(t.value).replace("\"", "")
101 # C or C++ comment (ignore)
102 def t_comment(self, t):
103 r'(/\*(.|\n)*?\*/)|(//.*)'
104 t.lexer.lineno += t.value.count('\n')
106 # Error handling rule
107 def t_error(self, t):
108 raise ParseError("Illegal character '{}' ({})"
109 "in {}: line {}".format(t.value[0],
110 hex(ord(t.value[0])),
115 # Define a rule so we can track line numbers
116 def t_newline(self, t):
118 t.lexer.lineno += len(t.value)
120 literals = ":{}[];=.,"
122 # A string containing ignored characters (spaces and tabs)
126 def crc_block_combine(block, crc):
127 s = str(block).encode()
128 return binascii.crc32(s, crc) & 0xffffffff
132 def __init__(self, caller, reply, events=None, stream=False):
136 self.events = [] if events is None else events
140 def __init__(self, name, flags, block):
144 self.crc = str(block).encode()
145 self.manual_print = False
146 self.manual_endian = False
148 if f == 'manual_print':
149 self.manual_print = True
150 elif f == 'manual_endian':
151 self.manual_endian = True
152 global_type_add(name, self)
155 return self.name + str(self.flags) + str(self.block)
159 def __init__(self, name, alias):
162 if isinstance(alias, Array):
163 a = { 'type': alias.fieldtype, # noqa: E201
164 'length': alias.length } # noqa: E202
166 a = { 'type': alias.fieldtype } # noqa: E201,E202
168 self.crc = str(alias).encode()
169 global_type_add(name, self)
172 return self.name + str(self.alias)
176 def __init__(self, name, block):
178 self.manual_print = False
179 self.manual_endian = False
182 self.crc = str(block).encode()
183 global_type_add(name, self)
186 return str(self.block)
190 def __init__(self, name, flags, block):
194 self.crc = str(block).encode()
195 self.dont_trace = False
196 self.manual_print = False
197 self.manual_endian = False
198 self.autoreply = False
199 self.singular = False
201 if f == 'dont_trace':
202 self.dont_trace = True
203 elif f == 'manual_print':
204 self.manual_print = True
205 elif f == 'manual_endian':
206 self.manual_endian = True
207 elif f == 'autoreply':
208 self.autoreply = True
211 if isinstance(b, Option):
212 if b[1] == 'singular' and b[2] == 'true':
217 return self.name + str(self.flags) + str(self.block)
221 def __init__(self, name, block, enumtype='u32'):
223 self.enumtype = enumtype
226 for i, b in enumerate(block):
231 block[i] = [b, count]
234 self.crc = str(block).encode()
235 global_type_add(name, self)
238 return self.name + str(self.block)
242 def __init__(self, filename):
243 self.filename = filename
246 parser = VPPAPI(filename=filename)
247 dirlist = dirlist_get()
250 f = os.path.join(dir, filename)
251 if os.path.exists(f):
253 if sys.version[0] == '2':
255 self.result = parser.parse_file(fd, None)
257 with open(f, encoding='utf-8') as fd:
258 self.result = parser.parse_file(fd, None)
265 def __init__(self, option):
267 self.crc = str(option).encode()
270 return str(self.option)
272 def __getitem__(self, index):
273 return self.option[index]
277 def __init__(self, fieldtype, name, length):
279 self.fieldtype = fieldtype
280 self.fieldname = name
281 if type(length) is str:
282 self.lengthfield = length
286 self.lengthfield = None
289 return str([self.fieldtype, self.fieldname, self.length,
294 def __init__(self, fieldtype, name, limit=None):
296 self.fieldtype = fieldtype
297 if name in keyword.kwlist:
298 raise ValueError("Fieldname {!r} is a python keyword and is not "
299 "accessible via the python API. ".format(name))
300 self.fieldname = name
304 return str([self.fieldtype, self.fieldname])
308 """ Coordinates of a syntactic element. Consists of:
311 - (optional) column number, for the Lexer
313 __slots__ = ('file', 'line', 'column', '__weakref__')
315 def __init__(self, file, line, column=None):
321 str = "%s:%s" % (self.file, self.line)
323 str += ":%s" % self.column
327 class ParseError(Exception):
334 class VPPAPIParser(object):
335 tokens = VPPAPILexer.tokens
337 def __init__(self, filename, logger):
338 self.filename = filename
342 def _parse_error(self, msg, coord):
343 raise ParseError("%s: %s" % (coord, msg))
345 def _parse_warning(self, msg, coord):
347 self.logger.warning("%s: %s" % (coord, msg))
349 def _coord(self, lineno, column=None):
352 line=lineno, column=column)
354 def _token_coord(self, p, token_idx):
355 """ Returns the coordinates for the YaccProduction object 'p' indexed
356 with 'token_idx'. The coordinate includes the 'lineno' and
357 'column'. Both follow the lex semantic, starting from 1.
359 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
362 column = (p.lexpos(token_idx) - (last_cr))
363 return self._coord(p.lineno(token_idx), column)
365 def p_slist(self, p):
383 def p_import(self, p):
384 '''import : IMPORT STRING_LITERAL ';' '''
387 def p_service(self, p):
388 '''service : SERVICE '{' service_statements '}' ';' '''
391 def p_service_statements(self, p):
392 '''service_statements : service_statement
393 | service_statements service_statement'''
399 def p_service_statement(self, p):
400 '''service_statement : RPC ID RETURNS NULL ';'
401 | RPC ID RETURNS ID ';'
402 | RPC ID RETURNS STREAM ID ';'
403 | RPC ID RETURNS ID EVENTS event_list ';' '''
405 # Verify that caller and reply differ
407 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
408 self._token_coord(p, 1))
410 p[0] = Service(p[2], p[4], p[6])
412 p[0] = Service(p[2], p[5], stream=True)
414 p[0] = Service(p[2], p[4])
416 def p_event_list(self, p):
417 '''event_list : events
418 | event_list events '''
424 def p_event(self, p):
430 '''enum : ENUM ID '{' enum_statements '}' ';' '''
431 p[0] = Enum(p[2], p[4])
433 def p_enum_type(self, p):
434 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
436 p[0] = Enum(p[2], p[6], enumtype=p[4])
438 p[0] = Enum(p[2], p[4])
440 def p_enum_size(self, p):
446 def p_define(self, p):
447 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
449 p[0] = Define(p[2], [], p[4])
451 def p_define_flist(self, p):
452 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
454 if 'typeonly' in p[1]:
455 p[0] = Typedef(p[3], p[1], p[5])
457 p[0] = Define(p[3], p[1], p[5])
459 def p_flist(self, p):
468 '''flag : MANUAL_PRINT
477 def p_typedef(self, p):
478 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
479 p[0] = Typedef(p[2], [], p[4])
481 def p_typedef_alias(self, p):
482 '''typedef : TYPEDEF declaration '''
483 p[0] = Using(p[2].fieldname, p[2])
485 def p_block_statements_opt(self, p):
486 '''block_statements_opt : block_statements '''
489 def p_block_statements(self, p):
490 '''block_statements : block_statement
491 | block_statements block_statement'''
497 def p_block_statement(self, p):
498 '''block_statement : declaration
502 def p_enum_statements(self, p):
503 '''enum_statements : enum_statement
504 | enum_statements enum_statement'''
510 def p_enum_statement(self, p):
511 '''enum_statement : ID '=' NUM ','
518 def p_field_options(self, p):
519 '''field_options : field_option
520 | field_options field_option'''
524 p[0] = { **p[1], **p[2] }
526 def p_field_option(self, p):
527 '''field_option : ID '=' assignee ','
530 p[0] = { p[1]: p[3] }
532 def p_declaration(self, p):
533 '''declaration : type_specifier ID ';'
534 | type_specifier ID '[' field_options ']' ';' '''
536 p[0] = Field(p[1], p[2], p[4])
538 p[0] = Field(p[1], p[2])
540 self._parse_error('ERROR')
541 self.fields.append(p[2])
543 def p_declaration_array(self, p):
544 '''declaration : type_specifier ID '[' NUM ']' ';'
545 | type_specifier ID '[' ID ']' ';' '''
547 return self._parse_error(
548 'array: %s' % p.value,
549 self._coord(lineno=p.lineno))
551 # Make this error later
552 if type(p[4]) is int and p[4] == 0:
553 # XXX: Line number is wrong
554 self._parse_warning('Old Style VLA: {} {}[{}];'
555 .format(p[1], p[2], p[4]),
556 self._token_coord(p, 1))
558 if type(p[4]) is str and p[4] not in self.fields:
559 # Verify that length field exists
560 self._parse_error('Missing length field: {} {}[{}];'
561 .format(p[1], p[2], p[4]),
562 self._token_coord(p, 1))
563 p[0] = Array(p[1], p[2], p[4])
565 def p_option(self, p):
566 '''option : OPTION ID '=' assignee ';' '''
567 p[0] = Option([p[1], p[2], p[4]])
569 def p_assignee(self, p):
576 def p_type_specifier(self, p):
577 '''type_specifier : U8
590 # Do a second pass later to verify that user defined types are defined
591 def p_typedef_specifier(self, p):
592 '''type_specifier : ID '''
593 if p[1] not in global_types:
594 self._parse_error('Undefined type: {}'.format(p[1]),
595 self._token_coord(p, 1))
598 def p_union(self, p):
599 '''union : UNION ID '{' block_statements_opt '}' ';' '''
600 p[0] = Union(p[2], p[4])
602 # Error rule for syntax errors
603 def p_error(self, p):
606 'before: %s' % p.value,
607 self._coord(lineno=p.lineno))
609 self._parse_error('At end of input', self.filename)
612 class VPPAPI(object):
614 def __init__(self, debug=False, filename='', logger=None):
615 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
616 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
617 write_tables=False, debug=debug)
620 def parse_string(self, code, debug=0, lineno=1):
621 self.lexer.lineno = lineno
622 return self.parser.parse(code, lexer=self.lexer, debug=debug)
624 def parse_file(self, fd, debug=0):
626 return self.parse_string(data, debug=debug)
628 def autoreply_block(self, name):
629 block = [Field('u32', 'context'),
630 Field('i32', 'retval')]
631 return Define(name + '_reply', [], block)
633 def process(self, objs):
643 tname = o.__class__.__name__
645 crc = binascii.crc32(o.crc, crc)
646 except AttributeError:
648 if isinstance(o, Define):
651 s[tname].append(self.autoreply_block(o.name))
652 elif isinstance(o, Option):
653 s[tname][o[1]] = o[2]
654 elif type(o) is list:
656 if isinstance(o2, Service):
657 s['Service'].append(o2)
658 elif (isinstance(o, Enum) or
659 isinstance(o, Typedef) or
660 isinstance(o, Union)):
662 elif isinstance(o, Using):
663 s['Alias'][o.name] = o.alias
666 raise ValueError('Unknown class type: {} {}'
670 msgs = {d.name: d for d in s['Define']}
671 svcs = {s.caller: s for s in s['Service']}
672 replies = {s.reply: s for s in s['Service']}
678 if service not in msgs:
680 'Service definition refers to unknown message'
681 ' definition: {}'.format(service))
682 if svcs[service].reply != 'null' and \
683 svcs[service].reply not in msgs:
684 raise ValueError('Service definition refers to unknown message'
685 ' definition in reply: {}'
686 .format(svcs[service].reply))
687 if service in replies:
688 raise ValueError('Service definition refers to message'
689 ' marked as reply: {}'.format(service))
690 for event in svcs[service].events:
691 if event not in msgs:
692 raise ValueError('Service definition refers to unknown '
693 'event: {} in message: {}'
694 .format(event, service))
695 seen_services[event] = True
697 # Create services implicitly
699 if d in seen_services:
701 if msgs[d].singular is True:
703 if d.endswith('_reply'):
706 if d[:-6] not in msgs:
707 raise ValueError('{} missing calling message'
710 if d.endswith('_dump'):
713 if d[:-5]+'_details' in msgs:
714 s['Service'].append(Service(d, d[:-5]+'_details',
717 raise ValueError('{} missing details message'
721 if d.endswith('_details'):
722 if d[:-8]+'_dump' not in msgs:
723 raise ValueError('{} missing dump message'
729 if d+'_reply' in msgs:
730 s['Service'].append(Service(d, d+'_reply'))
733 '{} missing reply message ({}) or service definition'
734 .format(d, d+'_reply'))
738 def process_imports(self, objs, in_import, result):
741 # Only allow the following object types from imported file
742 if in_import and not (isinstance(o, Enum) or
743 isinstance(o, Union) or
744 isinstance(o, Typedef) or
745 isinstance(o, Import) or
746 isinstance(o, Using)):
748 if isinstance(o, Import):
749 self.process_imports(o.result, True, result)
754 # Add message ids to each message.
757 o.block.insert(0, Field('u16', '_vl_msg_id'))
764 def dirlist_add(dirs):
767 dirlist = dirlist + dirs
773 def foldup_blocks(block, crc):
775 # Look up CRC in user defined types
776 if b.fieldtype.startswith('vl_api_'):
778 t = global_types[b.fieldtype]
780 crc = crc_block_combine(t.block, crc)
781 return foldup_blocks(t.block, crc)
788 f.crc = foldup_blocks(f.block,
789 binascii.crc32(f.crc))
795 cliparser = argparse.ArgumentParser(description='VPP API generator')
796 cliparser.add_argument('--pluginpath', default=""),
797 cliparser.add_argument('--includedir', action='append'),
798 if sys.version[0] == '2':
799 cliparser.add_argument('--input', type=argparse.FileType('r'),
801 cliparser.add_argument('--output', nargs='?',
802 type=argparse.FileType('w'),
806 cliparser.add_argument('--input',
807 type=argparse.FileType('r', encoding='UTF-8'),
809 cliparser.add_argument('--output', nargs='?',
810 type=argparse.FileType('w', encoding='UTF-8'),
813 cliparser.add_argument('output_module', nargs='?', default='C')
814 cliparser.add_argument('--debug', action='store_true')
815 cliparser.add_argument('--show-name', nargs=1)
816 args = cliparser.parse_args()
818 dirlist_add(args.includedir)
820 sys.excepthook = exception_handler
824 filename = args.show_name[0]
825 elif args.input != sys.stdin:
826 filename = args.input.name
831 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
833 logging.basicConfig()
834 log = logging.getLogger('vppapigen')
836 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
837 parsed_objects = parser.parse_file(args.input, log)
839 # Build a list of objects. Hash of lists.
841 parser.process_imports(parsed_objects, False, result)
842 s = parser.process(result)
845 s['Define'] = add_msg_id(s['Define'])
848 foldup_crcs(s['Define'])
854 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
855 for t in s['Define']:
856 pp.pprint([t.name, t.flags, t.block])
858 pp.pprint([t.name, t.block])
861 # Generate representation
863 from importlib.machinery import SourceFileLoader
867 if not args.pluginpath:
869 cand.append(os.path.dirname(os.path.realpath(__file__)))
870 cand.append(os.path.dirname(os.path.realpath(__file__)) +
874 if os.path.isfile('{}vppapigen_{}.py'
875 .format(c, args.output_module.lower())):
879 pluginpath = args.pluginpath + '/'
881 raise Exception('Output plugin not found')
882 module_path = '{}vppapigen_{}.py'.format(pluginpath,
883 args.output_module.lower())
886 plugin = SourceFileLoader(args.output_module,
887 module_path).load_module()
888 except Exception as err:
889 raise Exception('Error importing output plugin: {}, {}'
890 .format(module_path, err))
892 result = plugin.run(filename, s)
894 print(result, file=args.output)
896 raise Exception('Running plugin failed: {} {}'
897 .format(filename, result))
900 if __name__ == '__main__':