qapi-visit.py 12.2 KB
Newer Older
1 2 3 4
#
# QAPI visitor generator
#
# Copyright IBM, Corp. 2011
E
Eric Blake 已提交
5
# Copyright (C) 2014-2015 Red Hat, Inc.
6 7 8 9
#
# Authors:
#  Anthony Liguori <aliguori@us.ibm.com>
#  Michael Roth    <mdroth@linux.vnet.ibm.com>
10
#  Markus Armbruster <armbru@redhat.com>
11
#
12 13
# This work is licensed under the terms of the GNU GPL, version 2.
# See the COPYING file in the top-level directory.
14 15

from qapi import *
16
import re
17

18 19
# visit_type_FOO_implicit() is emitted as needed; track if it has already
# been output.
20
implicit_structs_seen = set()
21 22 23

# visit_type_FOO_fields() is always emitted; track if a forward declaration
# or implementation has already been output.
24
struct_fields_seen = set()
25

26

27 28 29 30 31
def gen_visit_decl(name, scalar=False):
    c_type = c_name(name) + ' *'
    if not scalar:
        c_type += '*'
    return mcgen('''
32
void visit_type_%(c_name)s(Visitor *v, %(c_type)sobj, const char *name, Error **errp);
33 34 35 36
''',
                 c_name=c_name(name), c_type=c_type)


37
def gen_visit_fields_decl(typ):
38
    ret = ''
39
    if typ.name not in struct_fields_seen:
40 41
        ret += mcgen('''

42
static void visit_type_%(c_type)s_fields(Visitor *v, %(c_type)s **obj, Error **errp);
43
''',
44
                     c_type=typ.c_name())
45 46 47 48 49 50 51 52 53 54
        struct_fields_seen.add(typ.name)
    return ret


def gen_visit_implicit_struct(typ):
    if typ in implicit_structs_seen:
        return ''
    implicit_structs_seen.add(typ)

    ret = gen_visit_fields_decl(typ)
55 56

    ret += mcgen('''
57

58
static void visit_type_implicit_%(c_type)s(Visitor *v, %(c_type)s **obj, Error **errp)
59 60 61
{
    Error *err = NULL;

62
    visit_start_implicit_struct(v, (void **)obj, sizeof(%(c_type)s), &err);
63
    if (!err) {
64 65
        visit_type_%(c_type)s_fields(v, obj, errp);
        visit_end_implicit_struct(v, &err);
66 67 68 69
    }
    error_propagate(errp, err);
}
''',
70
                 c_type=typ.c_name())
71
    return ret
72

73 74

def gen_visit_struct_fields(name, base, members):
75
    ret = ''
76

77
    if base:
E
Eric Blake 已提交
78
        ret += gen_visit_fields_decl(base)
79

E
Eric Blake 已提交
80
    struct_fields_seen.add(name)
81 82
    ret += mcgen('''

83
static void visit_type_%(c_name)s_fields(Visitor *v, %(c_name)s **obj, Error **errp)
84 85
{
    Error *err = NULL;
M
Markus Armbruster 已提交
86

87
''',
88
                 c_name=c_name(name))
P
Paolo Bonzini 已提交
89

90 91
    if base:
        ret += mcgen('''
E
Eric Blake 已提交
92
    visit_type_%(c_type)s_fields(v, (%(c_type)s **)obj, &err);
93
''',
E
Eric Blake 已提交
94
                     c_type=base.c_name())
E
Eric Blake 已提交
95
        ret += gen_err_check()
96

E
Eric Blake 已提交
97
    ret += gen_visit_fields(members, prefix='(*obj)->')
P
Paolo Bonzini 已提交
98

99 100
    # 'goto out' produced for base, and by gen_visit_fields() for each member
    if base or members:
101
        ret += mcgen('''
102

103 104 105
out:
''')
    ret += mcgen('''
106 107 108
    error_propagate(errp, err);
}
''')
109 110 111
    return ret


112 113 114
def gen_visit_struct(name, base, members):
    ret = gen_visit_struct_fields(name, base, members)

115 116 117 118
    # FIXME: if *obj is NULL on entry, and visit_start_struct() assigns to
    # *obj, but then visit_type_FOO_fields() fails, we should clean up *obj
    # rather than leaving it non-NULL. As currently written, the caller must
    # call qapi_free_FOO() to avoid a memory leak of the partial FOO.
119 120
    ret += mcgen('''

121
void visit_type_%(c_name)s(Visitor *v, %(c_name)s **obj, const char *name, Error **errp)
122
{
123 124
    Error *err = NULL;

125
    visit_start_struct(v, (void **)obj, "%(name)s", name, sizeof(%(c_name)s), &err);
126 127
    if (!err) {
        if (*obj) {
128
            visit_type_%(c_name)s_fields(v, obj, errp);
129
        }
130
        visit_end_struct(v, &err);
131
    }
132
    error_propagate(errp, err);
133
}
134
''',
135
                 name=name, c_name=c_name(name))
136 137 138

    return ret

139

140
def gen_visit_list(name, element_type):
141 142 143 144
    # FIXME: if *obj is NULL on entry, and the first visit_next_list()
    # assigns to *obj, while a later one fails, we should clean up *obj
    # rather than leaving it non-NULL. As currently written, the caller must
    # call qapi_free_FOOList() to avoid a memory leak of the partial FOOList.
145 146
    return mcgen('''

147
void visit_type_%(c_name)s(Visitor *v, %(c_name)s **obj, const char *name, Error **errp)
148
{
P
Paolo Bonzini 已提交
149
    Error *err = NULL;
150
    GenericList *i, **prev;
151

152
    visit_start_list(v, name, &err);
153 154 155 156 157
    if (err) {
        goto out;
    }

    for (prev = (GenericList **)obj;
158
         !err && (i = visit_next_list(v, prev, &err)) != NULL;
159
         prev = &i) {
160
        %(c_name)s *native_i = (%(c_name)s *)i;
161
        visit_type_%(c_elt_type)s(v, &native_i->value, NULL, &err);
162
    }
163 164 165

    error_propagate(errp, err);
    err = NULL;
166
    visit_end_list(v, &err);
167 168
out:
    error_propagate(errp, err);
169 170
}
''',
171
                 c_name=c_name(name), c_elt_type=element_type.c_name())
172

173 174

def gen_visit_enum(name):
175
    # FIXME cast from enum *obj to int * invalidly assumes enum is int
176 177
    return mcgen('''

178
void visit_type_%(c_name)s(Visitor *v, %(c_name)s *obj, const char *name, Error **errp)
179
{
180
    visit_type_enum(v, (int *)obj, %(c_name)s_lookup, "%(name)s", name, errp);
181 182
}
''',
183
                 c_name=c_name(name), name=name)
184

185

186
def gen_visit_alternate(name, variants):
K
Kevin Wolf 已提交
187 188
    ret = mcgen('''

189
void visit_type_%(c_name)s(Visitor *v, %(c_name)s **obj, const char *name, Error **errp)
K
Kevin Wolf 已提交
190 191 192
{
    Error *err = NULL;

193
    visit_start_implicit_struct(v, (void**) obj, sizeof(%(c_name)s), &err);
194 195 196
    if (err) {
        goto out;
    }
197
    visit_get_next_type(v, &(*obj)->type, name, &err);
198
    if (err) {
199
        goto out_obj;
200
    }
201
    switch ((*obj)->type) {
K
Kevin Wolf 已提交
202
''',
203
                c_name=c_name(name))
K
Kevin Wolf 已提交
204

205 206
    # FIXME: When 'number' but not 'int' is present in the alternate, we
    # should allow QTYPE_INT to promote to QTYPE_FLOAT.
207
    for var in variants.variants:
K
Kevin Wolf 已提交
208
        ret += mcgen('''
209
    case %(case)s:
210
        visit_type_%(c_type)s(v, &(*obj)->u.%(c_name)s, name, &err);
211
        break;
K
Kevin Wolf 已提交
212
''',
213
                     case=var.type.alternate_qtype(),
214 215
                     c_type=var.type.c_name(),
                     c_name=c_name(var.name))
K
Kevin Wolf 已提交
216 217

    ret += mcgen('''
218
    default:
219 220
        error_setg(&err, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",
                   "%(name)s");
K
Kevin Wolf 已提交
221
    }
222
out_obj:
223 224
    error_propagate(errp, err);
    err = NULL;
225
    visit_end_implicit_struct(v, &err);
226 227
out:
    error_propagate(errp, err);
K
Kevin Wolf 已提交
228
}
229 230
''',
                 name=name)
K
Kevin Wolf 已提交
231 232 233

    return ret

234

235 236
def gen_visit_union(name, base, variants):
    ret = ''
237

238
    if base:
239
        ret += gen_visit_fields_decl(base)
240

241 242 243
    for var in variants.variants:
        # Ugly special case for simple union TODO get rid of it
        if not var.simple_union_type():
244
            ret += gen_visit_implicit_struct(var.type)
245

246 247
    ret += mcgen('''

248
void visit_type_%(c_name)s(Visitor *v, %(c_name)s **obj, const char *name, Error **errp)
249
{
250 251
    Error *err = NULL;

252
    visit_start_struct(v, (void **)obj, "%(name)s", name, sizeof(%(c_name)s), &err);
253 254 255
    if (err) {
        goto out;
    }
256 257 258
    if (!*obj) {
        goto out_obj;
    }
259
''',
260
                 c_name=c_name(name), name=name)
261

262
    if base:
263
        ret += mcgen('''
264
    visit_type_%(c_name)s_fields(v, (%(c_name)s **)obj, &err);
265
''',
266 267 268
                     c_name=base.c_name())
    else:
        ret += mcgen('''
269
    visit_type_%(c_type)s(v, &(*obj)->%(c_name)s, "%(name)s", &err);
270 271
''',
                     c_type=variants.tag_member.type.c_name(),
272
                     c_name=c_name(variants.tag_member.name),
273 274 275
                     name=variants.tag_member.name)
    ret += gen_err_check(label='out_obj')
    ret += mcgen('''
276
    if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) {
277 278 279
        goto out_obj;
    }
    switch ((*obj)->%(c_name)s) {
280
''',
281
                 c_name=c_name(variants.tag_member.name))
282

283 284 285
    for var in variants.variants:
        # TODO ugly special case for simple union
        simple_union_type = var.simple_union_type()
286
        ret += mcgen('''
287
    case %(case)s:
288 289 290
''',
                     case=c_enum_const(variants.tag_member.type.name,
                                       var.name))
291
        if simple_union_type:
292
            ret += mcgen('''
293
        visit_type_%(c_type)s(v, &(*obj)->u.%(c_name)s, "data", &err);
294 295 296
''',
                         c_type=simple_union_type.c_name(),
                         c_name=c_name(var.name))
297
        else:
298
            ret += mcgen('''
299
        visit_type_implicit_%(c_type)s(v, &(*obj)->u.%(c_name)s, &err);
300 301 302
''',
                         c_type=var.type.c_name(),
                         c_name=c_name(var.name))
303
        ret += mcgen('''
304
        break;
305
''')
306 307

    ret += mcgen('''
308 309
    default:
        abort();
310
    }
311 312 313
out_obj:
    error_propagate(errp, err);
    err = NULL;
314
    if (*obj) {
315
        visit_end_union(v, !!(*obj)->u.data, &err);
316
    }
317 318
    error_propagate(errp, err);
    err = NULL;
319
    visit_end_struct(v, &err);
320 321
out:
    error_propagate(errp, err);
322 323 324
}
''')

325 326
    return ret

327

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
class QAPISchemaGenVisitVisitor(QAPISchemaVisitor):
    def __init__(self):
        self.decl = None
        self.defn = None
        self._btin = None

    def visit_begin(self, schema):
        self.decl = ''
        self.defn = ''
        self._btin = guardstart('QAPI_VISIT_BUILTIN')

    def visit_end(self):
        # To avoid header dependency hell, we always generate
        # declarations for built-in types in our header files and
        # simply guard them.  See also do_builtins (command line
        # option -b).
        self._btin += guardend('QAPI_VISIT_BUILTIN')
        self.decl = self._btin + self.decl
        self._btin = None

348 349
    def visit_needed(self, entity):
        # Visit everything except implicit objects
350 351
        return not (entity.is_implicit() and
                    isinstance(entity, QAPISchemaObjectType))
352

353
    def visit_enum_type(self, name, info, values, prefix):
354 355 356 357 358 359 360 361 362
        # Special case for our lone builtin enum type
        # TODO use something cleaner than existence of info
        if not info:
            self._btin += gen_visit_decl(name, scalar=True)
            if do_builtins:
                self.defn += gen_visit_enum(name)
        else:
            self.decl += gen_visit_decl(name, scalar=True)
            self.defn += gen_visit_enum(name)
363 364 365 366 367 368 369 370 371 372 373 374 375

    def visit_array_type(self, name, info, element_type):
        decl = gen_visit_decl(name)
        defn = gen_visit_list(name, element_type)
        if isinstance(element_type, QAPISchemaBuiltinType):
            self._btin += decl
            if do_builtins:
                self.defn += defn
        else:
            self.decl += decl
            self.defn += defn

    def visit_object_type(self, name, info, base, members, variants):
376 377
        self.decl += gen_visit_decl(name)
        if variants:
378 379 380 381
            if members:
                # Members other than variants.tag_member not implemented
                assert len(members) == 1
                assert members[0] == variants.tag_member
382 383 384
            self.defn += gen_visit_union(name, base, variants)
        else:
            self.defn += gen_visit_struct(name, base, members)
385 386 387 388 389 390 391 392 393

    def visit_alternate_type(self, name, info, variants):
        self.decl += gen_visit_decl(name)
        self.defn += gen_visit_alternate(name, variants)

# If you link code generated from multiple schemata, you want only one
# instance of the code for built-in types.  Generate it only when
# do_builtins, enabled by command line option -b.  See also
# QAPISchemaGenVisitVisitor.visit_end().
394
do_builtins = False
395

396 397 398
(input_file, output_dir, do_c, do_h, prefix, opts) = \
    parse_command_line("b", ["builtins"])

399
for o, a in opts:
400
    if o in ("-b", "--builtins"):
401
        do_builtins = True
402

403
c_comment = '''
404 405 406 407 408 409 410 411 412 413 414 415
/*
 * schema-defined QAPI visitor functions
 *
 * Copyright IBM, Corp. 2011
 *
 * Authors:
 *  Anthony Liguori   <aliguori@us.ibm.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
 * See the COPYING.LIB file in the top-level directory.
 *
 */
416 417
'''
h_comment = '''
418
/*
419
 * schema-defined QAPI visitor functions
420 421 422 423 424 425 426 427 428 429
 *
 * Copyright IBM, Corp. 2011
 *
 * Authors:
 *  Anthony Liguori   <aliguori@us.ibm.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
 * See the COPYING.LIB file in the top-level directory.
 *
 */
430 431 432 433 434
'''

(fdef, fdecl) = open_output(output_dir, do_c, do_h, prefix,
                            'qapi-visit.c', 'qapi-visit.h',
                            c_comment, h_comment)
435

436 437 438 439
fdef.write(mcgen('''
#include "qemu-common.h"
#include "%(prefix)sqapi-visit.h"
''',
440
                 prefix=prefix))
441

442
fdecl.write(mcgen('''
443
#include "qapi/visitor.h"
444
#include "qapi/qmp/qerror.h"
445
#include "%(prefix)sqapi-types.h"
446

447
''',
448
                  prefix=prefix))
449

450 451 452 453 454
schema = QAPISchema(input_file)
gen = QAPISchemaGenVisitVisitor()
schema.visit(gen)
fdef.write(gen.defn)
fdecl.write(gen.decl)
455

456
close_output(fdef, fdecl)