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)
156 return self.name + str(self.flags) + str(self.block)
160 def __init__(self, name, alias):
163 if isinstance(alias, Array):
164 a = { 'type': alias.fieldtype, # noqa: E201
165 'length': alias.length } # noqa: E202
167 a = { 'type': alias.fieldtype } # noqa: E201,E202
169 self.crc = str(alias).encode()
170 global_type_add(name, self)
173 return self.name + str(self.alias)
177 def __init__(self, name, block):
179 self.manual_print = False
180 self.manual_endian = False
183 self.crc = str(block).encode()
184 global_type_add(name, self)
187 return str(self.block)
191 def __init__(self, name, flags, block):
195 self.crc = str(block).encode()
196 self.dont_trace = False
197 self.manual_print = False
198 self.manual_endian = False
199 self.autoreply = False
200 self.singular = False
202 if f == 'dont_trace':
203 self.dont_trace = True
204 elif f == 'manual_print':
205 self.manual_print = True
206 elif f == 'manual_endian':
207 self.manual_endian = True
208 elif f == 'autoreply':
209 self.autoreply = True
212 if isinstance(b, Option):
213 if b[1] == 'singular' and b[2] == 'true':
218 return self.name + str(self.flags) + str(self.block)
222 def __init__(self, name, block, enumtype='u32'):
224 self.enumtype = enumtype
227 for i, b in enumerate(block):
232 block[i] = [b, count]
235 self.crc = str(block).encode()
236 global_type_add(name, self)
239 return self.name + str(self.block)
243 def __init__(self, filename):
244 self.filename = filename
247 parser = VPPAPI(filename=filename)
248 dirlist = dirlist_get()
251 f = os.path.join(dir, filename)
252 if os.path.exists(f):
255 with open(f, encoding='utf-8') as fd:
256 self.result = parser.parse_file(fd, None)
263 def __init__(self, option):
265 self.crc = str(option).encode()
268 return str(self.option)
270 def __getitem__(self, index):
271 return self.option[index]
275 def __init__(self, fieldtype, name, length):
277 self.fieldtype = fieldtype
278 self.fieldname = name
279 if type(length) is str:
280 self.lengthfield = length
284 self.lengthfield = None
287 return str([self.fieldtype, self.fieldname, self.length,
292 def __init__(self, fieldtype, name, limit=None):
294 self.fieldtype = fieldtype
295 if name in keyword.kwlist:
296 raise ValueError("Fieldname {!r} is a python keyword and is not "
297 "accessible via the python API. ".format(name))
298 self.fieldname = name
302 return str([self.fieldtype, self.fieldname])
306 """ Coordinates of a syntactic element. Consists of:
309 - (optional) column number, for the Lexer
311 __slots__ = ('file', 'line', 'column', '__weakref__')
313 def __init__(self, file, line, column=None):
319 str = "%s:%s" % (self.file, self.line)
321 str += ":%s" % self.column
325 class ParseError(Exception):
332 class VPPAPIParser(object):
333 tokens = VPPAPILexer.tokens
335 def __init__(self, filename, logger):
336 self.filename = filename
340 def _parse_error(self, msg, coord):
341 raise ParseError("%s: %s" % (coord, msg))
343 def _parse_warning(self, msg, coord):
345 self.logger.warning("%s: %s" % (coord, msg))
347 def _coord(self, lineno, column=None):
350 line=lineno, column=column)
352 def _token_coord(self, p, token_idx):
353 """ Returns the coordinates for the YaccProduction object 'p' indexed
354 with 'token_idx'. The coordinate includes the 'lineno' and
355 'column'. Both follow the lex semantic, starting from 1.
357 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
360 column = (p.lexpos(token_idx) - (last_cr))
361 return self._coord(p.lineno(token_idx), column)
363 def p_slist(self, p):
381 def p_import(self, p):
382 '''import : IMPORT STRING_LITERAL ';' '''
385 def p_service(self, p):
386 '''service : SERVICE '{' service_statements '}' ';' '''
389 def p_service_statements(self, p):
390 '''service_statements : service_statement
391 | service_statements service_statement'''
397 def p_service_statement(self, p):
398 '''service_statement : RPC ID RETURNS NULL ';'
399 | RPC ID RETURNS ID ';'
400 | RPC ID RETURNS STREAM ID ';'
401 | RPC ID RETURNS ID EVENTS event_list ';' '''
403 # Verify that caller and reply differ
405 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
406 self._token_coord(p, 1))
408 p[0] = Service(p[2], p[4], p[6])
410 p[0] = Service(p[2], p[5], stream=True)
412 p[0] = Service(p[2], p[4])
414 def p_event_list(self, p):
415 '''event_list : events
416 | event_list events '''
422 def p_event(self, p):
428 '''enum : ENUM ID '{' enum_statements '}' ';' '''
429 p[0] = Enum(p[2], p[4])
431 def p_enum_type(self, p):
432 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
434 p[0] = Enum(p[2], p[6], enumtype=p[4])
436 p[0] = Enum(p[2], p[4])
438 def p_enum_size(self, p):
444 def p_define(self, p):
445 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
447 p[0] = Define(p[2], [], p[4])
449 def p_define_flist(self, p):
450 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
452 if 'typeonly' in p[1]:
453 p[0] = Typedef(p[3], p[1], p[5])
455 p[0] = Define(p[3], p[1], p[5])
457 def p_flist(self, p):
466 '''flag : MANUAL_PRINT
475 def p_typedef(self, p):
476 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
477 p[0] = Typedef(p[2], [], p[4])
479 def p_typedef_alias(self, p):
480 '''typedef : TYPEDEF declaration '''
481 p[0] = Using(p[2].fieldname, p[2])
483 def p_block_statements_opt(self, p):
484 '''block_statements_opt : block_statements '''
487 def p_block_statements(self, p):
488 '''block_statements : block_statement
489 | block_statements block_statement'''
495 def p_block_statement(self, p):
496 '''block_statement : declaration
500 def p_enum_statements(self, p):
501 '''enum_statements : enum_statement
502 | enum_statements enum_statement'''
508 def p_enum_statement(self, p):
509 '''enum_statement : ID '=' NUM ','
516 def p_field_options(self, p):
517 '''field_options : field_option
518 | field_options field_option'''
522 p[0] = { **p[1], **p[2] }
524 def p_field_option(self, p):
525 '''field_option : ID '=' assignee ','
528 p[0] = { p[1]: p[3] }
530 def p_declaration(self, p):
531 '''declaration : type_specifier ID ';'
532 | type_specifier ID '[' field_options ']' ';' '''
534 p[0] = Field(p[1], p[2], p[4])
536 p[0] = Field(p[1], p[2])
538 self._parse_error('ERROR')
539 self.fields.append(p[2])
541 def p_declaration_array(self, p):
542 '''declaration : type_specifier ID '[' NUM ']' ';'
543 | type_specifier ID '[' ID ']' ';' '''
545 return self._parse_error(
546 'array: %s' % p.value,
547 self._coord(lineno=p.lineno))
549 # Make this error later
550 if type(p[4]) is int and p[4] == 0:
551 # XXX: Line number is wrong
552 self._parse_warning('Old Style VLA: {} {}[{}];'
553 .format(p[1], p[2], p[4]),
554 self._token_coord(p, 1))
556 if type(p[4]) is str and p[4] not in self.fields:
557 # Verify that length field exists
558 self._parse_error('Missing length field: {} {}[{}];'
559 .format(p[1], p[2], p[4]),
560 self._token_coord(p, 1))
561 p[0] = Array(p[1], p[2], p[4])
563 def p_option(self, p):
564 '''option : OPTION ID '=' assignee ';' '''
565 p[0] = Option([p[1], p[2], p[4]])
567 def p_assignee(self, p):
574 def p_type_specifier(self, p):
575 '''type_specifier : U8
588 # Do a second pass later to verify that user defined types are defined
589 def p_typedef_specifier(self, p):
590 '''type_specifier : ID '''
591 if p[1] not in global_types:
592 self._parse_error('Undefined type: {}'.format(p[1]),
593 self._token_coord(p, 1))
596 def p_union(self, p):
597 '''union : UNION ID '{' block_statements_opt '}' ';' '''
598 p[0] = Union(p[2], p[4])
600 # Error rule for syntax errors
601 def p_error(self, p):
604 'before: %s' % p.value,
605 self._coord(lineno=p.lineno))
607 self._parse_error('At end of input', self.filename)
610 class VPPAPI(object):
612 def __init__(self, debug=False, filename='', logger=None):
613 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
614 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
615 write_tables=False, debug=debug)
618 def parse_string(self, code, debug=0, lineno=1):
619 self.lexer.lineno = lineno
620 return self.parser.parse(code, lexer=self.lexer, debug=debug)
622 def parse_file(self, fd, debug=0):
624 return self.parse_string(data, debug=debug)
626 def autoreply_block(self, name):
627 block = [Field('u32', 'context'),
628 Field('i32', 'retval')]
629 return Define(name + '_reply', [], block)
631 def process(self, objs):
641 tname = o.__class__.__name__
643 crc = binascii.crc32(o.crc, crc)
644 except AttributeError:
646 if isinstance(o, Define):
649 s[tname].append(self.autoreply_block(o.name))
650 elif isinstance(o, Option):
651 s[tname][o[1]] = o[2]
652 elif type(o) is list:
654 if isinstance(o2, Service):
655 s['Service'].append(o2)
656 elif (isinstance(o, Enum) or
657 isinstance(o, Typedef) or
658 isinstance(o, Union)):
660 elif isinstance(o, Using):
661 s['Alias'][o.name] = o.alias
664 raise ValueError('Unknown class type: {} {}'
668 msgs = {d.name: d for d in s['Define']}
669 svcs = {s.caller: s for s in s['Service']}
670 replies = {s.reply: s for s in s['Service']}
676 if service not in msgs:
678 'Service definition refers to unknown message'
679 ' definition: {}'.format(service))
680 if svcs[service].reply != 'null' and \
681 svcs[service].reply not in msgs:
682 raise ValueError('Service definition refers to unknown message'
683 ' definition in reply: {}'
684 .format(svcs[service].reply))
685 if service in replies:
686 raise ValueError('Service definition refers to message'
687 ' marked as reply: {}'.format(service))
688 for event in svcs[service].events:
689 if event not in msgs:
690 raise ValueError('Service definition refers to unknown '
691 'event: {} in message: {}'
692 .format(event, service))
693 seen_services[event] = True
695 # Create services implicitly
697 if d in seen_services:
699 if msgs[d].singular is True:
701 if d.endswith('_reply'):
704 if d[:-6] not in msgs:
705 raise ValueError('{} missing calling message'
708 if d.endswith('_dump'):
711 if d[:-5]+'_details' in msgs:
712 s['Service'].append(Service(d, d[:-5]+'_details',
715 raise ValueError('{} missing details message'
719 if d.endswith('_details'):
720 if d[:-8]+'_dump' not in msgs:
721 raise ValueError('{} missing dump message'
727 if d+'_reply' in msgs:
728 s['Service'].append(Service(d, d+'_reply'))
731 '{} missing reply message ({}) or service definition'
732 .format(d, d+'_reply'))
736 def process_imports(self, objs, in_import, result):
739 # Only allow the following object types from imported file
740 if in_import and not (isinstance(o, Enum) or
741 isinstance(o, Union) or
742 isinstance(o, Typedef) or
743 isinstance(o, Import) or
744 isinstance(o, Using)):
746 if isinstance(o, Import):
747 self.process_imports(o.result, True, result)
752 # Add message ids to each message.
755 o.block.insert(0, Field('u16', '_vl_msg_id'))
762 def dirlist_add(dirs):
765 dirlist = dirlist + dirs
772 def foldup_blocks(block, crc):
774 # Look up CRC in user defined types
775 if b.fieldtype.startswith('vl_api_'):
777 t = global_types[b.fieldtype]
779 crc = crc_block_combine(t.block, crc)
780 return foldup_blocks(t.block, crc)
788 f.crc = foldup_blocks(f.block,
789 binascii.crc32(f.crc))
796 if sys.version_info < (3, 5,):
797 log.exception('vppapigen requires a supported version of python. '
798 'Please use version 3.5 or greater. '
799 'Using {}'.format(sys.version))
802 cliparser = argparse.ArgumentParser(description='VPP API generator')
803 cliparser.add_argument('--pluginpath', default=""),
804 cliparser.add_argument('--includedir', action='append'),
805 cliparser.add_argument('--input',
806 type=argparse.FileType('r', encoding='UTF-8'),
808 cliparser.add_argument('--output', nargs='?',
809 type=argparse.FileType('w', encoding='UTF-8'),
812 cliparser.add_argument('output_module', nargs='?', default='C')
813 cliparser.add_argument('--debug', action='store_true')
814 cliparser.add_argument('--show-name', nargs=1)
815 args = cliparser.parse_args()
817 dirlist_add(args.includedir)
819 sys.excepthook = exception_handler
823 filename = args.show_name[0]
824 elif args.input != sys.stdin:
825 filename = args.input.name
830 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
832 logging.basicConfig()
834 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
835 parsed_objects = parser.parse_file(args.input, log)
837 # Build a list of objects. Hash of lists.
839 parser.process_imports(parsed_objects, False, result)
840 s = parser.process(result)
843 s['Define'] = add_msg_id(s['Define'])
846 foldup_crcs(s['Define'])
852 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
853 for t in s['Define']:
854 pp.pprint([t.name, t.flags, t.block])
856 pp.pprint([t.name, t.block])
859 # Generate representation
861 from importlib.machinery import SourceFileLoader
865 if not args.pluginpath:
867 cand.append(os.path.dirname(os.path.realpath(__file__)))
868 cand.append(os.path.dirname(os.path.realpath(__file__)) +
872 if os.path.isfile('{}vppapigen_{}.py'
873 .format(c, args.output_module.lower())):
877 pluginpath = args.pluginpath + '/'
879 log.exception('Output plugin not found')
881 module_path = '{}vppapigen_{}.py'.format(pluginpath,
882 args.output_module.lower())
885 plugin = SourceFileLoader(args.output_module,
886 module_path).load_module()
887 except Exception as err:
888 log.exception('Error importing output plugin: {}, {}'
889 .format(module_path, err))
892 result = plugin.run(filename, s)
894 print(result, file=args.output)
896 log.exception('Running plugin failed: {} {}'
897 .format(filename, result))
902 if __name__ == '__main__':