Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / scripts / v8_attributes.py
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
31 Extends IdlType with property |constructor_type_name|.
32
33 Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
34 """
35
36 import idl_types
37 from idl_types import inherits_interface
38 from v8_globals import includes, interfaces
39 import v8_types
40 import v8_utilities
41 from v8_utilities import (capitalize, cpp_name, has_extended_attribute,
42                           has_extended_attribute_value, scoped_name, strip_suffix,
43                           uncapitalize, extended_attribute_value_as_list)
44
45
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
50
51     idl_type.add_includes_for_type()
52
53     # [CheckSecurity]
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')
62     # [PerWorldBindings]
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)
65     # [TypeChecking]
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')
76
77     # [OnlyExposedToPrivateScript]
78     is_only_exposed_to_private_script = 'OnlyExposedToPrivateScript' in extended_attributes
79
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')
84
85     context = {
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         'measure_as': v8_utilities.measure_as(attribute),  # [MeasureAs]
129         'name': attribute.name,
130         'only_exposed_to_private_script': is_only_exposed_to_private_script,
131         'per_context_enabled_function': v8_utilities.per_context_enabled_function_name(attribute),  # [PerContextEnabled]
132         'private_script_v8_value_to_local_cpp_value': idl_type.v8_value_to_local_cpp_value(
133             extended_attributes, 'v8Value', 'cppValue', isolate='scriptState->isolate()', used_in_private_script=True),
134         'property_attributes': property_attributes(attribute),
135         'put_forwards': 'PutForwards' in extended_attributes,
136         'reflect_empty': extended_attributes.get('ReflectEmpty'),
137         'reflect_invalid': extended_attributes.get('ReflectInvalid', ''),
138         'reflect_missing': extended_attributes.get('ReflectMissing'),
139         'reflect_only': extended_attribute_value_as_list(attribute, 'ReflectOnly'),
140         'runtime_enabled_function': v8_utilities.runtime_enabled_function_name(attribute),  # [RuntimeEnabled]
141         'setter_callback': setter_callback_name(interface, attribute),
142         'should_be_exposed_to_script': not (is_implemented_in_private_script and is_only_exposed_to_private_script),
143         'world_suffixes': ['', 'ForMainWorld']
144                           if 'PerWorldBindings' in extended_attributes
145                           else [''],  # [PerWorldBindings]
146     }
147
148     if is_constructor_attribute(attribute):
149         constructor_getter_context(interface, attribute, context)
150         return context
151     if not has_custom_getter(attribute):
152         getter_context(interface, attribute, context)
153     if (not has_custom_setter(attribute) and
154         (not attribute.is_read_only or 'PutForwards' in extended_attributes)):
155         setter_context(interface, attribute, context)
156
157     return context
158
159
160 ################################################################################
161 # Getter
162 ################################################################################
163
164 def getter_context(interface, attribute, context):
165     idl_type = attribute.idl_type
166     base_idl_type = idl_type.base_type
167     extended_attributes = attribute.extended_attributes
168
169     cpp_value = getter_expression(interface, attribute, context)
170     # Normally we can inline the function call into the return statement to
171     # avoid the overhead of using a Ref<> temporary, but for some cases
172     # (nullable types, EventHandler, [CachedAttribute], or if there are
173     # exceptions), we need to use a local variable.
174     # FIXME: check if compilers are smart enough to inline this, and if so,
175     # always use a local variable (for readability and CG simplicity).
176     release = False
177     if 'ImplementedInPrivateScript' in extended_attributes:
178         if (not idl_type.is_wrapper_type and
179             not idl_type.is_basic_type and
180             not idl_type.is_enum):
181             raise Exception('Private scripts supports only primitive types and DOM wrappers.')
182
183         context['cpp_value_original'] = cpp_value
184         cpp_value = 'result'
185         # EventHandler has special handling
186         if base_idl_type != 'EventHandler':
187             release = idl_type.release
188     elif (idl_type.is_explicit_nullable or
189         base_idl_type == 'EventHandler' or
190         'CachedAttribute' in extended_attributes or
191         'ReflectOnly' in extended_attributes or
192         context['is_keep_alive_for_gc'] or
193         context['is_getter_raises_exception']):
194         context['cpp_value_original'] = cpp_value
195         cpp_value = 'cppValue'
196         # EventHandler has special handling
197         if base_idl_type != 'EventHandler':
198             release = idl_type.release
199
200     def v8_set_return_value_statement(for_main_world=False):
201         if context['is_keep_alive_for_gc']:
202             return 'v8SetReturnValue(info, wrapper)'
203         return idl_type.v8_set_return_value(cpp_value, extended_attributes=extended_attributes, script_wrappable='impl', release=release, for_main_world=for_main_world)
204
205     context.update({
206         'cpp_value': cpp_value,
207         'cpp_value_to_v8_value': idl_type.cpp_value_to_v8_value(
208             cpp_value=cpp_value, creation_context='info.Holder()',
209             extended_attributes=extended_attributes),
210         'v8_set_return_value_for_main_world': v8_set_return_value_statement(for_main_world=True),
211         'v8_set_return_value': v8_set_return_value_statement(),
212     })
213
214
215 def getter_expression(interface, attribute, context):
216     arguments = []
217     this_getter_base_name = getter_base_name(interface, attribute, arguments)
218     getter_name = scoped_name(interface, attribute, this_getter_base_name)
219
220     if 'ImplementedInPrivateScript' in attribute.extended_attributes:
221         arguments.append('toFrameIfNotDetached(info.GetIsolate()->GetCurrentContext())')
222         arguments.append('impl')
223         arguments.append('&result')
224     arguments.extend(v8_utilities.call_with_arguments(
225         attribute.extended_attributes.get('CallWith')))
226     # Members of IDL partial interface definitions are implemented in C++ as
227     # static member functions, which for instance members (non-static members)
228     # take *impl as their first argument
229     if ('PartialInterfaceImplementedAs' in attribute.extended_attributes and
230         not 'ImplementedInPrivateScript' in attribute.extended_attributes and
231         not attribute.is_static):
232         arguments.append('*impl')
233     if attribute.idl_type.is_explicit_nullable:
234         arguments.append('isNull')
235     if context['is_getter_raises_exception']:
236         arguments.append('exceptionState')
237     return '%s(%s)' % (getter_name, ', '.join(arguments))
238
239
240 CONTENT_ATTRIBUTE_GETTER_NAMES = {
241     'boolean': 'fastHasAttribute',
242     'long': 'getIntegralAttribute',
243     'unsigned long': 'getUnsignedIntegralAttribute',
244 }
245
246
247 def getter_base_name(interface, attribute, arguments):
248     extended_attributes = attribute.extended_attributes
249
250     if 'ImplementedInPrivateScript' in extended_attributes:
251         return '%sAttributeGetter' % uncapitalize(cpp_name(attribute))
252
253     if 'Reflect' not in extended_attributes:
254         return uncapitalize(cpp_name(attribute))
255
256     content_attribute_name = extended_attributes['Reflect'] or attribute.name.lower()
257     if content_attribute_name in ['class', 'id', 'name']:
258         # Special-case for performance optimization.
259         return 'get%sAttribute' % content_attribute_name.capitalize()
260
261     arguments.append(scoped_content_attribute_name(interface, attribute))
262
263     base_idl_type = attribute.idl_type.base_type
264     if base_idl_type in CONTENT_ATTRIBUTE_GETTER_NAMES:
265         return CONTENT_ATTRIBUTE_GETTER_NAMES[base_idl_type]
266     if 'URL' in attribute.extended_attributes:
267         return 'getURLAttribute'
268     return 'fastGetAttribute'
269
270
271 def is_keep_alive_for_gc(interface, attribute):
272     idl_type = attribute.idl_type
273     base_idl_type = idl_type.base_type
274     extended_attributes = attribute.extended_attributes
275     return (
276         # For readonly attributes, for performance reasons we keep the attribute
277         # wrapper alive while the owner wrapper is alive, because the attribute
278         # never changes.
279         (attribute.is_read_only and
280          idl_type.is_wrapper_type and
281          # There are some exceptions, however:
282          not(
283              # Node lifetime is managed by object grouping.
284              inherits_interface(interface.name, 'Node') or
285              inherits_interface(base_idl_type, 'Node') or
286              # A self-reference is unnecessary.
287              attribute.name == 'self' or
288              # FIXME: Remove these hard-coded hacks.
289              base_idl_type in ['EventTarget', 'Window'] or
290              base_idl_type.startswith(('HTML', 'SVG')))))
291
292
293 ################################################################################
294 # Setter
295 ################################################################################
296
297 def setter_context(interface, attribute, context):
298     if 'PutForwards' in attribute.extended_attributes:
299         # Use target interface and attribute in place of original interface and
300         # attribute from this point onwards.
301         target_interface_name = attribute.idl_type.base_type
302         target_attribute_name = attribute.extended_attributes['PutForwards']
303         interface = interfaces[target_interface_name]
304         try:
305             attribute = next(candidate
306                              for candidate in interface.attributes
307                              if candidate.name == target_attribute_name)
308         except StopIteration:
309             raise Exception('[PutForward] target not found:\n'
310                             'Attribute "%s" is not present in interface "%s"' %
311                             (target_attribute_name, target_interface_name))
312
313     extended_attributes = attribute.extended_attributes
314     idl_type = attribute.idl_type
315
316     # [RaisesException], [RaisesException=Setter]
317     is_setter_raises_exception = (
318         'RaisesException' in extended_attributes and
319         extended_attributes['RaisesException'] in [None, 'Setter'])
320     # [TypeChecking=Interface]
321     has_type_checking_interface = (
322         (has_extended_attribute_value(interface, 'TypeChecking', 'Interface') or
323          has_extended_attribute_value(attribute, 'TypeChecking', 'Interface')) and
324         idl_type.is_wrapper_type)
325
326     context.update({
327         'has_setter_exception_state':
328             is_setter_raises_exception or has_type_checking_interface or
329             context['has_type_checking_unrestricted'] or
330             idl_type.v8_conversion_needs_exception_state,
331         'has_type_checking_interface': has_type_checking_interface,
332         'is_setter_call_with_execution_context': v8_utilities.has_extended_attribute_value(
333             attribute, 'SetterCallWith', 'ExecutionContext'),
334         'is_setter_raises_exception': is_setter_raises_exception,
335         'private_script_cpp_value_to_v8_value': idl_type.cpp_value_to_v8_value(
336             'cppValue', isolate='scriptState->isolate()',
337             creation_context='scriptState->context()->Global()'),
338         'v8_value_to_local_cpp_value': idl_type.v8_value_to_local_cpp_value(
339             extended_attributes, 'v8Value', 'cppValue'),
340     })
341
342     # setter_expression() depends on context values we set above.
343     context['cpp_setter'] = setter_expression(interface, attribute, context)
344
345
346 def setter_expression(interface, attribute, context):
347     extended_attributes = attribute.extended_attributes
348     arguments = v8_utilities.call_with_arguments(
349         extended_attributes.get('SetterCallWith') or
350         extended_attributes.get('CallWith'))
351
352     this_setter_base_name = setter_base_name(interface, attribute, arguments)
353     setter_name = scoped_name(interface, attribute, this_setter_base_name)
354
355     # Members of IDL partial interface definitions are implemented in C++ as
356     # static member functions, which for instance members (non-static members)
357     # take *impl as their first argument
358     if ('PartialInterfaceImplementedAs' in extended_attributes and
359         not 'ImplementedInPrivateScript' in extended_attributes and
360         not attribute.is_static):
361         arguments.append('*impl')
362     idl_type = attribute.idl_type
363     if 'ImplementedInPrivateScript' in extended_attributes:
364         arguments.append('toFrameIfNotDetached(info.GetIsolate()->GetCurrentContext())')
365         arguments.append('impl')
366         arguments.append('cppValue')
367     elif idl_type.base_type == 'EventHandler':
368         getter_name = scoped_name(interface, attribute, cpp_name(attribute))
369         context['event_handler_getter_expression'] = '%s(%s)' % (
370             getter_name, ', '.join(arguments))
371         if (interface.name in ['Window', 'WorkerGlobalScope'] and
372             attribute.name == 'onerror'):
373             includes.add('bindings/core/v8/V8ErrorHandler.h')
374             arguments.append('V8EventListenerList::findOrCreateWrapper<V8ErrorHandler>(v8Value, true, ScriptState::current(info.GetIsolate()))')
375         else:
376             arguments.append('V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate)')
377     elif idl_type.is_interface_type:
378         # FIXME: should be able to eliminate WTF::getPtr in most or all cases
379         arguments.append('WTF::getPtr(cppValue)')
380     else:
381         arguments.append('cppValue')
382     if context['is_setter_raises_exception']:
383         arguments.append('exceptionState')
384
385     return '%s(%s)' % (setter_name, ', '.join(arguments))
386
387
388 CONTENT_ATTRIBUTE_SETTER_NAMES = {
389     'boolean': 'setBooleanAttribute',
390     'long': 'setIntegralAttribute',
391     'unsigned long': 'setUnsignedIntegralAttribute',
392 }
393
394
395 def setter_base_name(interface, attribute, arguments):
396     if 'ImplementedInPrivateScript' in attribute.extended_attributes:
397         return '%sAttributeSetter' % uncapitalize(cpp_name(attribute))
398
399     if 'Reflect' not in attribute.extended_attributes:
400         return 'set%s' % capitalize(cpp_name(attribute))
401     arguments.append(scoped_content_attribute_name(interface, attribute))
402
403     base_idl_type = attribute.idl_type.base_type
404     if base_idl_type in CONTENT_ATTRIBUTE_SETTER_NAMES:
405         return CONTENT_ATTRIBUTE_SETTER_NAMES[base_idl_type]
406     return 'setAttribute'
407
408
409 def scoped_content_attribute_name(interface, attribute):
410     content_attribute_name = attribute.extended_attributes['Reflect'] or attribute.name.lower()
411     if interface.name.startswith('SVG'):
412         # SVG's xmlbase/xmlspace/xmllang need special behavior, i.e.
413         # it is in XMLNames namespace and the generated attribute has no xml prefix.
414         if attribute.name.startswith('xml'):
415             namespace = 'XMLNames'
416             content_attribute_name = content_attribute_name[3:]
417         else:
418             namespace = 'SVGNames'
419     else:
420         namespace = 'HTMLNames'
421     includes.add('core/%s.h' % namespace)
422     return '%s::%sAttr' % (namespace, content_attribute_name)
423
424
425 ################################################################################
426 # Attribute configuration
427 ################################################################################
428
429 # [Replaceable]
430 def setter_callback_name(interface, attribute):
431     cpp_class_name = cpp_name(interface)
432     extended_attributes = attribute.extended_attributes
433     if (('Replaceable' in extended_attributes and
434          'PutForwards' not in extended_attributes) or
435         is_constructor_attribute(attribute)):
436         return '{0}V8Internal::{0}ForceSetAttributeOnThisCallback'.format(cpp_class_name)
437     if attribute.is_read_only and 'PutForwards' not in extended_attributes:
438         return '0'
439     return '%sV8Internal::%sAttributeSetterCallback' % (cpp_class_name, attribute.name)
440
441
442 # [DoNotCheckSecurity], [Unforgeable]
443 def access_control_list(attribute):
444     extended_attributes = attribute.extended_attributes
445     access_control = []
446     if 'DoNotCheckSecurity' in extended_attributes:
447         do_not_check_security = extended_attributes['DoNotCheckSecurity']
448         if do_not_check_security == 'Setter':
449             access_control.append('v8::ALL_CAN_WRITE')
450         else:
451             access_control.append('v8::ALL_CAN_READ')
452             if (not attribute.is_read_only or
453                 'Replaceable' in extended_attributes):
454                 access_control.append('v8::ALL_CAN_WRITE')
455     if 'Unforgeable' in extended_attributes:
456         access_control.append('v8::PROHIBITS_OVERWRITING')
457     return access_control or ['v8::DEFAULT']
458
459
460 # [NotEnumerable], [Unforgeable]
461 def property_attributes(attribute):
462     extended_attributes = attribute.extended_attributes
463     property_attributes_list = []
464     if ('NotEnumerable' in extended_attributes or
465         is_constructor_attribute(attribute)):
466         property_attributes_list.append('v8::DontEnum')
467     if 'Unforgeable' in extended_attributes:
468         property_attributes_list.append('v8::DontDelete')
469     return property_attributes_list or ['v8::None']
470
471
472 # [Custom], [Custom=Getter]
473 def has_custom_getter(attribute):
474     extended_attributes = attribute.extended_attributes
475     return ('Custom' in extended_attributes and
476             extended_attributes['Custom'] in [None, 'Getter'])
477
478
479 # [Custom], [Custom=Setter]
480 def has_custom_setter(attribute):
481     extended_attributes = attribute.extended_attributes
482     return (not attribute.is_read_only and
483             'Custom' in extended_attributes and
484             extended_attributes['Custom'] in [None, 'Setter'])
485
486
487 ################################################################################
488 # Constructors
489 ################################################################################
490
491 idl_types.IdlType.constructor_type_name = property(
492     # FIXME: replace this with a [ConstructorAttribute] extended attribute
493     lambda self: strip_suffix(self.base_type, 'Constructor'))
494
495
496 def is_constructor_attribute(attribute):
497     # FIXME: replace this with [ConstructorAttribute] extended attribute
498     return attribute.idl_type.name.endswith('Constructor')
499
500
501 def constructor_getter_context(interface, attribute, context):
502     context['needs_constructor_getter_callback'] = context['measure_as'] or context['deprecate_as']