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+'
81 base = 16 if t.value.startswith('0x') else 10
82 t.value = int(t.value, base)
86 r'[a-zA-Z_][a-zA-Z_0-9]*'
87 # Check for reserved words
88 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
92 def t_STRING_LITERAL(self, t):
93 r'\"([^\\\n]|(\\.))*?\"'
94 t.value = str(t.value).replace("\"", "")
97 # C or C++ comment (ignore)
98 def t_comment(self, t):
99 r'(/\*(.|\n)*?\*/)|(//.*)'
100 t.lexer.lineno += t.value.count('\n')
102 # Error handling rule
103 def t_error(self, t):
104 raise ParseError("Illegal character '{}' ({})"
105 "in {}: line {}".format(t.value[0],
106 hex(ord(t.value[0])),
111 # Define a rule so we can track line numbers
112 def t_newline(self, t):
114 t.lexer.lineno += len(t.value)
116 literals = ":{}[];=.,"
118 # A string containing ignored characters (spaces and tabs)
122 def crc_block_combine(block, crc):
123 s = str(block).encode()
124 return binascii.crc32(s, crc) & 0xffffffff
127 def __init__(self, caller, reply, events=None, stream=False):
131 self.events = [] if events is None else events
135 def __init__(self, name, flags, block):
139 self.crc = str(block).encode()
140 self.manual_print = False
141 self.manual_endian = False
143 if f == 'manual_print':
144 self.manual_print = True
145 elif f == 'manual_endian':
146 self.manual_endian = True
147 global_type_add(name, self)
150 return self.name + str(self.flags) + str(self.block)
154 def __init__(self, name, alias):
157 if isinstance(alias, Array):
158 a = { 'type': alias.fieldtype, # noqa: E201
159 'length': alias.length } # noqa: E202
161 a = { 'type': alias.fieldtype } # noqa: E201,E202
163 self.crc = str(alias).encode()
164 global_type_add(name, self)
167 return self.name + str(self.alias)
171 def __init__(self, name, block):
173 self.manual_print = False
174 self.manual_endian = False
177 self.crc = str(block).encode()
178 global_type_add(name, self)
181 return str(self.block)
185 def __init__(self, name, flags, block):
189 self.crc = str(block).encode()
190 self.dont_trace = False
191 self.manual_print = False
192 self.manual_endian = False
193 self.autoreply = False
194 self.singular = False
196 if f == 'dont_trace':
197 self.dont_trace = True
198 elif f == 'manual_print':
199 self.manual_print = True
200 elif f == 'manual_endian':
201 self.manual_endian = True
202 elif f == 'autoreply':
203 self.autoreply = True
206 if isinstance(b, Option):
207 if b[1] == 'singular' and b[2] == 'true':
212 return self.name + str(self.flags) + str(self.block)
216 def __init__(self, name, block, enumtype='u32'):
218 self.enumtype = enumtype
221 for i, b in enumerate(block):
226 block[i] = [b, count]
229 self.crc = str(block).encode()
230 global_type_add(name, self)
233 return self.name + str(self.block)
237 def __init__(self, filename):
238 self.filename = filename
241 parser = VPPAPI(filename=filename)
242 dirlist = dirlist_get()
245 f = os.path.join(dir, filename)
246 if os.path.exists(f):
248 if sys.version[0] == '2':
250 self.result = parser.parse_file(fd, None)
252 with open(f, encoding='utf-8') as fd:
253 self.result = parser.parse_file(fd, None)
260 def __init__(self, option):
262 self.crc = str(option).encode()
265 return str(self.option)
267 def __getitem__(self, index):
268 return self.option[index]
272 def __init__(self, fieldtype, name, length):
274 self.fieldtype = fieldtype
275 self.fieldname = name
276 if type(length) is str:
277 self.lengthfield = length
281 self.lengthfield = None
284 return str([self.fieldtype, self.fieldname, self.length,
289 def __init__(self, fieldtype, name, limit=None):
291 self.fieldtype = fieldtype
292 self.fieldname = name
296 return str([self.fieldtype, self.fieldname])
300 """ Coordinates of a syntactic element. Consists of:
303 - (optional) column number, for the Lexer
305 __slots__ = ('file', 'line', 'column', '__weakref__')
307 def __init__(self, file, line, column=None):
313 str = "%s:%s" % (self.file, self.line)
315 str += ":%s" % self.column
319 class ParseError(Exception):
326 class VPPAPIParser(object):
327 tokens = VPPAPILexer.tokens
329 def __init__(self, filename, logger):
330 self.filename = filename
334 def _parse_error(self, msg, coord):
335 raise ParseError("%s: %s" % (coord, msg))
337 def _parse_warning(self, msg, coord):
339 self.logger.warning("%s: %s" % (coord, msg))
341 def _coord(self, lineno, column=None):
344 line=lineno, column=column)
346 def _token_coord(self, p, token_idx):
347 """ Returns the coordinates for the YaccProduction object 'p' indexed
348 with 'token_idx'. The coordinate includes the 'lineno' and
349 'column'. Both follow the lex semantic, starting from 1.
351 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
354 column = (p.lexpos(token_idx) - (last_cr))
355 return self._coord(p.lineno(token_idx), column)
357 def p_slist(self, p):
375 def p_import(self, p):
376 '''import : IMPORT STRING_LITERAL ';' '''
379 def p_service(self, p):
380 '''service : SERVICE '{' service_statements '}' ';' '''
383 def p_service_statements(self, p):
384 '''service_statements : service_statement
385 | service_statements service_statement'''
391 def p_service_statement(self, p):
392 '''service_statement : RPC ID RETURNS NULL ';'
393 | RPC ID RETURNS ID ';'
394 | RPC ID RETURNS STREAM ID ';'
395 | RPC ID RETURNS ID EVENTS event_list ';' '''
397 # Verify that caller and reply differ
399 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
400 self._token_coord(p, 1))
402 p[0] = Service(p[2], p[4], p[6])
404 p[0] = Service(p[2], p[5], stream=True)
406 p[0] = Service(p[2], p[4])
408 def p_event_list(self, p):
409 '''event_list : events
410 | event_list events '''
416 def p_event(self, p):
422 '''enum : ENUM ID '{' enum_statements '}' ';' '''
423 p[0] = Enum(p[2], p[4])
425 def p_enum_type(self, p):
426 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
428 p[0] = Enum(p[2], p[6], enumtype=p[4])
430 p[0] = Enum(p[2], p[4])
432 def p_enum_size(self, p):
438 def p_define(self, p):
439 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
441 p[0] = Define(p[2], [], p[4])
443 def p_define_flist(self, p):
444 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
446 if 'typeonly' in p[1]:
447 p[0] = Typedef(p[3], p[1], p[5])
449 p[0] = Define(p[3], p[1], p[5])
451 def p_flist(self, p):
460 '''flag : MANUAL_PRINT
469 def p_typedef(self, p):
470 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
471 p[0] = Typedef(p[2], [], p[4])
473 def p_typedef_alias(self, p):
474 '''typedef : TYPEDEF declaration '''
475 p[0] = Using(p[2].fieldname, p[2])
477 def p_block_statements_opt(self, p):
478 '''block_statements_opt : block_statements '''
481 def p_block_statements(self, p):
482 '''block_statements : block_statement
483 | block_statements block_statement'''
489 def p_block_statement(self, p):
490 '''block_statement : declaration
494 def p_enum_statements(self, p):
495 '''enum_statements : enum_statement
496 | enum_statements enum_statement'''
502 def p_enum_statement(self, p):
503 '''enum_statement : ID '=' NUM ','
510 def p_field_options(self, p):
511 '''field_options : field_option
512 | field_options field_option'''
516 p[0] = { **p[1], **p[2] }
518 def p_field_option(self, p):
519 '''field_option : ID '=' assignee ','
522 p[0] = { p[1]: p[3] }
524 def p_declaration(self, p):
525 '''declaration : type_specifier ID ';'
526 | type_specifier ID '[' field_options ']' ';' '''
528 p[0] = Field(p[1], p[2], p[4])
530 p[0] = Field(p[1], p[2])
532 self._parse_error('ERROR')
533 self.fields.append(p[2])
535 def p_declaration_array(self, p):
536 '''declaration : type_specifier ID '[' NUM ']' ';'
537 | type_specifier ID '[' ID ']' ';' '''
539 return self._parse_error(
540 'array: %s' % p.value,
541 self._coord(lineno=p.lineno))
543 # Make this error later
544 if type(p[4]) is int and p[4] == 0:
545 # XXX: Line number is wrong
546 self._parse_warning('Old Style VLA: {} {}[{}];'
547 .format(p[1], p[2], p[4]),
548 self._token_coord(p, 1))
550 if type(p[4]) is str and p[4] not in self.fields:
551 # Verify that length field exists
552 self._parse_error('Missing length field: {} {}[{}];'
553 .format(p[1], p[2], p[4]),
554 self._token_coord(p, 1))
555 p[0] = Array(p[1], p[2], p[4])
557 def p_option(self, p):
558 '''option : OPTION ID '=' assignee ';' '''
559 p[0] = Option([p[1], p[2], p[4]])
561 def p_assignee(self, p):
568 def p_type_specifier(self, p):
569 '''type_specifier : U8
582 # Do a second pass later to verify that user defined types are defined
583 def p_typedef_specifier(self, p):
584 '''type_specifier : ID '''
585 if p[1] not in global_types:
586 self._parse_error('Undefined type: {}'.format(p[1]),
587 self._token_coord(p, 1))
590 def p_union(self, p):
591 '''union : UNION ID '{' block_statements_opt '}' ';' '''
592 p[0] = Union(p[2], p[4])
594 # Error rule for syntax errors
595 def p_error(self, p):
598 'before: %s' % p.value,
599 self._coord(lineno=p.lineno))
601 self._parse_error('At end of input', self.filename)
604 class VPPAPI(object):
606 def __init__(self, debug=False, filename='', logger=None):
607 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
608 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
609 write_tables=False, debug=debug)
612 def parse_string(self, code, debug=0, lineno=1):
613 self.lexer.lineno = lineno
614 return self.parser.parse(code, lexer=self.lexer, debug=debug)
616 def parse_file(self, fd, debug=0):
618 return self.parse_string(data, debug=debug)
620 def autoreply_block(self, name):
621 block = [Field('u32', 'context'),
622 Field('i32', 'retval')]
623 return Define(name + '_reply', [], block)
625 def process(self, objs):
635 tname = o.__class__.__name__
637 crc = binascii.crc32(o.crc, crc)
638 except AttributeError:
640 if isinstance(o, Define):
643 s[tname].append(self.autoreply_block(o.name))
644 elif isinstance(o, Option):
645 s[tname][o[1]] = o[2]
646 elif type(o) is list:
648 if isinstance(o2, Service):
649 s['Service'].append(o2)
650 elif (isinstance(o, Enum) or
651 isinstance(o, Typedef) or
652 isinstance(o, Union)):
654 elif isinstance(o, Using):
655 s['Alias'][o.name] = o.alias
658 raise ValueError('Unknown class type: {} {}'
662 msgs = {d.name: d for d in s['Define']}
663 svcs = {s.caller: s for s in s['Service']}
664 replies = {s.reply: s for s in s['Service']}
670 if service not in msgs:
672 'Service definition refers to unknown message'
673 ' definition: {}'.format(service))
674 if svcs[service].reply != 'null' and \
675 svcs[service].reply not in msgs:
676 raise ValueError('Service definition refers to unknown message'
677 ' definition in reply: {}'
678 .format(svcs[service].reply))
679 if service in replies:
680 raise ValueError('Service definition refers to message'
681 ' marked as reply: {}'.format(service))
682 for event in svcs[service].events:
683 if event not in msgs:
684 raise ValueError('Service definition refers to unknown '
685 'event: {} in message: {}'
686 .format(event, service))
687 seen_services[event] = True
689 # Create services implicitly
691 if d in seen_services:
693 if msgs[d].singular is True:
695 if d.endswith('_reply'):
698 if d[:-6] not in msgs:
699 raise ValueError('{} missing calling message'
702 if d.endswith('_dump'):
705 if d[:-5]+'_details' in msgs:
706 s['Service'].append(Service(d, d[:-5]+'_details',
709 raise ValueError('{} missing details message'
713 if d.endswith('_details'):
714 if d[:-8]+'_dump' not in msgs:
715 raise ValueError('{} missing dump message'
721 if d+'_reply' in msgs:
722 s['Service'].append(Service(d, d+'_reply'))
725 '{} missing reply message ({}) or service definition'
726 .format(d, d+'_reply'))
730 def process_imports(self, objs, in_import, result):
733 # Only allow the following object types from imported file
734 if in_import and not (isinstance(o, Enum) or
735 isinstance(o, Union) or
736 isinstance(o, Typedef) or
737 isinstance(o, Import) or
738 isinstance(o, Using)):
740 if isinstance(o, Import):
741 self.process_imports(o.result, True, result)
746 # Add message ids to each message.
749 o.block.insert(0, Field('u16', '_vl_msg_id'))
756 def dirlist_add(dirs):
759 dirlist = dirlist + dirs
765 def foldup_blocks(block, crc):
767 # Look up CRC in user defined types
768 if b.fieldtype.startswith('vl_api_'):
770 t = global_types[b.fieldtype]
772 crc = crc_block_combine(t.block, crc)
773 return foldup_blocks(t.block, crc)
780 f.crc = foldup_blocks(f.block,
781 binascii.crc32(f.crc))
787 cliparser = argparse.ArgumentParser(description='VPP API generator')
788 cliparser.add_argument('--pluginpath', default=""),
789 cliparser.add_argument('--includedir', action='append'),
790 if sys.version[0] == '2':
791 cliparser.add_argument('--input', type=argparse.FileType('r'),
793 cliparser.add_argument('--output', nargs='?',
794 type=argparse.FileType('w'),
798 cliparser.add_argument('--input',
799 type=argparse.FileType('r', encoding='UTF-8'),
801 cliparser.add_argument('--output', nargs='?',
802 type=argparse.FileType('w', encoding='UTF-8'),
805 cliparser.add_argument('output_module', nargs='?', default='C')
806 cliparser.add_argument('--debug', action='store_true')
807 cliparser.add_argument('--show-name', nargs=1)
808 args = cliparser.parse_args()
810 dirlist_add(args.includedir)
812 sys.excepthook = exception_handler
816 filename = args.show_name[0]
817 elif args.input != sys.stdin:
818 filename = args.input.name
823 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
825 logging.basicConfig()
826 log = logging.getLogger('vppapigen')
828 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
829 parsed_objects = parser.parse_file(args.input, log)
831 # Build a list of objects. Hash of lists.
833 parser.process_imports(parsed_objects, False, result)
834 s = parser.process(result)
837 s['Define'] = add_msg_id(s['Define'])
840 foldup_crcs(s['Define'])
846 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
847 for t in s['Define']:
848 pp.pprint([t.name, t.flags, t.block])
850 pp.pprint([t.name, t.block])
853 # Generate representation
855 from importlib.machinery import SourceFileLoader
859 if not args.pluginpath:
861 cand.append(os.path.dirname(os.path.realpath(__file__)))
862 cand.append(os.path.dirname(os.path.realpath(__file__)) +
866 if os.path.isfile('{}vppapigen_{}.py'
867 .format(c, args.output_module.lower())):
871 pluginpath = args.pluginpath + '/'
873 raise Exception('Output plugin not found')
874 module_path = '{}vppapigen_{}.py'.format(pluginpath,
875 args.output_module.lower())
878 plugin = SourceFileLoader(args.output_module,
879 module_path).load_module()
880 except Exception as err:
881 raise Exception('Error importing output plugin: {}, {}'
882 .format(module_path, err))
884 result = plugin.run(filename, s)
886 print(result, file=args.output)
888 raise Exception('Running plugin failed: {} {}'
889 .format(filename, result))
892 if __name__ == '__main__':