1# Copyright (C) 2013 Google Inc. All rights reserved. 2# 3# Redistribution and use in source and binary forms, with or without 4# modification, are permitted provided that the following conditions are 5# met: 6# 7# * Redistributions of source code must retain the above copyright 8# notice, this list of conditions and the following disclaimer. 9# * Redistributions in binary form must reproduce the above 10# copyright notice, this list of conditions and the following disclaimer 11# in the documentation and/or other materials provided with the 12# distribution. 13# * Neither the name of Google Inc. nor the names of its 14# contributors may be used to endorse or promote products derived from 15# this software without specific prior written permission. 16# 17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 29"""Generate template values for attributes. 30 31Extends IdlType with property |constructor_type_name|. 32 33Design doc: http://www.chromium.org/developers/design-documents/idl-compiler 34""" 35 36import idl_types 37from idl_types import inherits_interface 38from v8_globals import includes, interfaces 39import v8_types 40import v8_utilities 41from v8_utilities import capitalize, cpp_name, has_extended_attribute, has_extended_attribute_value, scoped_name, strip_suffix, uncapitalize 42 43 44def generate_attribute(interface, attribute): 45 idl_type = attribute.idl_type 46 base_idl_type = idl_type.base_type 47 extended_attributes = attribute.extended_attributes 48 49 idl_type.add_includes_for_type() 50 51 # [CheckSecurity] 52 is_check_security_for_node = 'CheckSecurity' in extended_attributes 53 if is_check_security_for_node: 54 includes.add('bindings/v8/BindingSecurity.h') 55 # [Custom] 56 has_custom_getter = ('Custom' in extended_attributes and 57 extended_attributes['Custom'] in [None, 'Getter']) 58 has_custom_setter = (not attribute.is_read_only and 59 'Custom' in extended_attributes and 60 extended_attributes['Custom'] in [None, 'Setter']) 61 # [CustomElementCallbacks], [Reflect] 62 is_custom_element_callbacks = 'CustomElementCallbacks' in extended_attributes 63 is_reflect = 'Reflect' in extended_attributes 64 if is_custom_element_callbacks or is_reflect: 65 includes.add('core/dom/custom/CustomElementCallbackDispatcher.h') 66 # [PerWorldBindings] 67 if 'PerWorldBindings' in extended_attributes: 68 assert idl_type.is_wrapper_type or 'LogActivity' in extended_attributes, '[PerWorldBindings] should only be used with wrapper types: %s.%s' % (interface.name, attribute.name) 69 # [RaisesException], [RaisesException=Setter] 70 is_setter_raises_exception = ( 71 'RaisesException' in extended_attributes and 72 extended_attributes['RaisesException'] in [None, 'Setter']) 73 # [TypeChecking] 74 has_type_checking_interface = ( 75 (has_extended_attribute_value(interface, 'TypeChecking', 'Interface') or 76 has_extended_attribute_value(attribute, 'TypeChecking', 'Interface')) and 77 idl_type.is_wrapper_type) 78 has_type_checking_nullable = ( 79 (has_extended_attribute_value(interface, 'TypeChecking', 'Nullable') or 80 has_extended_attribute_value(attribute, 'TypeChecking', 'Nullable')) and 81 idl_type.is_wrapper_type) 82 has_type_checking_unrestricted = ( 83 (has_extended_attribute_value(interface, 'TypeChecking', 'Unrestricted') or 84 has_extended_attribute_value(attribute, 'TypeChecking', 'Unrestricted')) and 85 idl_type.name in ('Float', 'Double')) 86 87 if (base_idl_type == 'EventHandler' and 88 interface.name in ['Window', 'WorkerGlobalScope'] and 89 attribute.name == 'onerror'): 90 includes.add('bindings/v8/V8ErrorHandler.h') 91 92 contents = { 93 'access_control_list': access_control_list(attribute), 94 'activity_logging_world_list_for_getter': v8_utilities.activity_logging_world_list(attribute, 'Getter'), # [ActivityLogging] 95 'activity_logging_world_list_for_setter': v8_utilities.activity_logging_world_list(attribute, 'Setter'), # [ActivityLogging] 96 'activity_logging_include_old_value_for_setter': 'LogPreviousValue' in extended_attributes, # [ActivityLogging] 97 'activity_logging_world_check': v8_utilities.activity_logging_world_check(attribute), # [ActivityLogging] 98 'cached_attribute_validation_method': extended_attributes.get('CachedAttribute'), 99 'conditional_string': v8_utilities.conditional_string(attribute), 100 'constructor_type': idl_type.constructor_type_name 101 if is_constructor_attribute(attribute) else None, 102 'cpp_name': cpp_name(attribute), 103 'cpp_type': idl_type.cpp_type, 104 'cpp_value_to_v8_value': idl_type.cpp_value_to_v8_value(cpp_value='original', creation_context='info.Holder()'), 105 'deprecate_as': v8_utilities.deprecate_as(attribute), # [DeprecateAs] 106 'enum_validation_expression': idl_type.enum_validation_expression, 107 'has_custom_getter': has_custom_getter, 108 'has_custom_setter': has_custom_setter, 109 'has_setter_exception_state': 110 is_setter_raises_exception or has_type_checking_interface or 111 has_type_checking_nullable or has_type_checking_unrestricted or 112 idl_type.is_integer_type or 113 idl_type.name in ('ByteString', 'ScalarValueString'), 114 'has_type_checking_interface': has_type_checking_interface, 115 'has_type_checking_nullable': has_type_checking_nullable, 116 'has_type_checking_unrestricted': has_type_checking_unrestricted, 117 'idl_type': str(idl_type), # need trailing [] on array for Dictionary::ConversionContext::setConversionType 118 'is_call_with_execution_context': v8_utilities.has_extended_attribute_value(attribute, 'CallWith', 'ExecutionContext'), 119 'is_call_with_script_state': v8_utilities.has_extended_attribute_value(attribute, 'CallWith', 'ScriptState'), 120 'is_check_security_for_node': is_check_security_for_node, 121 'is_custom_element_callbacks': is_custom_element_callbacks, 122 'is_expose_js_accessors': 'ExposeJSAccessors' in extended_attributes, 123 'is_getter_raises_exception': # [RaisesException] 124 'RaisesException' in extended_attributes and 125 extended_attributes['RaisesException'] in (None, 'Getter'), 126 'is_initialized_by_event_constructor': 127 'InitializedByEventConstructor' in extended_attributes, 128 'is_keep_alive_for_gc': is_keep_alive_for_gc(interface, attribute), 129 'is_nullable': attribute.idl_type.is_nullable, 130 'is_partial_interface_member': 131 'PartialInterfaceImplementedAs' in extended_attributes, 132 'is_per_world_bindings': 'PerWorldBindings' in extended_attributes, 133 'is_read_only': attribute.is_read_only, 134 'is_reflect': is_reflect, 135 'is_replaceable': 'Replaceable' in attribute.extended_attributes, 136 'is_setter_call_with_execution_context': v8_utilities.has_extended_attribute_value(attribute, 'SetterCallWith', 'ExecutionContext'), 137 'is_setter_raises_exception': is_setter_raises_exception, 138 'is_static': attribute.is_static, 139 'is_url': 'URL' in extended_attributes, 140 'is_unforgeable': 'Unforgeable' in extended_attributes, 141 'measure_as': v8_utilities.measure_as(attribute), # [MeasureAs] 142 'name': attribute.name, 143 'per_context_enabled_function': v8_utilities.per_context_enabled_function_name(attribute), # [PerContextEnabled] 144 'property_attributes': property_attributes(attribute), 145 'put_forwards': 'PutForwards' in extended_attributes, 146 'reflect_empty': extended_attributes.get('ReflectEmpty'), 147 'reflect_invalid': extended_attributes.get('ReflectInvalid', ''), 148 'reflect_missing': extended_attributes.get('ReflectMissing'), 149 'reflect_only': extended_attributes['ReflectOnly'].split('|') 150 if 'ReflectOnly' in extended_attributes else None, 151 'setter_callback': setter_callback_name(interface, attribute), 152 'v8_type': v8_types.v8_type(base_idl_type), 153 'runtime_enabled_function': v8_utilities.runtime_enabled_function_name(attribute), # [RuntimeEnabled] 154 'world_suffixes': ['', 'ForMainWorld'] 155 if 'PerWorldBindings' in extended_attributes 156 else [''], # [PerWorldBindings] 157 } 158 159 if is_constructor_attribute(attribute): 160 generate_constructor_getter(interface, attribute, contents) 161 return contents 162 if not has_custom_getter: 163 generate_getter(interface, attribute, contents) 164 if (not has_custom_setter and 165 (not attribute.is_read_only or 'PutForwards' in extended_attributes)): 166 generate_setter(interface, attribute, contents) 167 168 return contents 169 170 171################################################################################ 172# Getter 173################################################################################ 174 175def generate_getter(interface, attribute, contents): 176 idl_type = attribute.idl_type 177 base_idl_type = idl_type.base_type 178 extended_attributes = attribute.extended_attributes 179 180 cpp_value = getter_expression(interface, attribute, contents) 181 # Normally we can inline the function call into the return statement to 182 # avoid the overhead of using a Ref<> temporary, but for some cases 183 # (nullable types, EventHandler, [CachedAttribute], or if there are 184 # exceptions), we need to use a local variable. 185 # FIXME: check if compilers are smart enough to inline this, and if so, 186 # always use a local variable (for readability and CG simplicity). 187 release = False 188 if (idl_type.is_nullable or 189 base_idl_type == 'EventHandler' or 190 'CachedAttribute' in extended_attributes or 191 'ReflectOnly' in extended_attributes or 192 contents['is_getter_raises_exception']): 193 contents['cpp_value_original'] = cpp_value 194 cpp_value = 'v8Value' 195 # EventHandler has special handling 196 if base_idl_type != 'EventHandler' and idl_type.is_interface_type: 197 release = True 198 199 def v8_set_return_value_statement(for_main_world=False): 200 if contents['is_keep_alive_for_gc']: 201 return 'v8SetReturnValue(info, wrapper)' 202 return idl_type.v8_set_return_value(cpp_value, extended_attributes=extended_attributes, script_wrappable='impl', release=release, for_main_world=for_main_world) 203 204 contents.update({ 205 'cpp_value': cpp_value, 206 'cpp_value_to_v8_value': idl_type.cpp_value_to_v8_value(cpp_value=cpp_value, creation_context='info.Holder()'), 207 'v8_set_return_value_for_main_world': v8_set_return_value_statement(for_main_world=True), 208 'v8_set_return_value': v8_set_return_value_statement(), 209 }) 210 211 212def getter_expression(interface, attribute, contents): 213 arguments = [] 214 this_getter_base_name = getter_base_name(interface, attribute, arguments) 215 getter_name = scoped_name(interface, attribute, this_getter_base_name) 216 217 arguments.extend(v8_utilities.call_with_arguments( 218 attribute.extended_attributes.get('CallWith'))) 219 # Members of IDL partial interface definitions are implemented in C++ as 220 # static member functions, which for instance members (non-static members) 221 # take *impl as their first argument 222 if ('PartialInterfaceImplementedAs' in attribute.extended_attributes and 223 not attribute.is_static): 224 arguments.append('*impl') 225 if attribute.idl_type.is_nullable and not contents['has_type_checking_nullable']: 226 arguments.append('isNull') 227 if contents['is_getter_raises_exception']: 228 arguments.append('exceptionState') 229 return '%s(%s)' % (getter_name, ', '.join(arguments)) 230 231 232CONTENT_ATTRIBUTE_GETTER_NAMES = { 233 'boolean': 'fastHasAttribute', 234 'long': 'getIntegralAttribute', 235 'unsigned long': 'getUnsignedIntegralAttribute', 236} 237 238 239def getter_base_name(interface, attribute, arguments): 240 extended_attributes = attribute.extended_attributes 241 if 'Reflect' not in extended_attributes: 242 return uncapitalize(cpp_name(attribute)) 243 244 content_attribute_name = extended_attributes['Reflect'] or attribute.name.lower() 245 if content_attribute_name in ['class', 'id', 'name']: 246 # Special-case for performance optimization. 247 return 'get%sAttribute' % content_attribute_name.capitalize() 248 249 arguments.append(scoped_content_attribute_name(interface, attribute)) 250 251 base_idl_type = attribute.idl_type.base_type 252 if base_idl_type in CONTENT_ATTRIBUTE_GETTER_NAMES: 253 return CONTENT_ATTRIBUTE_GETTER_NAMES[base_idl_type] 254 if 'URL' in attribute.extended_attributes: 255 return 'getURLAttribute' 256 return 'fastGetAttribute' 257 258 259def is_keep_alive_for_gc(interface, attribute): 260 idl_type = attribute.idl_type 261 base_idl_type = idl_type.base_type 262 extended_attributes = attribute.extended_attributes 263 return ( 264 # For readonly attributes, for performance reasons we keep the attribute 265 # wrapper alive while the owner wrapper is alive, because the attribute 266 # never changes. 267 (attribute.is_read_only and 268 idl_type.is_wrapper_type and 269 # There are some exceptions, however: 270 not( 271 # Node lifetime is managed by object grouping. 272 inherits_interface(interface.name, 'Node') or 273 inherits_interface(base_idl_type, 'Node') or 274 # A self-reference is unnecessary. 275 attribute.name == 'self' or 276 # FIXME: Remove these hard-coded hacks. 277 base_idl_type in ['EventTarget', 'Window'] or 278 base_idl_type.startswith(('HTML', 'SVG'))))) 279 280 281################################################################################ 282# Setter 283################################################################################ 284 285def generate_setter(interface, attribute, contents): 286 def target_attribute(): 287 target_interface_name = attribute.idl_type.base_type 288 target_attribute_name = extended_attributes['PutForwards'] 289 target_interface = interfaces[target_interface_name] 290 try: 291 return next(attribute 292 for attribute in target_interface.attributes 293 if attribute.name == target_attribute_name) 294 except StopIteration: 295 raise Exception('[PutForward] target not found:\n' 296 'Attribute "%s" is not present in interface "%s"' % 297 (target_attribute_name, target_interface_name)) 298 299 extended_attributes = attribute.extended_attributes 300 301 if 'PutForwards' in extended_attributes: 302 # Use target attribute in place of original attribute 303 attribute = target_attribute() 304 305 contents.update({ 306 'cpp_setter': setter_expression(interface, attribute, contents), 307 'v8_value_to_local_cpp_value': attribute.idl_type.v8_value_to_local_cpp_value(extended_attributes, 'v8Value', 'cppValue'), 308 }) 309 310 311def setter_expression(interface, attribute, contents): 312 extended_attributes = attribute.extended_attributes 313 arguments = v8_utilities.call_with_arguments( 314 extended_attributes.get('SetterCallWith') or 315 extended_attributes.get('CallWith')) 316 317 this_setter_base_name = setter_base_name(interface, attribute, arguments) 318 setter_name = scoped_name(interface, attribute, this_setter_base_name) 319 320 # Members of IDL partial interface definitions are implemented in C++ as 321 # static member functions, which for instance members (non-static members) 322 # take *impl as their first argument 323 if ('PartialInterfaceImplementedAs' in extended_attributes and 324 not attribute.is_static): 325 arguments.append('*impl') 326 idl_type = attribute.idl_type 327 if idl_type.base_type == 'EventHandler': 328 getter_name = scoped_name(interface, attribute, cpp_name(attribute)) 329 contents['event_handler_getter_expression'] = '%s(%s)' % ( 330 getter_name, ', '.join(arguments)) 331 if (interface.name in ['Window', 'WorkerGlobalScope'] and 332 attribute.name == 'onerror'): 333 includes.add('bindings/v8/V8ErrorHandler.h') 334 arguments.append('V8EventListenerList::findOrCreateWrapper<V8ErrorHandler>(v8Value, true, ScriptState::current(info.GetIsolate()))') 335 else: 336 arguments.append('V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate)') 337 elif idl_type.is_interface_type and not idl_type.array_type: 338 # FIXME: should be able to eliminate WTF::getPtr in most or all cases 339 arguments.append('WTF::getPtr(cppValue)') 340 else: 341 arguments.append('cppValue') 342 if contents['is_setter_raises_exception']: 343 arguments.append('exceptionState') 344 345 return '%s(%s)' % (setter_name, ', '.join(arguments)) 346 347 348CONTENT_ATTRIBUTE_SETTER_NAMES = { 349 'boolean': 'setBooleanAttribute', 350 'long': 'setIntegralAttribute', 351 'unsigned long': 'setUnsignedIntegralAttribute', 352} 353 354 355def setter_base_name(interface, attribute, arguments): 356 if 'Reflect' not in attribute.extended_attributes: 357 return 'set%s' % capitalize(cpp_name(attribute)) 358 arguments.append(scoped_content_attribute_name(interface, attribute)) 359 360 base_idl_type = attribute.idl_type.base_type 361 if base_idl_type in CONTENT_ATTRIBUTE_SETTER_NAMES: 362 return CONTENT_ATTRIBUTE_SETTER_NAMES[base_idl_type] 363 return 'setAttribute' 364 365 366def scoped_content_attribute_name(interface, attribute): 367 content_attribute_name = attribute.extended_attributes['Reflect'] or attribute.name.lower() 368 namespace = 'SVGNames' if interface.name.startswith('SVG') else 'HTMLNames' 369 includes.add('%s.h' % namespace) 370 return '%s::%sAttr' % (namespace, content_attribute_name) 371 372 373################################################################################ 374# Attribute configuration 375################################################################################ 376 377# [Replaceable] 378def setter_callback_name(interface, attribute): 379 cpp_class_name = cpp_name(interface) 380 extended_attributes = attribute.extended_attributes 381 if (('Replaceable' in extended_attributes and 382 'PutForwards' not in extended_attributes) or 383 is_constructor_attribute(attribute)): 384 # FIXME: rename to ForceSetAttributeOnThisCallback, since also used for Constructors 385 return '{0}V8Internal::{0}ReplaceableAttributeSetterCallback'.format(cpp_class_name) 386 if attribute.is_read_only and 'PutForwards' not in extended_attributes: 387 return '0' 388 return '%sV8Internal::%sAttributeSetterCallback' % (cpp_class_name, attribute.name) 389 390 391# [DoNotCheckSecurity], [Unforgeable] 392def access_control_list(attribute): 393 extended_attributes = attribute.extended_attributes 394 access_control = [] 395 if 'DoNotCheckSecurity' in extended_attributes: 396 do_not_check_security = extended_attributes['DoNotCheckSecurity'] 397 if do_not_check_security == 'Setter': 398 access_control.append('v8::ALL_CAN_WRITE') 399 else: 400 access_control.append('v8::ALL_CAN_READ') 401 if (not attribute.is_read_only or 402 'Replaceable' in extended_attributes): 403 access_control.append('v8::ALL_CAN_WRITE') 404 if 'Unforgeable' in extended_attributes: 405 access_control.append('v8::PROHIBITS_OVERWRITING') 406 return access_control or ['v8::DEFAULT'] 407 408 409# [NotEnumerable], [Unforgeable] 410def property_attributes(attribute): 411 extended_attributes = attribute.extended_attributes 412 property_attributes_list = [] 413 if ('NotEnumerable' in extended_attributes or 414 is_constructor_attribute(attribute)): 415 property_attributes_list.append('v8::DontEnum') 416 if 'Unforgeable' in extended_attributes: 417 property_attributes_list.append('v8::DontDelete') 418 return property_attributes_list or ['v8::None'] 419 420 421################################################################################ 422# Constructors 423################################################################################ 424 425idl_types.IdlType.constructor_type_name = property( 426 # FIXME: replace this with a [ConstructorAttribute] extended attribute 427 lambda self: strip_suffix(self.base_type, 'Constructor')) 428 429 430def is_constructor_attribute(attribute): 431 # FIXME: replace this with [ConstructorAttribute] extended attribute 432 return attribute.idl_type.base_type.endswith('Constructor') 433 434 435def generate_constructor_getter(interface, attribute, contents): 436 contents['needs_constructor_getter_callback'] = contents['measure_as'] or contents['deprecate_as'] 437