Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 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', |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 44 | 'null': 'NULL', |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 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 | |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 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): |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 344 | '''service_statement : RPC ID RETURNS NULL ';' |
| 345 | | RPC ID RETURNS ID ';' |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 346 | | RPC ID RETURNS STREAM ID ';' |
| 347 | | RPC ID RETURNS ID EVENTS event_list ';' ''' |
Marek Gradzki | fc70e3a | 2018-03-06 10:56:26 +0100 | [diff] [blame^] | 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)) |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 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 | |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 574 | |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 575 | msgs = {d.name: d for d in s['defines']} |
| 576 | svcs = {s.caller: s for s in s['services']} |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 577 | seen_services = {} |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 578 | |
| 579 | for service in svcs: |
| 580 | if service not in msgs: |
| 581 | raise ValueError('Service definition refers to unknown message' |
| 582 | ' definition: {}'.format(service)) |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 583 | if svcs[service].reply != 'null' and svcs[service].reply not in msgs: |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 584 | raise ValueError('Service definition refers to unknown message' |
| 585 | ' definition in reply: {}' |
| 586 | .format(svcs[service].reply)) |
| 587 | for event in svcs[service].events: |
| 588 | if event not in msgs: |
| 589 | raise ValueError('Service definition refers to unknown ' |
| 590 | 'event: {} in message: {}' |
| 591 | .format(event, service)) |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 592 | seen_services[event] = True |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 593 | |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 594 | # Create services implicitly |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 595 | for d in msgs: |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 596 | if d in seen_services: |
| 597 | continue |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 598 | if msgs[d].singular is True: |
| 599 | continue |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 600 | #if d.endswith('_counters'): |
| 601 | # continue |
| 602 | #if d.endswith('_event'): |
| 603 | # continue |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 604 | if d.endswith('_reply'): |
| 605 | if d[:-6] in svcs: |
| 606 | continue |
| 607 | if d[:-6] not in msgs: |
| 608 | self.logger.warning('{} missing calling message' |
| 609 | .format(d)) |
| 610 | continue |
| 611 | if d.endswith('_dump'): |
| 612 | if d in svcs: |
| 613 | continue |
| 614 | if d[:-5]+'_details' in msgs: |
| 615 | s['services'].append(Service(d, d[:-5]+'_details', |
| 616 | stream=True)) |
| 617 | else: |
| 618 | self.logger.error('{} missing details message' |
| 619 | .format(d)) |
| 620 | continue |
| 621 | |
| 622 | if d.endswith('_details'): |
| 623 | if d[:-8]+'_dump' not in msgs: |
| 624 | self.logger.error('{} missing dump message' |
| 625 | .format(d)) |
| 626 | continue |
| 627 | |
| 628 | if d in svcs: |
| 629 | continue |
| 630 | if d+'_reply' in msgs: |
| 631 | s['services'].append(Service(d, d+'_reply')) |
| 632 | else: |
| 633 | self.logger.warning('{} missing reply message ({})' |
| 634 | .format(d, d+'_reply')) |
| 635 | s['services'].append(Service(d, None)) |
| 636 | |
| 637 | return s |
| 638 | |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 639 | def process_imports(self, objs, in_import): |
| 640 | imported_objs = [] |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 641 | for o in objs: |
| 642 | if isinstance(o, Import): |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 643 | return objs + self.process_imports(o.result, True) |
| 644 | if in_import: |
| 645 | if isinstance(o, Define) and o.typeonly: |
| 646 | imported_objs.append(o) |
| 647 | if in_import: |
| 648 | return imported_objs |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 649 | return objs |
| 650 | |
| 651 | |
| 652 | # Add message ids to each message. |
| 653 | def add_msg_id(s): |
| 654 | for o in s: |
| 655 | o.block.insert(0, Field('u16', '_vl_msg_id')) |
| 656 | return s |
| 657 | |
| 658 | |
| 659 | def getcrc(s): |
| 660 | return binascii.crc32(str(s)) & 0xffffffff |
| 661 | |
| 662 | |
| 663 | dirlist = [] |
| 664 | |
| 665 | |
| 666 | def dirlist_add(dirs): |
| 667 | global dirlist |
| 668 | if dirs: |
| 669 | dirlist = dirlist + dirs |
| 670 | |
| 671 | |
| 672 | def dirlist_get(): |
| 673 | return dirlist |
| 674 | |
| 675 | |
| 676 | # |
| 677 | # Main |
| 678 | # |
| 679 | def main(): |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 680 | cliparser = argparse.ArgumentParser(description='VPP API generator') |
| 681 | cliparser.add_argument('--pluginpath', default=""), |
| 682 | cliparser.add_argument('--includedir', action='append'), |
| 683 | cliparser.add_argument('--input', type=argparse.FileType('r'), |
| 684 | default=sys.stdin) |
| 685 | cliparser.add_argument('--output', nargs='?', type=argparse.FileType('w'), |
| 686 | default=sys.stdout) |
| 687 | |
| 688 | cliparser.add_argument('output_module', nargs='?', default='C') |
| 689 | cliparser.add_argument('--debug', action='store_true') |
| 690 | cliparser.add_argument('--show-name', nargs=1) |
| 691 | args = cliparser.parse_args() |
| 692 | |
| 693 | dirlist_add(args.includedir) |
| 694 | if not args.debug: |
| 695 | sys.excepthook = exception_handler |
| 696 | |
| 697 | # Filename |
| 698 | if args.show_name: |
| 699 | filename = args.show_name[0] |
| 700 | elif args.input != sys.stdin: |
| 701 | filename = args.input.name |
| 702 | else: |
| 703 | filename = '' |
| 704 | |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 705 | if args.debug: |
| 706 | logging.basicConfig(stream=sys.stdout, level=logging.WARNING) |
| 707 | else: |
| 708 | logging.basicConfig() |
| 709 | log = logging.getLogger('vppapigen') |
| 710 | |
| 711 | |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 712 | parser = VPPAPI(debug=args.debug, filename=filename, logger=log) |
| 713 | result = parser.parse_file(args.input, log) |
| 714 | |
| 715 | # Build a list of objects. Hash of lists. |
Marek Gradzki | 51e5968 | 2018-03-06 10:05:44 +0100 | [diff] [blame] | 716 | result = parser.process_imports(result, False) |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 717 | s = parser.process(result) |
| 718 | |
| 719 | # Add msg_id field |
| 720 | s['defines'] = add_msg_id(s['defines']) |
| 721 | |
| 722 | file_crc = getcrc(s) |
| 723 | |
| 724 | # |
| 725 | # Debug |
| 726 | if args.debug: |
| 727 | import pprint |
| 728 | pp = pprint.PrettyPrinter(indent=4) |
| 729 | for t in s['defines']: |
| 730 | pp.pprint([t.name, t.flags, t.block]) |
| 731 | for t in s['typedefs']: |
| 732 | pp.pprint([t.name, t.flags, t.block]) |
| 733 | |
| 734 | # |
| 735 | # Generate representation |
| 736 | # |
| 737 | import imp |
| 738 | |
| 739 | # Default path |
Ole Troan | 3078737 | 2018-03-01 13:33:39 +0100 | [diff] [blame] | 740 | pluginpath = '' |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 741 | if not args.pluginpath: |
Ole Troan | 3078737 | 2018-03-01 13:33:39 +0100 | [diff] [blame] | 742 | cand = [] |
| 743 | cand.append(os.path.dirname(os.path.realpath(__file__))) |
| 744 | cand.append(os.path.dirname(os.path.realpath(__file__)) + \ |
| 745 | '/../share/vpp/') |
| 746 | for c in cand: |
| 747 | c += '/' |
| 748 | if os.path.isfile(c + args.output_module + '.py'): |
| 749 | pluginpath = c |
| 750 | break |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 751 | else: |
| 752 | pluginpath = args.pluginpath + '/' |
Ole Troan | 3078737 | 2018-03-01 13:33:39 +0100 | [diff] [blame] | 753 | if pluginpath == '': |
| 754 | raise Exception('Output plugin not found') |
Ole Troan | 9d42087 | 2017-10-12 13:06:35 +0200 | [diff] [blame] | 755 | module_path = pluginpath + args.output_module + '.py' |
| 756 | |
| 757 | try: |
| 758 | plugin = imp.load_source(args.output_module, module_path) |
| 759 | except Exception, err: |
| 760 | raise Exception('Error importing output plugin: {}, {}' |
| 761 | .format(module_path, err)) |
| 762 | |
| 763 | result = plugin.run(filename, s, file_crc) |
| 764 | if result: |
| 765 | print (result, file=args.output) |
| 766 | else: |
| 767 | raise Exception('Running plugin failed: {} {}' |
| 768 | .format(filename, result)) |
| 769 | |
| 770 | |
| 771 | if __name__ == '__main__': |
| 772 | main() |