API: Add service definitions for events and singleton messages (second attempt)
[vpp.git] / src / tools / vppapigen / vppapigen.py
1 #!/usr/bin/env python
2
3 from __future__ import print_function
4 import ply.lex as lex
5 import ply.yacc as yacc
6 import sys
7 import argparse
8 import logging
9 import binascii
10 import os
11
12 #
13 # VPP API language
14 #
15
16 # Global dictionary of new types (including enums)
17 global_types = {}
18
19
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
26
27
28 # All your trace are belong to us!
29 def exception_handler(exception_type, exception, traceback):
30     print ("%s: %s" % (exception_type.__name__, exception))
31
32
33 #
34 # Lexer
35 #
36 class VPPAPILexer(object):
37     def __init__(self, filename):
38         self.filename = filename
39
40     reserved = {
41         'service': 'SERVICE',
42         'rpc': 'RPC',
43         'returns': 'RETURNS',
44         'null': 'NULL',
45         'stream': 'STREAM',
46         'events': 'EVENTS',
47         'define': 'DEFINE',
48         'typedef': 'TYPEDEF',
49         'enum': 'ENUM',
50         'typeonly': 'TYPEONLY',
51         'manual_print': 'MANUAL_PRINT',
52         'manual_endian': 'MANUAL_ENDIAN',
53         'dont_trace': 'DONT_TRACE',
54         'autoreply': 'AUTOREPLY',
55         'option': 'OPTION',
56         'u8': 'U8',
57         'u16': 'U16',
58         'u32': 'U32',
59         'u64': 'U64',
60         'i8': 'I8',
61         'i16': 'I16',
62         'i32': 'I32',
63         'i64': 'I64',
64         'f64': 'F64',
65         'bool': 'BOOL',
66         'string': 'STRING',
67         'import': 'IMPORT',
68         'true': 'TRUE',
69         'false': 'FALSE',
70     }
71
72     tokens = ['STRING_LITERAL',
73               'ID', 'NUM'] + list(reserved.values())
74
75     t_ignore_LINE_COMMENT = '//.*'
76
77     def t_NUM(self, t):
78         r'0[xX][0-9a-fA-F]+|\d+'
79         base = 16 if t.value.startswith('0x') else 10
80         t.value = int(t.value, base)
81         return t
82
83     def t_ID(self, t):
84         r'[a-zA-Z_][a-zA-Z_0-9]*'
85         # Check for reserved words
86         t.type = VPPAPILexer.reserved.get(t.value, 'ID')
87         return t
88
89     # C string
90     def t_STRING_LITERAL(self, t):
91         r'\"([^\\\n]|(\\.))*?\"'
92         t.value = str(t.value).replace("\"", "")
93         return t
94
95     # C or C++ comment (ignore)
96     def t_comment(self, t):
97         r'(/\*(.|\n)*?\*/)|(//.*)'
98         t.lexer.lineno += t.value.count('\n')
99
100     # Error handling rule
101     def t_error(self, t):
102         raise ParseError("Illegal character '{}' ({})"
103                          "in {}: line {}".format(t.value[0],
104                                                  hex(ord(t.value[0])),
105                                                  self.filename,
106                                                  t.lexer.lineno))
107         t.lexer.skip(1)
108
109     # Define a rule so we can track line numbers
110     def t_newline(self, t):
111         r'\n+'
112         t.lexer.lineno += len(t.value)
113
114     literals = ":{}[];=.,"
115
116     # A string containing ignored characters (spaces and tabs)
117     t_ignore = ' \t'
118
119 class Service():
120     def __init__(self, caller, reply, events=[], stream=False):
121         self.caller = caller
122         self.reply = reply
123         self.stream = stream
124         self.events = events
125
126
127 class Typedef():
128     def __init__(self, name, flags, block):
129         self.name = name
130         self.flags = flags
131         self.block = block
132         self.crc = binascii.crc32(str(block)) & 0xffffffff
133         global_type_add(name)
134
135     def __repr__(self):
136         return self.name + str(self.flags) + str(self.block)
137
138
139 class Define():
140     def __init__(self, name, flags, block):
141         self.name = name
142         self.flags = flags
143         self.block = block
144         self.crc = binascii.crc32(str(block)) & 0xffffffff
145         self.typeonly = False
146         self.dont_trace = False
147         self.manual_print = False
148         self.manual_endian = False
149         self.autoreply = False
150         self.singular = False
151         for f in flags:
152             if f == 'typeonly':
153                 self.typeonly = True
154                 global_type_add(name)
155             elif f == 'dont_trace':
156                 self.dont_trace = True
157             elif f == 'manual_print':
158                 self.manual_print = True
159             elif f == 'manual_endian':
160                 self.manual_endian = True
161             elif f == 'autoreply':
162                 self.autoreply = True
163
164         for b in block:
165             if isinstance(b, Option):
166                 if b[1] == 'singular' and b[2] == 'true':
167                     self.singular = True
168                 block.remove(b)
169
170     def __repr__(self):
171         return self.name + str(self.flags) + str(self.block)
172
173
174 class Enum():
175     def __init__(self, name, block, enumtype='u32'):
176         self.name = name
177         self.enumtype = enumtype
178         count = 0
179         for i, b in enumerate(block):
180             if type(b) is list:
181                 count = b[1]
182             else:
183                 count += 1
184                 block[i] = [b, count]
185
186         self.block = block
187         self.crc = binascii.crc32(str(block)) & 0xffffffff
188         global_type_add(name)
189
190     def __repr__(self):
191         return self.name + str(self.block)
192
193
194 class Import():
195     def __init__(self, filename):
196         self.filename = filename
197
198         # Deal with imports
199         parser = VPPAPI(filename=filename)
200         dirlist = dirlist_get()
201         f = filename
202         for dir in dirlist:
203             f = os.path.join(dir, filename)
204             if os.path.exists(f):
205                 break
206         with open(f) as fd:
207             self.result = parser.parse_file(fd, None)
208
209     def __repr__(self):
210         return self.filename
211
212
213 class Option():
214     def __init__(self, option):
215         self.option = option
216         self.crc = binascii.crc32(str(option)) & 0xffffffff
217
218     def __repr__(self):
219         return str(self.option)
220
221     def __getitem__(self, index):
222         return self.option[index]
223
224
225 class Array():
226     def __init__(self, fieldtype, name, length):
227         self.type = 'Array'
228         self.fieldtype = fieldtype
229         self.fieldname = name
230         if type(length) is str:
231             self.lengthfield = length
232             self.length = 0
233         else:
234             self.length = length
235             self.lengthfield = None
236
237     def __repr__(self):
238         return str([self.fieldtype, self.fieldname, self.length,
239                     self.lengthfield])
240
241
242 class Field():
243     def __init__(self, fieldtype, name):
244         self.type = 'Field'
245         self.fieldtype = fieldtype
246         self.fieldname = name
247
248     def __repr__(self):
249         return str([self.fieldtype, self.fieldname])
250
251
252 class Coord(object):
253     """ Coordinates of a syntactic element. Consists of:
254             - File name
255             - Line number
256             - (optional) column number, for the Lexer
257     """
258     __slots__ = ('file', 'line', 'column', '__weakref__')
259
260     def __init__(self, file, line, column=None):
261         self.file = file
262         self.line = line
263         self.column = column
264
265     def __str__(self):
266         str = "%s:%s" % (self.file, self.line)
267         if self.column:
268             str += ":%s" % self.column
269         return str
270
271
272 class ParseError(Exception):
273     pass
274
275
276 #
277 # Grammar rules
278 #
279 class VPPAPIParser(object):
280     tokens = VPPAPILexer.tokens
281
282     def __init__(self, filename, logger):
283         self.filename = filename
284         self.logger = logger
285         self.fields = []
286
287     def _parse_error(self, msg, coord):
288         raise ParseError("%s: %s" % (coord, msg))
289
290     def _parse_warning(self, msg, coord):
291         if self.logger:
292             self.logger.warning("%s: %s" % (coord, msg))
293
294     def _coord(self, lineno, column=None):
295         return Coord(
296                 file=self.filename,
297                 line=lineno, column=column)
298
299     def _token_coord(self, p, token_idx):
300         """ Returns the coordinates for the YaccProduction object 'p' indexed
301             with 'token_idx'. The coordinate includes the 'lineno' and
302             'column'. Both follow the lex semantic, starting from 1.
303         """
304         last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
305         if last_cr < 0:
306             last_cr = -1
307         column = (p.lexpos(token_idx) - (last_cr))
308         return self._coord(p.lineno(token_idx), column)
309
310     def p_slist(self, p):
311         '''slist : stmt
312                  | slist stmt'''
313         if len(p) == 2:
314             p[0] = [p[1]]
315         else:
316             p[0] = p[1] + [p[2]]
317
318     def p_stmt(self, p):
319         '''stmt : define
320                 | typedef
321                 | option
322                 | import
323                 | enum
324                 | service'''
325         p[0] = p[1]
326
327     def p_import(self, p):
328         '''import : IMPORT STRING_LITERAL ';' '''
329         p[0] = Import(p[2])
330
331     def p_service(self, p):
332         '''service : SERVICE '{' service_statements '}' ';' '''
333         p[0] = p[3]
334
335     def p_service_statements(self, p):
336         '''service_statements : service_statement
337                         | service_statements service_statement'''
338         if len(p) == 2:
339             p[0] = [p[1]]
340         else:
341             p[0] = p[1] + [p[2]]
342
343     def p_service_statement(self, p):
344         '''service_statement : RPC ID RETURNS NULL ';'
345                              | RPC ID RETURNS ID ';'
346                              | RPC ID RETURNS STREAM ID ';'
347                              | RPC ID RETURNS ID EVENTS event_list ';' '''
348         if len(p) == 8:
349             p[0] = Service(p[2], p[4], p[6])
350         elif len(p) == 7:
351             p[0] = Service(p[2], p[5], stream=True)
352         else:
353             p[0] = Service(p[2], p[4])
354
355     def p_event_list(self, p):
356         '''event_list : events
357                       | event_list events '''
358         if len(p) == 2:
359             p[0] = [p[1]]
360         else:
361             p[0] = p[1] + [p[2]]
362
363     def p_event(self, p):
364         '''events : ID
365                   | ID ',' '''
366         p[0] = p[1]
367
368     def p_enum(self, p):
369         '''enum : ENUM ID '{' enum_statements '}' ';' '''
370         p[0] = Enum(p[2], p[4])
371
372     def p_enum_type(self, p):
373         ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
374         if len(p) == 9:
375             p[0] = Enum(p[2], p[6], enumtype=p[4])
376         else:
377             p[0] = Enum(p[2], p[4])
378
379     def p_enum_size(self, p):
380         ''' enum_size : U8
381                       | U16
382                       | U32 '''
383         p[0] = p[1]
384
385     def p_define(self, p):
386         '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
387         self.fields = []
388         p[0] = Define(p[2], [], p[4])
389
390     def p_define_flist(self, p):
391         '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
392         p[0] = Define(p[3], p[1], p[5])
393
394     def p_flist(self, p):
395         '''flist : flag
396                  | flist flag'''
397         if len(p) == 2:
398             p[0] = [p[1]]
399         else:
400             p[0] = p[1] + [p[2]]
401
402     def p_flag(self, p):
403         '''flag : MANUAL_PRINT
404                 | MANUAL_ENDIAN
405                 | DONT_TRACE
406                 | TYPEONLY
407                 | AUTOREPLY'''
408         if len(p) == 1:
409             return
410         p[0] = p[1]
411
412     def p_typedef(self, p):
413         '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
414         p[0] = Typedef(p[2], [], p[4])
415
416     def p_block_statements_opt(self, p):
417         '''block_statements_opt : block_statements'''
418         p[0] = p[1]
419
420     def p_block_statements(self, p):
421         '''block_statements : block_statement
422                             | block_statements block_statement'''
423         if len(p) == 2:
424             p[0] = [p[1]]
425         else:
426             p[0] = p[1] + [p[2]]
427
428     def p_block_statement(self, p):
429         '''block_statement : declaration
430                            | option '''
431         p[0] = p[1]
432
433     def p_enum_statements(self, p):
434         '''enum_statements : enum_statement
435                             | enum_statements enum_statement'''
436         if len(p) == 2:
437             p[0] = [p[1]]
438         else:
439             p[0] = p[1] + [p[2]]
440
441     def p_enum_statement(self, p):
442         '''enum_statement : ID '=' NUM ','
443                           | ID ',' '''
444         if len(p) == 5:
445             p[0] = [p[1], p[3]]
446         else:
447             p[0] = p[1]
448
449     def p_declaration(self, p):
450         '''declaration : type_specifier ID ';' '''
451         if len(p) != 4:
452             self._parse_error('ERROR')
453         self.fields.append(p[2])
454         p[0] = Field(p[1], p[2])
455
456     def p_declaration_array(self, p):
457         '''declaration : type_specifier ID '[' NUM ']' ';'
458                        | type_specifier ID '[' ID ']' ';' '''
459         if len(p) != 7:
460             return self._parse_error(
461                 'array: %s' % p.value,
462                 self._coord(lineno=p.lineno))
463
464         # Make this error later
465         if type(p[4]) is int and p[4] == 0:
466             # XXX: Line number is wrong
467             self._parse_warning('Old Style VLA: {} {}[{}];'
468                                 .format(p[1], p[2], p[4]),
469                                 self._token_coord(p, 1))
470
471         if type(p[4]) is str and p[4] not in self.fields:
472             # Verify that length field exists
473             self._parse_error('Missing length field: {} {}[{}];'
474                               .format(p[1], p[2], p[4]),
475                               self._token_coord(p, 1))
476         p[0] = Array(p[1], p[2], p[4])
477
478     def p_option(self, p):
479         '''option : OPTION ID '=' assignee ';' '''
480         p[0] = Option([p[1], p[2], p[4]])
481
482     def p_assignee(self, p):
483         '''assignee : NUM
484                     | TRUE
485                     | FALSE
486                     | STRING_LITERAL '''
487         p[0] = p[1]
488
489     def p_type_specifier(self, p):
490         '''type_specifier : U8
491                           | U16
492                           | U32
493                           | U64
494                           | I8
495                           | I16
496                           | I32
497                           | I64
498                           | F64
499                           | BOOL
500                           | STRING'''
501         p[0] = p[1]
502
503     # Do a second pass later to verify that user defined types are defined
504     def p_typedef_specifier(self, p):
505         '''type_specifier : ID '''
506         if p[1] not in global_types:
507             self._parse_error('Undefined type: {}'.format(p[1]),
508                               self._token_coord(p, 1))
509         p[0] = p[1]
510
511     # Error rule for syntax errors
512     def p_error(self, p):
513         if p:
514             self._parse_error(
515                 'before: %s' % p.value,
516                 self._coord(lineno=p.lineno))
517         else:
518             self._parse_error('At end of input', self.filename)
519
520
521 class VPPAPI(object):
522
523     def __init__(self, debug=False, filename='', logger=None):
524         self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
525         self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
526                                 tabmodule='vppapigentab', debug=debug)
527         self.logger = logger
528
529     def parse_string(self, code, debug=0, lineno=1):
530         self.lexer.lineno = lineno
531         return self.parser.parse(code, lexer=self.lexer, debug=debug)
532
533     def parse_file(self, fd, debug=0):
534         data = fd.read()
535         return self.parse_string(data, debug=debug)
536
537     def autoreply_block(self, name):
538         block = [Field('u32', 'context'),
539                  Field('i32', 'retval')]
540         return Define(name + '_reply', [], block)
541
542     def process(self, objs):
543         s = {}
544         s['defines'] = []
545         s['typedefs'] = []
546         s['imports'] = []
547         s['options'] = {}
548         s['enums'] = []
549         s['services'] = []
550
551         for o in objs:
552             if isinstance(o, Define):
553                 if o.typeonly:
554                     s['typedefs'].append(o)
555                 else:
556                     s['defines'].append(o)
557                     if o.autoreply:
558                         s['defines'].append(self.autoreply_block(o.name))
559             elif isinstance(o, Option):
560                 s['options'][o[1]] = o[2]
561             elif isinstance(o, Enum):
562                 s['enums'].append(o)
563             elif isinstance(o, Typedef):
564                 s['typedefs'].append(o)
565             elif type(o) is list:
566                 for o2 in o:
567                     if isinstance(o2, Service):
568                         s['services'].append(o2)
569
570
571         msgs = {d.name: d for d in s['defines']}
572         svcs = {s.caller: s for s in s['services']}
573         seen_services = {}
574
575         for service in svcs:
576             if service not in msgs:
577                 raise ValueError('Service definition refers to unknown message'
578                                  ' definition: {}'.format(service))
579             if svcs[service].reply != 'null' and svcs[service].reply not in msgs:
580                 raise ValueError('Service definition refers to unknown message'
581                                  ' definition in reply: {}'
582                                  .format(svcs[service].reply))
583             for event in svcs[service].events:
584                 if event not in msgs:
585                     raise ValueError('Service definition refers to unknown '
586                                      'event: {} in message: {}'
587                                      .format(event, service))
588                 seen_services[event] = True
589
590         # Create services implicitly
591         for d in msgs:
592             if d in seen_services:
593                 continue
594             if msgs[d].singular is True:
595                 continue
596             #if d.endswith('_counters'):
597             #    continue
598             #if d.endswith('_event'):
599             #    continue
600             if d.endswith('_reply'):
601                 if d[:-6] in svcs:
602                     continue
603                 if d[:-6] not in msgs:
604                     self.logger.warning('{} missing calling message'
605                                         .format(d))
606                 continue
607             if d.endswith('_dump'):
608                 if d in svcs:
609                     continue
610                 if d[:-5]+'_details' in msgs:
611                     s['services'].append(Service(d, d[:-5]+'_details',
612                                                  stream=True))
613                 else:
614                     self.logger.error('{} missing details message'
615                                       .format(d))
616                 continue
617
618             if d.endswith('_details'):
619                 if d[:-8]+'_dump' not in msgs:
620                     self.logger.error('{} missing dump message'
621                                       .format(d))
622                 continue
623
624             if d in svcs:
625                 continue
626             if d+'_reply' in msgs:
627                 s['services'].append(Service(d, d+'_reply'))
628             else:
629                 self.logger.warning('{} missing reply message ({})'
630                                     .format(d, d+'_reply'))
631                 s['services'].append(Service(d, None))
632
633         return s
634
635     def process_imports(self, objs, in_import):
636         imported_objs = []
637         for o in objs:
638             if isinstance(o, Import):
639                 return objs + self.process_imports(o.result, True)
640             if in_import:
641                 if isinstance(o, Define) and o.typeonly:
642                     imported_objs.append(o)
643         if in_import:
644             return imported_objs
645         return objs
646
647
648 # Add message ids to each message.
649 def add_msg_id(s):
650     for o in s:
651         o.block.insert(0, Field('u16', '_vl_msg_id'))
652     return s
653
654
655 def getcrc(s):
656     return binascii.crc32(str(s)) & 0xffffffff
657
658
659 dirlist = []
660
661
662 def dirlist_add(dirs):
663     global dirlist
664     if dirs:
665         dirlist = dirlist + dirs
666
667
668 def dirlist_get():
669     return dirlist
670
671
672 #
673 # Main
674 #
675 def main():
676     cliparser = argparse.ArgumentParser(description='VPP API generator')
677     cliparser.add_argument('--pluginpath', default=""),
678     cliparser.add_argument('--includedir', action='append'),
679     cliparser.add_argument('--input', type=argparse.FileType('r'),
680                            default=sys.stdin)
681     cliparser.add_argument('--output', nargs='?', type=argparse.FileType('w'),
682                            default=sys.stdout)
683
684     cliparser.add_argument('output_module', nargs='?', default='C')
685     cliparser.add_argument('--debug', action='store_true')
686     cliparser.add_argument('--show-name', nargs=1)
687     args = cliparser.parse_args()
688
689     dirlist_add(args.includedir)
690     if not args.debug:
691         sys.excepthook = exception_handler
692
693     # Filename
694     if args.show_name:
695         filename = args.show_name[0]
696     elif args.input != sys.stdin:
697         filename = args.input.name
698     else:
699         filename = ''
700
701     if args.debug:
702         logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
703     else:
704         logging.basicConfig()
705     log = logging.getLogger('vppapigen')
706
707
708     parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
709     result = parser.parse_file(args.input, log)
710
711     # Build a list of objects. Hash of lists.
712     result = parser.process_imports(result, False)
713     s = parser.process(result)
714
715     # Add msg_id field
716     s['defines'] = add_msg_id(s['defines'])
717
718     file_crc = getcrc(s)
719
720     #
721     # Debug
722     if args.debug:
723         import pprint
724         pp = pprint.PrettyPrinter(indent=4)
725         for t in s['defines']:
726             pp.pprint([t.name, t.flags, t.block])
727         for t in s['typedefs']:
728             pp.pprint([t.name, t.flags, t.block])
729
730     #
731     # Generate representation
732     #
733     import imp
734
735     # Default path
736     pluginpath = ''
737     if not args.pluginpath:
738         cand = []
739         cand.append(os.path.dirname(os.path.realpath(__file__)))
740         cand.append(os.path.dirname(os.path.realpath(__file__)) + \
741                     '/../share/vpp/')
742         for c in cand:
743             c += '/'
744             if os.path.isfile(c + args.output_module + '.py'):
745                 pluginpath = c
746                 break
747     else:
748         pluginpath = args.pluginpath + '/'
749     if pluginpath == '':
750         raise Exception('Output plugin not found')
751     module_path = pluginpath + args.output_module + '.py'
752
753     try:
754         plugin = imp.load_source(args.output_module, module_path)
755     except Exception, err:
756         raise Exception('Error importing output plugin: {}, {}'
757                         .format(module_path, err))
758
759     result = plugin.run(filename, s, file_crc)
760     if result:
761         print (result, file=args.output)
762     else:
763         raise Exception('Running plugin failed: {} {}'
764                         .format(filename, result))
765
766
767 if __name__ == '__main__':
768     main()