xref: /openbmc/qemu/scripts/qapi/expr.py (revision 6620801f)
1# -*- coding: utf-8 -*-
2#
3# Check (context-free) QAPI schema expression structure
4#
5# Copyright IBM, Corp. 2011
6# Copyright (c) 2013-2019 Red Hat Inc.
7#
8# Authors:
9#  Anthony Liguori <aliguori@us.ibm.com>
10#  Markus Armbruster <armbru@redhat.com>
11#  Eric Blake <eblake@redhat.com>
12#  Marc-André Lureau <marcandre.lureau@redhat.com>
13#
14# This work is licensed under the terms of the GNU GPL, version 2.
15# See the COPYING file in the top-level directory.
16
17import re
18from collections import OrderedDict
19from qapi.common import c_name
20from qapi.error import QAPISemError
21
22
23# Names must be letters, numbers, -, and _.  They must start with letter,
24# except for downstream extensions which must start with __RFQDN_.
25# Dots are only valid in the downstream extension prefix.
26valid_name = re.compile(r'^(__[a-zA-Z0-9.-]+_)?'
27                        '[a-zA-Z][a-zA-Z0-9_-]*$')
28
29
30def check_name_is_str(name, info, source):
31    if not isinstance(name, str):
32        raise QAPISemError(info, "%s requires a string name" % source)
33
34
35def check_name_str(name, info, source,
36                   allow_optional=False, enum_member=False,
37                   permit_upper=False):
38    global valid_name
39    membername = name
40
41    if allow_optional and name.startswith('*'):
42        membername = name[1:]
43    # Enum members can start with a digit, because the generated C
44    # code always prefixes it with the enum name
45    if enum_member and membername[0].isdigit():
46        membername = 'D' + membername
47    # Reserve the entire 'q_' namespace for c_name(), and for 'q_empty'
48    # and 'q_obj_*' implicit type names.
49    if not valid_name.match(membername) or \
50       c_name(membername, False).startswith('q_'):
51        raise QAPISemError(info, "%s has an invalid name" % source)
52    if not permit_upper and name.lower() != name:
53        raise QAPISemError(
54            info, "%s uses uppercase in name" % source)
55    assert not membername.startswith('*')
56
57
58def check_defn_name_str(name, info, meta):
59    check_name_str(name, info, meta, permit_upper=True)
60    if name.endswith('Kind') or name.endswith('List'):
61        raise QAPISemError(
62            info, "%s name should not end in '%s'" % (meta, name[-4:]))
63
64
65def check_keys(value, info, source, required, optional):
66
67    def pprint(elems):
68        return ', '.join("'" + e + "'" for e in sorted(elems))
69
70    missing = set(required) - set(value)
71    if missing:
72        raise QAPISemError(
73            info,
74            "%s misses key%s %s"
75            % (source, 's' if len(missing) > 1 else '',
76               pprint(missing)))
77    allowed = set(required + optional)
78    unknown = set(value) - allowed
79    if unknown:
80        raise QAPISemError(
81            info,
82            "%s has unknown key%s %s\nValid keys are %s."
83            % (source, 's' if len(unknown) > 1 else '',
84               pprint(unknown), pprint(allowed)))
85
86
87def check_flags(expr, info):
88    for key in ['gen', 'success-response']:
89        if key in expr and expr[key] is not False:
90            raise QAPISemError(
91                info, "flag '%s' may only use false value" % key)
92    for key in ['boxed', 'allow-oob', 'allow-preconfig']:
93        if key in expr and expr[key] is not True:
94            raise QAPISemError(
95                info, "flag '%s' may only use true value" % key)
96
97
98def check_if(expr, info, source):
99
100    def check_if_str(ifcond, info):
101        if not isinstance(ifcond, str):
102            raise QAPISemError(
103                info,
104                "'if' condition of %s must be a string or a list of strings"
105                % source)
106        if ifcond.strip() == '':
107            raise QAPISemError(
108                info,
109                "'if' condition '%s' of %s makes no sense"
110                % (ifcond, source))
111
112    ifcond = expr.get('if')
113    if ifcond is None:
114        return
115    if isinstance(ifcond, list):
116        if ifcond == []:
117            raise QAPISemError(
118                info, "'if' condition [] of %s is useless" % source)
119        for elt in ifcond:
120            check_if_str(elt, info)
121    else:
122        check_if_str(ifcond, info)
123        expr['if'] = [ifcond]
124
125
126def normalize_members(members):
127    if isinstance(members, OrderedDict):
128        for key, arg in members.items():
129            if isinstance(arg, dict):
130                continue
131            members[key] = {'type': arg}
132
133
134def check_type(value, info, source,
135               allow_array=False, allow_dict=False):
136    if value is None:
137        return
138
139    # Array type
140    if isinstance(value, list):
141        if not allow_array:
142            raise QAPISemError(info, "%s cannot be an array" % source)
143        if len(value) != 1 or not isinstance(value[0], str):
144            raise QAPISemError(info,
145                               "%s: array type must contain single type name" %
146                               source)
147        return
148
149    # Type name
150    if isinstance(value, str):
151        return
152
153    # Anonymous type
154
155    if not allow_dict:
156        raise QAPISemError(info, "%s should be a type name" % source)
157
158    if not isinstance(value, OrderedDict):
159        raise QAPISemError(info,
160                           "%s should be an object or type name" % source)
161
162    permit_upper = allow_dict in info.pragma.name_case_whitelist
163
164    # value is a dictionary, check that each member is okay
165    for (key, arg) in value.items():
166        key_source = "%s member '%s'" % (source, key)
167        check_name_str(key, info, key_source,
168                       allow_optional=True, permit_upper=permit_upper)
169        if c_name(key, False) == 'u' or c_name(key, False).startswith('has_'):
170            raise QAPISemError(info, "%s uses reserved name" % key_source)
171        check_keys(arg, info, key_source, ['type'], ['if'])
172        check_if(arg, info, key_source)
173        check_type(arg['type'], info, key_source, allow_array=True)
174
175
176def check_features(features, info):
177    if features is None:
178        return
179    if not isinstance(features, list):
180        raise QAPISemError(info, "'features' must be an array")
181    features[:] = [f if isinstance(f, dict) else {'name': f}
182                   for f in features]
183    for f in features:
184        source = "'features' member"
185        assert isinstance(f, dict)
186        check_keys(f, info, source, ['name'], ['if'])
187        check_name_is_str(f['name'], info, source)
188        source = "%s '%s'" % (source, f['name'])
189        check_name_str(f['name'], info, source)
190        check_if(f, info, source)
191
192
193def check_enum(expr, info):
194    name = expr['enum']
195    members = expr['data']
196    prefix = expr.get('prefix')
197
198    if not isinstance(members, list):
199        raise QAPISemError(info, "'data' must be an array")
200    if prefix is not None and not isinstance(prefix, str):
201        raise QAPISemError(info, "'prefix' must be a string")
202
203    permit_upper = name in info.pragma.name_case_whitelist
204
205    members[:] = [m if isinstance(m, dict) else {'name': m}
206                  for m in members]
207    for member in members:
208        source = "'data' member"
209        check_keys(member, info, source, ['name'], ['if'])
210        check_name_is_str(member['name'], info, source)
211        source = "%s '%s'" % (source, member['name'])
212        check_name_str(member['name'], info, source,
213                       enum_member=True, permit_upper=permit_upper)
214        check_if(member, info, source)
215
216
217def check_struct(expr, info):
218    name = expr['struct']
219    members = expr['data']
220
221    check_type(members, info, "'data'", allow_dict=name)
222    check_type(expr.get('base'), info, "'base'")
223    check_features(expr.get('features'), info)
224
225
226def check_union(expr, info):
227    name = expr['union']
228    base = expr.get('base')
229    discriminator = expr.get('discriminator')
230    members = expr['data']
231
232    if discriminator is None:   # simple union
233        if base is not None:
234            raise QAPISemError(info, "'base' requires 'discriminator'")
235    else:                       # flat union
236        check_type(base, info, "'base'", allow_dict=name)
237        if not base:
238            raise QAPISemError(info, "'discriminator' requires 'base'")
239        check_name_is_str(discriminator, info, "'discriminator'")
240
241    for (key, value) in members.items():
242        source = "'data' member '%s'" % key
243        check_name_str(key, info, source)
244        check_keys(value, info, source, ['type'], ['if'])
245        check_if(value, info, source)
246        check_type(value['type'], info, source, allow_array=not base)
247
248
249def check_alternate(expr, info):
250    members = expr['data']
251
252    if len(members) == 0:
253        raise QAPISemError(info, "'data' must not be empty")
254    for (key, value) in members.items():
255        source = "'data' member '%s'" % key
256        check_name_str(key, info, source)
257        check_keys(value, info, source, ['type'], ['if'])
258        check_if(value, info, source)
259        check_type(value['type'], info, source)
260
261
262def check_command(expr, info):
263    args = expr.get('data')
264    rets = expr.get('returns')
265    boxed = expr.get('boxed', False)
266
267    if boxed and args is None:
268        raise QAPISemError(info, "'boxed': true requires 'data'")
269    check_type(args, info, "'data'", allow_dict=not boxed)
270    check_type(rets, info, "'returns'", allow_array=True)
271    check_features(expr.get('features'), info)
272
273
274def check_event(expr, info):
275    args = expr.get('data')
276    boxed = expr.get('boxed', False)
277
278    if boxed and args is None:
279        raise QAPISemError(info, "'boxed': true requires 'data'")
280    check_type(args, info, "'data'", allow_dict=not boxed)
281
282
283def check_exprs(exprs):
284    for expr_elem in exprs:
285        expr = expr_elem['expr']
286        info = expr_elem['info']
287        doc = expr_elem.get('doc')
288
289        if 'include' in expr:
290            continue
291
292        if 'enum' in expr:
293            meta = 'enum'
294        elif 'union' in expr:
295            meta = 'union'
296        elif 'alternate' in expr:
297            meta = 'alternate'
298        elif 'struct' in expr:
299            meta = 'struct'
300        elif 'command' in expr:
301            meta = 'command'
302        elif 'event' in expr:
303            meta = 'event'
304        else:
305            raise QAPISemError(info, "expression is missing metatype")
306
307        name = expr[meta]
308        check_name_is_str(name, info, "'%s'" % meta)
309        info.set_defn(meta, name)
310        check_defn_name_str(name, info, meta)
311
312        if doc:
313            if doc.symbol != name:
314                raise QAPISemError(
315                    info, "documentation comment is for '%s'" % doc.symbol)
316            doc.check_expr(expr)
317        elif info.pragma.doc_required:
318            raise QAPISemError(info,
319                               "documentation comment required")
320
321        if meta == 'enum':
322            check_keys(expr, info, meta,
323                       ['enum', 'data'], ['if', 'prefix'])
324            check_enum(expr, info)
325        elif meta == 'union':
326            check_keys(expr, info, meta,
327                       ['union', 'data'],
328                       ['base', 'discriminator', 'if'])
329            normalize_members(expr.get('base'))
330            normalize_members(expr['data'])
331            check_union(expr, info)
332        elif meta == 'alternate':
333            check_keys(expr, info, meta,
334                       ['alternate', 'data'], ['if'])
335            normalize_members(expr['data'])
336            check_alternate(expr, info)
337        elif meta == 'struct':
338            check_keys(expr, info, meta,
339                       ['struct', 'data'], ['base', 'if', 'features'])
340            normalize_members(expr['data'])
341            check_struct(expr, info)
342        elif meta == 'command':
343            check_keys(expr, info, meta,
344                       ['command'],
345                       ['data', 'returns', 'boxed', 'if', 'features',
346                        'gen', 'success-response', 'allow-oob',
347                        'allow-preconfig'])
348            normalize_members(expr.get('data'))
349            check_command(expr, info)
350        elif meta == 'event':
351            check_keys(expr, info, meta,
352                       ['event'], ['data', 'boxed', 'if'])
353            normalize_members(expr.get('data'))
354            check_event(expr, info)
355        else:
356            assert False, 'unexpected meta type'
357
358        check_if(expr, info, meta)
359        check_flags(expr, info)
360
361    return exprs
362