1""" 2QAPI introspection generator 3 4Copyright (C) 2015-2018 Red Hat, Inc. 5 6Authors: 7 Markus Armbruster <armbru@redhat.com> 8 9This work is licensed under the terms of the GNU GPL, version 2. 10See the COPYING file in the top-level directory. 11""" 12 13from .common import ( 14 c_name, 15 gen_endif, 16 gen_if, 17 mcgen, 18) 19from .gen import QAPISchemaMonolithicCVisitor 20from .schema import ( 21 QAPISchemaArrayType, 22 QAPISchemaBuiltinType, 23 QAPISchemaType, 24) 25 26 27def _make_tree(obj, ifcond, features, extra=None): 28 if extra is None: 29 extra = {} 30 if ifcond: 31 extra['if'] = ifcond 32 if features: 33 obj['features'] = [(f.name, {'if': f.ifcond}) for f in features] 34 if extra: 35 return (obj, extra) 36 return obj 37 38 39def _tree_to_qlit(obj, level=0, suppress_first_indent=False): 40 41 def indent(level): 42 return level * 4 * ' ' 43 44 if isinstance(obj, tuple): 45 ifobj, extra = obj 46 ifcond = extra.get('if') 47 comment = extra.get('comment') 48 ret = '' 49 if comment: 50 ret += indent(level) + '/* %s */\n' % comment 51 if ifcond: 52 ret += gen_if(ifcond) 53 ret += _tree_to_qlit(ifobj, level) 54 if ifcond: 55 ret += '\n' + gen_endif(ifcond) 56 return ret 57 58 ret = '' 59 if not suppress_first_indent: 60 ret += indent(level) 61 if obj is None: 62 ret += 'QLIT_QNULL' 63 elif isinstance(obj, str): 64 ret += 'QLIT_QSTR(' + to_c_string(obj) + ')' 65 elif isinstance(obj, list): 66 elts = [_tree_to_qlit(elt, level + 1).strip('\n') 67 for elt in obj] 68 elts.append(indent(level + 1) + "{}") 69 ret += 'QLIT_QLIST(((QLitObject[]) {\n' 70 ret += '\n'.join(elts) + '\n' 71 ret += indent(level) + '}))' 72 elif isinstance(obj, dict): 73 elts = [] 74 for key, value in sorted(obj.items()): 75 elts.append(indent(level + 1) + '{ %s, %s }' % 76 (to_c_string(key), 77 _tree_to_qlit(value, level + 1, True))) 78 elts.append(indent(level + 1) + '{}') 79 ret += 'QLIT_QDICT(((QLitDictEntry[]) {\n' 80 ret += ',\n'.join(elts) + '\n' 81 ret += indent(level) + '}))' 82 elif isinstance(obj, bool): 83 ret += 'QLIT_QBOOL(%s)' % ('true' if obj else 'false') 84 else: 85 assert False # not implemented 86 if level > 0: 87 ret += ',' 88 return ret 89 90 91def to_c_string(string): 92 return '"' + string.replace('\\', r'\\').replace('"', r'\"') + '"' 93 94 95class QAPISchemaGenIntrospectVisitor(QAPISchemaMonolithicCVisitor): 96 97 def __init__(self, prefix, unmask): 98 super().__init__( 99 prefix, 'qapi-introspect', 100 ' * QAPI/QMP schema introspection', __doc__) 101 self._unmask = unmask 102 self._schema = None 103 self._trees = [] 104 self._used_types = [] 105 self._name_map = {} 106 self._genc.add(mcgen(''' 107#include "qemu/osdep.h" 108#include "%(prefix)sqapi-introspect.h" 109 110''', 111 prefix=prefix)) 112 113 def visit_begin(self, schema): 114 self._schema = schema 115 116 def visit_end(self): 117 # visit the types that are actually used 118 for typ in self._used_types: 119 typ.visit(self) 120 # generate C 121 name = c_name(self._prefix, protect=False) + 'qmp_schema_qlit' 122 self._genh.add(mcgen(''' 123#include "qapi/qmp/qlit.h" 124 125extern const QLitObject %(c_name)s; 126''', 127 c_name=c_name(name))) 128 self._genc.add(mcgen(''' 129const QLitObject %(c_name)s = %(c_string)s; 130''', 131 c_name=c_name(name), 132 c_string=_tree_to_qlit(self._trees))) 133 self._schema = None 134 self._trees = [] 135 self._used_types = [] 136 self._name_map = {} 137 138 def visit_needed(self, entity): 139 # Ignore types on first pass; visit_end() will pick up used types 140 return not isinstance(entity, QAPISchemaType) 141 142 def _name(self, name): 143 if self._unmask: 144 return name 145 if name not in self._name_map: 146 self._name_map[name] = '%d' % len(self._name_map) 147 return self._name_map[name] 148 149 def _use_type(self, typ): 150 # Map the various integer types to plain int 151 if typ.json_type() == 'int': 152 typ = self._schema.lookup_type('int') 153 elif (isinstance(typ, QAPISchemaArrayType) and 154 typ.element_type.json_type() == 'int'): 155 typ = self._schema.lookup_type('intList') 156 # Add type to work queue if new 157 if typ not in self._used_types: 158 self._used_types.append(typ) 159 # Clients should examine commands and events, not types. Hide 160 # type names as integers to reduce the temptation. Also, it 161 # saves a few characters on the wire. 162 if isinstance(typ, QAPISchemaBuiltinType): 163 return typ.name 164 if isinstance(typ, QAPISchemaArrayType): 165 return '[' + self._use_type(typ.element_type) + ']' 166 return self._name(typ.name) 167 168 def _gen_tree(self, name, mtype, obj, ifcond, features): 169 extra = None 170 if mtype not in ('command', 'event', 'builtin', 'array'): 171 if not self._unmask: 172 # Output a comment to make it easy to map masked names 173 # back to the source when reading the generated output. 174 extra = {'comment': '"%s" = %s' % (self._name(name), name)} 175 name = self._name(name) 176 obj['name'] = name 177 obj['meta-type'] = mtype 178 self._trees.append(_make_tree(obj, ifcond, features, extra)) 179 180 def _gen_member(self, member): 181 obj = {'name': member.name, 'type': self._use_type(member.type)} 182 if member.optional: 183 obj['default'] = None 184 return _make_tree(obj, member.ifcond, member.features) 185 186 def _gen_variants(self, tag_name, variants): 187 return {'tag': tag_name, 188 'variants': [self._gen_variant(v) for v in variants]} 189 190 def _gen_variant(self, variant): 191 obj = {'case': variant.name, 'type': self._use_type(variant.type)} 192 return _make_tree(obj, variant.ifcond, None) 193 194 def visit_builtin_type(self, name, info, json_type): 195 self._gen_tree(name, 'builtin', {'json-type': json_type}, [], None) 196 197 def visit_enum_type(self, name, info, ifcond, features, members, prefix): 198 self._gen_tree(name, 'enum', 199 {'values': [_make_tree(m.name, m.ifcond, None) 200 for m in members]}, 201 ifcond, features) 202 203 def visit_array_type(self, name, info, ifcond, element_type): 204 element = self._use_type(element_type) 205 self._gen_tree('[' + element + ']', 'array', {'element-type': element}, 206 ifcond, None) 207 208 def visit_object_type_flat(self, name, info, ifcond, features, 209 members, variants): 210 obj = {'members': [self._gen_member(m) for m in members]} 211 if variants: 212 obj.update(self._gen_variants(variants.tag_member.name, 213 variants.variants)) 214 215 self._gen_tree(name, 'object', obj, ifcond, features) 216 217 def visit_alternate_type(self, name, info, ifcond, features, variants): 218 self._gen_tree(name, 'alternate', 219 {'members': [ 220 _make_tree({'type': self._use_type(m.type)}, 221 m.ifcond, None) 222 for m in variants.variants]}, 223 ifcond, features) 224 225 def visit_command(self, name, info, ifcond, features, 226 arg_type, ret_type, gen, success_response, boxed, 227 allow_oob, allow_preconfig, coroutine): 228 arg_type = arg_type or self._schema.the_empty_object_type 229 ret_type = ret_type or self._schema.the_empty_object_type 230 obj = {'arg-type': self._use_type(arg_type), 231 'ret-type': self._use_type(ret_type)} 232 if allow_oob: 233 obj['allow-oob'] = allow_oob 234 self._gen_tree(name, 'command', obj, ifcond, features) 235 236 def visit_event(self, name, info, ifcond, features, arg_type, boxed): 237 arg_type = arg_type or self._schema.the_empty_object_type 238 self._gen_tree(name, 'event', {'arg-type': self._use_type(arg_type)}, 239 ifcond, features) 240 241 242def gen_introspect(schema, output_dir, prefix, opt_unmask): 243 vis = QAPISchemaGenIntrospectVisitor(prefix, opt_unmask) 244 schema.visit(vis) 245 vis.write(output_dir) 246