xref: /qemu/scripts/qapi/events.py (revision 922d42bb)
1"""
2QAPI event generator
3
4Copyright (c) 2014 Wenchao Xia
5Copyright (c) 2015-2018 Red Hat Inc.
6
7Authors:
8 Wenchao Xia <wenchaoqemu@gmail.com>
9 Markus Armbruster <armbru@redhat.com>
10
11This work is licensed under the terms of the GNU GPL, version 2.
12See the COPYING file in the top-level directory.
13"""
14
15from typing import List
16
17from .common import c_enum_const, c_name, mcgen
18from .gen import QAPISchemaModularCVisitor, build_params, ifcontext
19from .schema import (
20    QAPISchema,
21    QAPISchemaEnumMember,
22    QAPISchemaFeature,
23    QAPISchemaObjectType,
24)
25from .source import QAPISourceInfo
26from .types import gen_enum, gen_enum_lookup
27
28
29def build_event_send_proto(name: str,
30                           arg_type: QAPISchemaObjectType,
31                           boxed: bool) -> str:
32    return 'void qapi_event_send_%(c_name)s(%(param)s)' % {
33        'c_name': c_name(name.lower()),
34        'param': build_params(arg_type, boxed)}
35
36
37def gen_event_send_decl(name: str,
38                        arg_type: QAPISchemaObjectType,
39                        boxed: bool) -> str:
40    return mcgen('''
41
42%(proto)s;
43''',
44                 proto=build_event_send_proto(name, arg_type, boxed))
45
46
47def gen_param_var(typ: QAPISchemaObjectType) -> str:
48    """
49    Generate a struct variable holding the event parameters.
50
51    Initialize it with the function arguments defined in `gen_event_send`.
52    """
53    assert not typ.variants
54    ret = mcgen('''
55    %(c_name)s param = {
56''',
57                c_name=typ.c_name())
58    sep = '        '
59    for memb in typ.members:
60        ret += sep
61        sep = ', '
62        if memb.optional:
63            ret += 'has_' + c_name(memb.name) + sep
64        if memb.type.name == 'str':
65            # Cast away const added in build_params()
66            ret += '(char *)'
67        ret += c_name(memb.name)
68    ret += mcgen('''
69
70    };
71''')
72    if not typ.is_implicit():
73        ret += mcgen('''
74    %(c_name)s *arg = &param;
75''',
76                     c_name=typ.c_name())
77    return ret
78
79
80def gen_event_send(name: str,
81                   arg_type: QAPISchemaObjectType,
82                   boxed: bool,
83                   event_enum_name: str,
84                   event_emit: str) -> str:
85    # FIXME: Our declaration of local variables (and of 'errp' in the
86    # parameter list) can collide with exploded members of the event's
87    # data type passed in as parameters.  If this collision ever hits in
88    # practice, we can rename our local variables with a leading _ prefix,
89    # or split the code into a wrapper function that creates a boxed
90    # 'param' object then calls another to do the real work.
91    have_args = boxed or (arg_type and not arg_type.is_empty())
92
93    ret = mcgen('''
94
95%(proto)s
96{
97    QDict *qmp;
98''',
99                proto=build_event_send_proto(name, arg_type, boxed))
100
101    if have_args:
102        ret += mcgen('''
103    QObject *obj;
104    Visitor *v;
105''')
106        if not boxed:
107            ret += gen_param_var(arg_type)
108
109    ret += mcgen('''
110
111    qmp = qmp_event_build_dict("%(name)s");
112
113''',
114                 name=name)
115
116    if have_args:
117        ret += mcgen('''
118    v = qobject_output_visitor_new(&obj);
119''')
120        if not arg_type.is_implicit():
121            ret += mcgen('''
122    visit_type_%(c_name)s(v, "%(name)s", &arg, &error_abort);
123''',
124                         name=name, c_name=arg_type.c_name())
125        else:
126            ret += mcgen('''
127
128    visit_start_struct(v, "%(name)s", NULL, 0, &error_abort);
129    visit_type_%(c_name)s_members(v, &param, &error_abort);
130    visit_check_struct(v, &error_abort);
131    visit_end_struct(v, NULL);
132''',
133                         name=name, c_name=arg_type.c_name())
134        ret += mcgen('''
135
136    visit_complete(v, &obj);
137    qdict_put_obj(qmp, "data", obj);
138''')
139
140    ret += mcgen('''
141    %(event_emit)s(%(c_enum)s, qmp);
142
143''',
144                 event_emit=event_emit,
145                 c_enum=c_enum_const(event_enum_name, name))
146
147    if have_args:
148        ret += mcgen('''
149    visit_free(v);
150''')
151    ret += mcgen('''
152    qobject_unref(qmp);
153}
154''')
155    return ret
156
157
158class QAPISchemaGenEventVisitor(QAPISchemaModularCVisitor):
159
160    def __init__(self, prefix: str):
161        super().__init__(
162            prefix, 'qapi-events',
163            ' * Schema-defined QAPI/QMP events', None, __doc__)
164        self._event_enum_name = c_name(prefix + 'QAPIEvent', protect=False)
165        self._event_enum_members: List[QAPISchemaEnumMember] = []
166        self._event_emit_name = c_name(prefix + 'qapi_event_emit')
167
168    def _begin_user_module(self, name: str) -> None:
169        events = self._module_basename('qapi-events', name)
170        types = self._module_basename('qapi-types', name)
171        visit = self._module_basename('qapi-visit', name)
172        self._genc.add(mcgen('''
173#include "qemu/osdep.h"
174#include "%(prefix)sqapi-emit-events.h"
175#include "%(events)s.h"
176#include "%(visit)s.h"
177#include "qapi/error.h"
178#include "qapi/qmp/qdict.h"
179#include "qapi/qobject-output-visitor.h"
180#include "qapi/qmp-event.h"
181
182''',
183                             events=events, visit=visit,
184                             prefix=self._prefix))
185        self._genh.add(mcgen('''
186#include "qapi/util.h"
187#include "%(types)s.h"
188''',
189                             types=types))
190
191    def visit_end(self) -> None:
192        self._add_system_module('emit', ' * QAPI Events emission')
193        self._genc.preamble_add(mcgen('''
194#include "qemu/osdep.h"
195#include "%(prefix)sqapi-emit-events.h"
196''',
197                                      prefix=self._prefix))
198        self._genh.preamble_add(mcgen('''
199#include "qapi/util.h"
200'''))
201        self._genh.add(gen_enum(self._event_enum_name,
202                                self._event_enum_members))
203        self._genc.add(gen_enum_lookup(self._event_enum_name,
204                                       self._event_enum_members))
205        self._genh.add(mcgen('''
206
207void %(event_emit)s(%(event_enum)s event, QDict *qdict);
208''',
209                             event_emit=self._event_emit_name,
210                             event_enum=self._event_enum_name))
211
212    def visit_event(self,
213                    name: str,
214                    info: QAPISourceInfo,
215                    ifcond: List[str],
216                    features: List[QAPISchemaFeature],
217                    arg_type: QAPISchemaObjectType,
218                    boxed: bool) -> None:
219        with ifcontext(ifcond, self._genh, self._genc):
220            self._genh.add(gen_event_send_decl(name, arg_type, boxed))
221            self._genc.add(gen_event_send(name, arg_type, boxed,
222                                          self._event_enum_name,
223                                          self._event_emit_name))
224        # Note: we generate the enum member regardless of @ifcond, to
225        # keep the enumeration usable in target-independent code.
226        self._event_enum_members.append(QAPISchemaEnumMember(name, None))
227
228
229def gen_events(schema: QAPISchema,
230               output_dir: str,
231               prefix: str) -> None:
232    vis = QAPISchemaGenEventVisitor(prefix)
233    schema.visit(vis)
234    vis.write(output_dir)
235