1# -*- coding: utf-8 -*- 2# 3# QAPI schema internal representation 4# 5# Copyright (c) 2015-2019 Red Hat Inc. 6# 7# Authors: 8# Markus Armbruster <armbru@redhat.com> 9# Eric Blake <eblake@redhat.com> 10# Marc-André Lureau <marcandre.lureau@redhat.com> 11# 12# This work is licensed under the terms of the GNU GPL, version 2. 13# See the COPYING file in the top-level directory. 14 15# TODO catching name collisions in generated code would be nice 16 17from collections import OrderedDict 18import os 19import re 20from typing import Optional 21 22from .common import ( 23 POINTER_SUFFIX, 24 c_name, 25 cgen_ifcond, 26 docgen_ifcond, 27 gen_endif, 28 gen_if, 29) 30from .error import QAPIError, QAPISemError, QAPISourceError 31from .expr import check_exprs 32from .parser import QAPISchemaParser 33 34 35class QAPISchemaIfCond: 36 def __init__(self, ifcond=None): 37 self.ifcond = ifcond 38 39 def _cgen(self): 40 return cgen_ifcond(self.ifcond) 41 42 def gen_if(self): 43 return gen_if(self._cgen()) 44 45 def gen_endif(self): 46 return gen_endif(self._cgen()) 47 48 def docgen(self): 49 return docgen_ifcond(self.ifcond) 50 51 def is_present(self): 52 return bool(self.ifcond) 53 54 55class QAPISchemaEntity: 56 meta: Optional[str] = None 57 58 def __init__(self, name: str, info, doc, ifcond=None, features=None): 59 assert name is None or isinstance(name, str) 60 for f in features or []: 61 assert isinstance(f, QAPISchemaFeature) 62 f.set_defined_in(name) 63 self.name = name 64 self._module = None 65 # For explicitly defined entities, info points to the (explicit) 66 # definition. For builtins (and their arrays), info is None. 67 # For implicitly defined entities, info points to a place that 68 # triggered the implicit definition (there may be more than one 69 # such place). 70 self.info = info 71 self.doc = doc 72 self._ifcond = ifcond or QAPISchemaIfCond() 73 self.features = features or [] 74 self._checked = False 75 76 def c_name(self): 77 return c_name(self.name) 78 79 def check(self, schema): 80 assert not self._checked 81 seen = {} 82 for f in self.features: 83 f.check_clash(self.info, seen) 84 self._checked = True 85 86 def connect_doc(self, doc=None): 87 doc = doc or self.doc 88 if doc: 89 for f in self.features: 90 doc.connect_feature(f) 91 92 def check_doc(self): 93 if self.doc: 94 self.doc.check() 95 96 def _set_module(self, schema, info): 97 assert self._checked 98 fname = info.fname if info else QAPISchemaModule.BUILTIN_MODULE_NAME 99 self._module = schema.module_by_fname(fname) 100 self._module.add_entity(self) 101 102 def set_module(self, schema): 103 self._set_module(schema, self.info) 104 105 @property 106 def ifcond(self): 107 assert self._checked 108 return self._ifcond 109 110 def is_implicit(self): 111 return not self.info 112 113 def visit(self, visitor): 114 assert self._checked 115 116 def describe(self): 117 assert self.meta 118 return "%s '%s'" % (self.meta, self.name) 119 120 121class QAPISchemaVisitor: 122 def visit_begin(self, schema): 123 pass 124 125 def visit_end(self): 126 pass 127 128 def visit_module(self, name): 129 pass 130 131 def visit_needed(self, entity): 132 # Default to visiting everything 133 return True 134 135 def visit_include(self, name, info): 136 pass 137 138 def visit_builtin_type(self, name, info, json_type): 139 pass 140 141 def visit_enum_type(self, name, info, ifcond, features, members, prefix): 142 pass 143 144 def visit_array_type(self, name, info, ifcond, element_type): 145 pass 146 147 def visit_object_type(self, name, info, ifcond, features, 148 base, members, variants): 149 pass 150 151 def visit_object_type_flat(self, name, info, ifcond, features, 152 members, variants): 153 pass 154 155 def visit_alternate_type(self, name, info, ifcond, features, variants): 156 pass 157 158 def visit_command(self, name, info, ifcond, features, 159 arg_type, ret_type, gen, success_response, boxed, 160 allow_oob, allow_preconfig, coroutine): 161 pass 162 163 def visit_event(self, name, info, ifcond, features, arg_type, boxed): 164 pass 165 166 167class QAPISchemaModule: 168 169 BUILTIN_MODULE_NAME = './builtin' 170 171 def __init__(self, name): 172 self.name = name 173 self._entity_list = [] 174 175 @staticmethod 176 def is_system_module(name: str) -> bool: 177 """ 178 System modules are internally defined modules. 179 180 Their names start with the "./" prefix. 181 """ 182 return name.startswith('./') 183 184 @classmethod 185 def is_user_module(cls, name: str) -> bool: 186 """ 187 User modules are those defined by the user in qapi JSON files. 188 189 They do not start with the "./" prefix. 190 """ 191 return not cls.is_system_module(name) 192 193 @classmethod 194 def is_builtin_module(cls, name: str) -> bool: 195 """ 196 The built-in module is a single System module for the built-in types. 197 198 It is always "./builtin". 199 """ 200 return name == cls.BUILTIN_MODULE_NAME 201 202 def add_entity(self, ent): 203 self._entity_list.append(ent) 204 205 def visit(self, visitor): 206 visitor.visit_module(self.name) 207 for entity in self._entity_list: 208 if visitor.visit_needed(entity): 209 entity.visit(visitor) 210 211 212class QAPISchemaInclude(QAPISchemaEntity): 213 def __init__(self, sub_module, info): 214 super().__init__(None, info, None) 215 self._sub_module = sub_module 216 217 def visit(self, visitor): 218 super().visit(visitor) 219 visitor.visit_include(self._sub_module.name, self.info) 220 221 222class QAPISchemaType(QAPISchemaEntity): 223 # Return the C type for common use. 224 # For the types we commonly box, this is a pointer type. 225 def c_type(self): 226 pass 227 228 # Return the C type to be used in a parameter list. 229 def c_param_type(self): 230 return self.c_type() 231 232 # Return the C type to be used where we suppress boxing. 233 def c_unboxed_type(self): 234 return self.c_type() 235 236 def json_type(self): 237 pass 238 239 def alternate_qtype(self): 240 json2qtype = { 241 'null': 'QTYPE_QNULL', 242 'string': 'QTYPE_QSTRING', 243 'number': 'QTYPE_QNUM', 244 'int': 'QTYPE_QNUM', 245 'boolean': 'QTYPE_QBOOL', 246 'object': 'QTYPE_QDICT' 247 } 248 return json2qtype.get(self.json_type()) 249 250 def doc_type(self): 251 if self.is_implicit(): 252 return None 253 return self.name 254 255 def check(self, schema): 256 QAPISchemaEntity.check(self, schema) 257 if 'deprecated' in [f.name for f in self.features]: 258 raise QAPISemError( 259 self.info, "feature 'deprecated' is not supported for types") 260 261 def describe(self): 262 assert self.meta 263 return "%s type '%s'" % (self.meta, self.name) 264 265 266class QAPISchemaBuiltinType(QAPISchemaType): 267 meta = 'built-in' 268 269 def __init__(self, name, json_type, c_type): 270 super().__init__(name, None, None) 271 assert not c_type or isinstance(c_type, str) 272 assert json_type in ('string', 'number', 'int', 'boolean', 'null', 273 'value') 274 self._json_type_name = json_type 275 self._c_type_name = c_type 276 277 def c_name(self): 278 return self.name 279 280 def c_type(self): 281 return self._c_type_name 282 283 def c_param_type(self): 284 if self.name == 'str': 285 return 'const ' + self._c_type_name 286 return self._c_type_name 287 288 def json_type(self): 289 return self._json_type_name 290 291 def doc_type(self): 292 return self.json_type() 293 294 def visit(self, visitor): 295 super().visit(visitor) 296 visitor.visit_builtin_type(self.name, self.info, self.json_type()) 297 298 299class QAPISchemaEnumType(QAPISchemaType): 300 meta = 'enum' 301 302 def __init__(self, name, info, doc, ifcond, features, members, prefix): 303 super().__init__(name, info, doc, ifcond, features) 304 for m in members: 305 assert isinstance(m, QAPISchemaEnumMember) 306 m.set_defined_in(name) 307 assert prefix is None or isinstance(prefix, str) 308 self.members = members 309 self.prefix = prefix 310 311 def check(self, schema): 312 super().check(schema) 313 seen = {} 314 for m in self.members: 315 m.check_clash(self.info, seen) 316 317 def connect_doc(self, doc=None): 318 super().connect_doc(doc) 319 doc = doc or self.doc 320 for m in self.members: 321 m.connect_doc(doc) 322 323 def is_implicit(self): 324 # See QAPISchema._make_implicit_enum_type() and ._def_predefineds() 325 return self.name.endswith('Kind') or self.name == 'QType' 326 327 def c_type(self): 328 return c_name(self.name) 329 330 def member_names(self): 331 return [m.name for m in self.members] 332 333 def json_type(self): 334 return 'string' 335 336 def visit(self, visitor): 337 super().visit(visitor) 338 visitor.visit_enum_type( 339 self.name, self.info, self.ifcond, self.features, 340 self.members, self.prefix) 341 342 343class QAPISchemaArrayType(QAPISchemaType): 344 meta = 'array' 345 346 def __init__(self, name, info, element_type): 347 super().__init__(name, info, None) 348 assert isinstance(element_type, str) 349 self._element_type_name = element_type 350 self.element_type = None 351 352 def check(self, schema): 353 super().check(schema) 354 self.element_type = schema.resolve_type( 355 self._element_type_name, self.info, 356 self.info and self.info.defn_meta) 357 assert not isinstance(self.element_type, QAPISchemaArrayType) 358 359 def set_module(self, schema): 360 self._set_module(schema, self.element_type.info) 361 362 @property 363 def ifcond(self): 364 assert self._checked 365 return self.element_type.ifcond 366 367 def is_implicit(self): 368 return True 369 370 def c_type(self): 371 return c_name(self.name) + POINTER_SUFFIX 372 373 def json_type(self): 374 return 'array' 375 376 def doc_type(self): 377 elt_doc_type = self.element_type.doc_type() 378 if not elt_doc_type: 379 return None 380 return 'array of ' + elt_doc_type 381 382 def visit(self, visitor): 383 super().visit(visitor) 384 visitor.visit_array_type(self.name, self.info, self.ifcond, 385 self.element_type) 386 387 def describe(self): 388 assert self.meta 389 return "%s type ['%s']" % (self.meta, self._element_type_name) 390 391 392class QAPISchemaObjectType(QAPISchemaType): 393 def __init__(self, name, info, doc, ifcond, features, 394 base, local_members, variants): 395 # struct has local_members, optional base, and no variants 396 # flat union has base, variants, and no local_members 397 # simple union has local_members, variants, and no base 398 super().__init__(name, info, doc, ifcond, features) 399 self.meta = 'union' if variants else 'struct' 400 assert base is None or isinstance(base, str) 401 for m in local_members: 402 assert isinstance(m, QAPISchemaObjectTypeMember) 403 m.set_defined_in(name) 404 if variants is not None: 405 assert isinstance(variants, QAPISchemaVariants) 406 variants.set_defined_in(name) 407 self._base_name = base 408 self.base = None 409 self.local_members = local_members 410 self.variants = variants 411 self.members = None 412 413 def check(self, schema): 414 # This calls another type T's .check() exactly when the C 415 # struct emitted by gen_object() contains that T's C struct 416 # (pointers don't count). 417 if self.members is not None: 418 # A previous .check() completed: nothing to do 419 return 420 if self._checked: 421 # Recursed: C struct contains itself 422 raise QAPISemError(self.info, 423 "object %s contains itself" % self.name) 424 425 super().check(schema) 426 assert self._checked and self.members is None 427 428 seen = OrderedDict() 429 if self._base_name: 430 self.base = schema.resolve_type(self._base_name, self.info, 431 "'base'") 432 if (not isinstance(self.base, QAPISchemaObjectType) 433 or self.base.variants): 434 raise QAPISemError( 435 self.info, 436 "'base' requires a struct type, %s isn't" 437 % self.base.describe()) 438 self.base.check(schema) 439 self.base.check_clash(self.info, seen) 440 for m in self.local_members: 441 m.check(schema) 442 m.check_clash(self.info, seen) 443 members = seen.values() 444 445 if self.variants: 446 self.variants.check(schema, seen) 447 self.variants.check_clash(self.info, seen) 448 449 self.members = members # mark completed 450 451 # Check that the members of this type do not cause duplicate JSON members, 452 # and update seen to track the members seen so far. Report any errors 453 # on behalf of info, which is not necessarily self.info 454 def check_clash(self, info, seen): 455 assert self._checked 456 assert not self.variants # not implemented 457 for m in self.members: 458 m.check_clash(info, seen) 459 460 def connect_doc(self, doc=None): 461 super().connect_doc(doc) 462 doc = doc or self.doc 463 if self.base and self.base.is_implicit(): 464 self.base.connect_doc(doc) 465 for m in self.local_members: 466 m.connect_doc(doc) 467 468 @property 469 def ifcond(self): 470 assert self._checked 471 if isinstance(self._ifcond, QAPISchemaType): 472 # Simple union wrapper type inherits from wrapped type; 473 # see _make_implicit_object_type() 474 return self._ifcond.ifcond 475 return self._ifcond 476 477 def is_implicit(self): 478 # See QAPISchema._make_implicit_object_type(), as well as 479 # _def_predefineds() 480 return self.name.startswith('q_') 481 482 def is_empty(self): 483 assert self.members is not None 484 return not self.members and not self.variants 485 486 def c_name(self): 487 assert self.name != 'q_empty' 488 return super().c_name() 489 490 def c_type(self): 491 assert not self.is_implicit() 492 return c_name(self.name) + POINTER_SUFFIX 493 494 def c_unboxed_type(self): 495 return c_name(self.name) 496 497 def json_type(self): 498 return 'object' 499 500 def visit(self, visitor): 501 super().visit(visitor) 502 visitor.visit_object_type( 503 self.name, self.info, self.ifcond, self.features, 504 self.base, self.local_members, self.variants) 505 visitor.visit_object_type_flat( 506 self.name, self.info, self.ifcond, self.features, 507 self.members, self.variants) 508 509 510class QAPISchemaAlternateType(QAPISchemaType): 511 meta = 'alternate' 512 513 def __init__(self, name, info, doc, ifcond, features, variants): 514 super().__init__(name, info, doc, ifcond, features) 515 assert isinstance(variants, QAPISchemaVariants) 516 assert variants.tag_member 517 variants.set_defined_in(name) 518 variants.tag_member.set_defined_in(self.name) 519 self.variants = variants 520 521 def check(self, schema): 522 super().check(schema) 523 self.variants.tag_member.check(schema) 524 # Not calling self.variants.check_clash(), because there's nothing 525 # to clash with 526 self.variants.check(schema, {}) 527 # Alternate branch names have no relation to the tag enum values; 528 # so we have to check for potential name collisions ourselves. 529 seen = {} 530 types_seen = {} 531 for v in self.variants.variants: 532 v.check_clash(self.info, seen) 533 qtype = v.type.alternate_qtype() 534 if not qtype: 535 raise QAPISemError( 536 self.info, 537 "%s cannot use %s" 538 % (v.describe(self.info), v.type.describe())) 539 conflicting = set([qtype]) 540 if qtype == 'QTYPE_QSTRING': 541 if isinstance(v.type, QAPISchemaEnumType): 542 for m in v.type.members: 543 if m.name in ['on', 'off']: 544 conflicting.add('QTYPE_QBOOL') 545 if re.match(r'[-+0-9.]', m.name): 546 # lazy, could be tightened 547 conflicting.add('QTYPE_QNUM') 548 else: 549 conflicting.add('QTYPE_QNUM') 550 conflicting.add('QTYPE_QBOOL') 551 for qt in conflicting: 552 if qt in types_seen: 553 raise QAPISemError( 554 self.info, 555 "%s can't be distinguished from '%s'" 556 % (v.describe(self.info), types_seen[qt])) 557 types_seen[qt] = v.name 558 559 def connect_doc(self, doc=None): 560 super().connect_doc(doc) 561 doc = doc or self.doc 562 for v in self.variants.variants: 563 v.connect_doc(doc) 564 565 def c_type(self): 566 return c_name(self.name) + POINTER_SUFFIX 567 568 def json_type(self): 569 return 'value' 570 571 def visit(self, visitor): 572 super().visit(visitor) 573 visitor.visit_alternate_type( 574 self.name, self.info, self.ifcond, self.features, self.variants) 575 576 577class QAPISchemaVariants: 578 def __init__(self, tag_name, info, tag_member, variants): 579 # Flat unions pass tag_name but not tag_member. 580 # Simple unions and alternates pass tag_member but not tag_name. 581 # After check(), tag_member is always set, and tag_name remains 582 # a reliable witness of being used by a flat union. 583 assert bool(tag_member) != bool(tag_name) 584 assert (isinstance(tag_name, str) or 585 isinstance(tag_member, QAPISchemaObjectTypeMember)) 586 for v in variants: 587 assert isinstance(v, QAPISchemaVariant) 588 self._tag_name = tag_name 589 self.info = info 590 self.tag_member = tag_member 591 self.variants = variants 592 593 def set_defined_in(self, name): 594 for v in self.variants: 595 v.set_defined_in(name) 596 597 def check(self, schema, seen): 598 if not self.tag_member: # flat union 599 self.tag_member = seen.get(c_name(self._tag_name)) 600 base = "'base'" 601 # Pointing to the base type when not implicit would be 602 # nice, but we don't know it here 603 if not self.tag_member or self._tag_name != self.tag_member.name: 604 raise QAPISemError( 605 self.info, 606 "discriminator '%s' is not a member of %s" 607 % (self._tag_name, base)) 608 # Here we do: 609 base_type = schema.lookup_type(self.tag_member.defined_in) 610 assert base_type 611 if not base_type.is_implicit(): 612 base = "base type '%s'" % self.tag_member.defined_in 613 if not isinstance(self.tag_member.type, QAPISchemaEnumType): 614 raise QAPISemError( 615 self.info, 616 "discriminator member '%s' of %s must be of enum type" 617 % (self._tag_name, base)) 618 if self.tag_member.optional: 619 raise QAPISemError( 620 self.info, 621 "discriminator member '%s' of %s must not be optional" 622 % (self._tag_name, base)) 623 if self.tag_member.ifcond.is_present(): 624 raise QAPISemError( 625 self.info, 626 "discriminator member '%s' of %s must not be conditional" 627 % (self._tag_name, base)) 628 else: # simple union 629 assert isinstance(self.tag_member.type, QAPISchemaEnumType) 630 assert not self.tag_member.optional 631 assert not self.tag_member.ifcond.is_present() 632 if self._tag_name: # flat union 633 # branches that are not explicitly covered get an empty type 634 cases = {v.name for v in self.variants} 635 for m in self.tag_member.type.members: 636 if m.name not in cases: 637 v = QAPISchemaVariant(m.name, self.info, 638 'q_empty', m.ifcond) 639 v.set_defined_in(self.tag_member.defined_in) 640 self.variants.append(v) 641 if not self.variants: 642 raise QAPISemError(self.info, "union has no branches") 643 for v in self.variants: 644 v.check(schema) 645 # Union names must match enum values; alternate names are 646 # checked separately. Use 'seen' to tell the two apart. 647 if seen: 648 if v.name not in self.tag_member.type.member_names(): 649 raise QAPISemError( 650 self.info, 651 "branch '%s' is not a value of %s" 652 % (v.name, self.tag_member.type.describe())) 653 if (not isinstance(v.type, QAPISchemaObjectType) 654 or v.type.variants): 655 raise QAPISemError( 656 self.info, 657 "%s cannot use %s" 658 % (v.describe(self.info), v.type.describe())) 659 v.type.check(schema) 660 661 def check_clash(self, info, seen): 662 for v in self.variants: 663 # Reset seen map for each variant, since qapi names from one 664 # branch do not affect another branch 665 v.type.check_clash(info, dict(seen)) 666 667 668class QAPISchemaMember: 669 """ Represents object members, enum members and features """ 670 role = 'member' 671 672 def __init__(self, name, info, ifcond=None): 673 assert isinstance(name, str) 674 self.name = name 675 self.info = info 676 self.ifcond = ifcond or QAPISchemaIfCond() 677 self.defined_in = None 678 679 def set_defined_in(self, name): 680 assert not self.defined_in 681 self.defined_in = name 682 683 def check_clash(self, info, seen): 684 cname = c_name(self.name) 685 if cname in seen: 686 raise QAPISemError( 687 info, 688 "%s collides with %s" 689 % (self.describe(info), seen[cname].describe(info))) 690 seen[cname] = self 691 692 def connect_doc(self, doc): 693 if doc: 694 doc.connect_member(self) 695 696 def describe(self, info): 697 role = self.role 698 defined_in = self.defined_in 699 assert defined_in 700 701 if defined_in.startswith('q_obj_'): 702 # See QAPISchema._make_implicit_object_type() - reverse the 703 # mapping there to create a nice human-readable description 704 defined_in = defined_in[6:] 705 if defined_in.endswith('-arg'): 706 # Implicit type created for a command's dict 'data' 707 assert role == 'member' 708 role = 'parameter' 709 elif defined_in.endswith('-base'): 710 # Implicit type created for a flat union's dict 'base' 711 role = 'base ' + role 712 else: 713 # Implicit type created for a simple union's branch 714 assert defined_in.endswith('-wrapper') 715 # Unreachable and not implemented 716 assert False 717 elif defined_in.endswith('Kind'): 718 # See QAPISchema._make_implicit_enum_type() 719 # Implicit enum created for simple union's branches 720 assert role == 'value' 721 role = 'branch' 722 elif defined_in != info.defn_name: 723 return "%s '%s' of type '%s'" % (role, self.name, defined_in) 724 return "%s '%s'" % (role, self.name) 725 726 727class QAPISchemaEnumMember(QAPISchemaMember): 728 role = 'value' 729 730 731class QAPISchemaFeature(QAPISchemaMember): 732 role = 'feature' 733 734 735class QAPISchemaObjectTypeMember(QAPISchemaMember): 736 def __init__(self, name, info, typ, optional, ifcond=None, features=None): 737 super().__init__(name, info, ifcond) 738 assert isinstance(typ, str) 739 assert isinstance(optional, bool) 740 for f in features or []: 741 assert isinstance(f, QAPISchemaFeature) 742 f.set_defined_in(name) 743 self._type_name = typ 744 self.type = None 745 self.optional = optional 746 self.features = features or [] 747 748 def check(self, schema): 749 assert self.defined_in 750 self.type = schema.resolve_type(self._type_name, self.info, 751 self.describe) 752 seen = {} 753 for f in self.features: 754 f.check_clash(self.info, seen) 755 756 def connect_doc(self, doc): 757 super().connect_doc(doc) 758 if doc: 759 for f in self.features: 760 doc.connect_feature(f) 761 762 763class QAPISchemaVariant(QAPISchemaObjectTypeMember): 764 role = 'branch' 765 766 def __init__(self, name, info, typ, ifcond=None): 767 super().__init__(name, info, typ, False, ifcond) 768 769 770class QAPISchemaCommand(QAPISchemaEntity): 771 meta = 'command' 772 773 def __init__(self, name, info, doc, ifcond, features, 774 arg_type, ret_type, 775 gen, success_response, boxed, allow_oob, allow_preconfig, 776 coroutine): 777 super().__init__(name, info, doc, ifcond, features) 778 assert not arg_type or isinstance(arg_type, str) 779 assert not ret_type or isinstance(ret_type, str) 780 self._arg_type_name = arg_type 781 self.arg_type = None 782 self._ret_type_name = ret_type 783 self.ret_type = None 784 self.gen = gen 785 self.success_response = success_response 786 self.boxed = boxed 787 self.allow_oob = allow_oob 788 self.allow_preconfig = allow_preconfig 789 self.coroutine = coroutine 790 791 def check(self, schema): 792 super().check(schema) 793 if self._arg_type_name: 794 self.arg_type = schema.resolve_type( 795 self._arg_type_name, self.info, "command's 'data'") 796 if not isinstance(self.arg_type, QAPISchemaObjectType): 797 raise QAPISemError( 798 self.info, 799 "command's 'data' cannot take %s" 800 % self.arg_type.describe()) 801 if self.arg_type.variants and not self.boxed: 802 raise QAPISemError( 803 self.info, 804 "command's 'data' can take %s only with 'boxed': true" 805 % self.arg_type.describe()) 806 if self._ret_type_name: 807 self.ret_type = schema.resolve_type( 808 self._ret_type_name, self.info, "command's 'returns'") 809 if self.name not in self.info.pragma.command_returns_exceptions: 810 typ = self.ret_type 811 if isinstance(typ, QAPISchemaArrayType): 812 typ = self.ret_type.element_type 813 assert typ 814 if not isinstance(typ, QAPISchemaObjectType): 815 raise QAPISemError( 816 self.info, 817 "command's 'returns' cannot take %s" 818 % self.ret_type.describe()) 819 820 def connect_doc(self, doc=None): 821 super().connect_doc(doc) 822 doc = doc or self.doc 823 if doc: 824 if self.arg_type and self.arg_type.is_implicit(): 825 self.arg_type.connect_doc(doc) 826 827 def visit(self, visitor): 828 super().visit(visitor) 829 visitor.visit_command( 830 self.name, self.info, self.ifcond, self.features, 831 self.arg_type, self.ret_type, self.gen, self.success_response, 832 self.boxed, self.allow_oob, self.allow_preconfig, 833 self.coroutine) 834 835 836class QAPISchemaEvent(QAPISchemaEntity): 837 meta = 'event' 838 839 def __init__(self, name, info, doc, ifcond, features, arg_type, boxed): 840 super().__init__(name, info, doc, ifcond, features) 841 assert not arg_type or isinstance(arg_type, str) 842 self._arg_type_name = arg_type 843 self.arg_type = None 844 self.boxed = boxed 845 846 def check(self, schema): 847 super().check(schema) 848 if self._arg_type_name: 849 self.arg_type = schema.resolve_type( 850 self._arg_type_name, self.info, "event's 'data'") 851 if not isinstance(self.arg_type, QAPISchemaObjectType): 852 raise QAPISemError( 853 self.info, 854 "event's 'data' cannot take %s" 855 % self.arg_type.describe()) 856 if self.arg_type.variants and not self.boxed: 857 raise QAPISemError( 858 self.info, 859 "event's 'data' can take %s only with 'boxed': true" 860 % self.arg_type.describe()) 861 862 def connect_doc(self, doc=None): 863 super().connect_doc(doc) 864 doc = doc or self.doc 865 if doc: 866 if self.arg_type and self.arg_type.is_implicit(): 867 self.arg_type.connect_doc(doc) 868 869 def visit(self, visitor): 870 super().visit(visitor) 871 visitor.visit_event( 872 self.name, self.info, self.ifcond, self.features, 873 self.arg_type, self.boxed) 874 875 876class QAPISchema: 877 def __init__(self, fname): 878 self.fname = fname 879 880 try: 881 parser = QAPISchemaParser(fname) 882 except OSError as err: 883 raise QAPIError( 884 f"can't read schema file '{fname}': {err.strerror}" 885 ) from err 886 887 exprs = check_exprs(parser.exprs) 888 self.docs = parser.docs 889 self._entity_list = [] 890 self._entity_dict = {} 891 self._module_dict = OrderedDict() 892 self._schema_dir = os.path.dirname(fname) 893 self._make_module(QAPISchemaModule.BUILTIN_MODULE_NAME) 894 self._make_module(fname) 895 self._predefining = True 896 self._def_predefineds() 897 self._predefining = False 898 self._def_exprs(exprs) 899 self.check() 900 901 def _def_entity(self, ent): 902 # Only the predefined types are allowed to not have info 903 assert ent.info or self._predefining 904 self._entity_list.append(ent) 905 if ent.name is None: 906 return 907 # TODO reject names that differ only in '_' vs. '.' vs. '-', 908 # because they're liable to clash in generated C. 909 other_ent = self._entity_dict.get(ent.name) 910 if other_ent: 911 if other_ent.info: 912 where = QAPISourceError(other_ent.info, "previous definition") 913 raise QAPISemError( 914 ent.info, 915 "'%s' is already defined\n%s" % (ent.name, where)) 916 raise QAPISemError( 917 ent.info, "%s is already defined" % other_ent.describe()) 918 self._entity_dict[ent.name] = ent 919 920 def lookup_entity(self, name, typ=None): 921 ent = self._entity_dict.get(name) 922 if typ and not isinstance(ent, typ): 923 return None 924 return ent 925 926 def lookup_type(self, name): 927 return self.lookup_entity(name, QAPISchemaType) 928 929 def resolve_type(self, name, info, what): 930 typ = self.lookup_type(name) 931 if not typ: 932 if callable(what): 933 what = what(info) 934 raise QAPISemError( 935 info, "%s uses unknown type '%s'" % (what, name)) 936 return typ 937 938 def _module_name(self, fname: str) -> str: 939 if QAPISchemaModule.is_system_module(fname): 940 return fname 941 return os.path.relpath(fname, self._schema_dir) 942 943 def _make_module(self, fname): 944 name = self._module_name(fname) 945 if name not in self._module_dict: 946 self._module_dict[name] = QAPISchemaModule(name) 947 return self._module_dict[name] 948 949 def module_by_fname(self, fname): 950 name = self._module_name(fname) 951 return self._module_dict[name] 952 953 def _def_include(self, expr, info, doc): 954 include = expr['include'] 955 assert doc is None 956 self._def_entity(QAPISchemaInclude(self._make_module(include), info)) 957 958 def _def_builtin_type(self, name, json_type, c_type): 959 self._def_entity(QAPISchemaBuiltinType(name, json_type, c_type)) 960 # Instantiating only the arrays that are actually used would 961 # be nice, but we can't as long as their generated code 962 # (qapi-builtin-types.[ch]) may be shared by some other 963 # schema. 964 self._make_array_type(name, None) 965 966 def _def_predefineds(self): 967 for t in [('str', 'string', 'char' + POINTER_SUFFIX), 968 ('number', 'number', 'double'), 969 ('int', 'int', 'int64_t'), 970 ('int8', 'int', 'int8_t'), 971 ('int16', 'int', 'int16_t'), 972 ('int32', 'int', 'int32_t'), 973 ('int64', 'int', 'int64_t'), 974 ('uint8', 'int', 'uint8_t'), 975 ('uint16', 'int', 'uint16_t'), 976 ('uint32', 'int', 'uint32_t'), 977 ('uint64', 'int', 'uint64_t'), 978 ('size', 'int', 'uint64_t'), 979 ('bool', 'boolean', 'bool'), 980 ('any', 'value', 'QObject' + POINTER_SUFFIX), 981 ('null', 'null', 'QNull' + POINTER_SUFFIX)]: 982 self._def_builtin_type(*t) 983 self.the_empty_object_type = QAPISchemaObjectType( 984 'q_empty', None, None, None, None, None, [], None) 985 self._def_entity(self.the_empty_object_type) 986 987 qtypes = ['none', 'qnull', 'qnum', 'qstring', 'qdict', 'qlist', 988 'qbool'] 989 qtype_values = self._make_enum_members( 990 [{'name': n} for n in qtypes], None) 991 992 self._def_entity(QAPISchemaEnumType('QType', None, None, None, None, 993 qtype_values, 'QTYPE')) 994 995 def _make_features(self, features, info): 996 if features is None: 997 return [] 998 return [QAPISchemaFeature(f['name'], info, 999 QAPISchemaIfCond(f.get('if'))) 1000 for f in features] 1001 1002 def _make_enum_members(self, values, info): 1003 return [QAPISchemaEnumMember(v['name'], info, 1004 QAPISchemaIfCond(v.get('if'))) 1005 for v in values] 1006 1007 def _make_implicit_enum_type(self, name, info, ifcond, values): 1008 # See also QAPISchemaObjectTypeMember.describe() 1009 name = name + 'Kind' # reserved by check_defn_name_str() 1010 self._def_entity(QAPISchemaEnumType( 1011 name, info, None, ifcond, None, 1012 self._make_enum_members(values, info), 1013 None)) 1014 return name 1015 1016 def _make_array_type(self, element_type, info): 1017 name = element_type + 'List' # reserved by check_defn_name_str() 1018 if not self.lookup_type(name): 1019 self._def_entity(QAPISchemaArrayType(name, info, element_type)) 1020 return name 1021 1022 def _make_implicit_object_type(self, name, info, ifcond, role, members): 1023 if not members: 1024 return None 1025 # See also QAPISchemaObjectTypeMember.describe() 1026 name = 'q_obj_%s-%s' % (name, role) 1027 typ = self.lookup_entity(name, QAPISchemaObjectType) 1028 if typ: 1029 # The implicit object type has multiple users. This is 1030 # either a duplicate definition (which will be flagged 1031 # later), or an implicit wrapper type used for multiple 1032 # simple unions. In the latter case, ifcond should be the 1033 # disjunction of its user's ifconds. Not implemented. 1034 # Instead, we always pass the wrapped type's ifcond, which 1035 # is trivially the same for all users. It's also 1036 # necessary for the wrapper to compile. But it's not 1037 # tight: the disjunction need not imply it. We may end up 1038 # compiling useless wrapper types. 1039 # TODO kill simple unions or implement the disjunction 1040 pass 1041 else: 1042 self._def_entity(QAPISchemaObjectType( 1043 name, info, None, ifcond, None, None, members, None)) 1044 return name 1045 1046 def _def_enum_type(self, expr, info, doc): 1047 name = expr['enum'] 1048 data = expr['data'] 1049 prefix = expr.get('prefix') 1050 ifcond = QAPISchemaIfCond(expr.get('if')) 1051 features = self._make_features(expr.get('features'), info) 1052 self._def_entity(QAPISchemaEnumType( 1053 name, info, doc, ifcond, features, 1054 self._make_enum_members(data, info), prefix)) 1055 1056 def _make_member(self, name, typ, ifcond, features, info): 1057 optional = False 1058 if name.startswith('*'): 1059 name = name[1:] 1060 optional = True 1061 if isinstance(typ, list): 1062 assert len(typ) == 1 1063 typ = self._make_array_type(typ[0], info) 1064 return QAPISchemaObjectTypeMember(name, info, typ, optional, ifcond, 1065 self._make_features(features, info)) 1066 1067 def _make_members(self, data, info): 1068 return [self._make_member(key, value['type'], 1069 QAPISchemaIfCond(value.get('if')), 1070 value.get('features'), info) 1071 for (key, value) in data.items()] 1072 1073 def _def_struct_type(self, expr, info, doc): 1074 name = expr['struct'] 1075 base = expr.get('base') 1076 data = expr['data'] 1077 ifcond = QAPISchemaIfCond(expr.get('if')) 1078 features = self._make_features(expr.get('features'), info) 1079 self._def_entity(QAPISchemaObjectType( 1080 name, info, doc, ifcond, features, base, 1081 self._make_members(data, info), 1082 None)) 1083 1084 def _make_variant(self, case, typ, ifcond, info): 1085 return QAPISchemaVariant(case, info, typ, ifcond) 1086 1087 def _make_simple_variant(self, case, typ, ifcond, info): 1088 if isinstance(typ, list): 1089 assert len(typ) == 1 1090 typ = self._make_array_type(typ[0], info) 1091 typ = self._make_implicit_object_type( 1092 typ, info, self.lookup_type(typ), 1093 'wrapper', [self._make_member('data', typ, None, None, info)]) 1094 return QAPISchemaVariant(case, info, typ, ifcond) 1095 1096 def _def_union_type(self, expr, info, doc): 1097 name = expr['union'] 1098 data = expr['data'] 1099 base = expr.get('base') 1100 ifcond = QAPISchemaIfCond(expr.get('if')) 1101 features = self._make_features(expr.get('features'), info) 1102 tag_name = expr.get('discriminator') 1103 tag_member = None 1104 if isinstance(base, dict): 1105 base = self._make_implicit_object_type( 1106 name, info, ifcond, 1107 'base', self._make_members(base, info)) 1108 if tag_name: 1109 variants = [ 1110 self._make_variant(key, value['type'], 1111 QAPISchemaIfCond(value.get('if')), 1112 info) 1113 for (key, value) in data.items()] 1114 members = [] 1115 else: 1116 variants = [ 1117 self._make_simple_variant(key, value['type'], 1118 QAPISchemaIfCond(value.get('if')), 1119 info) 1120 for (key, value) in data.items()] 1121 enum = [{'name': v.name, 'if': v.ifcond.ifcond} for v in variants] 1122 typ = self._make_implicit_enum_type(name, info, ifcond, enum) 1123 tag_member = QAPISchemaObjectTypeMember('type', info, typ, False) 1124 members = [tag_member] 1125 self._def_entity( 1126 QAPISchemaObjectType(name, info, doc, ifcond, features, 1127 base, members, 1128 QAPISchemaVariants( 1129 tag_name, info, tag_member, variants))) 1130 1131 def _def_alternate_type(self, expr, info, doc): 1132 name = expr['alternate'] 1133 data = expr['data'] 1134 ifcond = QAPISchemaIfCond(expr.get('if')) 1135 features = self._make_features(expr.get('features'), info) 1136 variants = [ 1137 self._make_variant(key, value['type'], 1138 QAPISchemaIfCond(value.get('if')), 1139 info) 1140 for (key, value) in data.items()] 1141 tag_member = QAPISchemaObjectTypeMember('type', info, 'QType', False) 1142 self._def_entity( 1143 QAPISchemaAlternateType(name, info, doc, ifcond, features, 1144 QAPISchemaVariants( 1145 None, info, tag_member, variants))) 1146 1147 def _def_command(self, expr, info, doc): 1148 name = expr['command'] 1149 data = expr.get('data') 1150 rets = expr.get('returns') 1151 gen = expr.get('gen', True) 1152 success_response = expr.get('success-response', True) 1153 boxed = expr.get('boxed', False) 1154 allow_oob = expr.get('allow-oob', False) 1155 allow_preconfig = expr.get('allow-preconfig', False) 1156 coroutine = expr.get('coroutine', False) 1157 ifcond = QAPISchemaIfCond(expr.get('if')) 1158 features = self._make_features(expr.get('features'), info) 1159 if isinstance(data, OrderedDict): 1160 data = self._make_implicit_object_type( 1161 name, info, ifcond, 1162 'arg', self._make_members(data, info)) 1163 if isinstance(rets, list): 1164 assert len(rets) == 1 1165 rets = self._make_array_type(rets[0], info) 1166 self._def_entity(QAPISchemaCommand(name, info, doc, ifcond, features, 1167 data, rets, 1168 gen, success_response, 1169 boxed, allow_oob, allow_preconfig, 1170 coroutine)) 1171 1172 def _def_event(self, expr, info, doc): 1173 name = expr['event'] 1174 data = expr.get('data') 1175 boxed = expr.get('boxed', False) 1176 ifcond = QAPISchemaIfCond(expr.get('if')) 1177 features = self._make_features(expr.get('features'), info) 1178 if isinstance(data, OrderedDict): 1179 data = self._make_implicit_object_type( 1180 name, info, ifcond, 1181 'arg', self._make_members(data, info)) 1182 self._def_entity(QAPISchemaEvent(name, info, doc, ifcond, features, 1183 data, boxed)) 1184 1185 def _def_exprs(self, exprs): 1186 for expr_elem in exprs: 1187 expr = expr_elem['expr'] 1188 info = expr_elem['info'] 1189 doc = expr_elem.get('doc') 1190 if 'enum' in expr: 1191 self._def_enum_type(expr, info, doc) 1192 elif 'struct' in expr: 1193 self._def_struct_type(expr, info, doc) 1194 elif 'union' in expr: 1195 self._def_union_type(expr, info, doc) 1196 elif 'alternate' in expr: 1197 self._def_alternate_type(expr, info, doc) 1198 elif 'command' in expr: 1199 self._def_command(expr, info, doc) 1200 elif 'event' in expr: 1201 self._def_event(expr, info, doc) 1202 elif 'include' in expr: 1203 self._def_include(expr, info, doc) 1204 else: 1205 assert False 1206 1207 def check(self): 1208 for ent in self._entity_list: 1209 ent.check(self) 1210 ent.connect_doc() 1211 ent.check_doc() 1212 for ent in self._entity_list: 1213 ent.set_module(self) 1214 1215 def visit(self, visitor): 1216 visitor.visit_begin(self) 1217 for mod in self._module_dict.values(): 1218 mod.visit(visitor) 1219 visitor.visit_end() 1220