blob: 03362b0e6565161be9898828982e395d83a8fd6c [file] [log] [blame]
Nathan Skrzypczak5c2f9642019-09-09 16:45:06 +02001#!/usr/bin/env python3
Ole Troan9d420872017-10-12 13:06:35 +02002
Ole Troan9d420872017-10-12 13:06:35 +02003import ply.lex as lex
4import ply.yacc as yacc
5import sys
6import argparse
Paul Vinciguerraff47fb62019-08-06 19:58:24 -04007import keyword
Ole Troan9d420872017-10-12 13:06:35 +02008import logging
9import binascii
10import os
Ole Troan33a58172019-09-04 09:12:29 +020011import sys
Ole Troan9d420872017-10-12 13:06:35 +020012
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -040013log = logging.getLogger('vppapigen')
14
Ole Troand6743b12018-03-07 08:40:58 +010015# Ensure we don't leave temporary files around
16sys.dont_write_bytecode = True
17
Ole Troan9d420872017-10-12 13:06:35 +020018#
19# VPP API language
20#
21
22# Global dictionary of new types (including enums)
23global_types = {}
24
Paul Vinciguerra4bf84902019-07-31 00:34:05 -040025seen_imports = {}
26
Ole Troan9d420872017-10-12 13:06:35 +020027
Ole Troan8dbfb432019-04-24 14:31:18 +020028def global_type_add(name, obj):
Ole Troan9d420872017-10-12 13:06:35 +020029 '''Add new type to the dictionary of types '''
30 type_name = 'vl_api_' + name + '_t'
Paul Vinciguerra4bf84902019-07-31 00:34:05 -040031 if type_name in global_types:
32 raise KeyError("Attempted redefinition of {!r} with {!r}.".format(
33 name, obj))
Ole Troan8dbfb432019-04-24 14:31:18 +020034 global_types[type_name] = obj
Ole Troan9d420872017-10-12 13:06:35 +020035
36
37# All your trace are belong to us!
38def exception_handler(exception_type, exception, traceback):
Ole Troan17225df2018-04-11 09:50:03 +020039 print("%s: %s" % (exception_type.__name__, exception))
Ole Troan9d420872017-10-12 13:06:35 +020040
41
42#
43# Lexer
44#
45class VPPAPILexer(object):
46 def __init__(self, filename):
47 self.filename = filename
48
49 reserved = {
50 'service': 'SERVICE',
51 'rpc': 'RPC',
52 'returns': 'RETURNS',
Marek Gradzki51e59682018-03-06 10:05:44 +010053 'null': 'NULL',
Ole Troan9d420872017-10-12 13:06:35 +020054 'stream': 'STREAM',
55 'events': 'EVENTS',
56 'define': 'DEFINE',
57 'typedef': 'TYPEDEF',
58 'enum': 'ENUM',
59 'typeonly': 'TYPEONLY',
60 'manual_print': 'MANUAL_PRINT',
61 'manual_endian': 'MANUAL_ENDIAN',
62 'dont_trace': 'DONT_TRACE',
63 'autoreply': 'AUTOREPLY',
64 'option': 'OPTION',
65 'u8': 'U8',
66 'u16': 'U16',
67 'u32': 'U32',
68 'u64': 'U64',
69 'i8': 'I8',
70 'i16': 'I16',
71 'i32': 'I32',
72 'i64': 'I64',
73 'f64': 'F64',
74 'bool': 'BOOL',
75 'string': 'STRING',
76 'import': 'IMPORT',
77 'true': 'TRUE',
78 'false': 'FALSE',
Ole Troan2c2feab2018-04-24 00:02:37 -040079 'union': 'UNION',
Ole Troan9d420872017-10-12 13:06:35 +020080 }
81
82 tokens = ['STRING_LITERAL',
83 'ID', 'NUM'] + list(reserved.values())
84
85 t_ignore_LINE_COMMENT = '//.*'
86
Ole Troan33a58172019-09-04 09:12:29 +020087 def t_FALSE(self, t):
88 r'false'
89 t.value = False
90 return t
91
92 def t_TRUE(self, t):
93 r'false'
94 t.value = True
95 return t
96
Ole Troan9d420872017-10-12 13:06:35 +020097 def t_NUM(self, t):
Paul Vinciguerra063f3742019-07-02 13:00:58 -040098 r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
Ole Troan9d420872017-10-12 13:06:35 +020099 base = 16 if t.value.startswith('0x') else 10
Paul Vinciguerra063f3742019-07-02 13:00:58 -0400100 if '.' in t.value:
101 t.value = float(t.value)
102 else:
103 t.value = int(t.value, base)
Ole Troan9d420872017-10-12 13:06:35 +0200104 return t
105
106 def t_ID(self, t):
107 r'[a-zA-Z_][a-zA-Z_0-9]*'
108 # Check for reserved words
109 t.type = VPPAPILexer.reserved.get(t.value, 'ID')
110 return t
111
112 # C string
113 def t_STRING_LITERAL(self, t):
114 r'\"([^\\\n]|(\\.))*?\"'
115 t.value = str(t.value).replace("\"", "")
116 return t
117
118 # C or C++ comment (ignore)
119 def t_comment(self, t):
120 r'(/\*(.|\n)*?\*/)|(//.*)'
121 t.lexer.lineno += t.value.count('\n')
122
123 # Error handling rule
124 def t_error(self, t):
125 raise ParseError("Illegal character '{}' ({})"
126 "in {}: line {}".format(t.value[0],
127 hex(ord(t.value[0])),
128 self.filename,
129 t.lexer.lineno))
130 t.lexer.skip(1)
131
132 # Define a rule so we can track line numbers
133 def t_newline(self, t):
134 r'\n+'
135 t.lexer.lineno += len(t.value)
136
137 literals = ":{}[];=.,"
138
139 # A string containing ignored characters (spaces and tabs)
140 t_ignore = ' \t'
141
Ole Troan17225df2018-04-11 09:50:03 +0200142
Ole Troan8dbfb432019-04-24 14:31:18 +0200143def crc_block_combine(block, crc):
Ole Troan58914252018-10-23 10:50:07 +0200144 s = str(block).encode()
Ole Troan8dbfb432019-04-24 14:31:18 +0200145 return binascii.crc32(s, crc) & 0xffffffff
Ole Troan58914252018-10-23 10:50:07 +0200146
Paul Vinciguerra063f3742019-07-02 13:00:58 -0400147
Ole Troand5a78a52019-09-18 12:12:47 +0200148def vla_is_last_check(name, block):
149 vla = False
150 for i, b in enumerate(block):
151 if isinstance(b, Array) and b.vla:
152 vla = True
153 if i + 1 < len(block):
154 raise ValueError(
155 'VLA field "{}" must be the last field in message "{}"'
156 .format(b.fieldname, name))
157 elif b.fieldtype.startswith('vl_api_'):
158 if global_types[b.fieldtype].vla:
159 vla = True
160 if i + 1 < len(block):
161 raise ValueError(
162 'VLA field "{}" must be the last '
163 'field in message "{}"'
164 .format(b.fieldname, name))
165 elif b.fieldtype == 'string' and b.length == 0:
166 vla = True
167 if i + 1 < len(block):
168 raise ValueError(
169 'VLA field "{}" must be the last '
170 'field in message "{}"'
171 .format(b.fieldname, name))
172 return vla
173
174
Ole Troan9d420872017-10-12 13:06:35 +0200175class Service():
Paul Vinciguerra7e0c48e2019-02-01 19:37:45 -0800176 def __init__(self, caller, reply, events=None, stream=False):
Ole Troan9d420872017-10-12 13:06:35 +0200177 self.caller = caller
178 self.reply = reply
179 self.stream = stream
Paul Vinciguerra7e0c48e2019-02-01 19:37:45 -0800180 self.events = [] if events is None else events
Ole Troan9d420872017-10-12 13:06:35 +0200181
182
183class Typedef():
184 def __init__(self, name, flags, block):
185 self.name = name
186 self.flags = flags
187 self.block = block
Ole Troan8dbfb432019-04-24 14:31:18 +0200188 self.crc = str(block).encode()
Ole Troan2c2feab2018-04-24 00:02:37 -0400189 self.manual_print = False
190 self.manual_endian = False
191 for f in flags:
192 if f == 'manual_print':
193 self.manual_print = True
194 elif f == 'manual_endian':
195 self.manual_endian = True
Ole Troan33a58172019-09-04 09:12:29 +0200196
Ole Troan8dbfb432019-04-24 14:31:18 +0200197 global_type_add(name, self)
Ole Troan9d420872017-10-12 13:06:35 +0200198
Ole Troand5a78a52019-09-18 12:12:47 +0200199 self.vla = vla_is_last_check(name, block)
Ole Troane5ff5a32019-08-23 22:55:18 +0200200
Ole Troan9d420872017-10-12 13:06:35 +0200201 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200202 return self.name + str(self.flags) + str(self.block)
Ole Troan9d420872017-10-12 13:06:35 +0200203
204
Ole Troan53fffa12018-11-13 12:36:56 +0100205class Using():
Ole Troan33a58172019-09-04 09:12:29 +0200206 def __init__(self, name, flags, alias):
Ole Troan53fffa12018-11-13 12:36:56 +0100207 self.name = name
Ole Troane5ff5a32019-08-23 22:55:18 +0200208 self.vla = False
Ole Troan53fffa12018-11-13 12:36:56 +0100209
Ole Troan33a58172019-09-04 09:12:29 +0200210 self.manual_print = False
211 self.manual_endian = False
212 for f in flags:
213 if f == 'manual_print':
214 self.manual_print = True
215 elif f == 'manual_endian':
216 self.manual_endian = True
217
Ole Troan53fffa12018-11-13 12:36:56 +0100218 if isinstance(alias, Array):
Ole Troane5ff5a32019-08-23 22:55:18 +0200219 a = {'type': alias.fieldtype,
220 'length': alias.length}
Ole Troan53fffa12018-11-13 12:36:56 +0100221 else:
Ole Troane5ff5a32019-08-23 22:55:18 +0200222 a = {'type': alias.fieldtype}
Ole Troan53fffa12018-11-13 12:36:56 +0100223 self.alias = a
Ole Troan8dbfb432019-04-24 14:31:18 +0200224 self.crc = str(alias).encode()
225 global_type_add(name, self)
Ole Troan53fffa12018-11-13 12:36:56 +0100226
227 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200228 return self.name + str(self.alias)
Ole Troan53fffa12018-11-13 12:36:56 +0100229
230
Ole Troan2c2feab2018-04-24 00:02:37 -0400231class Union():
Ole Troan33a58172019-09-04 09:12:29 +0200232 def __init__(self, name, flags, block):
Ole Troan2c2feab2018-04-24 00:02:37 -0400233 self.type = 'Union'
234 self.manual_print = False
235 self.manual_endian = False
Ole Troan2c2feab2018-04-24 00:02:37 -0400236 self.name = name
Ole Troan33a58172019-09-04 09:12:29 +0200237
Ole Troan33a58172019-09-04 09:12:29 +0200238 for f in flags:
239 if f == 'manual_print':
240 self.manual_print = True
241 elif f == 'manual_endian':
242 self.manual_endian = True
243
Ole Troan2c2feab2018-04-24 00:02:37 -0400244 self.block = block
Ole Troan8dbfb432019-04-24 14:31:18 +0200245 self.crc = str(block).encode()
Ole Troand5a78a52019-09-18 12:12:47 +0200246 self.vla = vla_is_last_check(name, block)
247
Ole Troan8dbfb432019-04-24 14:31:18 +0200248 global_type_add(name, self)
Ole Troan2c2feab2018-04-24 00:02:37 -0400249
250 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200251 return str(self.block)
Ole Troan2c2feab2018-04-24 00:02:37 -0400252
253
Ole Troan9d420872017-10-12 13:06:35 +0200254class Define():
255 def __init__(self, name, flags, block):
256 self.name = name
257 self.flags = flags
258 self.block = block
Ole Troan8dbfb432019-04-24 14:31:18 +0200259 self.crc = str(block).encode()
Ole Troan9d420872017-10-12 13:06:35 +0200260 self.dont_trace = False
261 self.manual_print = False
262 self.manual_endian = False
263 self.autoreply = False
264 self.singular = False
265 for f in flags:
Ole Troan2c2feab2018-04-24 00:02:37 -0400266 if f == 'dont_trace':
Ole Troan9d420872017-10-12 13:06:35 +0200267 self.dont_trace = True
268 elif f == 'manual_print':
269 self.manual_print = True
270 elif f == 'manual_endian':
271 self.manual_endian = True
272 elif f == 'autoreply':
273 self.autoreply = True
274
Ole Troand5a78a52019-09-18 12:12:47 +0200275 for b in block:
Ole Troan9d420872017-10-12 13:06:35 +0200276 if isinstance(b, Option):
277 if b[1] == 'singular' and b[2] == 'true':
278 self.singular = True
279 block.remove(b)
Ole Troand5a78a52019-09-18 12:12:47 +0200280 self.vla = vla_is_last_check(name, block)
Ole Troane5ff5a32019-08-23 22:55:18 +0200281
Ole Troan9d420872017-10-12 13:06:35 +0200282 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200283 return self.name + str(self.flags) + str(self.block)
Ole Troan9d420872017-10-12 13:06:35 +0200284
285
286class Enum():
287 def __init__(self, name, block, enumtype='u32'):
288 self.name = name
289 self.enumtype = enumtype
Ole Troane5ff5a32019-08-23 22:55:18 +0200290 self.vla = False
Ole Troan2c2feab2018-04-24 00:02:37 -0400291
Ole Troan9d420872017-10-12 13:06:35 +0200292 count = 0
293 for i, b in enumerate(block):
294 if type(b) is list:
295 count = b[1]
296 else:
297 count += 1
298 block[i] = [b, count]
299
300 self.block = block
Ole Troan8dbfb432019-04-24 14:31:18 +0200301 self.crc = str(block).encode()
302 global_type_add(name, self)
Ole Troan9d420872017-10-12 13:06:35 +0200303
304 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200305 return self.name + str(self.block)
Ole Troan9d420872017-10-12 13:06:35 +0200306
307
308class Import():
Paul Vinciguerra4bf84902019-07-31 00:34:05 -0400309
310 def __new__(cls, *args, **kwargs):
311 if args[0] not in seen_imports:
312 instance = super().__new__(cls)
313 instance._initialized = False
314 seen_imports[args[0]] = instance
315
316 return seen_imports[args[0]]
317
Ole Troan9d420872017-10-12 13:06:35 +0200318 def __init__(self, filename):
Paul Vinciguerra4bf84902019-07-31 00:34:05 -0400319 if self._initialized:
320 return
321 else:
322 self.filename = filename
323 # Deal with imports
324 parser = VPPAPI(filename=filename)
325 dirlist = dirlist_get()
326 f = filename
327 for dir in dirlist:
328 f = os.path.join(dir, filename)
329 if os.path.exists(f):
330 break
331 if sys.version[0] == '2':
332 with open(f) as fd:
333 self.result = parser.parse_file(fd, None)
334 else:
335 with open(f, encoding='utf-8') as fd:
336 self.result = parser.parse_file(fd, None)
337 self._initialized = True
Ole Troan9d420872017-10-12 13:06:35 +0200338
339 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200340 return self.filename
Ole Troan9d420872017-10-12 13:06:35 +0200341
342
343class Option():
Ole Troan33a58172019-09-04 09:12:29 +0200344 def __init__(self, option, value):
345 self.type = 'Option'
Ole Troan9d420872017-10-12 13:06:35 +0200346 self.option = option
Ole Troan33a58172019-09-04 09:12:29 +0200347 self.value = value
Ole Troan8dbfb432019-04-24 14:31:18 +0200348 self.crc = str(option).encode()
Ole Troan9d420872017-10-12 13:06:35 +0200349
350 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200351 return str(self.option)
Ole Troan9d420872017-10-12 13:06:35 +0200352
353 def __getitem__(self, index):
354 return self.option[index]
355
356
357class Array():
Ole Troane5ff5a32019-08-23 22:55:18 +0200358 def __init__(self, fieldtype, name, length, modern_vla=False):
Ole Troan9d420872017-10-12 13:06:35 +0200359 self.type = 'Array'
360 self.fieldtype = fieldtype
361 self.fieldname = name
Ole Troane5ff5a32019-08-23 22:55:18 +0200362 self.modern_vla = modern_vla
Ole Troan9d420872017-10-12 13:06:35 +0200363 if type(length) is str:
364 self.lengthfield = length
365 self.length = 0
Ole Troane5ff5a32019-08-23 22:55:18 +0200366 self.vla = True
Ole Troan9d420872017-10-12 13:06:35 +0200367 else:
368 self.length = length
369 self.lengthfield = None
Ole Troane5ff5a32019-08-23 22:55:18 +0200370 self.vla = False
Ole Troan9d420872017-10-12 13:06:35 +0200371
372 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200373 return str([self.fieldtype, self.fieldname, self.length,
374 self.lengthfield])
Ole Troan9d420872017-10-12 13:06:35 +0200375
376
377class Field():
Ole Troan9ac11382019-04-23 17:11:01 +0200378 def __init__(self, fieldtype, name, limit=None):
Ole Troan9d420872017-10-12 13:06:35 +0200379 self.type = 'Field'
380 self.fieldtype = fieldtype
Ole Troane5ff5a32019-08-23 22:55:18 +0200381
382 if self.fieldtype == 'string':
383 raise ValueError("The string type {!r} is an "
384 "array type ".format(name))
385
Paul Vinciguerraff47fb62019-08-06 19:58:24 -0400386 if name in keyword.kwlist:
387 raise ValueError("Fieldname {!r} is a python keyword and is not "
388 "accessible via the python API. ".format(name))
Ole Troan9d420872017-10-12 13:06:35 +0200389 self.fieldname = name
Ole Troan9ac11382019-04-23 17:11:01 +0200390 self.limit = limit
Ole Troan9d420872017-10-12 13:06:35 +0200391
392 def __repr__(self):
Vratko Polak7520e172019-08-01 10:31:49 +0200393 return str([self.fieldtype, self.fieldname])
Ole Troan9d420872017-10-12 13:06:35 +0200394
395
396class Coord(object):
397 """ Coordinates of a syntactic element. Consists of:
398 - File name
399 - Line number
400 - (optional) column number, for the Lexer
401 """
402 __slots__ = ('file', 'line', 'column', '__weakref__')
403
404 def __init__(self, file, line, column=None):
405 self.file = file
406 self.line = line
407 self.column = column
408
409 def __str__(self):
410 str = "%s:%s" % (self.file, self.line)
411 if self.column:
412 str += ":%s" % self.column
413 return str
414
415
416class ParseError(Exception):
417 pass
418
419
420#
421# Grammar rules
422#
423class VPPAPIParser(object):
424 tokens = VPPAPILexer.tokens
425
426 def __init__(self, filename, logger):
427 self.filename = filename
428 self.logger = logger
429 self.fields = []
430
431 def _parse_error(self, msg, coord):
432 raise ParseError("%s: %s" % (coord, msg))
433
434 def _parse_warning(self, msg, coord):
435 if self.logger:
436 self.logger.warning("%s: %s" % (coord, msg))
437
438 def _coord(self, lineno, column=None):
439 return Coord(
440 file=self.filename,
441 line=lineno, column=column)
442
443 def _token_coord(self, p, token_idx):
444 """ Returns the coordinates for the YaccProduction object 'p' indexed
445 with 'token_idx'. The coordinate includes the 'lineno' and
446 'column'. Both follow the lex semantic, starting from 1.
447 """
448 last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
449 if last_cr < 0:
450 last_cr = -1
451 column = (p.lexpos(token_idx) - (last_cr))
452 return self._coord(p.lineno(token_idx), column)
453
454 def p_slist(self, p):
455 '''slist : stmt
456 | slist stmt'''
457 if len(p) == 2:
458 p[0] = [p[1]]
459 else:
460 p[0] = p[1] + [p[2]]
461
462 def p_stmt(self, p):
463 '''stmt : define
464 | typedef
465 | option
466 | import
467 | enum
Ole Troan2c2feab2018-04-24 00:02:37 -0400468 | union
Ole Troan9d420872017-10-12 13:06:35 +0200469 | service'''
470 p[0] = p[1]
471
472 def p_import(self, p):
473 '''import : IMPORT STRING_LITERAL ';' '''
474 p[0] = Import(p[2])
475
476 def p_service(self, p):
477 '''service : SERVICE '{' service_statements '}' ';' '''
478 p[0] = p[3]
479
480 def p_service_statements(self, p):
481 '''service_statements : service_statement
482 | service_statements service_statement'''
483 if len(p) == 2:
484 p[0] = [p[1]]
485 else:
486 p[0] = p[1] + [p[2]]
487
488 def p_service_statement(self, p):
Marek Gradzki51e59682018-03-06 10:05:44 +0100489 '''service_statement : RPC ID RETURNS NULL ';'
490 | RPC ID RETURNS ID ';'
Ole Troan9d420872017-10-12 13:06:35 +0200491 | RPC ID RETURNS STREAM ID ';'
492 | RPC ID RETURNS ID EVENTS event_list ';' '''
Marek Gradzkifc70e3a2018-03-06 10:56:26 +0100493 if p[2] == p[4]:
494 # Verify that caller and reply differ
Ole Troan17225df2018-04-11 09:50:03 +0200495 self._parse_error(
496 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
497 self._token_coord(p, 1))
Ole Troan9d420872017-10-12 13:06:35 +0200498 if len(p) == 8:
499 p[0] = Service(p[2], p[4], p[6])
500 elif len(p) == 7:
501 p[0] = Service(p[2], p[5], stream=True)
502 else:
503 p[0] = Service(p[2], p[4])
504
505 def p_event_list(self, p):
506 '''event_list : events
507 | event_list events '''
508 if len(p) == 2:
509 p[0] = [p[1]]
510 else:
511 p[0] = p[1] + [p[2]]
512
513 def p_event(self, p):
514 '''events : ID
515 | ID ',' '''
516 p[0] = p[1]
517
518 def p_enum(self, p):
519 '''enum : ENUM ID '{' enum_statements '}' ';' '''
520 p[0] = Enum(p[2], p[4])
521
522 def p_enum_type(self, p):
523 ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
524 if len(p) == 9:
525 p[0] = Enum(p[2], p[6], enumtype=p[4])
526 else:
527 p[0] = Enum(p[2], p[4])
528
529 def p_enum_size(self, p):
530 ''' enum_size : U8
531 | U16
532 | U32 '''
533 p[0] = p[1]
534
535 def p_define(self, p):
536 '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
537 self.fields = []
538 p[0] = Define(p[2], [], p[4])
539
540 def p_define_flist(self, p):
541 '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
Ole Troan2c2feab2018-04-24 00:02:37 -0400542 # Legacy typedef
543 if 'typeonly' in p[1]:
Paul Vinciguerrae7174822019-08-07 00:05:59 -0400544 self._parse_error('legacy typedef. use typedef: {} {}[{}];'
545 .format(p[1], p[2], p[4]),
546 self._token_coord(p, 1))
Ole Troan2c2feab2018-04-24 00:02:37 -0400547 else:
548 p[0] = Define(p[3], p[1], p[5])
Ole Troan9d420872017-10-12 13:06:35 +0200549
550 def p_flist(self, p):
551 '''flist : flag
552 | flist flag'''
553 if len(p) == 2:
554 p[0] = [p[1]]
555 else:
556 p[0] = p[1] + [p[2]]
557
558 def p_flag(self, p):
559 '''flag : MANUAL_PRINT
560 | MANUAL_ENDIAN
561 | DONT_TRACE
562 | TYPEONLY
563 | AUTOREPLY'''
564 if len(p) == 1:
565 return
566 p[0] = p[1]
567
568 def p_typedef(self, p):
569 '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
570 p[0] = Typedef(p[2], [], p[4])
571
Ole Troan33a58172019-09-04 09:12:29 +0200572 def p_typedef_flist(self, p):
573 '''typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';' '''
574 p[0] = Typedef(p[3], p[1], p[5])
575
Ole Troan53fffa12018-11-13 12:36:56 +0100576 def p_typedef_alias(self, p):
577 '''typedef : TYPEDEF declaration '''
Ole Troan33a58172019-09-04 09:12:29 +0200578 p[0] = Using(p[2].fieldname, [], p[2])
579
580 def p_typedef_alias_flist(self, p):
581 '''typedef : flist TYPEDEF declaration '''
582 p[0] = Using(p[3].fieldname, p[1], p[3])
Ole Troan53fffa12018-11-13 12:36:56 +0100583
Ole Troan9d420872017-10-12 13:06:35 +0200584 def p_block_statements_opt(self, p):
Ole Troan2c2feab2018-04-24 00:02:37 -0400585 '''block_statements_opt : block_statements '''
Ole Troan9d420872017-10-12 13:06:35 +0200586 p[0] = p[1]
587
588 def p_block_statements(self, p):
589 '''block_statements : block_statement
590 | block_statements block_statement'''
591 if len(p) == 2:
592 p[0] = [p[1]]
593 else:
594 p[0] = p[1] + [p[2]]
595
596 def p_block_statement(self, p):
597 '''block_statement : declaration
598 | option '''
599 p[0] = p[1]
600
601 def p_enum_statements(self, p):
602 '''enum_statements : enum_statement
Ole Troan9ac11382019-04-23 17:11:01 +0200603 | enum_statements enum_statement'''
Ole Troan9d420872017-10-12 13:06:35 +0200604 if len(p) == 2:
605 p[0] = [p[1]]
606 else:
607 p[0] = p[1] + [p[2]]
608
609 def p_enum_statement(self, p):
610 '''enum_statement : ID '=' NUM ','
611 | ID ',' '''
612 if len(p) == 5:
613 p[0] = [p[1], p[3]]
614 else:
615 p[0] = p[1]
616
Ole Troan85465582019-04-30 10:04:36 +0200617 def p_field_options(self, p):
618 '''field_options : field_option
619 | field_options field_option'''
620 if len(p) == 2:
621 p[0] = p[1]
622 else:
Ole Troane5ff5a32019-08-23 22:55:18 +0200623 p[0] = {**p[1], **p[2]}
Ole Troan85465582019-04-30 10:04:36 +0200624
625 def p_field_option(self, p):
Ole Troane5ff5a32019-08-23 22:55:18 +0200626 '''field_option : ID
627 | ID '=' assignee ','
Ole Troan85465582019-04-30 10:04:36 +0200628 | ID '=' assignee
Ole Troane5ff5a32019-08-23 22:55:18 +0200629
Ole Troan85465582019-04-30 10:04:36 +0200630 '''
Ole Troane5ff5a32019-08-23 22:55:18 +0200631 if len(p) == 2:
632 p[0] = {p[1]: None}
633 else:
634 p[0] = {p[1]: p[3]}
Ole Troan85465582019-04-30 10:04:36 +0200635
Ole Troan9d420872017-10-12 13:06:35 +0200636 def p_declaration(self, p):
Ole Troan9ac11382019-04-23 17:11:01 +0200637 '''declaration : type_specifier ID ';'
Ole Troan85465582019-04-30 10:04:36 +0200638 | type_specifier ID '[' field_options ']' ';' '''
639 if len(p) == 7:
640 p[0] = Field(p[1], p[2], p[4])
Ole Troan9ac11382019-04-23 17:11:01 +0200641 elif len(p) == 4:
642 p[0] = Field(p[1], p[2])
643 else:
Ole Troan9d420872017-10-12 13:06:35 +0200644 self._parse_error('ERROR')
645 self.fields.append(p[2])
Ole Troan9ac11382019-04-23 17:11:01 +0200646
Ole Troane5ff5a32019-08-23 22:55:18 +0200647 def p_declaration_array_vla(self, p):
648 '''declaration : type_specifier ID '[' ']' ';' '''
649 p[0] = Array(p[1], p[2], 0, modern_vla=True)
650
Ole Troan9d420872017-10-12 13:06:35 +0200651 def p_declaration_array(self, p):
652 '''declaration : type_specifier ID '[' NUM ']' ';'
653 | type_specifier ID '[' ID ']' ';' '''
Ole Troane5ff5a32019-08-23 22:55:18 +0200654
Ole Troan9d420872017-10-12 13:06:35 +0200655 if len(p) != 7:
656 return self._parse_error(
657 'array: %s' % p.value,
658 self._coord(lineno=p.lineno))
659
660 # Make this error later
661 if type(p[4]) is int and p[4] == 0:
662 # XXX: Line number is wrong
663 self._parse_warning('Old Style VLA: {} {}[{}];'
664 .format(p[1], p[2], p[4]),
665 self._token_coord(p, 1))
666
667 if type(p[4]) is str and p[4] not in self.fields:
668 # Verify that length field exists
669 self._parse_error('Missing length field: {} {}[{}];'
670 .format(p[1], p[2], p[4]),
671 self._token_coord(p, 1))
672 p[0] = Array(p[1], p[2], p[4])
673
674 def p_option(self, p):
675 '''option : OPTION ID '=' assignee ';' '''
Ole Troan33a58172019-09-04 09:12:29 +0200676 p[0] = Option(p[2], p[4])
Ole Troan9d420872017-10-12 13:06:35 +0200677
678 def p_assignee(self, p):
679 '''assignee : NUM
680 | TRUE
681 | FALSE
682 | STRING_LITERAL '''
683 p[0] = p[1]
684
685 def p_type_specifier(self, p):
686 '''type_specifier : U8
687 | U16
688 | U32
689 | U64
690 | I8
691 | I16
692 | I32
693 | I64
694 | F64
695 | BOOL
696 | STRING'''
697 p[0] = p[1]
698
699 # Do a second pass later to verify that user defined types are defined
700 def p_typedef_specifier(self, p):
701 '''type_specifier : ID '''
702 if p[1] not in global_types:
703 self._parse_error('Undefined type: {}'.format(p[1]),
704 self._token_coord(p, 1))
705 p[0] = p[1]
706
Ole Troan2c2feab2018-04-24 00:02:37 -0400707 def p_union(self, p):
708 '''union : UNION ID '{' block_statements_opt '}' ';' '''
Ole Troan33a58172019-09-04 09:12:29 +0200709 p[0] = Union(p[2], [], p[4])
710
711 def p_union_flist(self, p):
712 '''union : flist UNION ID '{' block_statements_opt '}' ';' '''
713 p[0] = Union(p[3], p[1], p[5])
Ole Troan2c2feab2018-04-24 00:02:37 -0400714
Ole Troan9d420872017-10-12 13:06:35 +0200715 # Error rule for syntax errors
716 def p_error(self, p):
717 if p:
718 self._parse_error(
719 'before: %s' % p.value,
720 self._coord(lineno=p.lineno))
721 else:
722 self._parse_error('At end of input', self.filename)
723
724
725class VPPAPI(object):
726
727 def __init__(self, debug=False, filename='', logger=None):
728 self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
729 self.parser = yacc.yacc(module=VPPAPIParser(filename, logger),
Ole Troand6743b12018-03-07 08:40:58 +0100730 write_tables=False, debug=debug)
Ole Troan9d420872017-10-12 13:06:35 +0200731 self.logger = logger
732
733 def parse_string(self, code, debug=0, lineno=1):
734 self.lexer.lineno = lineno
735 return self.parser.parse(code, lexer=self.lexer, debug=debug)
736
737 def parse_file(self, fd, debug=0):
738 data = fd.read()
739 return self.parse_string(data, debug=debug)
740
741 def autoreply_block(self, name):
742 block = [Field('u32', 'context'),
743 Field('i32', 'retval')]
744 return Define(name + '_reply', [], block)
745
746 def process(self, objs):
747 s = {}
Ole Troan2c2feab2018-04-24 00:02:37 -0400748 s['Option'] = {}
749 s['Define'] = []
750 s['Service'] = []
751 s['types'] = []
752 s['Import'] = []
Ole Troan53fffa12018-11-13 12:36:56 +0100753 s['Alias'] = {}
Ole Troan8dbfb432019-04-24 14:31:18 +0200754 crc = 0
Ole Troan9d420872017-10-12 13:06:35 +0200755 for o in objs:
Ole Troan2c2feab2018-04-24 00:02:37 -0400756 tname = o.__class__.__name__
Ole Troan8dbfb432019-04-24 14:31:18 +0200757 try:
758 crc = binascii.crc32(o.crc, crc)
759 except AttributeError:
760 pass
Ole Troan9d420872017-10-12 13:06:35 +0200761 if isinstance(o, Define):
Ole Troan2c2feab2018-04-24 00:02:37 -0400762 s[tname].append(o)
763 if o.autoreply:
764 s[tname].append(self.autoreply_block(o.name))
Ole Troan9d420872017-10-12 13:06:35 +0200765 elif isinstance(o, Option):
Ole Troan2c2feab2018-04-24 00:02:37 -0400766 s[tname][o[1]] = o[2]
Ole Troan9d420872017-10-12 13:06:35 +0200767 elif type(o) is list:
768 for o2 in o:
769 if isinstance(o2, Service):
Ole Troan2c2feab2018-04-24 00:02:37 -0400770 s['Service'].append(o2)
Ole Troan58914252018-10-23 10:50:07 +0200771 elif (isinstance(o, Enum) or
772 isinstance(o, Typedef) or
773 isinstance(o, Union)):
Ole Troan2c2feab2018-04-24 00:02:37 -0400774 s['types'].append(o)
Ole Troan53fffa12018-11-13 12:36:56 +0100775 elif isinstance(o, Using):
Ole Troan33a58172019-09-04 09:12:29 +0200776 s['Alias'][o.name] = o
Ole Troan2c2feab2018-04-24 00:02:37 -0400777 else:
778 if tname not in s:
Ole Troan58914252018-10-23 10:50:07 +0200779 raise ValueError('Unknown class type: {} {}'
780 .format(tname, o))
Ole Troan2c2feab2018-04-24 00:02:37 -0400781 s[tname].append(o)
Ole Troan9d420872017-10-12 13:06:35 +0200782
Ole Troan2c2feab2018-04-24 00:02:37 -0400783 msgs = {d.name: d for d in s['Define']}
784 svcs = {s.caller: s for s in s['Service']}
785 replies = {s.reply: s for s in s['Service']}
Marek Gradzki51e59682018-03-06 10:05:44 +0100786 seen_services = {}
Ole Troan9d420872017-10-12 13:06:35 +0200787
Ole Troan8dbfb432019-04-24 14:31:18 +0200788 s['file_crc'] = crc
789
Ole Troan9d420872017-10-12 13:06:35 +0200790 for service in svcs:
791 if service not in msgs:
Ole Troan17225df2018-04-11 09:50:03 +0200792 raise ValueError(
793 'Service definition refers to unknown message'
794 ' definition: {}'.format(service))
795 if svcs[service].reply != 'null' and \
796 svcs[service].reply not in msgs:
Ole Troan9d420872017-10-12 13:06:35 +0200797 raise ValueError('Service definition refers to unknown message'
798 ' definition in reply: {}'
799 .format(svcs[service].reply))
Marek Gradzkib533f3f2018-03-06 11:10:56 +0100800 if service in replies:
801 raise ValueError('Service definition refers to message'
802 ' marked as reply: {}'.format(service))
Ole Troan9d420872017-10-12 13:06:35 +0200803 for event in svcs[service].events:
804 if event not in msgs:
805 raise ValueError('Service definition refers to unknown '
806 'event: {} in message: {}'
807 .format(event, service))
Marek Gradzki51e59682018-03-06 10:05:44 +0100808 seen_services[event] = True
Ole Troan9d420872017-10-12 13:06:35 +0200809
Marek Gradzki51e59682018-03-06 10:05:44 +0100810 # Create services implicitly
Ole Troan9d420872017-10-12 13:06:35 +0200811 for d in msgs:
Marek Gradzki51e59682018-03-06 10:05:44 +0100812 if d in seen_services:
813 continue
Ole Troan9d420872017-10-12 13:06:35 +0200814 if msgs[d].singular is True:
815 continue
Ole Troan9d420872017-10-12 13:06:35 +0200816 if d.endswith('_reply'):
817 if d[:-6] in svcs:
818 continue
819 if d[:-6] not in msgs:
Marek Gradzkicc134712018-03-06 12:25:02 +0100820 raise ValueError('{} missing calling message'
821 .format(d))
Ole Troan9d420872017-10-12 13:06:35 +0200822 continue
823 if d.endswith('_dump'):
824 if d in svcs:
825 continue
826 if d[:-5]+'_details' in msgs:
Ole Troan2c2feab2018-04-24 00:02:37 -0400827 s['Service'].append(Service(d, d[:-5]+'_details',
Ole Troan58914252018-10-23 10:50:07 +0200828 stream=True))
Ole Troan9d420872017-10-12 13:06:35 +0200829 else:
Marek Gradzkicc134712018-03-06 12:25:02 +0100830 raise ValueError('{} missing details message'
831 .format(d))
Ole Troan9d420872017-10-12 13:06:35 +0200832 continue
833
834 if d.endswith('_details'):
835 if d[:-8]+'_dump' not in msgs:
Marek Gradzkicc134712018-03-06 12:25:02 +0100836 raise ValueError('{} missing dump message'
837 .format(d))
Ole Troan9d420872017-10-12 13:06:35 +0200838 continue
839
840 if d in svcs:
841 continue
842 if d+'_reply' in msgs:
Ole Troan2c2feab2018-04-24 00:02:37 -0400843 s['Service'].append(Service(d, d+'_reply'))
Ole Troan9d420872017-10-12 13:06:35 +0200844 else:
Ole Troan17225df2018-04-11 09:50:03 +0200845 raise ValueError(
846 '{} missing reply message ({}) or service definition'
847 .format(d, d+'_reply'))
Ole Troan9d420872017-10-12 13:06:35 +0200848
849 return s
850
Ole Troan2c2feab2018-04-24 00:02:37 -0400851 def process_imports(self, objs, in_import, result):
Marek Gradzki51e59682018-03-06 10:05:44 +0100852 imported_objs = []
Ole Troan9d420872017-10-12 13:06:35 +0200853 for o in objs:
Ole Troan2c2feab2018-04-24 00:02:37 -0400854 # Only allow the following object types from imported file
855 if in_import and not (isinstance(o, Enum) or
856 isinstance(o, Union) or
Ole Troan10a09892018-06-29 11:32:33 +0200857 isinstance(o, Typedef) or
Ole Troan53fffa12018-11-13 12:36:56 +0100858 isinstance(o, Import) or
859 isinstance(o, Using)):
Ole Troan2c2feab2018-04-24 00:02:37 -0400860 continue
Ole Troan2c2feab2018-04-24 00:02:37 -0400861 if isinstance(o, Import):
Ole Troan33a58172019-09-04 09:12:29 +0200862 result.append(o)
Paul Vinciguerra4bf84902019-07-31 00:34:05 -0400863 result = self.process_imports(o.result, True, result)
Ole Troan10a09892018-06-29 11:32:33 +0200864 else:
865 result.append(o)
Paul Vinciguerra4bf84902019-07-31 00:34:05 -0400866 return result
Ole Troan9d420872017-10-12 13:06:35 +0200867
Ole Troan58914252018-10-23 10:50:07 +0200868
Ole Troan9d420872017-10-12 13:06:35 +0200869# Add message ids to each message.
870def add_msg_id(s):
871 for o in s:
872 o.block.insert(0, Field('u16', '_vl_msg_id'))
873 return s
874
875
Ole Troan9d420872017-10-12 13:06:35 +0200876dirlist = []
877
878
879def dirlist_add(dirs):
880 global dirlist
881 if dirs:
882 dirlist = dirlist + dirs
883
884
885def dirlist_get():
886 return dirlist
887
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -0400888
Ole Troan8dbfb432019-04-24 14:31:18 +0200889def foldup_blocks(block, crc):
890 for b in block:
891 # Look up CRC in user defined types
892 if b.fieldtype.startswith('vl_api_'):
893 # Recursively
894 t = global_types[b.fieldtype]
895 try:
896 crc = crc_block_combine(t.block, crc)
897 return foldup_blocks(t.block, crc)
Ole Troane5ff5a32019-08-23 22:55:18 +0200898 except AttributeError:
Ole Troan8dbfb432019-04-24 14:31:18 +0200899 pass
900 return crc
901
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -0400902
Ole Troan8dbfb432019-04-24 14:31:18 +0200903def foldup_crcs(s):
904 for f in s:
905 f.crc = foldup_blocks(f.block,
906 binascii.crc32(f.crc))
Ole Troan9d420872017-10-12 13:06:35 +0200907
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -0400908
Ole Troan9d420872017-10-12 13:06:35 +0200909#
910# Main
911#
912def main():
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -0400913 if sys.version_info < (3, 5,):
914 log.exception('vppapigen requires a supported version of python. '
915 'Please use version 3.5 or greater. '
916 'Using {}'.format(sys.version))
917 return 1
918
Ole Troan9d420872017-10-12 13:06:35 +0200919 cliparser = argparse.ArgumentParser(description='VPP API generator')
920 cliparser.add_argument('--pluginpath', default=""),
921 cliparser.add_argument('--includedir', action='append'),
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -0400922 cliparser.add_argument('--input',
923 type=argparse.FileType('r', encoding='UTF-8'),
924 default=sys.stdin)
925 cliparser.add_argument('--output', nargs='?',
926 type=argparse.FileType('w', encoding='UTF-8'),
927 default=sys.stdout)
Ole Troan9d420872017-10-12 13:06:35 +0200928
929 cliparser.add_argument('output_module', nargs='?', default='C')
930 cliparser.add_argument('--debug', action='store_true')
931 cliparser.add_argument('--show-name', nargs=1)
932 args = cliparser.parse_args()
933
934 dirlist_add(args.includedir)
935 if not args.debug:
936 sys.excepthook = exception_handler
937
938 # Filename
939 if args.show_name:
940 filename = args.show_name[0]
941 elif args.input != sys.stdin:
942 filename = args.input.name
943 else:
944 filename = ''
945
Marek Gradzki51e59682018-03-06 10:05:44 +0100946 if args.debug:
947 logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
948 else:
949 logging.basicConfig()
Marek Gradzki51e59682018-03-06 10:05:44 +0100950
Ole Troan9d420872017-10-12 13:06:35 +0200951 parser = VPPAPI(debug=args.debug, filename=filename, logger=log)
Ole Troan2c2feab2018-04-24 00:02:37 -0400952 parsed_objects = parser.parse_file(args.input, log)
Ole Troan9d420872017-10-12 13:06:35 +0200953
954 # Build a list of objects. Hash of lists.
Ole Troan2c2feab2018-04-24 00:02:37 -0400955 result = []
Ole Troan33a58172019-09-04 09:12:29 +0200956
957 if args.output_module == 'C':
958 s = parser.process(parsed_objects)
959 else:
Paul Vinciguerra4bf84902019-07-31 00:34:05 -0400960 result = parser.process_imports(parsed_objects, False, result)
Ole Troan33a58172019-09-04 09:12:29 +0200961 s = parser.process(result)
Ole Troan9d420872017-10-12 13:06:35 +0200962
963 # Add msg_id field
Ole Troan2c2feab2018-04-24 00:02:37 -0400964 s['Define'] = add_msg_id(s['Define'])
Ole Troan9d420872017-10-12 13:06:35 +0200965
Ole Troan8dbfb432019-04-24 14:31:18 +0200966 # Fold up CRCs
967 foldup_crcs(s['Define'])
Ole Troan9d420872017-10-12 13:06:35 +0200968
969 #
970 # Debug
971 if args.debug:
972 import pprint
Ole Troan10a09892018-06-29 11:32:33 +0200973 pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
Ole Troan2c2feab2018-04-24 00:02:37 -0400974 for t in s['Define']:
Ole Troan9d420872017-10-12 13:06:35 +0200975 pp.pprint([t.name, t.flags, t.block])
Ole Troan2c2feab2018-04-24 00:02:37 -0400976 for t in s['types']:
977 pp.pprint([t.name, t.block])
Ole Troan9d420872017-10-12 13:06:35 +0200978
979 #
980 # Generate representation
981 #
Paul Vinciguerraf4647ed2019-02-12 12:21:01 -0800982 from importlib.machinery import SourceFileLoader
Ole Troan9d420872017-10-12 13:06:35 +0200983
984 # Default path
Ole Troan30787372018-03-01 13:33:39 +0100985 pluginpath = ''
Ole Troan9d420872017-10-12 13:06:35 +0200986 if not args.pluginpath:
Ole Troan30787372018-03-01 13:33:39 +0100987 cand = []
988 cand.append(os.path.dirname(os.path.realpath(__file__)))
Ole Troan17225df2018-04-11 09:50:03 +0200989 cand.append(os.path.dirname(os.path.realpath(__file__)) +
Ole Troan30787372018-03-01 13:33:39 +0100990 '/../share/vpp/')
991 for c in cand:
992 c += '/'
Ole Troan58914252018-10-23 10:50:07 +0200993 if os.path.isfile('{}vppapigen_{}.py'
994 .format(c, args.output_module.lower())):
Ole Troan30787372018-03-01 13:33:39 +0100995 pluginpath = c
996 break
Ole Troan9d420872017-10-12 13:06:35 +0200997 else:
998 pluginpath = args.pluginpath + '/'
Ole Troan30787372018-03-01 13:33:39 +0100999 if pluginpath == '':
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001000 log.exception('Output plugin not found')
1001 return 1
Ole Troan58914252018-10-23 10:50:07 +02001002 module_path = '{}vppapigen_{}.py'.format(pluginpath,
1003 args.output_module.lower())
Ole Troan9d420872017-10-12 13:06:35 +02001004
1005 try:
Paul Vinciguerraf4647ed2019-02-12 12:21:01 -08001006 plugin = SourceFileLoader(args.output_module,
1007 module_path).load_module()
Ole Troan58914252018-10-23 10:50:07 +02001008 except Exception as err:
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001009 log.exception('Error importing output plugin: {}, {}'
1010 .format(module_path, err))
1011 return 1
Ole Troan9d420872017-10-12 13:06:35 +02001012
Ole Troan8dbfb432019-04-24 14:31:18 +02001013 result = plugin.run(filename, s)
Ole Troan9d420872017-10-12 13:06:35 +02001014 if result:
Ole Troan17225df2018-04-11 09:50:03 +02001015 print(result, file=args.output)
Ole Troan9d420872017-10-12 13:06:35 +02001016 else:
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001017 log.exception('Running plugin failed: {} {}'
1018 .format(filename, result))
1019 return 1
1020 return 0
Ole Troan9d420872017-10-12 13:06:35 +02001021
1022
1023if __name__ == '__main__':
Paul Vinciguerra2cd3cc82019-08-06 22:02:45 -04001024 sys.exit(main())