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