1"""
2QAPI visitor generator
3
4Copyright IBM, Corp. 2011
5Copyright (C) 2014-2018 Red Hat, Inc.
6
7Authors:
8 Anthony Liguori <aliguori@us.ibm.com>
9 Michael Roth    <mdroth@linux.vnet.ibm.com>
10 Markus Armbruster <armbru@redhat.com>
11
12This work is licensed under the terms of the GNU GPL, version 2.
13See the COPYING file in the top-level directory.
14"""
15
16from typing import List, Optional, Sequence
17
18from .common import (
19    c_enum_const,
20    c_name,
21    gen_endif,
22    gen_if,
23    indent,
24    mcgen,
25)
26from .gen import QAPISchemaModularCVisitor, ifcontext
27from .schema import (
28    QAPISchema,
29    QAPISchemaEnumMember,
30    QAPISchemaEnumType,
31    QAPISchemaFeature,
32    QAPISchemaObjectType,
33    QAPISchemaObjectTypeMember,
34    QAPISchemaType,
35    QAPISchemaVariants,
36)
37from .source import QAPISourceInfo
38
39
40def gen_visit_decl(name: str, scalar: bool = False) -> str:
41    c_type = c_name(name) + ' *'
42    if not scalar:
43        c_type += '*'
44    return mcgen('''
45
46bool visit_type_%(c_name)s(Visitor *v, const char *name,
47                 %(c_type)sobj, Error **errp);
48''',
49                 c_name=c_name(name), c_type=c_type)
50
51
52def gen_visit_members_decl(name: str) -> str:
53    return mcgen('''
54
55bool visit_type_%(c_name)s_members(Visitor *v, %(c_name)s *obj, Error **errp);
56''',
57                 c_name=c_name(name))
58
59
60def gen_visit_object_members(name: str,
61                             base: Optional[QAPISchemaObjectType],
62                             members: List[QAPISchemaObjectTypeMember],
63                             variants: Optional[QAPISchemaVariants]) -> str:
64    ret = mcgen('''
65
66bool visit_type_%(c_name)s_members(Visitor *v, %(c_name)s *obj, Error **errp)
67{
68''',
69                c_name=c_name(name))
70
71    if base:
72        ret += mcgen('''
73    if (!visit_type_%(c_type)s_members(v, (%(c_type)s *)obj, errp)) {
74        return false;
75    }
76''',
77                     c_type=base.c_name())
78
79    for memb in members:
80        deprecated = 'deprecated' in [f.name for f in memb.features]
81        ret += gen_if(memb.ifcond)
82        if memb.optional:
83            ret += mcgen('''
84    if (visit_optional(v, "%(name)s", &obj->has_%(c_name)s)) {
85''',
86                         name=memb.name, c_name=c_name(memb.name))
87            indent.increase()
88        if deprecated:
89            ret += mcgen('''
90    if (!visit_deprecated_accept(v, "%(name)s", errp)) {
91        return false;
92    }
93    if (visit_deprecated(v, "%(name)s")) {
94''',
95                         name=memb.name)
96            indent.increase()
97        ret += mcgen('''
98    if (!visit_type_%(c_type)s(v, "%(name)s", &obj->%(c_name)s, errp)) {
99        return false;
100    }
101''',
102                     c_type=memb.type.c_name(), name=memb.name,
103                     c_name=c_name(memb.name))
104        if deprecated:
105            indent.decrease()
106            ret += mcgen('''
107    }
108''')
109        if memb.optional:
110            indent.decrease()
111            ret += mcgen('''
112    }
113''')
114        ret += gen_endif(memb.ifcond)
115
116    if variants:
117        tag_member = variants.tag_member
118        assert isinstance(tag_member.type, QAPISchemaEnumType)
119
120        ret += mcgen('''
121    switch (obj->%(c_name)s) {
122''',
123                     c_name=c_name(tag_member.name))
124
125        for var in variants.variants:
126            case_str = c_enum_const(tag_member.type.name, var.name,
127                                    tag_member.type.prefix)
128            ret += gen_if(var.ifcond)
129            if var.type.name == 'q_empty':
130                # valid variant and nothing to do
131                ret += mcgen('''
132    case %(case)s:
133        break;
134''',
135                             case=case_str)
136            else:
137                ret += mcgen('''
138    case %(case)s:
139        return visit_type_%(c_type)s_members(v, &obj->u.%(c_name)s, errp);
140''',
141                             case=case_str,
142                             c_type=var.type.c_name(), c_name=c_name(var.name))
143
144            ret += gen_endif(var.ifcond)
145        ret += mcgen('''
146    default:
147        abort();
148    }
149''')
150
151    ret += mcgen('''
152    return true;
153}
154''')
155    return ret
156
157
158def gen_visit_list(name: str, element_type: QAPISchemaType) -> str:
159    return mcgen('''
160
161bool visit_type_%(c_name)s(Visitor *v, const char *name,
162                 %(c_name)s **obj, Error **errp)
163{
164    bool ok = false;
165    %(c_name)s *tail;
166    size_t size = sizeof(**obj);
167
168    if (!visit_start_list(v, name, (GenericList **)obj, size, errp)) {
169        return false;
170    }
171
172    for (tail = *obj; tail;
173         tail = (%(c_name)s *)visit_next_list(v, (GenericList *)tail, size)) {
174        if (!visit_type_%(c_elt_type)s(v, NULL, &tail->value, errp)) {
175            goto out_obj;
176        }
177    }
178
179    ok = visit_check_list(v, errp);
180out_obj:
181    visit_end_list(v, (void **)obj);
182    if (!ok && visit_is_input(v)) {
183        qapi_free_%(c_name)s(*obj);
184        *obj = NULL;
185    }
186    return ok;
187}
188''',
189                 c_name=c_name(name), c_elt_type=element_type.c_name())
190
191
192def gen_visit_enum(name: str) -> str:
193    return mcgen('''
194
195bool visit_type_%(c_name)s(Visitor *v, const char *name,
196                 %(c_name)s *obj, Error **errp)
197{
198    int value = *obj;
199    bool ok = visit_type_enum(v, name, &value, &%(c_name)s_lookup, errp);
200    *obj = value;
201    return ok;
202}
203''',
204                 c_name=c_name(name))
205
206
207def gen_visit_alternate(name: str, variants: QAPISchemaVariants) -> str:
208    ret = mcgen('''
209
210bool visit_type_%(c_name)s(Visitor *v, const char *name,
211                 %(c_name)s **obj, Error **errp)
212{
213    bool ok = false;
214
215    if (!visit_start_alternate(v, name, (GenericAlternate **)obj,
216                               sizeof(**obj), errp)) {
217        return false;
218    }
219    if (!*obj) {
220        /* incomplete */
221        assert(visit_is_dealloc(v));
222        ok = true;
223        goto out_obj;
224    }
225    switch ((*obj)->type) {
226''',
227                c_name=c_name(name))
228
229    for var in variants.variants:
230        ret += gen_if(var.ifcond)
231        ret += mcgen('''
232    case %(case)s:
233''',
234                     case=var.type.alternate_qtype())
235        if isinstance(var.type, QAPISchemaObjectType):
236            ret += mcgen('''
237        if (!visit_start_struct(v, name, NULL, 0, errp)) {
238            break;
239        }
240        if (visit_type_%(c_type)s_members(v, &(*obj)->u.%(c_name)s, errp)) {
241            ok = visit_check_struct(v, errp);
242        }
243        visit_end_struct(v, NULL);
244''',
245                         c_type=var.type.c_name(),
246                         c_name=c_name(var.name))
247        else:
248            ret += mcgen('''
249        ok = visit_type_%(c_type)s(v, name, &(*obj)->u.%(c_name)s, errp);
250''',
251                         c_type=var.type.c_name(),
252                         c_name=c_name(var.name))
253        ret += mcgen('''
254        break;
255''')
256        ret += gen_endif(var.ifcond)
257
258    ret += mcgen('''
259    case QTYPE_NONE:
260        abort();
261    default:
262        assert(visit_is_input(v));
263        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",
264                   "%(name)s");
265        /* Avoid passing invalid *obj to qapi_free_%(c_name)s() */
266        g_free(*obj);
267        *obj = NULL;
268    }
269out_obj:
270    visit_end_alternate(v, (void **)obj);
271    if (!ok && visit_is_input(v)) {
272        qapi_free_%(c_name)s(*obj);
273        *obj = NULL;
274    }
275    return ok;
276}
277''',
278                 name=name, c_name=c_name(name))
279
280    return ret
281
282
283def gen_visit_object(name: str) -> str:
284    return mcgen('''
285
286bool visit_type_%(c_name)s(Visitor *v, const char *name,
287                 %(c_name)s **obj, Error **errp)
288{
289    bool ok = false;
290
291    if (!visit_start_struct(v, name, (void **)obj, sizeof(%(c_name)s), errp)) {
292        return false;
293    }
294    if (!*obj) {
295        /* incomplete */
296        assert(visit_is_dealloc(v));
297        ok = true;
298        goto out_obj;
299    }
300    if (!visit_type_%(c_name)s_members(v, *obj, errp)) {
301        goto out_obj;
302    }
303    ok = visit_check_struct(v, errp);
304out_obj:
305    visit_end_struct(v, (void **)obj);
306    if (!ok && visit_is_input(v)) {
307        qapi_free_%(c_name)s(*obj);
308        *obj = NULL;
309    }
310    return ok;
311}
312''',
313                 c_name=c_name(name))
314
315
316class QAPISchemaGenVisitVisitor(QAPISchemaModularCVisitor):
317
318    def __init__(self, prefix: str):
319        super().__init__(
320            prefix, 'qapi-visit', ' * Schema-defined QAPI visitors',
321            ' * Built-in QAPI visitors', __doc__)
322
323    def _begin_builtin_module(self) -> None:
324        self._genc.preamble_add(mcgen('''
325#include "qemu/osdep.h"
326#include "qapi/error.h"
327#include "qapi/qapi-builtin-visit.h"
328'''))
329        self._genh.preamble_add(mcgen('''
330#include "qapi/visitor.h"
331#include "qapi/qapi-builtin-types.h"
332
333'''))
334
335    def _begin_user_module(self, name: str) -> None:
336        types = self._module_basename('qapi-types', name)
337        visit = self._module_basename('qapi-visit', name)
338        self._genc.preamble_add(mcgen('''
339#include "qemu/osdep.h"
340#include "qapi/error.h"
341#include "qapi/qmp/qerror.h"
342#include "%(visit)s.h"
343''',
344                                      visit=visit))
345        self._genh.preamble_add(mcgen('''
346#include "qapi/qapi-builtin-visit.h"
347#include "%(types)s.h"
348
349''',
350                                      types=types))
351
352    def visit_enum_type(self,
353                        name: str,
354                        info: Optional[QAPISourceInfo],
355                        ifcond: Sequence[str],
356                        features: List[QAPISchemaFeature],
357                        members: List[QAPISchemaEnumMember],
358                        prefix: Optional[str]) -> None:
359        with ifcontext(ifcond, self._genh, self._genc):
360            self._genh.add(gen_visit_decl(name, scalar=True))
361            self._genc.add(gen_visit_enum(name))
362
363    def visit_array_type(self,
364                         name: str,
365                         info: Optional[QAPISourceInfo],
366                         ifcond: Sequence[str],
367                         element_type: QAPISchemaType) -> None:
368        with ifcontext(ifcond, self._genh, self._genc):
369            self._genh.add(gen_visit_decl(name))
370            self._genc.add(gen_visit_list(name, element_type))
371
372    def visit_object_type(self,
373                          name: str,
374                          info: Optional[QAPISourceInfo],
375                          ifcond: Sequence[str],
376                          features: List[QAPISchemaFeature],
377                          base: Optional[QAPISchemaObjectType],
378                          members: List[QAPISchemaObjectTypeMember],
379                          variants: Optional[QAPISchemaVariants]) -> None:
380        # Nothing to do for the special empty builtin
381        if name == 'q_empty':
382            return
383        with ifcontext(ifcond, self._genh, self._genc):
384            self._genh.add(gen_visit_members_decl(name))
385            self._genc.add(gen_visit_object_members(name, base,
386                                                    members, variants))
387            # TODO Worth changing the visitor signature, so we could
388            # directly use rather than repeat type.is_implicit()?
389            if not name.startswith('q_'):
390                # only explicit types need an allocating visit
391                self._genh.add(gen_visit_decl(name))
392                self._genc.add(gen_visit_object(name))
393
394    def visit_alternate_type(self,
395                             name: str,
396                             info: Optional[QAPISourceInfo],
397                             ifcond: Sequence[str],
398                             features: List[QAPISchemaFeature],
399                             variants: QAPISchemaVariants) -> None:
400        with ifcontext(ifcond, self._genh, self._genc):
401            self._genh.add(gen_visit_decl(name))
402            self._genc.add(gen_visit_alternate(name, variants))
403
404
405def gen_visit(schema: QAPISchema,
406              output_dir: str,
407              prefix: str,
408              opt_builtins: bool) -> None:
409    vis = QAPISchemaGenVisitVisitor(prefix)
410    schema.visit(vis)
411    vis.write(output_dir, opt_builtins)
412