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 17from collections import OrderedDict 18import re 19 20from .common import c_name 21from .error import QAPISemError 22 23 24# Names must be letters, numbers, -, and _. They must start with letter, 25# except for downstream extensions which must start with __RFQDN_. 26# Dots are only valid in the downstream extension prefix. 27valid_name = re.compile(r'^(__[a-zA-Z0-9.-]+_)?' 28 '[a-zA-Z][a-zA-Z0-9_-]*$') 29 30 31def check_name_is_str(name, info, source): 32 if not isinstance(name, str): 33 raise QAPISemError(info, "%s requires a string name" % source) 34 35 36def check_name_str(name, info, source, 37 allow_optional=False, enum_member=False, 38 permit_upper=False): 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', 'coroutine']: 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 if 'allow-oob' in expr and 'coroutine' in expr: 97 # This is not necessarily a fundamental incompatibility, but 98 # we don't have a use case and the desired semantics isn't 99 # obvious. The simplest solution is to forbid it until we get 100 # a use case for it. 101 raise QAPISemError(info, "flags 'allow-oob' and 'coroutine' " 102 "are incompatible") 103 104 105def check_if(expr, info, source): 106 107 def check_if_str(ifcond, info): 108 if not isinstance(ifcond, str): 109 raise QAPISemError( 110 info, 111 "'if' condition of %s must be a string or a list of strings" 112 % source) 113 if ifcond.strip() == '': 114 raise QAPISemError( 115 info, 116 "'if' condition '%s' of %s makes no sense" 117 % (ifcond, source)) 118 119 ifcond = expr.get('if') 120 if ifcond is None: 121 return 122 if isinstance(ifcond, list): 123 if ifcond == []: 124 raise QAPISemError( 125 info, "'if' condition [] of %s is useless" % source) 126 for elt in ifcond: 127 check_if_str(elt, info) 128 else: 129 check_if_str(ifcond, info) 130 expr['if'] = [ifcond] 131 132 133def normalize_members(members): 134 if isinstance(members, OrderedDict): 135 for key, arg in members.items(): 136 if isinstance(arg, dict): 137 continue 138 members[key] = {'type': arg} 139 140 141def check_type(value, info, source, 142 allow_array=False, allow_dict=False): 143 if value is None: 144 return 145 146 # Array type 147 if isinstance(value, list): 148 if not allow_array: 149 raise QAPISemError(info, "%s cannot be an array" % source) 150 if len(value) != 1 or not isinstance(value[0], str): 151 raise QAPISemError(info, 152 "%s: array type must contain single type name" % 153 source) 154 return 155 156 # Type name 157 if isinstance(value, str): 158 return 159 160 # Anonymous type 161 162 if not allow_dict: 163 raise QAPISemError(info, "%s should be a type name" % source) 164 165 if not isinstance(value, OrderedDict): 166 raise QAPISemError(info, 167 "%s should be an object or type name" % source) 168 169 permit_upper = allow_dict in info.pragma.name_case_whitelist 170 171 # value is a dictionary, check that each member is okay 172 for (key, arg) in value.items(): 173 key_source = "%s member '%s'" % (source, key) 174 check_name_str(key, info, key_source, 175 allow_optional=True, permit_upper=permit_upper) 176 if c_name(key, False) == 'u' or c_name(key, False).startswith('has_'): 177 raise QAPISemError(info, "%s uses reserved name" % key_source) 178 check_keys(arg, info, key_source, ['type'], ['if', 'features']) 179 check_if(arg, info, key_source) 180 check_features(arg.get('features'), info) 181 check_type(arg['type'], info, key_source, allow_array=True) 182 183 184def check_features(features, info): 185 if features is None: 186 return 187 if not isinstance(features, list): 188 raise QAPISemError(info, "'features' must be an array") 189 features[:] = [f if isinstance(f, dict) else {'name': f} 190 for f in features] 191 for f in features: 192 source = "'features' member" 193 assert isinstance(f, dict) 194 check_keys(f, info, source, ['name'], ['if']) 195 check_name_is_str(f['name'], info, source) 196 source = "%s '%s'" % (source, f['name']) 197 check_name_str(f['name'], info, source) 198 check_if(f, info, source) 199 200 201def check_enum(expr, info): 202 name = expr['enum'] 203 members = expr['data'] 204 prefix = expr.get('prefix') 205 206 if not isinstance(members, list): 207 raise QAPISemError(info, "'data' must be an array") 208 if prefix is not None and not isinstance(prefix, str): 209 raise QAPISemError(info, "'prefix' must be a string") 210 211 permit_upper = name in info.pragma.name_case_whitelist 212 213 members[:] = [m if isinstance(m, dict) else {'name': m} 214 for m in members] 215 for member in members: 216 source = "'data' member" 217 check_keys(member, info, source, ['name'], ['if']) 218 check_name_is_str(member['name'], info, source) 219 source = "%s '%s'" % (source, member['name']) 220 check_name_str(member['name'], info, source, 221 enum_member=True, permit_upper=permit_upper) 222 check_if(member, info, source) 223 224 225def check_struct(expr, info): 226 name = expr['struct'] 227 members = expr['data'] 228 229 check_type(members, info, "'data'", allow_dict=name) 230 check_type(expr.get('base'), info, "'base'") 231 232 233def check_union(expr, info): 234 name = expr['union'] 235 base = expr.get('base') 236 discriminator = expr.get('discriminator') 237 members = expr['data'] 238 239 if discriminator is None: # simple union 240 if base is not None: 241 raise QAPISemError(info, "'base' requires 'discriminator'") 242 else: # flat union 243 check_type(base, info, "'base'", allow_dict=name) 244 if not base: 245 raise QAPISemError(info, "'discriminator' requires 'base'") 246 check_name_is_str(discriminator, info, "'discriminator'") 247 248 for (key, value) in members.items(): 249 source = "'data' member '%s'" % key 250 check_name_str(key, info, source) 251 check_keys(value, info, source, ['type'], ['if']) 252 check_if(value, info, source) 253 check_type(value['type'], info, source, allow_array=not base) 254 255 256def check_alternate(expr, info): 257 members = expr['data'] 258 259 if not members: 260 raise QAPISemError(info, "'data' must not be empty") 261 for (key, value) in members.items(): 262 source = "'data' member '%s'" % key 263 check_name_str(key, info, source) 264 check_keys(value, info, source, ['type'], ['if']) 265 check_if(value, info, source) 266 check_type(value['type'], info, source) 267 268 269def check_command(expr, info): 270 args = expr.get('data') 271 rets = expr.get('returns') 272 boxed = expr.get('boxed', False) 273 274 if boxed and args is None: 275 raise QAPISemError(info, "'boxed': true requires 'data'") 276 check_type(args, info, "'data'", allow_dict=not boxed) 277 check_type(rets, info, "'returns'", allow_array=True) 278 279 280def check_event(expr, info): 281 args = expr.get('data') 282 boxed = expr.get('boxed', False) 283 284 if boxed and args is None: 285 raise QAPISemError(info, "'boxed': true requires 'data'") 286 check_type(args, info, "'data'", allow_dict=not boxed) 287 288 289def check_exprs(exprs): 290 for expr_elem in exprs: 291 expr = expr_elem['expr'] 292 info = expr_elem['info'] 293 doc = expr_elem.get('doc') 294 295 if 'include' in expr: 296 continue 297 298 if 'enum' in expr: 299 meta = 'enum' 300 elif 'union' in expr: 301 meta = 'union' 302 elif 'alternate' in expr: 303 meta = 'alternate' 304 elif 'struct' in expr: 305 meta = 'struct' 306 elif 'command' in expr: 307 meta = 'command' 308 elif 'event' in expr: 309 meta = 'event' 310 else: 311 raise QAPISemError(info, "expression is missing metatype") 312 313 name = expr[meta] 314 check_name_is_str(name, info, "'%s'" % meta) 315 info.set_defn(meta, name) 316 check_defn_name_str(name, info, meta) 317 318 if doc: 319 if doc.symbol != name: 320 raise QAPISemError( 321 info, "documentation comment is for '%s'" % doc.symbol) 322 doc.check_expr(expr) 323 elif info.pragma.doc_required: 324 raise QAPISemError(info, 325 "documentation comment required") 326 327 if meta == 'enum': 328 check_keys(expr, info, meta, 329 ['enum', 'data'], ['if', 'features', 'prefix']) 330 check_enum(expr, info) 331 elif meta == 'union': 332 check_keys(expr, info, meta, 333 ['union', 'data'], 334 ['base', 'discriminator', 'if', 'features']) 335 normalize_members(expr.get('base')) 336 normalize_members(expr['data']) 337 check_union(expr, info) 338 elif meta == 'alternate': 339 check_keys(expr, info, meta, 340 ['alternate', 'data'], ['if', 'features']) 341 normalize_members(expr['data']) 342 check_alternate(expr, info) 343 elif meta == 'struct': 344 check_keys(expr, info, meta, 345 ['struct', 'data'], ['base', 'if', 'features']) 346 normalize_members(expr['data']) 347 check_struct(expr, info) 348 elif meta == 'command': 349 check_keys(expr, info, meta, 350 ['command'], 351 ['data', 'returns', 'boxed', 'if', 'features', 352 'gen', 'success-response', 'allow-oob', 353 'allow-preconfig', 'coroutine']) 354 normalize_members(expr.get('data')) 355 check_command(expr, info) 356 elif meta == 'event': 357 check_keys(expr, info, meta, 358 ['event'], ['data', 'boxed', 'if', 'features']) 359 normalize_members(expr.get('data')) 360 check_event(expr, info) 361 else: 362 assert False, 'unexpected meta type' 363 364 check_if(expr, info, meta) 365 check_features(expr.get('features'), info) 366 check_flags(expr, info) 367 368 return exprs 369