1 # -*- coding: utf-8 -*-
3 # Check (context-free) QAPI schema expression structure
5 # Copyright IBM, Corp. 2011
6 # Copyright (c) 2013-2019 Red Hat Inc.
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>
14 # This work is licensed under the terms of the GNU GPL, version 2.
15 # See the COPYING file in the top-level directory.
18 from collections
import OrderedDict
19 from qapi
.common
import c_name
20 from qapi
.error
import QAPISemError
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.
26 valid_name
= re
.compile(r
'^(__[a-zA-Z0-9.-]+_)?'
27 '[a-zA-Z][a-zA-Z0-9_-]*$')
30 def check_name_is_str(name
, info
, source
):
31 if not isinstance(name
, str):
32 raise QAPISemError(info
, "%s requires a string name" % source
)
35 def check_name_str(name
, info
, source
,
36 allow_optional
=False, enum_member
=False,
41 if allow_optional
and name
.startswith('*'):
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
:
54 info
, "%s uses uppercase in name" % source
)
55 assert not membername
.startswith('*')
58 def 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'):
62 info
, "%s name should not end in '%s'" % (meta
, name
[-4:]))
65 def check_keys(value
, info
, source
, required
, optional
):
68 return ', '.join("'" + e
+ "'" for e
in sorted(elems
))
70 missing
= set(required
) - set(value
)
75 % (source
, 's' if len(missing
) > 1 else '',
77 allowed
= set(required
+ optional
)
78 unknown
= set(value
) - allowed
82 "%s has unknown key%s %s\nValid keys are %s."
83 % (source
, 's' if len(unknown
) > 1 else '',
84 pprint(unknown
), pprint(allowed
)))
87 def check_flags(expr
, info
):
88 for key
in ['gen', 'success-response']:
89 if key
in expr
and expr
[key
] is not False:
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:
95 info
, "flag '%s' may only use true value" % key
)
98 def normalize_if(expr
):
99 ifcond
= expr
.get('if')
100 if isinstance(ifcond
, str):
101 expr
['if'] = [ifcond
]
104 def check_if(expr
, info
, source
):
106 def check_if_str(ifcond
, info
):
107 if not isinstance(ifcond
, str):
110 "'if' condition of %s must be a string or a list of strings"
112 if ifcond
.strip() == '':
115 "'if' condition '%s' of %s makes no sense"
118 ifcond
= expr
.get('if')
121 if isinstance(ifcond
, list):
124 info
, "'if' condition [] of %s is useless" % source
)
126 check_if_str(elt
, info
)
128 check_if_str(ifcond
, info
)
131 def normalize_members(members
):
132 if isinstance(members
, OrderedDict
):
133 for key
, arg
in members
.items():
134 if isinstance(arg
, dict):
136 members
[key
] = {'type': arg
}
139 def check_type(value
, info
, source
,
140 allow_array
=False, allow_dict
=False):
145 if isinstance(value
, list):
147 raise QAPISemError(info
, "%s cannot be an array" % source
)
148 if len(value
) != 1 or not isinstance(value
[0], str):
149 raise QAPISemError(info
,
150 "%s: array type must contain single type name" %
155 if isinstance(value
, str):
161 raise QAPISemError(info
, "%s should be a type name" % source
)
163 if not isinstance(value
, OrderedDict
):
164 raise QAPISemError(info
,
165 "%s should be an object or type name" % source
)
167 permit_upper
= allow_dict
in info
.pragma
.name_case_whitelist
169 # value is a dictionary, check that each member is okay
170 for (key
, arg
) in value
.items():
171 key_source
= "%s member '%s'" % (source
, key
)
172 check_name_str(key
, info
, key_source
,
173 allow_optional
=True, permit_upper
=permit_upper
)
174 if c_name(key
, False) == 'u' or c_name(key
, False).startswith('has_'):
175 raise QAPISemError(info
, "%s uses reserved name" % key_source
)
176 check_keys(arg
, info
, key_source
, ['type'], ['if'])
177 check_if(arg
, info
, key_source
)
179 check_type(arg
['type'], info
, key_source
, allow_array
=True)
182 def normalize_features(features
):
183 if isinstance(features
, list):
184 features
[:] = [f
if isinstance(f
, dict) else {'name': f
}
188 def normalize_enum(expr
):
189 if isinstance(expr
['data'], list):
190 expr
['data'] = [m
if isinstance(m
, dict) else {'name': m
}
191 for m
in expr
['data']]
194 def check_enum(expr
, info
):
196 members
= expr
['data']
197 prefix
= expr
.get('prefix')
199 if not isinstance(members
, list):
200 raise QAPISemError(info
, "'data' must be an array")
201 if prefix
is not None and not isinstance(prefix
, str):
202 raise QAPISemError(info
, "'prefix' must be a string")
204 permit_upper
= name
in info
.pragma
.name_case_whitelist
206 for member
in members
:
207 source
= "'data' member"
208 check_keys(member
, info
, source
, ['name'], ['if'])
209 check_name_is_str(member
['name'], info
, source
)
210 source
= "%s '%s'" % (source
, member
['name'])
211 check_name_str(member
['name'], info
, source
,
212 enum_member
=True, permit_upper
=permit_upper
)
213 check_if(member
, info
, source
)
217 def check_struct(expr
, info
):
218 name
= expr
['struct']
219 members
= expr
['data']
220 features
= expr
.get('features')
222 check_type(members
, info
, "'data'", allow_dict
=name
)
223 check_type(expr
.get('base'), info
, "'base'")
226 if not isinstance(features
, list):
227 raise QAPISemError(info
, "'features' must be an array")
229 source
= "'features' member"
230 assert isinstance(f
, dict)
231 check_keys(f
, info
, source
, ['name'], ['if'])
232 check_name_is_str(f
['name'], info
, source
)
233 source
= "%s '%s'" % (source
, f
['name'])
234 check_name_str(f
['name'], info
, source
)
235 check_if(f
, info
, source
)
239 def check_union(expr
, info
):
241 base
= expr
.get('base')
242 discriminator
= expr
.get('discriminator')
243 members
= expr
['data']
245 if discriminator
is None: # simple union
247 raise QAPISemError(info
, "'base' requires 'discriminator'")
249 check_type(base
, info
, "'base'", allow_dict
=name
)
251 raise QAPISemError(info
, "'discriminator' requires 'base'")
252 check_name_is_str(discriminator
, info
, "'discriminator'")
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
)
260 check_type(value
['type'], info
, source
, allow_array
=not base
)
263 def check_alternate(expr
, info
):
264 members
= expr
['data']
266 if len(members
) == 0:
267 raise QAPISemError(info
, "'data' must not be empty")
268 for (key
, value
) in members
.items():
269 source
= "'data' member '%s'" % key
270 check_name_str(key
, info
, source
)
271 check_keys(value
, info
, source
, ['type'], ['if'])
272 check_if(value
, info
, source
)
274 check_type(value
['type'], info
, source
)
277 def check_command(expr
, info
):
278 args
= expr
.get('data')
279 rets
= expr
.get('returns')
280 boxed
= expr
.get('boxed', False)
282 if boxed
and args
is None:
283 raise QAPISemError(info
, "'boxed': true requires 'data'")
284 check_type(args
, info
, "'data'", allow_dict
=not boxed
)
285 check_type(rets
, info
, "'returns'", allow_array
=True)
288 def check_event(expr
, info
):
289 args
= expr
.get('data')
290 boxed
= expr
.get('boxed', False)
292 if boxed
and args
is None:
293 raise QAPISemError(info
, "'boxed': true requires 'data'")
294 check_type(args
, info
, "'data'", allow_dict
=not boxed
)
297 def check_exprs(exprs
):
298 for expr_elem
in exprs
:
299 expr
= expr_elem
['expr']
300 info
= expr_elem
['info']
301 doc
= expr_elem
.get('doc')
303 if 'include' in expr
:
308 elif 'union' in expr
:
310 elif 'alternate' in expr
:
312 elif 'struct' in expr
:
314 elif 'command' in expr
:
316 elif 'event' in expr
:
319 raise QAPISemError(info
, "expression is missing metatype")
322 check_name_is_str(name
, info
, "'%s'" % meta
)
323 info
.set_defn(meta
, name
)
324 check_defn_name_str(name
, info
, meta
)
327 if doc
.symbol
!= name
:
329 info
, "documentation comment is for '%s'" % doc
.symbol
)
331 elif info
.pragma
.doc_required
:
332 raise QAPISemError(info
,
333 "documentation comment required")
336 check_keys(expr
, info
, meta
,
337 ['enum', 'data'], ['if', 'prefix'])
339 check_enum(expr
, info
)
340 elif meta
== 'union':
341 check_keys(expr
, info
, meta
,
343 ['base', 'discriminator', 'if'])
344 normalize_members(expr
.get('base'))
345 normalize_members(expr
['data'])
346 check_union(expr
, info
)
347 elif meta
== 'alternate':
348 check_keys(expr
, info
, meta
,
349 ['alternate', 'data'], ['if'])
350 normalize_members(expr
['data'])
351 check_alternate(expr
, info
)
352 elif meta
== 'struct':
353 check_keys(expr
, info
, meta
,
354 ['struct', 'data'], ['base', 'if', 'features'])
355 normalize_members(expr
['data'])
356 normalize_features(expr
.get('features'))
357 check_struct(expr
, info
)
358 elif meta
== 'command':
359 check_keys(expr
, info
, meta
,
361 ['data', 'returns', 'boxed', 'if',
362 'gen', 'success-response', 'allow-oob',
364 normalize_members(expr
.get('data'))
365 check_command(expr
, info
)
366 elif meta
== 'event':
367 check_keys(expr
, info
, meta
,
368 ['event'], ['data', 'boxed', 'if'])
369 normalize_members(expr
.get('data'))
370 check_event(expr
, info
)
372 assert False, 'unexpected meta type'
375 check_if(expr
, info
, meta
)
376 check_flags(expr
, info
)