3 from __future__ import print_function
5 import ply.yacc as yacc
16 # Global dictionary of new types (including enums)
20 def global_type_add(name):
21 '''Add new type to the dictionary of types '''
22 type_name = 'vl_api_' + name + '_t'
23 if type_name in global_types:
24 raise KeyError('Type is already defined: {}'.format(name))
25 global_types[type_name] = True
28 # All your trace are belong to us!
29 def exception_handler(exception_type, exception, traceback):
30 print ("%s: %s" % (exception_type.__name__, exception))
36 class VPPAPILexer(object):
37 def __init__(self, filename):
38 self.filename = filename
49 'typeonly': 'TYPEONLY',
50 'manual_print': 'MANUAL_PRINT',
51 'manual_endian': 'MANUAL_ENDIAN',
52 'dont_trace': 'DONT_TRACE',
53 'autoreply': 'AUTOREPLY',
71 tokens = ['STRING_LITERAL',
72 'ID', 'NUM'] + list(reserved.values())
74 t_ignore_LINE_COMMENT = '//.*'
77 r'0[xX][0-9a-fA-F]+|\d+'
78 base = 16 if t.value.startswith('0x') else 10
79 t.value = int(t.value, base)
83 r'[a-zA-Z_][a-zA-Z_0-9]*'
84 # Check for reserved words
85 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
89 def t_STRING_LITERAL(self, t):
90 r'\"([^\\\n]|(\\.))*?\"'
91 t.value = str(t.value).replace("\"", "")
94 # C or C++ comment (ignore)
95 def t_comment(self, t):
96 r'(/\*(.|\n)*?\*/)|(//.*)'
97 t.lexer.lineno += t.value.count('\n')
100 def t_error(self, t):
101 raise ParseError("Illegal character '{}' ({})"
102 "in {}: line {}".format(t.value[0],
103 hex(ord(t.value[0])),
108 # Define a rule so we can track line numbers
109 def t_newline(self, t):
111 t.lexer.lineno += len(t.value)
113 literals = ":{}[];=.,"
115 # A string containing ignored characters (spaces and tabs)
119 class Iterator(type):
125 def __init__(self, caller, reply, events=[], stream=False):
133 def __init__(self, name, flags, block):
137 self.crc = binascii.crc32(str(block)) & 0xffffffff
138 global_type_add(name)
141 return self.name + str(self.flags) + str(self.block)
145 def __init__(self, name, flags, block):
149 self.crc = binascii.crc32(str(block)) & 0xffffffff
150 self.typeonly = False
151 self.dont_trace = False
152 self.manual_print = False
153 self.manual_endian = False
154 self.autoreply = False
155 self.singular = False
159 global_type_add(name)
160 elif f == 'dont_trace':
161 self.dont_trace = True
162 elif f == 'manual_print':
163 self.manual_print = True
164 elif f == 'manual_endian':
165 self.manual_endian = True
166 elif f == 'autoreply':
167 self.autoreply = True
170 if isinstance(b, Option):
171 if b[1] == 'singular' and b[2] == 'true':
176 return self.name + str(self.flags) + str(self.block)
180 def __init__(self, name, block, enumtype='u32'):
182 self.enumtype = enumtype
184 for i, b in enumerate(block):
189 block[i] = [b, count]
192 self.crc = binascii.crc32(str(block)) & 0xffffffff
193 global_type_add(name)
196 return self.name + str(self.block)
200 def __init__(self, filename):
201 self.filename = filename
204 parser = VPPAPI(filename=filename)
205 dirlist = dirlist_get()
208 f = os.path.join(dir, filename)
209 if os.path.exists(f):
212 self.result = parser.parse_file(fd, None)
219 def __init__(self, option):
221 self.crc = binascii.crc32(str(option)) & 0xffffffff
224 return str(self.option)
226 def __getitem__(self, index):
227 return self.option[index]
231 def __init__(self, fieldtype, name, length):
233 self.fieldtype = fieldtype
234 self.fieldname = name
235 if type(length) is str:
236 self.lengthfield = length
240 self.lengthfield = None
243 return str([self.fieldtype, self.fieldname, self.length,
248 def __init__(self, fieldtype, name):
250 self.fieldtype = fieldtype
251 self.fieldname = name
254 return str([self.fieldtype, self.fieldname])
258 """ Coordinates of a syntactic element. Consists of:
261 - (optional) column number, for the Lexer
263 __slots__ = ('file', 'line', 'column', '__weakref__')
265 def __init__(self, file, line, column=None):
271 str = "%s:%s" % (self.file, self.line)
273 str += ":%s" % self.column
277 class ParseError(Exception):
284 class VPPAPIParser(object):
285 tokens = VPPAPILexer.tokens
287 def __init__(self, filename, logger):
288 self.filename = filename
292 def _parse_error(self, msg, coord):
293 raise ParseError("%s: %s" % (coord, msg))
295 def _parse_warning(self, msg, coord):
297 self.logger.warning("%s: %s" % (coord, msg))
299 def _coord(self, lineno, column=None):
302 line=lineno, column=column)
304 def _token_coord(self, p, token_idx):
305 """ Returns the coordinates for the YaccProduction object 'p' indexed
306 with 'token_idx'. The coordinate includes the 'lineno' and
307 'column'. Both follow the lex semantic, starting from 1.
309 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
312 column = (p.lexpos(token_idx) - (last_cr))
313 return self._coord(p.lineno(token_idx), column)
315 def p_slist(self, p):
332 def p_import(self, p):
333 '''import : IMPORT STRING_LITERAL ';' '''
336 def p_service(self, p):
337 '''service : SERVICE '{' service_statements '}' ';' '''
340 def p_service_statements(self, p):
341 '''service_statements : service_statement
342 | service_statements service_statement'''
348 def p_service_statement(self, p):
349 '''service_statement : RPC ID RETURNS ID ';'
350 | RPC ID RETURNS STREAM ID ';'
351 | RPC ID RETURNS ID EVENTS event_list ';' '''
353 p[0] = Service(p[2], p[4], p[6])
355 p[0] = Service(p[2], p[5], stream=True)
357 p[0] = Service(p[2], p[4])
359 def p_event_list(self, p):
360 '''event_list : events
361 | event_list events '''
367 def p_event(self, p):
373 '''enum : ENUM ID '{' enum_statements '}' ';' '''
374 p[0] = Enum(p[2], p[4])
376 def p_enum_type(self, p):
377 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
379 p[0] = Enum(p[2], p[6], enumtype=p[4])
381 p[0] = Enum(p[2], p[4])
383 def p_enum_size(self, p):
389 def p_define(self, p):
390 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
392 p[0] = Define(p[2], [], p[4])
394 def p_define_flist(self, p):
395 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
396 p[0] = Define(p[3], p[1], p[5])
398 def p_flist(self, p):
407 '''flag : MANUAL_PRINT
416 def p_typedef(self, p):
417 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
418 p[0] = Typedef(p[2], [], p[4])
420 def p_block_statements_opt(self, p):
421 '''block_statements_opt : block_statements'''
424 def p_block_statements(self, p):
425 '''block_statements : block_statement
426 | block_statements block_statement'''
432 def p_block_statement(self, p):
433 '''block_statement : declaration
437 def p_enum_statements(self, p):
438 '''enum_statements : enum_statement
439 | enum_statements enum_statement'''
445 def p_enum_statement(self, p):
446 '''enum_statement : ID '=' NUM ','
453 def p_declaration(self, p):
454 '''declaration : type_specifier ID ';' '''
456 self._parse_error('ERROR')
457 self.fields.append(p[2])
458 p[0] = Field(p[1], p[2])
460 def p_declaration_array(self, p):
461 '''declaration : type_specifier ID '[' NUM ']' ';'
462 | type_specifier ID '[' ID ']' ';' '''
464 return self._parse_error(
465 'array: %s' % p.value,
466 self._coord(lineno=p.lineno))
468 # Make this error later
469 if type(p[4]) is int and p[4] == 0:
470 # XXX: Line number is wrong
471 self._parse_warning('Old Style VLA: {} {}[{}];'
472 .format(p[1], p[2], p[4]),
473 self._token_coord(p, 1))
475 if type(p[4]) is str and p[4] not in self.fields:
476 # Verify that length field exists
477 self._parse_error('Missing length field: {} {}[{}];'
478 .format(p[1], p[2], p[4]),
479 self._token_coord(p, 1))
480 p[0] = Array(p[1], p[2], p[4])
482 def p_option(self, p):
483 '''option : OPTION ID '=' assignee ';' '''
484 p[0] = Option([p[1], p[2], p[4]])
486 def p_assignee(self, p):
493 def p_type_specifier(self, p):
494 '''type_specifier : U8
507 # Do a second pass later to verify that user defined types are defined
508 def p_typedef_specifier(self, p):
509 '''type_specifier : ID '''
510 if p[1] not in global_types:
511 self._parse_error('Undefined type: {}'.format(p[1]),
512 self._token_coord(p, 1))
515 # Error rule for syntax errors
516 def p_error(self, p):
519 'before: %s' % p.value,
520 self._coord(lineno=p.lineno))
522 self._parse_error('At end of input', self.filename)
525 class VPPAPI(object):
527 def __init__(self, debug=False, filename='', logger=None):
528 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
529 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
530 tabmodule='vppapigentab', debug=debug)
533 def parse_string(self, code, debug=0, lineno=1):
534 self.lexer.lineno = lineno
535 return self.parser.parse(code, lexer=self.lexer, debug=debug)
537 def parse_file(self, fd, debug=0):
539 return self.parse_string(data, debug=debug)
541 def autoreply_block(self, name):
542 block = [Field('u32', 'context'),
543 Field('i32', 'retval')]
544 return Define(name + '_reply', [], block)
546 def process(self, objs):
556 if isinstance(o, Define):
558 s['typedefs'].append(o)
560 s['defines'].append(o)
562 s['defines'].append(self.autoreply_block(o.name))
563 elif isinstance(o, Option):
564 s['options'][o[1]] = o[2]
565 elif isinstance(o, Enum):
567 elif isinstance(o, Typedef):
568 s['typedefs'].append(o)
569 elif type(o) is list:
571 if isinstance(o2, Service):
572 s['services'].append(o2)
574 # Create services implicitly
575 msgs = {d.name: d for d in s['defines']}
576 svcs = {s.caller: s for s in s['services']}
579 if service not in msgs:
580 raise ValueError('Service definition refers to unknown message'
581 ' definition: {}'.format(service))
582 if svcs[service].reply not in msgs:
583 raise ValueError('Service definition refers to unknown message'
584 ' definition in reply: {}'
585 .format(svcs[service].reply))
586 for event in svcs[service].events:
587 if event not in msgs:
588 raise ValueError('Service definition refers to unknown '
589 'event: {} in message: {}'
590 .format(event, service))
593 if msgs[d].singular is True:
595 if d.endswith('_counters'):
597 if d.endswith('_reply'):
600 if d[:-6] not in msgs:
601 self.logger.warning('{} missing calling message'
604 if d.endswith('_dump'):
607 if d[:-5]+'_details' in msgs:
608 s['services'].append(Service(d, d[:-5]+'_details',
611 self.logger.error('{} missing details message'
615 if d.endswith('_details'):
616 if d[:-8]+'_dump' not in msgs:
617 self.logger.error('{} missing dump message'
623 if d+'_reply' in msgs:
624 s['services'].append(Service(d, d+'_reply'))
626 self.logger.warning('{} missing reply message ({})'
627 .format(d, d+'_reply'))
628 s['services'].append(Service(d, None))
632 def process_imports(self, objs):
634 if isinstance(o, Import):
635 return objs + self.process_imports(o.result)
639 # Add message ids to each message.
642 o.block.insert(0, Field('u16', '_vl_msg_id'))
647 return binascii.crc32(str(s)) & 0xffffffff
653 def dirlist_add(dirs):
656 dirlist = dirlist + dirs
667 logging.basicConfig()
668 log = logging.getLogger('vppapigen')
670 cliparser = argparse.ArgumentParser(description='VPP API generator')
671 cliparser.add_argument('--pluginpath', default=""),
672 cliparser.add_argument('--includedir', action='append'),
673 cliparser.add_argument('--input', type=argparse.FileType('r'),
675 cliparser.add_argument('--output', nargs='?', type=argparse.FileType('w'),
678 cliparser.add_argument('output_module', nargs='?', default='C')
679 cliparser.add_argument('--debug', action='store_true')
680 cliparser.add_argument('--show-name', nargs=1)
681 args = cliparser.parse_args()
683 dirlist_add(args.includedir)
685 sys.excepthook = exception_handler
689 filename = args.show_name[0]
690 elif args.input != sys.stdin:
691 filename = args.input.name
695 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
696 result = parser.parse_file(args.input, log)
698 # Build a list of objects. Hash of lists.
699 result = parser.process_imports(result)
700 s = parser.process(result)
703 s['defines'] = add_msg_id(s['defines'])
711 pp = pprint.PrettyPrinter(indent=4)
712 for t in s['defines']:
713 pp.pprint([t.name, t.flags, t.block])
714 for t in s['typedefs']:
715 pp.pprint([t.name, t.flags, t.block])
718 # Generate representation
724 if not args.pluginpath:
726 cand.append(os.path.dirname(os.path.realpath(__file__)))
727 cand.append(os.path.dirname(os.path.realpath(__file__)) + \
731 if os.path.isfile(c + args.output_module + '.py'):
735 pluginpath = args.pluginpath + '/'
737 raise Exception('Output plugin not found')
738 module_path = pluginpath + args.output_module + '.py'
741 plugin = imp.load_source(args.output_module, module_path)
742 except Exception, err:
743 raise Exception('Error importing output plugin: {}, {}'
744 .format(module_path, err))
746 result = plugin.run(filename, s, file_crc)
748 print (result, file=args.output)
750 raise Exception('Running plugin failed: {} {}'
751 .format(filename, result))
754 if __name__ == '__main__':