xref: /openbmc/qemu/scripts/qapi/gen.py (revision 17d40c395748dab4cd579d698b89ba6f51ffb692)
1# -*- coding: utf-8 -*-
2#
3# QAPI code generation
4#
5# Copyright (c) 2015-2019 Red Hat Inc.
6#
7# Authors:
8#  Markus Armbruster <armbru@redhat.com>
9#  Marc-André Lureau <marcandre.lureau@redhat.com>
10#
11# This work is licensed under the terms of the GNU GPL, version 2.
12# See the COPYING file in the top-level directory.
13
14from contextlib import contextmanager
15import errno
16import os
17import re
18from typing import (
19    Dict,
20    Iterator,
21    List,
22    Optional,
23    Tuple,
24)
25
26from .common import (
27    c_fname,
28    c_name,
29    gen_endif,
30    gen_if,
31    guardend,
32    guardstart,
33    mcgen,
34)
35from .schema import QAPISchemaObjectType, QAPISchemaVisitor
36from .source import QAPISourceInfo
37
38
39class QAPIGen:
40    def __init__(self, fname: Optional[str]):
41        self.fname = fname
42        self._preamble = ''
43        self._body = ''
44
45    def preamble_add(self, text: str) -> None:
46        self._preamble += text
47
48    def add(self, text: str) -> None:
49        self._body += text
50
51    def get_content(self) -> str:
52        return self._top() + self._preamble + self._body + self._bottom()
53
54    def _top(self) -> str:
55        return ''
56
57    def _bottom(self) -> str:
58        return ''
59
60    def write(self, output_dir: str) -> None:
61        # Include paths starting with ../ are used to reuse modules of the main
62        # schema in specialised schemas. Don't overwrite the files that are
63        # already generated for the main schema.
64        if self.fname.startswith('../'):
65            return
66        pathname = os.path.join(output_dir, self.fname)
67        odir = os.path.dirname(pathname)
68        if odir:
69            try:
70                os.makedirs(odir)
71            except os.error as e:
72                if e.errno != errno.EEXIST:
73                    raise
74        fd = os.open(pathname, os.O_RDWR | os.O_CREAT, 0o666)
75        f = open(fd, 'r+', encoding='utf-8')
76        text = self.get_content()
77        oldtext = f.read(len(text) + 1)
78        if text != oldtext:
79            f.seek(0)
80            f.truncate(0)
81            f.write(text)
82        f.close()
83
84
85def _wrap_ifcond(ifcond: List[str], before: str, after: str) -> str:
86    if before == after:
87        return after   # suppress empty #if ... #endif
88
89    assert after.startswith(before)
90    out = before
91    added = after[len(before):]
92    if added[0] == '\n':
93        out += '\n'
94        added = added[1:]
95    out += gen_if(ifcond)
96    out += added
97    out += gen_endif(ifcond)
98    return out
99
100
101def build_params(arg_type: Optional[QAPISchemaObjectType],
102                 boxed: bool,
103                 extra: Optional[str] = None) -> str:
104    ret = ''
105    sep = ''
106    if boxed:
107        assert arg_type
108        ret += '%s arg' % arg_type.c_param_type()
109        sep = ', '
110    elif arg_type:
111        assert not arg_type.variants
112        for memb in arg_type.members:
113            ret += sep
114            sep = ', '
115            if memb.optional:
116                ret += 'bool has_%s, ' % c_name(memb.name)
117            ret += '%s %s' % (memb.type.c_param_type(),
118                              c_name(memb.name))
119    if extra:
120        ret += sep + extra
121    return ret if ret else 'void'
122
123
124class QAPIGenCCode(QAPIGen):
125    def __init__(self, fname: Optional[str]):
126        super().__init__(fname)
127        self._start_if: Optional[Tuple[List[str], str, str]] = None
128
129    def start_if(self, ifcond: List[str]) -> None:
130        assert self._start_if is None
131        self._start_if = (ifcond, self._body, self._preamble)
132
133    def end_if(self) -> None:
134        assert self._start_if
135        self._wrap_ifcond()
136        self._start_if = None
137
138    def _wrap_ifcond(self) -> None:
139        self._body = _wrap_ifcond(self._start_if[0],
140                                  self._start_if[1], self._body)
141        self._preamble = _wrap_ifcond(self._start_if[0],
142                                      self._start_if[2], self._preamble)
143
144    def get_content(self) -> str:
145        assert self._start_if is None
146        return super().get_content()
147
148
149class QAPIGenC(QAPIGenCCode):
150    def __init__(self, fname: str, blurb: str, pydoc: str):
151        super().__init__(fname)
152        self._blurb = blurb
153        self._copyright = '\n * '.join(re.findall(r'^Copyright .*', pydoc,
154                                                  re.MULTILINE))
155
156    def _top(self) -> str:
157        return mcgen('''
158/* AUTOMATICALLY GENERATED, DO NOT MODIFY */
159
160/*
161%(blurb)s
162 *
163 * %(copyright)s
164 *
165 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
166 * See the COPYING.LIB file in the top-level directory.
167 */
168
169''',
170                     blurb=self._blurb, copyright=self._copyright)
171
172    def _bottom(self) -> str:
173        return mcgen('''
174
175/* Dummy declaration to prevent empty .o file */
176char qapi_dummy_%(name)s;
177''',
178                     name=c_fname(self.fname))
179
180
181class QAPIGenH(QAPIGenC):
182    def _top(self) -> str:
183        return super()._top() + guardstart(self.fname)
184
185    def _bottom(self) -> str:
186        return guardend(self.fname)
187
188
189@contextmanager
190def ifcontext(ifcond: List[str], *args: QAPIGenCCode) -> Iterator[None]:
191    """
192    A with-statement context manager that wraps with `start_if()` / `end_if()`.
193
194    :param ifcond: A list of conditionals, passed to `start_if()`.
195    :param args: any number of `QAPIGenCCode`.
196
197    Example::
198
199        with ifcontext(ifcond, self._genh, self._genc):
200            modify self._genh and self._genc ...
201
202    Is equivalent to calling::
203
204        self._genh.start_if(ifcond)
205        self._genc.start_if(ifcond)
206        modify self._genh and self._genc ...
207        self._genh.end_if()
208        self._genc.end_if()
209    """
210    for arg in args:
211        arg.start_if(ifcond)
212    yield
213    for arg in args:
214        arg.end_if()
215
216
217class QAPISchemaMonolithicCVisitor(QAPISchemaVisitor):
218    def __init__(self,
219                 prefix: str,
220                 what: str,
221                 blurb: str,
222                 pydoc: str):
223        self._prefix = prefix
224        self._what = what
225        self._genc = QAPIGenC(self._prefix + self._what + '.c',
226                              blurb, pydoc)
227        self._genh = QAPIGenH(self._prefix + self._what + '.h',
228                              blurb, pydoc)
229
230    def write(self, output_dir: str) -> None:
231        self._genc.write(output_dir)
232        self._genh.write(output_dir)
233
234
235class QAPISchemaModularCVisitor(QAPISchemaVisitor):
236    def __init__(self,
237                 prefix: str,
238                 what: str,
239                 user_blurb: str,
240                 builtin_blurb: Optional[str],
241                 pydoc: str):
242        self._prefix = prefix
243        self._what = what
244        self._user_blurb = user_blurb
245        self._builtin_blurb = builtin_blurb
246        self._pydoc = pydoc
247        self._genc: Optional[QAPIGenC] = None
248        self._genh: Optional[QAPIGenH] = None
249        self._module: Dict[Optional[str], Tuple[QAPIGenC, QAPIGenH]] = {}
250        self._main_module: Optional[str] = None
251
252    @staticmethod
253    def _is_user_module(name: Optional[str]) -> bool:
254        return bool(name and not name.startswith('./'))
255
256    @staticmethod
257    def _is_builtin_module(name: Optional[str]) -> bool:
258        return not name
259
260    def _module_dirname(self, what: str, name: Optional[str]) -> str:
261        if self._is_user_module(name):
262            return os.path.dirname(name)
263        return ''
264
265    def _module_basename(self, what: str, name: Optional[str]) -> str:
266        ret = '' if self._is_builtin_module(name) else self._prefix
267        if self._is_user_module(name):
268            basename = os.path.basename(name)
269            ret += what
270            if name != self._main_module:
271                ret += '-' + os.path.splitext(basename)[0]
272        else:
273            name = name[2:] if name else 'builtin'
274            ret += re.sub(r'-', '-' + name + '-', what)
275        return ret
276
277    def _module_filename(self, what: str, name: Optional[str]) -> str:
278        return os.path.join(self._module_dirname(what, name),
279                            self._module_basename(what, name))
280
281    def _add_module(self, name: Optional[str], blurb: str) -> None:
282        basename = self._module_filename(self._what, name)
283        genc = QAPIGenC(basename + '.c', blurb, self._pydoc)
284        genh = QAPIGenH(basename + '.h', blurb, self._pydoc)
285        self._module[name] = (genc, genh)
286        self._genc, self._genh = self._module[name]
287
288    def _add_user_module(self, name: str, blurb: str) -> None:
289        assert self._is_user_module(name)
290        if self._main_module is None:
291            self._main_module = name
292        self._add_module(name, blurb)
293
294    def _add_system_module(self, name: Optional[str], blurb: str) -> None:
295        self._add_module(name and './' + name, blurb)
296
297    def write(self, output_dir: str, opt_builtins: bool = False) -> None:
298        for name in self._module:
299            if self._is_builtin_module(name) and not opt_builtins:
300                continue
301            (genc, genh) = self._module[name]
302            genc.write(output_dir)
303            genh.write(output_dir)
304
305    def _begin_system_module(self, name: None) -> None:
306        pass
307
308    def _begin_user_module(self, name: str) -> None:
309        pass
310
311    def visit_module(self, name: Optional[str]) -> None:
312        if name is None:
313            if self._builtin_blurb:
314                self._add_system_module(None, self._builtin_blurb)
315                self._begin_system_module(name)
316            else:
317                # The built-in module has not been created.  No code may
318                # be generated.
319                self._genc = None
320                self._genh = None
321        else:
322            self._add_user_module(name, self._user_blurb)
323            self._begin_user_module(name)
324
325    def visit_include(self, name: str, info: QAPISourceInfo) -> None:
326        relname = os.path.relpath(self._module_filename(self._what, name),
327                                  os.path.dirname(self._genh.fname))
328        self._genh.preamble_add(mcgen('''
329#include "%(relname)s.h"
330''',
331                                      relname=relname))
332