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 membername = name 39 40 if allow_optional and name.startswith('*'): 41 membername = name[1:] 42 # Enum members can start with a digit, because the generated C 43 # code always prefixes it with the enum name 44 if enum_member and membername[0].isdigit(): 45 membername = 'D' + membername 46 # Reserve the entire 'q_' namespace for c_name(), and for 'q_empty' 47 # and 'q_obj_*' implicit type names. 48 if not valid_name.match(membername) or \ 49 c_name(membername, False).startswith('q_'): 50 raise QAPISemError(info, "%s has an invalid name" % source) 51 if not permit_upper and name.lower() != name: 52 raise QAPISemError( 53 info, "%s uses uppercase in name" % source) 54 assert not membername.startswith('*') 55 56 57def check_defn_name_str(name, info, meta): 58 check_name_str(name, info, meta, permit_upper=True) 59 if name.endswith('Kind') or name.endswith('List'): 60 raise QAPISemError( 61 info, "%s name should not end in '%s'" % (meta, name[-4:])) 62 63 64def check_keys(value, info, source, required, optional): 65 66 def pprint(elems): 67 return ', '.join("'" + e + "'" for e in sorted(elems)) 68 69 missing = set(required) - set(value) 70 if missing: 71 raise QAPISemError( 72 info, 73 "%s misses key%s %s" 74 % (source, 's' if len(missing) > 1 else '', 75 pprint(missing))) 76 allowed = set(required + optional) 77 unknown = set(value) - allowed 78 if unknown: 79 raise QAPISemError( 80 info, 81 "%s has unknown key%s %s\nValid keys are %s." 82 % (source, 's' if len(unknown) > 1 else '', 83 pprint(unknown), pprint(allowed))) 84 85 86def check_flags(expr, info): 87 for key in ['gen', 'success-response']: 88 if key in expr and expr[key] is not False: 89 raise QAPISemError( 90 info, "flag '%s' may only use false value" % key) 91 for key in ['boxed', 'allow-oob', 'allow-preconfig']: 92 if key in expr and expr[key] is not True: 93 raise QAPISemError( 94 info, "flag '%s' may only use true value" % key) 95 96 97def check_if(expr, info, source): 98 99 def check_if_str(ifcond, info): 100 if not isinstance(ifcond, str): 101 raise QAPISemError( 102 info, 103 "'if' condition of %s must be a string or a list of strings" 104 % source) 105 if ifcond.strip() == '': 106 raise QAPISemError( 107 info, 108 "'if' condition '%s' of %s makes no sense" 109 % (ifcond, source)) 110 111 ifcond = expr.get('if') 112 if ifcond is None: 113 return 114 if isinstance(ifcond, list): 115 if ifcond == []: 116 raise QAPISemError( 117 info, "'if' condition [] of %s is useless" % source) 118 for elt in ifcond: 119 check_if_str(elt, info) 120 else: 121 check_if_str(ifcond, info) 122 expr['if'] = [ifcond] 123 124 125def normalize_members(members): 126 if isinstance(members, OrderedDict): 127 for key, arg in members.items(): 128 if isinstance(arg, dict): 129 continue 130 members[key] = {'type': arg} 131 132 133def check_type(value, info, source, 134 allow_array=False, allow_dict=False): 135 if value is None: 136 return 137 138 # Array type 139 if isinstance(value, list): 140 if not allow_array: 141 raise QAPISemError(info, "%s cannot be an array" % source) 142 if len(value) != 1 or not isinstance(value[0], str): 143 raise QAPISemError(info, 144 "%s: array type must contain single type name" % 145 source) 146 return 147 148 # Type name 149 if isinstance(value, str): 150 return 151 152 # Anonymous type 153 154 if not allow_dict: 155 raise QAPISemError(info, "%s should be a type name" % source) 156 157 if not isinstance(value, OrderedDict): 158 raise QAPISemError(info, 159 "%s should be an object or type name" % source) 160 161 permit_upper = allow_dict in info.pragma.name_case_whitelist 162 163 # value is a dictionary, check that each member is okay 164 for (key, arg) in value.items(): 165 key_source = "%s member '%s'" % (source, key) 166 check_name_str(key, info, key_source, 167 allow_optional=True, permit_upper=permit_upper) 168 if c_name(key, False) == 'u' or c_name(key, False).startswith('has_'): 169 raise QAPISemError(info, "%s uses reserved name" % key_source) 170 check_keys(arg, info, key_source, ['type'], ['if']) 171 check_if(arg, info, key_source) 172 check_type(arg['type'], info, key_source, allow_array=True) 173 174 175def check_features(features, info): 176 if features is None: 177 return 178 if not isinstance(features, list): 179 raise QAPISemError(info, "'features' must be an array") 180 features[:] = [f if isinstance(f, dict) else {'name': f} 181 for f in features] 182 for f in features: 183 source = "'features' member" 184 assert isinstance(f, dict) 185 check_keys(f, info, source, ['name'], ['if']) 186 check_name_is_str(f['name'], info, source) 187 source = "%s '%s'" % (source, f['name']) 188 check_name_str(f['name'], info, source) 189 check_if(f, info, source) 190 191 192def check_enum(expr, info): 193 name = expr['enum'] 194 members = expr['data'] 195 prefix = expr.get('prefix') 196 197 if not isinstance(members, list): 198 raise QAPISemError(info, "'data' must be an array") 199 if prefix is not None and not isinstance(prefix, str): 200 raise QAPISemError(info, "'prefix' must be a string") 201 202 permit_upper = name in info.pragma.name_case_whitelist 203 204 members[:] = [m if isinstance(m, dict) else {'name': m} 205 for m in members] 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) 214 215 216def check_struct(expr, info): 217 name = expr['struct'] 218 members = expr['data'] 219 220 check_type(members, info, "'data'", allow_dict=name) 221 check_type(expr.get('base'), info, "'base'") 222 check_features(expr.get('features'), info) 223 224 225def check_union(expr, info): 226 name = expr['union'] 227 base = expr.get('base') 228 discriminator = expr.get('discriminator') 229 members = expr['data'] 230 231 if discriminator is None: # simple union 232 if base is not None: 233 raise QAPISemError(info, "'base' requires 'discriminator'") 234 else: # flat union 235 check_type(base, info, "'base'", allow_dict=name) 236 if not base: 237 raise QAPISemError(info, "'discriminator' requires 'base'") 238 check_name_is_str(discriminator, info, "'discriminator'") 239 240 for (key, value) in members.items(): 241 source = "'data' member '%s'" % key 242 check_name_str(key, info, source) 243 check_keys(value, info, source, ['type'], ['if']) 244 check_if(value, info, source) 245 check_type(value['type'], info, source, allow_array=not base) 246 247 248def check_alternate(expr, info): 249 members = expr['data'] 250 251 if not members: 252 raise QAPISemError(info, "'data' must not be empty") 253 for (key, value) in members.items(): 254 source = "'data' member '%s'" % key 255 check_name_str(key, info, source) 256 check_keys(value, info, source, ['type'], ['if']) 257 check_if(value, info, source) 258 check_type(value['type'], info, source) 259 260 261def check_command(expr, info): 262 args = expr.get('data') 263 rets = expr.get('returns') 264 boxed = expr.get('boxed', False) 265 266 if boxed and args is None: 267 raise QAPISemError(info, "'boxed': true requires 'data'") 268 check_type(args, info, "'data'", allow_dict=not boxed) 269 check_type(rets, info, "'returns'", allow_array=True) 270 check_features(expr.get('features'), info) 271 272 273def check_event(expr, info): 274 args = expr.get('data') 275 boxed = expr.get('boxed', False) 276 277 if boxed and args is None: 278 raise QAPISemError(info, "'boxed': true requires 'data'") 279 check_type(args, info, "'data'", allow_dict=not boxed) 280 281 282def check_exprs(exprs): 283 for expr_elem in exprs: 284 expr = expr_elem['expr'] 285 info = expr_elem['info'] 286 doc = expr_elem.get('doc') 287 288 if 'include' in expr: 289 continue 290 291 if 'enum' in expr: 292 meta = 'enum' 293 elif 'union' in expr: 294 meta = 'union' 295 elif 'alternate' in expr: 296 meta = 'alternate' 297 elif 'struct' in expr: 298 meta = 'struct' 299 elif 'command' in expr: 300 meta = 'command' 301 elif 'event' in expr: 302 meta = 'event' 303 else: 304 raise QAPISemError(info, "expression is missing metatype") 305 306 name = expr[meta] 307 check_name_is_str(name, info, "'%s'" % meta) 308 info.set_defn(meta, name) 309 check_defn_name_str(name, info, meta) 310 311 if doc: 312 if doc.symbol != name: 313 raise QAPISemError( 314 info, "documentation comment is for '%s'" % doc.symbol) 315 doc.check_expr(expr) 316 elif info.pragma.doc_required: 317 raise QAPISemError(info, 318 "documentation comment required") 319 320 if meta == 'enum': 321 check_keys(expr, info, meta, 322 ['enum', 'data'], ['if', 'prefix']) 323 check_enum(expr, info) 324 elif meta == 'union': 325 check_keys(expr, info, meta, 326 ['union', 'data'], 327 ['base', 'discriminator', 'if']) 328 normalize_members(expr.get('base')) 329 normalize_members(expr['data']) 330 check_union(expr, info) 331 elif meta == 'alternate': 332 check_keys(expr, info, meta, 333 ['alternate', 'data'], ['if']) 334 normalize_members(expr['data']) 335 check_alternate(expr, info) 336 elif meta == 'struct': 337 check_keys(expr, info, meta, 338 ['struct', 'data'], ['base', 'if', 'features']) 339 normalize_members(expr['data']) 340 check_struct(expr, info) 341 elif meta == 'command': 342 check_keys(expr, info, meta, 343 ['command'], 344 ['data', 'returns', 'boxed', 'if', 'features', 345 'gen', 'success-response', 'allow-oob', 346 'allow-preconfig']) 347 normalize_members(expr.get('data')) 348 check_command(expr, info) 349 elif meta == 'event': 350 check_keys(expr, info, meta, 351 ['event'], ['data', 'boxed', 'if']) 352 normalize_members(expr.get('data')) 353 check_event(expr, info) 354 else: 355 assert False, 'unexpected meta type' 356 357 check_if(expr, info, meta) 358 check_flags(expr, info) 359 360 return exprs 361