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