vppapigen: do not allow to define message as both request and reply
[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 p[2] == p[4]:
349             # Verify that caller and reply differ
350             self._parse_error('Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
351                               self._token_coord(p, 1))
352         if len(p) == 8:
353             p[0] = Service(p[2], p[4], p[6])
354         elif len(p) == 7:
355             p[0] = Service(p[2], p[5], stream=True)
356         else:
357             p[0] = Service(p[2], p[4])
358
359     def p_event_list(self, p):
360         '''event_list : events
361                       | event_list events '''
362         if len(p) == 2:
363             p[0] = [p[1]]
364         else:
365             p[0] = p[1] + [p[2]]
366
367     def p_event(self, p):
368         '''events : ID
369                   | ID ',' '''
370         p[0] = p[1]
371
372     def p_enum(self, p):
373         '''enum : ENUM ID '{' enum_statements '}' ';' '''
374         p[0] = Enum(p[2], p[4])
375
376     def p_enum_type(self, p):
377         ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
378         if len(p) == 9:
379             p[0] = Enum(p[2], p[6], enumtype=p[4])
380         else:
381             p[0] = Enum(p[2], p[4])
382
383     def p_enum_size(self, p):
384         ''' enum_size : U8
385                       | U16
386                       | U32 '''
387         p[0] = p[1]
388
389     def p_define(self, p):
390         '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
391         self.fields = []
392         p[0] = Define(p[2], [], p[4])
393
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])
397
398     def p_flist(self, p):
399         '''flist : flag
400                  | flist flag'''
401         if len(p) == 2:
402             p[0] = [p[1]]
403         else:
404             p[0] = p[1] + [p[2]]
405
406     def p_flag(self, p):
407         '''flag : MANUAL_PRINT
408                 | MANUAL_ENDIAN
409                 | DONT_TRACE
410                 | TYPEONLY
411                 | AUTOREPLY'''
412         if len(p) == 1:
413             return
414         p[0] = p[1]
415
416     def p_typedef(self, p):
417         '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
418         p[0] = Typedef(p[2], [], p[4])
419
420     def p_block_statements_opt(self, p):
421         '''block_statements_opt : block_statements'''
422         p[0] = p[1]
423
424     def p_block_statements(self, p):
425         '''block_statements : block_statement
426                             | block_statements block_statement'''
427         if len(p) == 2:
428             p[0] = [p[1]]
429         else:
430             p[0] = p[1] + [p[2]]
431
432     def p_block_statement(self, p):
433         '''block_statement : declaration
434                            | option '''
435         p[0] = p[1]
436
437     def p_enum_statements(self, p):
438         '''enum_statements : enum_statement
439                             | enum_statements enum_statement'''
440         if len(p) == 2:
441             p[0] = [p[1]]
442         else:
443             p[0] = p[1] + [p[2]]
444
445     def p_enum_statement(self, p):
446         '''enum_statement : ID '=' NUM ','
447                           | ID ',' '''
448         if len(p) == 5:
449             p[0] = [p[1], p[3]]
450         else:
451             p[0] = p[1]
452
453     def p_declaration(self, p):
454         '''declaration : type_specifier ID ';' '''
455         if len(p) != 4:
456             self._parse_error('ERROR')
457         self.fields.append(p[2])
458         p[0] = Field(p[1], p[2])
459
460     def p_declaration_array(self, p):
461         '''declaration : type_specifier ID '[' NUM ']' ';'
462                        | type_specifier ID '[' ID ']' ';' '''
463         if len(p) != 7:
464             return self._parse_error(
465                 'array: %s' % p.value,
466                 self._coord(lineno=p.lineno))
467
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))
474
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])
481
482     def p_option(self, p):
483         '''option : OPTION ID '=' assignee ';' '''
484         p[0] = Option([p[1], p[2], p[4]])
485
486     def p_assignee(self, p):
487         '''assignee : NUM
488                     | TRUE
489                     | FALSE
490                     | STRING_LITERAL '''
491         p[0] = p[1]
492
493     def p_type_specifier(self, p):
494         '''type_specifier : U8
495                           | U16
496                           | U32
497                           | U64
498                           | I8
499                           | I16
500                           | I32
501                           | I64
502                           | F64
503                           | BOOL
504                           | STRING'''
505         p[0] = p[1]
506
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))
513         p[0] = p[1]
514
515     # Error rule for syntax errors
516     def p_error(self, p):
517         if p:
518             self._parse_error(
519                 'before: %s' % p.value,
520                 self._coord(lineno=p.lineno))
521         else:
522             self._parse_error('At end of input', self.filename)
523
524
525 class VPPAPI(object):
526
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)
531         self.logger = logger
532
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)
536
537     def parse_file(self, fd, debug=0):
538         data = fd.read()
539         return self.parse_string(data, debug=debug)
540
541     def autoreply_block(self, name):
542         block = [Field('u32', 'context'),
543                  Field('i32', 'retval')]
544         return Define(name + '_reply', [], block)
545
546     def process(self, objs):
547         s = {}
548         s['defines'] = []
549         s['typedefs'] = []
550         s['imports'] = []
551         s['options'] = {}
552         s['enums'] = []
553         s['services'] = []
554
555         for o in objs:
556             if isinstance(o, Define):
557                 if o.typeonly:
558                     s['typedefs'].append(o)
559                 else:
560                     s['defines'].append(o)
561                     if o.autoreply:
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):
566                 s['enums'].append(o)
567             elif isinstance(o, Typedef):
568                 s['typedefs'].append(o)
569             elif type(o) is list:
570                 for o2 in o:
571                     if isinstance(o2, Service):
572                         s['services'].append(o2)
573
574
575         msgs = {d.name: d for d in s['defines']}
576         svcs = {s.caller: s for s in s['services']}
577         replies = {s.reply: s for s in s['services']}
578         seen_services = {}
579
580         for service in svcs:
581             if service not in msgs:
582                 raise ValueError('Service definition refers to unknown message'
583                                  ' definition: {}'.format(service))
584             if svcs[service].reply != 'null' and svcs[service].reply not in msgs:
585                 raise ValueError('Service definition refers to unknown message'
586                                  ' definition in reply: {}'
587                                  .format(svcs[service].reply))
588             if service in replies:
589                 raise ValueError('Service definition refers to message'
590                                  ' marked as reply: {}'.format(service))
591             for event in svcs[service].events:
592                 if event not in msgs:
593                     raise ValueError('Service definition refers to unknown '
594                                      'event: {} in message: {}'
595                                      .format(event, service))
596                 seen_services[event] = True
597
598         # Create services implicitly
599         for d in msgs:
600             if d in seen_services:
601                 continue
602             if msgs[d].singular is True:
603                 continue
604             #if d.endswith('_counters'):
605             #    continue
606             #if d.endswith('_event'):
607             #    continue
608             if d.endswith('_reply'):
609                 if d[:-6] in svcs:
610                     continue
611                 if d[:-6] not in msgs:
612                     self.logger.warning('{} missing calling message'
613                                         .format(d))
614                 continue
615             if d.endswith('_dump'):
616                 if d in svcs:
617                     continue
618                 if d[:-5]+'_details' in msgs:
619                     s['services'].append(Service(d, d[:-5]+'_details',
620                                                  stream=True))
621                 else:
622                     self.logger.error('{} missing details message'
623                                       .format(d))
624                 continue
625
626             if d.endswith('_details'):
627                 if d[:-8]+'_dump' not in msgs:
628                     self.logger.error('{} missing dump message'
629                                       .format(d))
630                 continue
631
632             if d in svcs:
633                 continue
634             if d+'_reply' in msgs:
635                 s['services'].append(Service(d, d+'_reply'))
636             else:
637                 self.logger.warning('{} missing reply message ({})'
638                                     .format(d, d+'_reply'))
639                 s['services'].append(Service(d, None))
640
641         return s
642
643     def process_imports(self, objs, in_import):
644         imported_objs = []
645         for o in objs:
646             if isinstance(o, Import):
647                 return objs + self.process_imports(o.result, True)
648             if in_import:
649                 if isinstance(o, Define) and o.typeonly:
650                     imported_objs.append(o)
651         if in_import:
652             return imported_objs
653         return objs
654
655
656 # Add message ids to each message.
657 def add_msg_id(s):
658     for o in s:
659         o.block.insert(0, Field('u16', '_vl_msg_id'))
660     return s
661
662
663 def getcrc(s):
664     return binascii.crc32(str(s)) & 0xffffffff
665
666
667 dirlist = []
668
669
670 def dirlist_add(dirs):
671     global dirlist
672     if dirs:
673         dirlist = dirlist + dirs
674
675
676 def dirlist_get():
677     return dirlist
678
679
680 #
681 # Main
682 #
683 def main():
684     cliparser = argparse.ArgumentParser(description='VPP API generator')
685     cliparser.add_argument('--pluginpath', default=""),
686     cliparser.add_argument('--includedir', action='append'),
687     cliparser.add_argument('--input', type=argparse.FileType('r'),
688                            default=sys.stdin)
689     cliparser.add_argument('--output', nargs='?', type=argparse.FileType('w'),
690                            default=sys.stdout)
691
692     cliparser.add_argument('output_module', nargs='?', default='C')
693     cliparser.add_argument('--debug', action='store_true')
694     cliparser.add_argument('--show-name', nargs=1)
695     args = cliparser.parse_args()
696
697     dirlist_add(args.includedir)
698     if not args.debug:
699         sys.excepthook = exception_handler
700
701     # Filename
702     if args.show_name:
703         filename = args.show_name[0]
704     elif args.input != sys.stdin:
705         filename = args.input.name
706     else:
707         filename = ''
708
709     if args.debug:
710         logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
711     else:
712         logging.basicConfig()
713     log = logging.getLogger('vppapigen')
714
715
716     parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
717     result = parser.parse_file(args.input, log)
718
719     # Build a list of objects. Hash of lists.
720     result = parser.process_imports(result, False)
721     s = parser.process(result)
722
723     # Add msg_id field
724     s['defines'] = add_msg_id(s['defines'])
725
726     file_crc = getcrc(s)
727
728     #
729     # Debug
730     if args.debug:
731         import pprint
732         pp = pprint.PrettyPrinter(indent=4)
733         for t in s['defines']:
734             pp.pprint([t.name, t.flags, t.block])
735         for t in s['typedefs']:
736             pp.pprint([t.name, t.flags, t.block])
737
738     #
739     # Generate representation
740     #
741     import imp
742
743     # Default path
744     pluginpath = ''
745     if not args.pluginpath:
746         cand = []
747         cand.append(os.path.dirname(os.path.realpath(__file__)))
748         cand.append(os.path.dirname(os.path.realpath(__file__)) + \
749                     '/../share/vpp/')
750         for c in cand:
751             c += '/'
752             if os.path.isfile(c + args.output_module + '.py'):
753                 pluginpath = c
754                 break
755     else:
756         pluginpath = args.pluginpath + '/'
757     if pluginpath == '':
758         raise Exception('Output plugin not found')
759     module_path = pluginpath + args.output_module + '.py'
760
761     try:
762         plugin = imp.load_source(args.output_module, module_path)
763     except Exception, err:
764         raise Exception('Error importing output plugin: {}, {}'
765                         .format(module_path, err))
766
767     result = plugin.run(filename, s, file_crc)
768     if result:
769         print (result, file=args.output)
770     else:
771         raise Exception('Running plugin failed: {} {}'
772                         .format(filename, result))
773
774
775 if __name__ == '__main__':
776     main()