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