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 self._parse_error('legacy typedef. use typedef: {} {}[{}];'
454 .format(p[1], p[2], p[4]),
455 self._token_coord(p, 1))
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
774 def foldup_blocks(block, crc):
776 # Look up CRC in user defined types
777 if b.fieldtype.startswith('vl_api_'):
779 t = global_types[b.fieldtype]
781 crc = crc_block_combine(t.block, crc)
782 return foldup_blocks(t.block, crc)
790 f.crc = foldup_blocks(f.block,
791 binascii.crc32(f.crc))
798 if sys.version_info < (3, 5,):
799 log.exception('vppapigen requires a supported version of python. '
800 'Please use version 3.5 or greater. '
801 'Using {}'.format(sys.version))
804 cliparser = argparse.ArgumentParser(description='VPP API generator')
805 cliparser.add_argument('--pluginpath', default=""),
806 cliparser.add_argument('--includedir', action='append'),
807 cliparser.add_argument('--input',
808 type=argparse.FileType('r', encoding='UTF-8'),
810 cliparser.add_argument('--output', nargs='?',
811 type=argparse.FileType('w', encoding='UTF-8'),
814 cliparser.add_argument('output_module', nargs='?', default='C')
815 cliparser.add_argument('--debug', action='store_true')
816 cliparser.add_argument('--show-name', nargs=1)
817 args = cliparser.parse_args()
819 dirlist_add(args.includedir)
821 sys.excepthook = exception_handler
825 filename = args.show_name[0]
826 elif args.input != sys.stdin:
827 filename = args.input.name
832 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
834 logging.basicConfig()
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 log.exception('Output plugin not found')
883 module_path = '{}vppapigen_{}.py'.format(pluginpath,
884 args.output_module.lower())
887 plugin = SourceFileLoader(args.output_module,
888 module_path).load_module()
889 except Exception as err:
890 log.exception('Error importing output plugin: {}, {}'
891 .format(module_path, err))
894 result = plugin.run(filename, s)
896 print(result, file=args.output)
898 log.exception('Running plugin failed: {} {}'
899 .format(filename, result))
904 if __name__ == '__main__':