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+\.?\d*'
81 base = 16 if t.value.startswith('0x') else 10
83 t.value = float(t.value)
85 t.value = int(t.value, base)
89 r'[a-zA-Z_][a-zA-Z_0-9]*'
90 # Check for reserved words
91 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
95 def t_STRING_LITERAL(self, t):
96 r'\"([^\\\n]|(\\.))*?\"'
97 t.value = str(t.value).replace("\"", "")
100 # C or C++ comment (ignore)
101 def t_comment(self, t):
102 r'(/\*(.|\n)*?\*/)|(//.*)'
103 t.lexer.lineno += t.value.count('\n')
105 # Error handling rule
106 def t_error(self, t):
107 raise ParseError("Illegal character '{}' ({})"
108 "in {}: line {}".format(t.value[0],
109 hex(ord(t.value[0])),
114 # Define a rule so we can track line numbers
115 def t_newline(self, t):
117 t.lexer.lineno += len(t.value)
119 literals = ":{}[];=.,"
121 # A string containing ignored characters (spaces and tabs)
125 def crc_block_combine(block, crc):
126 s = str(block).encode()
127 return binascii.crc32(s, crc) & 0xffffffff
131 def __init__(self, caller, reply, events=None, stream=False):
135 self.events = [] if events is None else events
139 def __init__(self, name, flags, block):
143 self.crc = str(block).encode()
144 self.manual_print = False
145 self.manual_endian = False
147 if f == 'manual_print':
148 self.manual_print = True
149 elif f == 'manual_endian':
150 self.manual_endian = True
151 global_type_add(name, self)
154 return self.name + str(self.flags) + str(self.block)
158 def __init__(self, name, alias):
161 if isinstance(alias, Array):
162 a = { 'type': alias.fieldtype, # noqa: E201
163 'length': alias.length } # noqa: E202
165 a = { 'type': alias.fieldtype } # noqa: E201,E202
167 self.crc = str(alias).encode()
168 global_type_add(name, self)
171 return self.name + str(self.alias)
175 def __init__(self, name, block):
177 self.manual_print = False
178 self.manual_endian = False
181 self.crc = str(block).encode()
182 global_type_add(name, self)
185 return str(self.block)
189 def __init__(self, name, flags, block):
193 self.crc = str(block).encode()
194 self.dont_trace = False
195 self.manual_print = False
196 self.manual_endian = False
197 self.autoreply = False
198 self.singular = False
200 if f == 'dont_trace':
201 self.dont_trace = True
202 elif f == 'manual_print':
203 self.manual_print = True
204 elif f == 'manual_endian':
205 self.manual_endian = True
206 elif f == 'autoreply':
207 self.autoreply = True
210 if isinstance(b, Option):
211 if b[1] == 'singular' and b[2] == 'true':
216 return self.name + str(self.flags) + str(self.block)
220 def __init__(self, name, block, enumtype='u32'):
222 self.enumtype = enumtype
225 for i, b in enumerate(block):
230 block[i] = [b, count]
233 self.crc = str(block).encode()
234 global_type_add(name, self)
237 return self.name + str(self.block)
241 def __init__(self, filename):
242 self.filename = filename
245 parser = VPPAPI(filename=filename)
246 dirlist = dirlist_get()
249 f = os.path.join(dir, filename)
250 if os.path.exists(f):
252 if sys.version[0] == '2':
254 self.result = parser.parse_file(fd, None)
256 with open(f, encoding='utf-8') as fd:
257 self.result = parser.parse_file(fd, None)
264 def __init__(self, option):
266 self.crc = str(option).encode()
269 return str(self.option)
271 def __getitem__(self, index):
272 return self.option[index]
276 def __init__(self, fieldtype, name, length):
278 self.fieldtype = fieldtype
279 self.fieldname = name
280 if type(length) is str:
281 self.lengthfield = length
285 self.lengthfield = None
288 return str([self.fieldtype, self.fieldname, self.length,
293 def __init__(self, fieldtype, name, limit=None):
295 self.fieldtype = fieldtype
296 self.fieldname = name
300 return str([self.fieldtype, self.fieldname])
304 """ Coordinates of a syntactic element. Consists of:
307 - (optional) column number, for the Lexer
309 __slots__ = ('file', 'line', 'column', '__weakref__')
311 def __init__(self, file, line, column=None):
317 str = "%s:%s" % (self.file, self.line)
319 str += ":%s" % self.column
323 class ParseError(Exception):
330 class VPPAPIParser(object):
331 tokens = VPPAPILexer.tokens
333 def __init__(self, filename, logger):
334 self.filename = filename
338 def _parse_error(self, msg, coord):
339 raise ParseError("%s: %s" % (coord, msg))
341 def _parse_warning(self, msg, coord):
343 self.logger.warning("%s: %s" % (coord, msg))
345 def _coord(self, lineno, column=None):
348 line=lineno, column=column)
350 def _token_coord(self, p, token_idx):
351 """ Returns the coordinates for the YaccProduction object 'p' indexed
352 with 'token_idx'. The coordinate includes the 'lineno' and
353 'column'. Both follow the lex semantic, starting from 1.
355 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
358 column = (p.lexpos(token_idx) - (last_cr))
359 return self._coord(p.lineno(token_idx), column)
361 def p_slist(self, p):
379 def p_import(self, p):
380 '''import : IMPORT STRING_LITERAL ';' '''
383 def p_service(self, p):
384 '''service : SERVICE '{' service_statements '}' ';' '''
387 def p_service_statements(self, p):
388 '''service_statements : service_statement
389 | service_statements service_statement'''
395 def p_service_statement(self, p):
396 '''service_statement : RPC ID RETURNS NULL ';'
397 | RPC ID RETURNS ID ';'
398 | RPC ID RETURNS STREAM ID ';'
399 | RPC ID RETURNS ID EVENTS event_list ';' '''
401 # Verify that caller and reply differ
403 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
404 self._token_coord(p, 1))
406 p[0] = Service(p[2], p[4], p[6])
408 p[0] = Service(p[2], p[5], stream=True)
410 p[0] = Service(p[2], p[4])
412 def p_event_list(self, p):
413 '''event_list : events
414 | event_list events '''
420 def p_event(self, p):
426 '''enum : ENUM ID '{' enum_statements '}' ';' '''
427 p[0] = Enum(p[2], p[4])
429 def p_enum_type(self, p):
430 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
432 p[0] = Enum(p[2], p[6], enumtype=p[4])
434 p[0] = Enum(p[2], p[4])
436 def p_enum_size(self, p):
442 def p_define(self, p):
443 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
445 p[0] = Define(p[2], [], p[4])
447 def p_define_flist(self, p):
448 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
450 if 'typeonly' in p[1]:
451 p[0] = Typedef(p[3], p[1], p[5])
453 p[0] = Define(p[3], p[1], p[5])
455 def p_flist(self, p):
464 '''flag : MANUAL_PRINT
473 def p_typedef(self, p):
474 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
475 p[0] = Typedef(p[2], [], p[4])
477 def p_typedef_alias(self, p):
478 '''typedef : TYPEDEF declaration '''
479 p[0] = Using(p[2].fieldname, p[2])
481 def p_block_statements_opt(self, p):
482 '''block_statements_opt : block_statements '''
485 def p_block_statements(self, p):
486 '''block_statements : block_statement
487 | block_statements block_statement'''
493 def p_block_statement(self, p):
494 '''block_statement : declaration
498 def p_enum_statements(self, p):
499 '''enum_statements : enum_statement
500 | enum_statements enum_statement'''
506 def p_enum_statement(self, p):
507 '''enum_statement : ID '=' NUM ','
514 def p_field_options(self, p):
515 '''field_options : field_option
516 | field_options field_option'''
520 p[0] = { **p[1], **p[2] }
522 def p_field_option(self, p):
523 '''field_option : ID '=' assignee ','
526 p[0] = { p[1]: p[3] }
528 def p_declaration(self, p):
529 '''declaration : type_specifier ID ';'
530 | type_specifier ID '[' field_options ']' ';' '''
532 p[0] = Field(p[1], p[2], p[4])
534 p[0] = Field(p[1], p[2])
536 self._parse_error('ERROR')
537 self.fields.append(p[2])
539 def p_declaration_array(self, p):
540 '''declaration : type_specifier ID '[' NUM ']' ';'
541 | type_specifier ID '[' ID ']' ';' '''
543 return self._parse_error(
544 'array: %s' % p.value,
545 self._coord(lineno=p.lineno))
547 # Make this error later
548 if type(p[4]) is int and p[4] == 0:
549 # XXX: Line number is wrong
550 self._parse_warning('Old Style VLA: {} {}[{}];'
551 .format(p[1], p[2], p[4]),
552 self._token_coord(p, 1))
554 if type(p[4]) is str and p[4] not in self.fields:
555 # Verify that length field exists
556 self._parse_error('Missing length field: {} {}[{}];'
557 .format(p[1], p[2], p[4]),
558 self._token_coord(p, 1))
559 p[0] = Array(p[1], p[2], p[4])
561 def p_option(self, p):
562 '''option : OPTION ID '=' assignee ';' '''
563 p[0] = Option([p[1], p[2], p[4]])
565 def p_assignee(self, p):
572 def p_type_specifier(self, p):
573 '''type_specifier : U8
586 # Do a second pass later to verify that user defined types are defined
587 def p_typedef_specifier(self, p):
588 '''type_specifier : ID '''
589 if p[1] not in global_types:
590 self._parse_error('Undefined type: {}'.format(p[1]),
591 self._token_coord(p, 1))
594 def p_union(self, p):
595 '''union : UNION ID '{' block_statements_opt '}' ';' '''
596 p[0] = Union(p[2], p[4])
598 # Error rule for syntax errors
599 def p_error(self, p):
602 'before: %s' % p.value,
603 self._coord(lineno=p.lineno))
605 self._parse_error('At end of input', self.filename)
608 class VPPAPI(object):
610 def __init__(self, debug=False, filename='', logger=None):
611 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
612 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
613 write_tables=False, debug=debug)
616 def parse_string(self, code, debug=0, lineno=1):
617 self.lexer.lineno = lineno
618 return self.parser.parse(code, lexer=self.lexer, debug=debug)
620 def parse_file(self, fd, debug=0):
622 return self.parse_string(data, debug=debug)
624 def autoreply_block(self, name):
625 block = [Field('u32', 'context'),
626 Field('i32', 'retval')]
627 return Define(name + '_reply', [], block)
629 def process(self, objs):
639 tname = o.__class__.__name__
641 crc = binascii.crc32(o.crc, crc)
642 except AttributeError:
644 if isinstance(o, Define):
647 s[tname].append(self.autoreply_block(o.name))
648 elif isinstance(o, Option):
649 s[tname][o[1]] = o[2]
650 elif type(o) is list:
652 if isinstance(o2, Service):
653 s['Service'].append(o2)
654 elif (isinstance(o, Enum) or
655 isinstance(o, Typedef) or
656 isinstance(o, Union)):
658 elif isinstance(o, Using):
659 s['Alias'][o.name] = o.alias
662 raise ValueError('Unknown class type: {} {}'
666 msgs = {d.name: d for d in s['Define']}
667 svcs = {s.caller: s for s in s['Service']}
668 replies = {s.reply: s for s in s['Service']}
674 if service not in msgs:
676 'Service definition refers to unknown message'
677 ' definition: {}'.format(service))
678 if svcs[service].reply != 'null' and \
679 svcs[service].reply not in msgs:
680 raise ValueError('Service definition refers to unknown message'
681 ' definition in reply: {}'
682 .format(svcs[service].reply))
683 if service in replies:
684 raise ValueError('Service definition refers to message'
685 ' marked as reply: {}'.format(service))
686 for event in svcs[service].events:
687 if event not in msgs:
688 raise ValueError('Service definition refers to unknown '
689 'event: {} in message: {}'
690 .format(event, service))
691 seen_services[event] = True
693 # Create services implicitly
695 if d in seen_services:
697 if msgs[d].singular is True:
699 if d.endswith('_reply'):
702 if d[:-6] not in msgs:
703 raise ValueError('{} missing calling message'
706 if d.endswith('_dump'):
709 if d[:-5]+'_details' in msgs:
710 s['Service'].append(Service(d, d[:-5]+'_details',
713 raise ValueError('{} missing details message'
717 if d.endswith('_details'):
718 if d[:-8]+'_dump' not in msgs:
719 raise ValueError('{} missing dump message'
725 if d+'_reply' in msgs:
726 s['Service'].append(Service(d, d+'_reply'))
729 '{} missing reply message ({}) or service definition'
730 .format(d, d+'_reply'))
734 def process_imports(self, objs, in_import, result):
737 # Only allow the following object types from imported file
738 if in_import and not (isinstance(o, Enum) or
739 isinstance(o, Union) or
740 isinstance(o, Typedef) or
741 isinstance(o, Import) or
742 isinstance(o, Using)):
744 if isinstance(o, Import):
745 self.process_imports(o.result, True, result)
750 # Add message ids to each message.
753 o.block.insert(0, Field('u16', '_vl_msg_id'))
760 def dirlist_add(dirs):
763 dirlist = dirlist + dirs
769 def foldup_blocks(block, crc):
771 # Look up CRC in user defined types
772 if b.fieldtype.startswith('vl_api_'):
774 t = global_types[b.fieldtype]
776 crc = crc_block_combine(t.block, crc)
777 return foldup_blocks(t.block, crc)
784 f.crc = foldup_blocks(f.block,
785 binascii.crc32(f.crc))
791 cliparser = argparse.ArgumentParser(description='VPP API generator')
792 cliparser.add_argument('--pluginpath', default=""),
793 cliparser.add_argument('--includedir', action='append'),
794 if sys.version[0] == '2':
795 cliparser.add_argument('--input', type=argparse.FileType('r'),
797 cliparser.add_argument('--output', nargs='?',
798 type=argparse.FileType('w'),
802 cliparser.add_argument('--input',
803 type=argparse.FileType('r', encoding='UTF-8'),
805 cliparser.add_argument('--output', nargs='?',
806 type=argparse.FileType('w', encoding='UTF-8'),
809 cliparser.add_argument('output_module', nargs='?', default='C')
810 cliparser.add_argument('--debug', action='store_true')
811 cliparser.add_argument('--show-name', nargs=1)
812 args = cliparser.parse_args()
814 dirlist_add(args.includedir)
816 sys.excepthook = exception_handler
820 filename = args.show_name[0]
821 elif args.input != sys.stdin:
822 filename = args.input.name
827 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
829 logging.basicConfig()
830 log = logging.getLogger('vppapigen')
832 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
833 parsed_objects = parser.parse_file(args.input, log)
835 # Build a list of objects. Hash of lists.
837 parser.process_imports(parsed_objects, False, result)
838 s = parser.process(result)
841 s['Define'] = add_msg_id(s['Define'])
844 foldup_crcs(s['Define'])
850 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
851 for t in s['Define']:
852 pp.pprint([t.name, t.flags, t.block])
854 pp.pprint([t.name, t.block])
857 # Generate representation
859 from importlib.machinery import SourceFileLoader
863 if not args.pluginpath:
865 cand.append(os.path.dirname(os.path.realpath(__file__)))
866 cand.append(os.path.dirname(os.path.realpath(__file__)) +
870 if os.path.isfile('{}vppapigen_{}.py'
871 .format(c, args.output_module.lower())):
875 pluginpath = args.pluginpath + '/'
877 raise Exception('Output plugin not found')
878 module_path = '{}vppapigen_{}.py'.format(pluginpath,
879 args.output_module.lower())
882 plugin = SourceFileLoader(args.output_module,
883 module_path).load_module()
884 except Exception as err:
885 raise Exception('Error importing output plugin: {}, {}'
886 .format(module_path, err))
888 result = plugin.run(filename, s)
890 print(result, file=args.output)
892 raise Exception('Running plugin failed: {} {}'
893 .format(filename, result))
896 if __name__ == '__main__':