• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 methods.
30
31Extends IdlType and IdlUnionType with property |union_arguments|.
32
33Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
34"""
35
36from idl_types import IdlType, IdlUnionType, inherits_interface
37from v8_globals import includes
38import v8_types
39import v8_utilities
40from v8_utilities import has_extended_attribute_value
41
42
43# Methods with any of these require custom method registration code in the
44# interface's configure*Template() function.
45CUSTOM_REGISTRATION_EXTENDED_ATTRIBUTES = frozenset([
46    'DoNotCheckSecurity',
47    'DoNotCheckSignature',
48    'NotEnumerable',
49    'ReadOnly',
50    'Unforgeable',
51])
52
53
54def argument_needs_try_catch(argument):
55    idl_type = argument.idl_type
56    base_type = not idl_type.array_or_sequence_type and idl_type.base_type
57
58    return not (
59        # These cases are handled by separate code paths in the
60        # generate_argument() macro in Source/bindings/templates/methods.cpp.
61        idl_type.is_callback_interface or
62        base_type == 'SerializedScriptValue' or
63        (argument.is_variadic and idl_type.is_wrapper_type) or
64        # String and enumeration arguments converted using one of the
65        # TOSTRING_* macros in Source/bindings/v8/V8BindingMacros.h don't
66        # use a v8::TryCatch.
67        (base_type == 'DOMString' and not argument.is_variadic))
68
69
70def generate_method(interface, method):
71    arguments = method.arguments
72    extended_attributes = method.extended_attributes
73    idl_type = method.idl_type
74    is_static = method.is_static
75    name = method.name
76
77    idl_type.add_includes_for_type()
78    this_cpp_value = cpp_value(interface, method, len(arguments))
79
80    def function_template():
81        if is_static:
82            return 'functionTemplate'
83        if 'Unforgeable' in extended_attributes:
84            return 'instanceTemplate'
85        return 'prototypeTemplate'
86
87    is_call_with_script_arguments = has_extended_attribute_value(method, 'CallWith', 'ScriptArguments')
88    if is_call_with_script_arguments:
89        includes.update(['bindings/v8/ScriptCallStackFactory.h',
90                         'core/inspector/ScriptArguments.h'])
91    is_call_with_script_state = has_extended_attribute_value(method, 'CallWith', 'ScriptState')
92    if is_call_with_script_state:
93        includes.add('bindings/v8/ScriptState.h')
94    is_check_security_for_node = 'CheckSecurity' in extended_attributes
95    if is_check_security_for_node:
96        includes.add('bindings/v8/BindingSecurity.h')
97    is_custom_element_callbacks = 'CustomElementCallbacks' in extended_attributes
98    if is_custom_element_callbacks:
99        includes.add('core/dom/custom/CustomElementCallbackDispatcher.h')
100
101    has_event_listener_argument = any(
102        argument for argument in arguments
103        if argument.idl_type.name == 'EventListener')
104    is_check_security_for_frame = (
105        'CheckSecurity' in interface.extended_attributes and
106        'DoNotCheckSecurity' not in extended_attributes)
107    is_raises_exception = 'RaisesException' in extended_attributes
108
109    arguments_need_try_catch = any(argument_needs_try_catch(argument)
110                                   for argument in arguments)
111
112    return {
113        'activity_logging_world_list': v8_utilities.activity_logging_world_list(method),  # [ActivityLogging]
114        'arguments': [generate_argument(interface, method, argument, index)
115                      for index, argument in enumerate(arguments)],
116        'arguments_need_try_catch': arguments_need_try_catch,
117        'conditional_string': v8_utilities.conditional_string(method),
118        'cpp_type': idl_type.cpp_type,
119        'cpp_value': this_cpp_value,
120        'custom_registration_extended_attributes':
121            CUSTOM_REGISTRATION_EXTENDED_ATTRIBUTES.intersection(
122                extended_attributes.iterkeys()),
123        'deprecate_as': v8_utilities.deprecate_as(method),  # [DeprecateAs]
124        'function_template': function_template(),
125        'has_custom_registration': is_static or
126            v8_utilities.has_extended_attribute(
127                method, CUSTOM_REGISTRATION_EXTENDED_ATTRIBUTES),
128        'has_event_listener_argument': has_event_listener_argument,
129        'has_exception_state':
130            has_event_listener_argument or
131            is_raises_exception or
132            is_check_security_for_frame or
133            any(argument for argument in arguments
134                if argument.idl_type.name in ('ByteString',
135                                              'ScalarValueString',
136                                              'SerializedScriptValue') or
137                   argument.idl_type.is_integer_type),
138        'idl_type': idl_type.base_type,
139        'is_call_with_execution_context': has_extended_attribute_value(method, 'CallWith', 'ExecutionContext'),
140        'is_call_with_script_arguments': is_call_with_script_arguments,
141        'is_call_with_script_state': is_call_with_script_state,
142        'is_check_security_for_frame': is_check_security_for_frame,
143        'is_check_security_for_node': is_check_security_for_node,
144        'is_custom': 'Custom' in extended_attributes,
145        'is_custom_element_callbacks': is_custom_element_callbacks,
146        'is_do_not_check_security': 'DoNotCheckSecurity' in extended_attributes,
147        'is_do_not_check_signature': 'DoNotCheckSignature' in extended_attributes,
148        'is_partial_interface_member':
149            'PartialInterfaceImplementedAs' in extended_attributes,
150        'is_per_world_bindings': 'PerWorldBindings' in extended_attributes,
151        'is_raises_exception': is_raises_exception,
152        'is_read_only': 'ReadOnly' in extended_attributes,
153        'is_static': is_static,
154        'is_variadic': arguments and arguments[-1].is_variadic,
155        'measure_as': v8_utilities.measure_as(method),  # [MeasureAs]
156        'name': name,
157        'number_of_arguments': len(arguments),
158        'number_of_required_arguments': len([
159            argument for argument in arguments
160            if not (argument.is_optional or argument.is_variadic)]),
161        'number_of_required_or_variadic_arguments': len([
162            argument for argument in arguments
163            if not argument.is_optional]),
164        'per_context_enabled_function': v8_utilities.per_context_enabled_function_name(method),  # [PerContextEnabled]
165        'property_attributes': property_attributes(method),
166        'runtime_enabled_function': v8_utilities.runtime_enabled_function_name(method),  # [RuntimeEnabled]
167        'signature': 'v8::Local<v8::Signature>()' if is_static or 'DoNotCheckSignature' in extended_attributes else 'defaultSignature',
168        'union_arguments': idl_type.union_arguments,
169        'v8_set_return_value_for_main_world': v8_set_return_value(interface.name, method, this_cpp_value, for_main_world=True),
170        'v8_set_return_value': v8_set_return_value(interface.name, method, this_cpp_value),
171        'world_suffixes': ['', 'ForMainWorld'] if 'PerWorldBindings' in extended_attributes else [''],  # [PerWorldBindings]
172    }
173
174
175def generate_argument(interface, method, argument, index):
176    extended_attributes = argument.extended_attributes
177    idl_type = argument.idl_type
178    this_cpp_value = cpp_value(interface, method, index)
179    is_variadic_wrapper_type = argument.is_variadic and idl_type.is_wrapper_type
180
181    return {
182        'cpp_type': idl_type.cpp_type_args(extended_attributes=extended_attributes,
183                                           used_as_argument=True,
184                                           used_as_variadic_argument=argument.is_variadic),
185        'cpp_value': this_cpp_value,
186        # FIXME: check that the default value's type is compatible with the argument's
187        'default_value': str(argument.default_value) if argument.default_value else None,
188        'enum_validation_expression': idl_type.enum_validation_expression,
189        # FIXME: remove once [Default] removed and just use argument.default_value
190        'has_default': 'Default' in extended_attributes or argument.default_value,
191        'has_event_listener_argument': any(
192            argument_so_far for argument_so_far in method.arguments[:index]
193            if argument_so_far.idl_type.name == 'EventListener'),
194        'has_type_checking_interface':
195            (has_extended_attribute_value(interface, 'TypeChecking', 'Interface') or
196             has_extended_attribute_value(method, 'TypeChecking', 'Interface')) and
197            idl_type.is_wrapper_type,
198        'has_type_checking_unrestricted':
199            (has_extended_attribute_value(interface, 'TypeChecking', 'Unrestricted') or
200             has_extended_attribute_value(method, 'TypeChecking', 'Unrestricted')) and
201            idl_type.name in ('Float', 'Double'),
202        # Dictionary is special-cased, but arrays and sequences shouldn't be
203        'idl_type': not idl_type.array_or_sequence_type and idl_type.base_type,
204        'idl_type_object': idl_type,
205        'index': index,
206        'is_clamp': 'Clamp' in extended_attributes,
207        'is_callback_interface': idl_type.is_callback_interface,
208        'is_nullable': idl_type.is_nullable,
209        'is_optional': argument.is_optional,
210        'is_variadic_wrapper_type': is_variadic_wrapper_type,
211        'vector_type': v8_types.cpp_ptr_type('Vector', 'HeapVector', idl_type.gc_type),
212        'is_wrapper_type': idl_type.is_wrapper_type,
213        'name': argument.name,
214        'v8_set_return_value_for_main_world': v8_set_return_value(interface.name, method, this_cpp_value, for_main_world=True),
215        'v8_set_return_value': v8_set_return_value(interface.name, method, this_cpp_value),
216        'v8_value_to_local_cpp_value': v8_value_to_local_cpp_value(argument, index),
217    }
218
219
220################################################################################
221# Value handling
222################################################################################
223
224def cpp_value(interface, method, number_of_arguments):
225    def cpp_argument(argument):
226        idl_type = argument.idl_type
227        if idl_type.name == 'EventListener':
228            if (interface.name == 'EventTarget' and
229                method.name == 'removeEventListener'):
230                # FIXME: remove this special case by moving get() into
231                # EventTarget::removeEventListener
232                return '%s.get()' % argument.name
233            return argument.name
234        if (idl_type.is_callback_interface or
235            idl_type.name in ['NodeFilter', 'XPathNSResolver']):
236            # FIXME: remove this special case
237            return '%s.release()' % argument.name
238        return argument.name
239
240    # Truncate omitted optional arguments
241    arguments = method.arguments[:number_of_arguments]
242    cpp_arguments = []
243    if method.is_constructor:
244        call_with_values = interface.extended_attributes.get('ConstructorCallWith')
245    else:
246        call_with_values = method.extended_attributes.get('CallWith')
247    cpp_arguments.extend(v8_utilities.call_with_arguments(call_with_values))
248    # Members of IDL partial interface definitions are implemented in C++ as
249    # static member functions, which for instance members (non-static members)
250    # take *impl as their first argument
251    if ('PartialInterfaceImplementedAs' in method.extended_attributes and
252        not method.is_static):
253        cpp_arguments.append('*impl')
254    cpp_arguments.extend(cpp_argument(argument) for argument in arguments)
255    this_union_arguments = method.idl_type and method.idl_type.union_arguments
256    if this_union_arguments:
257        cpp_arguments.extend(this_union_arguments)
258
259    if ('RaisesException' in method.extended_attributes or
260        (method.is_constructor and
261         has_extended_attribute_value(interface, 'RaisesException', 'Constructor'))):
262        cpp_arguments.append('exceptionState')
263
264    if method.name == 'Constructor':
265        base_name = 'create'
266    elif method.name == 'NamedConstructor':
267        base_name = 'createForJSConstructor'
268    else:
269        base_name = v8_utilities.cpp_name(method)
270
271    cpp_method_name = v8_utilities.scoped_name(interface, method, base_name)
272    return '%s(%s)' % (cpp_method_name, ', '.join(cpp_arguments))
273
274
275def v8_set_return_value(interface_name, method, cpp_value, for_main_world=False):
276    idl_type = method.idl_type
277    extended_attributes = method.extended_attributes
278    if not idl_type or idl_type.name == 'void':
279        # Constructors and void methods don't have a return type
280        return None
281
282    release = False
283    # [CallWith=ScriptState], [RaisesException]
284    if (has_extended_attribute_value(method, 'CallWith', 'ScriptState') or
285        'RaisesException' in extended_attributes or
286        idl_type.is_union_type):
287        cpp_value = 'result'  # use local variable for value
288        release = idl_type.release
289
290    script_wrappable = 'impl' if inherits_interface(interface_name, 'Node') else ''
291    return idl_type.v8_set_return_value(cpp_value, extended_attributes, script_wrappable=script_wrappable, release=release, for_main_world=for_main_world)
292
293
294def v8_value_to_local_cpp_variadic_value(argument, index):
295    assert argument.is_variadic
296    idl_type = argument.idl_type
297
298    macro = 'TONATIVE_VOID_INTERNAL'
299    macro_args = [
300      argument.name,
301      'toNativeArguments<%s>(info, %s)' % (idl_type.cpp_type, index),
302    ]
303
304    return '%s(%s)' % (macro, ', '.join(macro_args))
305
306
307def v8_value_to_local_cpp_value(argument, index):
308    extended_attributes = argument.extended_attributes
309    idl_type = argument.idl_type
310    name = argument.name
311    if argument.is_variadic:
312        return v8_value_to_local_cpp_variadic_value(argument, index)
313    # FIXME: This special way of handling string arguments with null defaults
314    # can go away once we fully support default values.
315    if (argument.is_optional and
316        idl_type.name in ('String', 'ByteString', 'ScalarValueString') and
317        argument.default_value and argument.default_value.is_null):
318        v8_value = 'argumentOrNull(info, %s)' % index
319    else:
320        v8_value = 'info[%s]' % index
321    return idl_type.v8_value_to_local_cpp_value(extended_attributes, v8_value,
322                                                name, index=index, declare_variable=False)
323
324
325################################################################################
326# Auxiliary functions
327################################################################################
328
329# [NotEnumerable]
330def property_attributes(method):
331    extended_attributes = method.extended_attributes
332    property_attributes_list = []
333    if 'NotEnumerable' in extended_attributes:
334        property_attributes_list.append('v8::DontEnum')
335    if 'ReadOnly' in extended_attributes:
336        property_attributes_list.append('v8::ReadOnly')
337    if property_attributes_list:
338        property_attributes_list.insert(0, 'v8::DontDelete')
339    return property_attributes_list
340
341
342def union_arguments(idl_type):
343    """Return list of ['result0Enabled', 'result0', 'result1Enabled', ...] for union types, for use in setting return value"""
344    return [arg
345            for i in range(len(idl_type.member_types))
346            for arg in ['result%sEnabled' % i, 'result%s' % i]]
347
348IdlType.union_arguments = property(lambda self: None)
349IdlUnionType.union_arguments = property(union_arguments)
350