1 # Copyright (C) 2013 Google Inc. All rights reserved.
3 # Redistribution and use in source and binary forms, with or without
4 # modification, are permitted provided that the following conditions are
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
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.
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.
29 """Generate template values for attributes.
31 Extends IdlType with property |constructor_type_name|.
33 Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
37 from idl_types import inherits_interface
38 from v8_globals import includes, interfaces
41 from v8_utilities import (cpp_name_or_partial, capitalize, cpp_name, has_extended_attribute,
42 has_extended_attribute_value, scoped_name, strip_suffix,
43 uncapitalize, extended_attribute_value_as_list)
46 def attribute_context(interface, attribute):
47 idl_type = attribute.idl_type
48 base_idl_type = idl_type.base_type
49 extended_attributes = attribute.extended_attributes
51 idl_type.add_includes_for_type()
54 is_check_security_for_node = 'CheckSecurity' in extended_attributes
55 if is_check_security_for_node:
56 includes.add('bindings/core/v8/BindingSecurity.h')
57 # [CustomElementCallbacks], [Reflect]
58 is_custom_element_callbacks = 'CustomElementCallbacks' in extended_attributes
59 is_reflect = 'Reflect' in extended_attributes
60 if is_custom_element_callbacks or is_reflect:
61 includes.add('core/dom/custom/CustomElementProcessingStack.h')
63 if 'PerWorldBindings' in extended_attributes:
64 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)
66 has_type_checking_unrestricted = (
67 (has_extended_attribute_value(interface, 'TypeChecking', 'Unrestricted') or
68 has_extended_attribute_value(attribute, 'TypeChecking', 'Unrestricted')) and
69 idl_type.name in ('Float', 'Double'))
70 # [ImplementedInPrivateScript]
71 is_implemented_in_private_script = 'ImplementedInPrivateScript' in extended_attributes
72 if is_implemented_in_private_script:
73 includes.add('bindings/core/v8/PrivateScriptRunner.h')
74 includes.add('core/frame/LocalFrame.h')
75 includes.add('platform/ScriptForbiddenScope.h')
77 # [OnlyExposedToPrivateScript]
78 is_only_exposed_to_private_script = 'OnlyExposedToPrivateScript' in extended_attributes
80 if (base_idl_type == 'EventHandler' and
81 interface.name in ['Window', 'WorkerGlobalScope'] and
82 attribute.name == 'onerror'):
83 includes.add('bindings/core/v8/V8ErrorHandler.h')
86 'access_control_list': access_control_list(attribute),
87 'activity_logging_world_list_for_getter': v8_utilities.activity_logging_world_list(attribute, 'Getter'), # [ActivityLogging]
88 'activity_logging_world_list_for_setter': v8_utilities.activity_logging_world_list(attribute, 'Setter'), # [ActivityLogging]
89 'activity_logging_world_check': v8_utilities.activity_logging_world_check(attribute), # [ActivityLogging]
90 'argument_cpp_type': idl_type.cpp_type_args(used_as_rvalue_type=True),
91 'cached_attribute_validation_method': extended_attributes.get('CachedAttribute'),
92 'conditional_string': v8_utilities.conditional_string(attribute),
93 'constructor_type': idl_type.constructor_type_name
94 if is_constructor_attribute(attribute) else None,
95 'cpp_name': cpp_name(attribute),
96 'cpp_type': idl_type.cpp_type,
97 'cpp_type_initializer': idl_type.cpp_type_initializer,
98 'deprecate_as': v8_utilities.deprecate_as(attribute), # [DeprecateAs]
99 'enum_validation_expression': idl_type.enum_validation_expression,
100 'exposed_test': v8_utilities.exposed(attribute, interface), # [Exposed]
101 'has_custom_getter': has_custom_getter(attribute),
102 'has_custom_setter': has_custom_setter(attribute),
103 'has_type_checking_unrestricted': has_type_checking_unrestricted,
104 'idl_type': str(idl_type), # need trailing [] on array for Dictionary::ConversionContext::setConversionType
105 'is_call_with_execution_context': v8_utilities.has_extended_attribute_value(attribute, 'CallWith', 'ExecutionContext'),
106 'is_call_with_script_state': v8_utilities.has_extended_attribute_value(attribute, 'CallWith', 'ScriptState'),
107 'is_check_security_for_node': is_check_security_for_node,
108 'is_custom_element_callbacks': is_custom_element_callbacks,
109 'is_expose_js_accessors': 'ExposeJSAccessors' in extended_attributes,
110 'is_getter_raises_exception': # [RaisesException]
111 'RaisesException' in extended_attributes and
112 extended_attributes['RaisesException'] in (None, 'Getter'),
113 'is_implemented_in_private_script': is_implemented_in_private_script,
114 'is_initialized_by_event_constructor':
115 'InitializedByEventConstructor' in extended_attributes,
116 'is_keep_alive_for_gc': is_keep_alive_for_gc(interface, attribute),
117 'is_nullable': idl_type.is_nullable,
118 'is_explicit_nullable': idl_type.is_explicit_nullable,
119 'is_partial_interface_member':
120 'PartialInterfaceImplementedAs' in extended_attributes,
121 'is_per_world_bindings': 'PerWorldBindings' in extended_attributes,
122 'is_read_only': attribute.is_read_only,
123 'is_reflect': is_reflect,
124 'is_replaceable': 'Replaceable' in attribute.extended_attributes,
125 'is_static': attribute.is_static,
126 'is_url': 'URL' in extended_attributes,
127 'is_unforgeable': 'Unforgeable' in extended_attributes,
128 'use_output_parameter_for_result': idl_type.use_output_parameter_for_result,
129 'measure_as': v8_utilities.measure_as(attribute), # [MeasureAs]
130 'name': attribute.name,
131 'only_exposed_to_private_script': is_only_exposed_to_private_script,
132 'per_context_enabled_function': v8_utilities.per_context_enabled_function_name(attribute), # [PerContextEnabled]
133 'private_script_v8_value_to_local_cpp_value': idl_type.v8_value_to_local_cpp_value(
134 extended_attributes, 'v8Value', 'cppValue', isolate='scriptState->isolate()', used_in_private_script=True),
135 'property_attributes': property_attributes(attribute),
136 'put_forwards': 'PutForwards' in extended_attributes,
137 'reflect_empty': extended_attributes.get('ReflectEmpty'),
138 'reflect_invalid': extended_attributes.get('ReflectInvalid', ''),
139 'reflect_missing': extended_attributes.get('ReflectMissing'),
140 'reflect_only': extended_attribute_value_as_list(attribute, 'ReflectOnly'),
141 'runtime_enabled_function': v8_utilities.runtime_enabled_function_name(attribute), # [RuntimeEnabled]
142 'setter_callback': setter_callback_name(interface, attribute),
143 'should_be_exposed_to_script': not (is_implemented_in_private_script and is_only_exposed_to_private_script),
144 'world_suffixes': ['', 'ForMainWorld']
145 if 'PerWorldBindings' in extended_attributes
146 else [''], # [PerWorldBindings]
149 if is_constructor_attribute(attribute):
150 constructor_getter_context(interface, attribute, context)
152 if not has_custom_getter(attribute):
153 getter_context(interface, attribute, context)
154 if (not has_custom_setter(attribute) and
155 (not attribute.is_read_only or 'PutForwards' in extended_attributes)):
156 setter_context(interface, attribute, context)
161 ################################################################################
163 ################################################################################
165 def getter_context(interface, attribute, context):
166 idl_type = attribute.idl_type
167 base_idl_type = idl_type.base_type
168 extended_attributes = attribute.extended_attributes
170 cpp_value = getter_expression(interface, attribute, context)
171 # Normally we can inline the function call into the return statement to
172 # avoid the overhead of using a Ref<> temporary, but for some cases
173 # (nullable types, EventHandler, [CachedAttribute], or if there are
174 # exceptions), we need to use a local variable.
175 # FIXME: check if compilers are smart enough to inline this, and if so,
176 # always use a local variable (for readability and CG simplicity).
178 if 'ImplementedInPrivateScript' in extended_attributes:
179 if (not idl_type.is_wrapper_type and
180 not idl_type.is_basic_type and
181 not idl_type.is_enum):
182 raise Exception('Private scripts supports only primitive types and DOM wrappers.')
184 context['cpp_value_original'] = cpp_value
186 # EventHandler has special handling
187 if base_idl_type != 'EventHandler':
188 release = idl_type.release
189 elif (idl_type.is_explicit_nullable or
190 base_idl_type == 'EventHandler' or
191 'CachedAttribute' in extended_attributes or
192 'ReflectOnly' in extended_attributes or
193 context['is_keep_alive_for_gc'] or
194 context['is_getter_raises_exception']):
195 context['cpp_value_original'] = cpp_value
196 cpp_value = 'cppValue'
197 # EventHandler has special handling
198 if base_idl_type != 'EventHandler':
199 release = idl_type.release
201 def v8_set_return_value_statement(for_main_world=False):
202 if context['is_keep_alive_for_gc']:
203 return 'v8SetReturnValue(info, wrapper)'
204 return idl_type.v8_set_return_value(cpp_value, extended_attributes=extended_attributes, script_wrappable='impl', release=release, for_main_world=for_main_world)
207 'cpp_value': cpp_value,
208 'cpp_value_to_v8_value': idl_type.cpp_value_to_v8_value(
209 cpp_value=cpp_value, creation_context='info.Holder()',
210 extended_attributes=extended_attributes),
211 'v8_set_return_value_for_main_world': v8_set_return_value_statement(for_main_world=True),
212 'v8_set_return_value': v8_set_return_value_statement(),
216 def getter_expression(interface, attribute, context):
218 this_getter_base_name = getter_base_name(interface, attribute, arguments)
219 getter_name = scoped_name(interface, attribute, this_getter_base_name)
221 if 'ImplementedInPrivateScript' in attribute.extended_attributes:
222 arguments.append('toFrameIfNotDetached(info.GetIsolate()->GetCurrentContext())')
223 arguments.append('impl')
224 arguments.append('&result')
225 arguments.extend(v8_utilities.call_with_arguments(
226 attribute.extended_attributes.get('CallWith')))
227 # Members of IDL partial interface definitions are implemented in C++ as
228 # static member functions, which for instance members (non-static members)
229 # take *impl as their first argument
230 if ('PartialInterfaceImplementedAs' in attribute.extended_attributes and
231 not 'ImplementedInPrivateScript' in attribute.extended_attributes and
232 not attribute.is_static):
233 arguments.append('*impl')
234 if attribute.idl_type.is_explicit_nullable:
235 arguments.append('isNull')
236 if context['is_getter_raises_exception']:
237 arguments.append('exceptionState')
238 if attribute.idl_type.use_output_parameter_for_result:
239 arguments.append('result')
240 return '%s(%s)' % (getter_name, ', '.join(arguments))
243 CONTENT_ATTRIBUTE_GETTER_NAMES = {
244 'boolean': 'fastHasAttribute',
245 'long': 'getIntegralAttribute',
246 'unsigned long': 'getUnsignedIntegralAttribute',
250 def getter_base_name(interface, attribute, arguments):
251 extended_attributes = attribute.extended_attributes
253 if 'ImplementedInPrivateScript' in extended_attributes:
254 return '%sAttributeGetter' % uncapitalize(cpp_name(attribute))
256 if 'Reflect' not in extended_attributes:
257 return uncapitalize(cpp_name(attribute))
259 content_attribute_name = extended_attributes['Reflect'] or attribute.name.lower()
260 if content_attribute_name in ['class', 'id', 'name']:
261 # Special-case for performance optimization.
262 return 'get%sAttribute' % content_attribute_name.capitalize()
264 arguments.append(scoped_content_attribute_name(interface, attribute))
266 base_idl_type = attribute.idl_type.base_type
267 if base_idl_type in CONTENT_ATTRIBUTE_GETTER_NAMES:
268 return CONTENT_ATTRIBUTE_GETTER_NAMES[base_idl_type]
269 if 'URL' in attribute.extended_attributes:
270 return 'getURLAttribute'
271 return 'fastGetAttribute'
274 def is_keep_alive_for_gc(interface, attribute):
275 idl_type = attribute.idl_type
276 base_idl_type = idl_type.base_type
277 extended_attributes = attribute.extended_attributes
279 # For readonly attributes, for performance reasons we keep the attribute
280 # wrapper alive while the owner wrapper is alive, because the attribute
282 (attribute.is_read_only and
283 idl_type.is_wrapper_type and
284 # There are some exceptions, however:
286 # Node lifetime is managed by object grouping.
287 inherits_interface(interface.name, 'Node') or
288 inherits_interface(base_idl_type, 'Node') or
289 # A self-reference is unnecessary.
290 attribute.name == 'self' or
291 # FIXME: Remove these hard-coded hacks.
292 base_idl_type in ['EventTarget', 'Window'] or
293 base_idl_type.startswith(('HTML', 'SVG')))))
296 ################################################################################
298 ################################################################################
300 def setter_context(interface, attribute, context):
301 if 'PutForwards' in attribute.extended_attributes:
302 # Use target interface and attribute in place of original interface and
303 # attribute from this point onwards.
304 target_interface_name = attribute.idl_type.base_type
305 target_attribute_name = attribute.extended_attributes['PutForwards']
306 interface = interfaces[target_interface_name]
308 attribute = next(candidate
309 for candidate in interface.attributes
310 if candidate.name == target_attribute_name)
311 except StopIteration:
312 raise Exception('[PutForward] target not found:\n'
313 'Attribute "%s" is not present in interface "%s"' %
314 (target_attribute_name, target_interface_name))
316 extended_attributes = attribute.extended_attributes
317 idl_type = attribute.idl_type
319 # [RaisesException], [RaisesException=Setter]
320 is_setter_raises_exception = (
321 'RaisesException' in extended_attributes and
322 extended_attributes['RaisesException'] in [None, 'Setter'])
323 # [TypeChecking=Interface]
324 has_type_checking_interface = (
325 (has_extended_attribute_value(interface, 'TypeChecking', 'Interface') or
326 has_extended_attribute_value(attribute, 'TypeChecking', 'Interface')) and
327 idl_type.is_wrapper_type)
329 type_checked = (has_type_checking_interface and
330 # These allow null values, so a type-check is still required.
331 not idl_type.is_nullable)
334 'has_setter_exception_state':
335 is_setter_raises_exception or has_type_checking_interface or
336 context['has_type_checking_unrestricted'] or
337 idl_type.v8_conversion_needs_exception_state,
338 'has_type_checking_interface': has_type_checking_interface,
339 'is_setter_call_with_execution_context': v8_utilities.has_extended_attribute_value(
340 attribute, 'SetterCallWith', 'ExecutionContext'),
341 'is_setter_raises_exception': is_setter_raises_exception,
342 'private_script_cpp_value_to_v8_value': idl_type.cpp_value_to_v8_value(
343 'cppValue', isolate='scriptState->isolate()',
344 creation_context='scriptState->context()->Global()'),
345 'v8_value_to_local_cpp_value': idl_type.v8_value_to_local_cpp_value(
346 extended_attributes, 'v8Value', 'cppValue',
347 needs_type_check=not type_checked),
350 # setter_expression() depends on context values we set above.
351 context['cpp_setter'] = setter_expression(interface, attribute, context)
354 def setter_expression(interface, attribute, context):
355 extended_attributes = attribute.extended_attributes
356 arguments = v8_utilities.call_with_arguments(
357 extended_attributes.get('SetterCallWith') or
358 extended_attributes.get('CallWith'))
360 this_setter_base_name = setter_base_name(interface, attribute, arguments)
361 setter_name = scoped_name(interface, attribute, this_setter_base_name)
363 # Members of IDL partial interface definitions are implemented in C++ as
364 # static member functions, which for instance members (non-static members)
365 # take *impl as their first argument
366 if ('PartialInterfaceImplementedAs' in extended_attributes and
367 not 'ImplementedInPrivateScript' in extended_attributes and
368 not attribute.is_static):
369 arguments.append('*impl')
370 idl_type = attribute.idl_type
371 if 'ImplementedInPrivateScript' in extended_attributes:
372 arguments.append('toFrameIfNotDetached(info.GetIsolate()->GetCurrentContext())')
373 arguments.append('impl')
374 arguments.append('cppValue')
375 elif idl_type.base_type == 'EventHandler':
376 getter_name = scoped_name(interface, attribute, cpp_name(attribute))
377 context['event_handler_getter_expression'] = '%s(%s)' % (
378 getter_name, ', '.join(arguments))
379 if (interface.name in ['Window', 'WorkerGlobalScope'] and
380 attribute.name == 'onerror'):
381 includes.add('bindings/core/v8/V8ErrorHandler.h')
382 arguments.append('V8EventListenerList::findOrCreateWrapper<V8ErrorHandler>(v8Value, true, ScriptState::current(info.GetIsolate()))')
384 arguments.append('V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate)')
385 elif idl_type.is_interface_type:
386 # FIXME: should be able to eliminate WTF::getPtr in most or all cases
387 arguments.append('WTF::getPtr(cppValue)')
389 arguments.append('cppValue')
390 if context['is_setter_raises_exception']:
391 arguments.append('exceptionState')
393 return '%s(%s)' % (setter_name, ', '.join(arguments))
396 CONTENT_ATTRIBUTE_SETTER_NAMES = {
397 'boolean': 'setBooleanAttribute',
398 'long': 'setIntegralAttribute',
399 'unsigned long': 'setUnsignedIntegralAttribute',
403 def setter_base_name(interface, attribute, arguments):
404 if 'ImplementedInPrivateScript' in attribute.extended_attributes:
405 return '%sAttributeSetter' % uncapitalize(cpp_name(attribute))
407 if 'Reflect' not in attribute.extended_attributes:
408 return 'set%s' % capitalize(cpp_name(attribute))
409 arguments.append(scoped_content_attribute_name(interface, attribute))
411 base_idl_type = attribute.idl_type.base_type
412 if base_idl_type in CONTENT_ATTRIBUTE_SETTER_NAMES:
413 return CONTENT_ATTRIBUTE_SETTER_NAMES[base_idl_type]
414 return 'setAttribute'
417 def scoped_content_attribute_name(interface, attribute):
418 content_attribute_name = attribute.extended_attributes['Reflect'] or attribute.name.lower()
419 if interface.name.startswith('SVG'):
420 # SVG's xmlbase/xmlspace/xmllang need special behavior, i.e.
421 # it is in XMLNames namespace and the generated attribute has no xml prefix.
422 if attribute.name.startswith('xml'):
423 namespace = 'XMLNames'
424 content_attribute_name = content_attribute_name[3:]
426 namespace = 'SVGNames'
428 namespace = 'HTMLNames'
429 includes.add('core/%s.h' % namespace)
430 return '%s::%sAttr' % (namespace, content_attribute_name)
433 ################################################################################
434 # Attribute configuration
435 ################################################################################
438 def setter_callback_name(interface, attribute):
439 cpp_class_name = cpp_name(interface)
440 cpp_class_name_or_partial = cpp_name_or_partial(interface)
442 extended_attributes = attribute.extended_attributes
443 if (('Replaceable' in extended_attributes and
444 'PutForwards' not in extended_attributes) or
445 is_constructor_attribute(attribute)):
446 return '%sV8Internal::%sForceSetAttributeOnThisCallback' % (
447 cpp_class_name_or_partial, cpp_class_name)
448 if attribute.is_read_only and 'PutForwards' not in extended_attributes:
450 return '%sV8Internal::%sAttributeSetterCallback' % (cpp_class_name_or_partial, attribute.name)
453 # [DoNotCheckSecurity], [Unforgeable]
454 def access_control_list(attribute):
455 extended_attributes = attribute.extended_attributes
457 if 'DoNotCheckSecurity' in extended_attributes:
458 do_not_check_security = extended_attributes['DoNotCheckSecurity']
459 if do_not_check_security == 'Setter':
460 access_control.append('v8::ALL_CAN_WRITE')
462 access_control.append('v8::ALL_CAN_READ')
463 if (not attribute.is_read_only or
464 'Replaceable' in extended_attributes):
465 access_control.append('v8::ALL_CAN_WRITE')
466 if 'Unforgeable' in extended_attributes:
467 access_control.append('v8::PROHIBITS_OVERWRITING')
468 return access_control or ['v8::DEFAULT']
471 # [NotEnumerable], [Unforgeable]
472 def property_attributes(attribute):
473 extended_attributes = attribute.extended_attributes
474 property_attributes_list = []
475 if ('NotEnumerable' in extended_attributes or
476 is_constructor_attribute(attribute)):
477 property_attributes_list.append('v8::DontEnum')
478 if 'Unforgeable' in extended_attributes:
479 property_attributes_list.append('v8::DontDelete')
480 return property_attributes_list or ['v8::None']
483 # [Custom], [Custom=Getter]
484 def has_custom_getter(attribute):
485 extended_attributes = attribute.extended_attributes
486 return ('Custom' in extended_attributes and
487 extended_attributes['Custom'] in [None, 'Getter'])
490 # [Custom], [Custom=Setter]
491 def has_custom_setter(attribute):
492 extended_attributes = attribute.extended_attributes
493 return (not attribute.is_read_only and
494 'Custom' in extended_attributes and
495 extended_attributes['Custom'] in [None, 'Setter'])
498 ################################################################################
500 ################################################################################
502 idl_types.IdlType.constructor_type_name = property(
503 # FIXME: replace this with a [ConstructorAttribute] extended attribute
504 lambda self: strip_suffix(self.base_type, 'Constructor'))
507 def is_constructor_attribute(attribute):
508 # FIXME: replace this with [ConstructorAttribute] extended attribute
509 return attribute.idl_type.name.endswith('Constructor')
512 def constructor_getter_context(interface, attribute, context):
513 context['needs_constructor_getter_callback'] = context['measure_as'] or context['deprecate_as']