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