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', |
| 44 | 'stream': 'STREAM', |
| 45 | 'events': 'EVENTS', |
| 46 | 'define': 'DEFINE', |
| 47 | 'typedef': 'TYPEDEF', |
| 48 | 'enum': 'ENUM', |
| 49 | 'typeonly': 'TYPEONLY', |
| 50 | 'manual_print': 'MANUAL_PRINT', |
| 51 | 'manual_endian': 'MANUAL_ENDIAN', |
| 52 | 'dont_trace': 'DONT_TRACE', |
| 53 | 'autoreply': 'AUTOREPLY', |
| 54 | 'option': 'OPTION', |
| 55 | 'u8': 'U8', |
| 56 | 'u16': 'U16', |
| 57 | 'u32': 'U32', |
| 58 | 'u64': 'U64', |
| 59 | 'i8': 'I8', |
| 60 | 'i16': 'I16', |
| 61 | 'i32': 'I32', |
| 62 | 'i64': 'I64', |
| 63 | 'f64': 'F64', |
| 64 | 'bool': 'BOOL', |
| 65 | 'string': 'STRING', |
| 66 | 'import': 'IMPORT', |
| 67 | 'true': 'TRUE', |
| 68 | 'false': 'FALSE', |
| 69 | } |
| 70 | |
| 71 | tokens = ['STRING_LITERAL', |
| 72 | 'ID', 'NUM'] + list(reserved.values()) |
| 73 | |
| 74 | t_ignore_LINE_COMMENT = '//.*' |
| 75 | |
| 76 | def t_NUM(self, t): |
| 77 | r'0[xX][0-9a-fA-F]+|\d+' |
| 78 | base = 16 if t.value.startswith('0x') else 10 |
| 79 | t.value = int(t.value, base) |
| 80 | return t |
| 81 | |
| 82 | def t_ID(self, t): |
| 83 | r'[a-zA-Z_][a-zA-Z_0-9]*' |
| 84 | # Check for reserved words |
| 85 | t.type = VPPAPILexer.reserved.get(t.value, 'ID') |
| 86 | return t |
| 87 | |
| 88 | # C string |
| 89 | def t_STRING_LITERAL(self, t): |
| 90 | r'\"([^\\\n]|(\\.))*?\"' |
| 91 | t.value = str(t.value).replace("\"", "") |
| 92 | return t |
| 93 | |
| 94 | # C or C++ comment (ignore) |
| 95 | def t_comment(self, t): |
| 96 | r'(/\*(.|\n)*?\*/)|(//.*)' |
| 97 | t.lexer.lineno += t.value.count('\n') |
| 98 | |
| 99 | # Error handling rule |
| 100 | def t_error(self, t): |
| 101 | raise ParseError("Illegal character '{}' ({})" |
| 102 | "in {}: line {}".format(t.value[0], |
| 103 | hex(ord(t.value[0])), |
| 104 | self.filename, |
| 105 | t.lexer.lineno)) |
| 106 | t.lexer.skip(1) |
| 107 | |
| 108 | # Define a rule so we can track line numbers |
| 109 | def t_newline(self, t): |
| 110 | r'\n+' |
| 111 | t.lexer.lineno += len(t.value) |
| 112 | |
| 113 | literals = ":{}[];=.," |
| 114 | |
| 115 | # A string containing ignored characters (spaces and tabs) |
| 116 | t_ignore = ' \t' |
| 117 | |
| 118 | |
| 119 | class Iterator(type): |
| 120 | def __iter__(self): |
| 121 | return self.iter() |
| 122 | |
| 123 | |
| 124 | class Service(): |
| 125 | def __init__(self, caller, reply, events=[], stream=False): |
| 126 | self.caller = caller |
| 127 | self.reply = reply |
| 128 | self.stream = stream |
| 129 | self.events = events |
| 130 | |
| 131 | |
| 132 | class Typedef(): |
| 133 | def __init__(self, name, flags, block): |
| 134 | self.name = name |
| 135 | self.flags = flags |
| 136 | self.block = block |
| 137 | self.crc = binascii.crc32(str(block)) & 0xffffffff |
| 138 | global_type_add(name) |
| 139 | |
| 140 | def __repr__(self): |
| 141 | return self.name + str(self.flags) + str(self.block) |
| 142 | |
| 143 | |
| 144 | class Define(): |
| 145 | def __init__(self, name, flags, block): |
| 146 | self.name = name |
| 147 | self.flags = flags |
| 148 | self.block = block |
| 149 | self.crc = binascii.crc32(str(block)) & 0xffffffff |
| 150 | self.typeonly = False |
| 151 | self.dont_trace = False |
| 152 | self.manual_print = False |
| 153 | self.manual_endian = False |
| 154 | self.autoreply = False |
| 155 | self.singular = False |
| 156 | for f in flags: |
| 157 | if f == 'typeonly': |
| 158 | self.typeonly = True |
| 159 | global_type_add(name) |
| 160 | elif f == 'dont_trace': |
| 161 | self.dont_trace = True |
| 162 | elif f == 'manual_print': |
| 163 | self.manual_print = True |
| 164 | elif f == 'manual_endian': |
| 165 | self.manual_endian = True |
| 166 | elif f == 'autoreply': |
| 167 | self.autoreply = True |
| 168 | |
| 169 | for b in block: |
| 170 | if isinstance(b, Option): |
| 171 | if b[1] == 'singular' and b[2] == 'true': |
| 172 | self.singular = True |
| 173 | block.remove(b) |
| 174 | |
| 175 | def __repr__(self): |
| 176 | return self.name + str(self.flags) + str(self.block) |
| 177 | |
| 178 | |
| 179 | class Enum(): |
| 180 | def __init__(self, name, block, enumtype='u32'): |
| 181 | self.name = name |
| 182 | self.enumtype = enumtype |
| 183 | count = 0 |
| 184 | for i, b in enumerate(block): |
| 185 | if type(b) is list: |
| 186 | count = b[1] |
| 187 | else: |
| 188 | count += 1 |
| 189 | block[i] = [b, count] |
| 190 | |
| 191 | self.block = block |
| 192 | self.crc = binascii.crc32(str(block)) & 0xffffffff |
| 193 | global_type_add(name) |
| 194 | |
| 195 | def __repr__(self): |
| 196 | return self.name + str(self.block) |
| 197 | |
| 198 | |
| 199 | class Import(): |
| 200 | def __init__(self, filename): |
| 201 | self.filename = filename |
| 202 | |
| 203 | # Deal with imports |
| 204 | parser = VPPAPI(filename=filename) |
| 205 | dirlist = dirlist_get() |
| 206 | f = filename |
| 207 | for dir in dirlist: |
| 208 | f = os.path.join(dir, filename) |
| 209 | if os.path.exists(f): |
| 210 | break |
| 211 | with open(f) as fd: |
| 212 | self.result = parser.parse_file(fd, None) |
| 213 | |
| 214 | def __repr__(self): |
| 215 | return self.filename |
| 216 | |
| 217 | |
| 218 | class Option(): |
| 219 | def __init__(self, option): |
| 220 | self.option = option |
| 221 | self.crc = binascii.crc32(str(option)) & 0xffffffff |
| 222 | |
| 223 | def __repr__(self): |
| 224 | return str(self.option) |
| 225 | |
| 226 | def __getitem__(self, index): |
| 227 | return self.option[index] |
| 228 | |
| 229 | |
| 230 | class Array(): |
| 231 | def __init__(self, fieldtype, name, length): |
| 232 | self.type = 'Array' |
| 233 | self.fieldtype = fieldtype |
| 234 | self.fieldname = name |
| 235 | if type(length) is str: |
| 236 | self.lengthfield = length |
| 237 | self.length = 0 |
| 238 | else: |
| 239 | self.length = length |
| 240 | self.lengthfield = None |
| 241 | |
| 242 | def __repr__(self): |
| 243 | return str([self.fieldtype, self.fieldname, self.length, |
| 244 | self.lengthfield]) |
| 245 | |
| 246 | |
| 247 | class Field(): |
| 248 | def __init__(self, fieldtype, name): |
| 249 | self.type = 'Field' |
| 250 | self.fieldtype = fieldtype |
| 251 | self.fieldname = name |
| 252 | |
| 253 | def __repr__(self): |
| 254 | return str([self.fieldtype, self.fieldname]) |
| 255 | |
| 256 | |
| 257 | class Coord(object): |
| 258 | """ Coordinates of a syntactic element. Consists of: |
| 259 | - File name |
| 260 | - Line number |
| 261 | - (optional) column number, for the Lexer |
| 262 | """ |
| 263 | __slots__ = ('file', 'line', 'column', '__weakref__') |
| 264 | |
| 265 | def __init__(self, file, line, column=None): |
| 266 | self.file = file |
| 267 | self.line = line |
| 268 | self.column = column |
| 269 | |
| 270 | def __str__(self): |
| 271 | str = "%s:%s" % (self.file, self.line) |
| 272 | if self.column: |
| 273 | str += ":%s" % self.column |
| 274 | return str |
| 275 | |
| 276 | |
| 277 | class ParseError(Exception): |
| 278 | pass |
| 279 | |
| 280 | |
| 281 | # |
| 282 | # Grammar rules |
| 283 | # |
| 284 | class VPPAPIParser(object): |
| 285 | tokens = VPPAPILexer.tokens |
| 286 | |
| 287 | def __init__(self, filename, logger): |
| 288 | self.filename = filename |
| 289 | self.logger = logger |
| 290 | self.fields = [] |
| 291 | |
| 292 | def _parse_error(self, msg, coord): |
| 293 | raise ParseError("%s: %s" % (coord, msg)) |
| 294 | |
| 295 | def _parse_warning(self, msg, coord): |
| 296 | if self.logger: |
| 297 | self.logger.warning("%s: %s" % (coord, msg)) |
| 298 | |
| 299 | def _coord(self, lineno, column=None): |
| 300 | return Coord( |
| 301 | file=self.filename, |
| 302 | line=lineno, column=column) |
| 303 | |
| 304 | def _token_coord(self, p, token_idx): |
| 305 | """ Returns the coordinates for the YaccProduction object 'p' indexed |
| 306 | with 'token_idx'. The coordinate includes the 'lineno' and |
| 307 | 'column'. Both follow the lex semantic, starting from 1. |
| 308 | """ |
| 309 | last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx)) |
| 310 | if last_cr < 0: |
| 311 | last_cr = -1 |
| 312 | column = (p.lexpos(token_idx) - (last_cr)) |
| 313 | return self._coord(p.lineno(token_idx), column) |
| 314 | |
| 315 | def p_slist(self, p): |
| 316 | '''slist : stmt |
| 317 | | slist stmt''' |
| 318 | if len(p) == 2: |
| 319 | p[0] = [p[1]] |
| 320 | else: |
| 321 | p[0] = p[1] + [p[2]] |
| 322 | |
| 323 | def p_stmt(self, p): |
| 324 | '''stmt : define |
| 325 | | typedef |
| 326 | | option |
| 327 | | import |
| 328 | | enum |
| 329 | | service''' |
| 330 | p[0] = p[1] |
| 331 | |
| 332 | def p_import(self, p): |
| 333 | '''import : IMPORT STRING_LITERAL ';' ''' |
| 334 | p[0] = Import(p[2]) |
| 335 | |
| 336 | def p_service(self, p): |
| 337 | '''service : SERVICE '{' service_statements '}' ';' ''' |
| 338 | p[0] = p[3] |
| 339 | |
| 340 | def p_service_statements(self, p): |
| 341 | '''service_statements : service_statement |
| 342 | | service_statements service_statement''' |
| 343 | if len(p) == 2: |
| 344 | p[0] = [p[1]] |
| 345 | else: |
| 346 | p[0] = p[1] + [p[2]] |
| 347 | |
| 348 | def p_service_statement(self, p): |
| 349 | '''service_statement : RPC ID RETURNS ID ';' |
| 350 | | RPC ID RETURNS STREAM ID ';' |
| 351 | | RPC ID RETURNS ID EVENTS event_list ';' ''' |
| 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 | # Create services implicitly |
| 575 | msgs = {d.name: d for d in s['defines']} |
| 576 | svcs = {s.caller: s for s in s['services']} |
| 577 | |
| 578 | for service in svcs: |
| 579 | if service not in msgs: |
| 580 | raise ValueError('Service definition refers to unknown message' |
| 581 | ' definition: {}'.format(service)) |
| 582 | if svcs[service].reply not in msgs: |
| 583 | raise ValueError('Service definition refers to unknown message' |
| 584 | ' definition in reply: {}' |
| 585 | .format(svcs[service].reply)) |
| 586 | for event in svcs[service].events: |
| 587 | if event not in msgs: |
| 588 | raise ValueError('Service definition refers to unknown ' |
| 589 | 'event: {} in message: {}' |
| 590 | .format(event, service)) |
| 591 | |
| 592 | for d in msgs: |
| 593 | if msgs[d].singular is True: |
| 594 | continue |
| 595 | if d.endswith('_counters'): |
| 596 | continue |
| 597 | if d.endswith('_reply'): |
| 598 | if d[:-6] in svcs: |
| 599 | continue |
| 600 | if d[:-6] not in msgs: |
| 601 | self.logger.warning('{} missing calling message' |
| 602 | .format(d)) |
| 603 | continue |
| 604 | if d.endswith('_dump'): |
| 605 | if d in svcs: |
| 606 | continue |
| 607 | if d[:-5]+'_details' in msgs: |
| 608 | s['services'].append(Service(d, d[:-5]+'_details', |
| 609 | stream=True)) |
| 610 | else: |
| 611 | self.logger.error('{} missing details message' |
| 612 | .format(d)) |
| 613 | continue |
| 614 | |
| 615 | if d.endswith('_details'): |
| 616 | if d[:-8]+'_dump' not in msgs: |
| 617 | self.logger.error('{} missing dump message' |
| 618 | .format(d)) |
| 619 | continue |
| 620 | |
| 621 | if d in svcs: |
| 622 | continue |
| 623 | if d+'_reply' in msgs: |
| 624 | s['services'].append(Service(d, d+'_reply')) |
| 625 | else: |
| 626 | self.logger.warning('{} missing reply message ({})' |
| 627 | .format(d, d+'_reply')) |
| 628 | s['services'].append(Service(d, None)) |
| 629 | |
| 630 | return s |
| 631 | |
| 632 | def process_imports(self, objs): |
| 633 | for o in objs: |
| 634 | if isinstance(o, Import): |
| 635 | return objs + self.process_imports(o.result) |
| 636 | return objs |
| 637 | |
| 638 | |
| 639 | # Add message ids to each message. |
| 640 | def add_msg_id(s): |
| 641 | for o in s: |
| 642 | o.block.insert(0, Field('u16', '_vl_msg_id')) |
| 643 | return s |
| 644 | |
| 645 | |
| 646 | def getcrc(s): |
| 647 | return binascii.crc32(str(s)) & 0xffffffff |
| 648 | |
| 649 | |
| 650 | dirlist = [] |
| 651 | |
| 652 | |
| 653 | def dirlist_add(dirs): |
| 654 | global dirlist |
| 655 | if dirs: |
| 656 | dirlist = dirlist + dirs |
| 657 | |
| 658 | |
| 659 | def dirlist_get(): |
| 660 | return dirlist |
| 661 | |
| 662 | |
| 663 | # |
| 664 | # Main |
| 665 | # |
| 666 | def main(): |
| 667 | logging.basicConfig() |
| 668 | log = logging.getLogger('vppapigen') |
| 669 | |
| 670 | cliparser = argparse.ArgumentParser(description='VPP API generator') |
| 671 | cliparser.add_argument('--pluginpath', default=""), |
| 672 | cliparser.add_argument('--includedir', action='append'), |
| 673 | cliparser.add_argument('--input', type=argparse.FileType('r'), |
| 674 | default=sys.stdin) |
| 675 | cliparser.add_argument('--output', nargs='?', type=argparse.FileType('w'), |
| 676 | default=sys.stdout) |
| 677 | |
| 678 | cliparser.add_argument('output_module', nargs='?', default='C') |
| 679 | cliparser.add_argument('--debug', action='store_true') |
| 680 | cliparser.add_argument('--show-name', nargs=1) |
| 681 | args = cliparser.parse_args() |
| 682 | |
| 683 | dirlist_add(args.includedir) |
| 684 | if not args.debug: |
| 685 | sys.excepthook = exception_handler |
| 686 | |
| 687 | # Filename |
| 688 | if args.show_name: |
| 689 | filename = args.show_name[0] |
| 690 | elif args.input != sys.stdin: |
| 691 | filename = args.input.name |
| 692 | else: |
| 693 | filename = '' |
| 694 | |
| 695 | parser = VPPAPI(debug=args.debug, filename=filename, logger=log) |
| 696 | result = parser.parse_file(args.input, log) |
| 697 | |
| 698 | # Build a list of objects. Hash of lists. |
| 699 | result = parser.process_imports(result) |
| 700 | s = parser.process(result) |
| 701 | |
| 702 | # Add msg_id field |
| 703 | s['defines'] = add_msg_id(s['defines']) |
| 704 | |
| 705 | file_crc = getcrc(s) |
| 706 | |
| 707 | # |
| 708 | # Debug |
| 709 | if args.debug: |
| 710 | import pprint |
| 711 | pp = pprint.PrettyPrinter(indent=4) |
| 712 | for t in s['defines']: |
| 713 | pp.pprint([t.name, t.flags, t.block]) |
| 714 | for t in s['typedefs']: |
| 715 | pp.pprint([t.name, t.flags, t.block]) |
| 716 | |
| 717 | # |
| 718 | # Generate representation |
| 719 | # |
| 720 | import imp |
| 721 | |
| 722 | # Default path |
| 723 | if not args.pluginpath: |
| 724 | pluginpath = os.path.dirname(os.path.realpath(__file__)) + \ |
| 725 | '/../share/vpp/' |
| 726 | else: |
| 727 | pluginpath = args.pluginpath + '/' |
| 728 | module_path = pluginpath + args.output_module + '.py' |
| 729 | |
| 730 | try: |
| 731 | plugin = imp.load_source(args.output_module, module_path) |
| 732 | except Exception, err: |
| 733 | raise Exception('Error importing output plugin: {}, {}' |
| 734 | .format(module_path, err)) |
| 735 | |
| 736 | result = plugin.run(filename, s, file_crc) |
| 737 | if result: |
| 738 | print (result, file=args.output) |
| 739 | else: |
| 740 | raise Exception('Running plugin failed: {} {}' |
| 741 | .format(filename, result)) |
| 742 | |
| 743 | |
| 744 | if __name__ == '__main__': |
| 745 | main() |