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 """Functions for type handling and type conversion (Blink/C++ <-> V8/JS).
31 Extends IdlType and IdlUnionType with V8-specific properties, methods, and
35 http://www.w3.org/TR/WebIDL/#es-type-mapping
37 Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
42 from idl_types import IdlTypeBase, IdlType, IdlUnionType, IdlArrayOrSequenceType, IdlNullableType
43 import v8_attributes # for IdlType.constructor_type_name
44 from v8_globals import includes
47 ################################################################################
48 # V8-specific handling of IDL types
49 ################################################################################
51 NON_WRAPPER_TYPES = frozenset([
56 'SerializedScriptValue',
58 TYPED_ARRAY_TYPES = frozenset([
69 ARRAY_BUFFER_AND_VIEW_TYPES = TYPED_ARRAY_TYPES.union(frozenset([
75 IdlType.is_array_buffer_or_view = property(
76 lambda self: self.base_type in ARRAY_BUFFER_AND_VIEW_TYPES)
78 IdlType.is_typed_array = property(
79 lambda self: self.base_type in TYPED_ARRAY_TYPES)
81 IdlType.is_wrapper_type = property(
82 lambda self: (self.is_interface_type and
83 self.base_type not in NON_WRAPPER_TYPES))
86 ################################################################################
88 ################################################################################
90 CPP_TYPE_SAME_AS_IDL_TYPE = set([
101 CPP_UNSIGNED_TYPES = set([
107 CPP_SPECIAL_CONVERSION_RULES = {
109 'Dictionary': 'Dictionary',
110 'EventHandler': 'EventListener*',
111 'NodeFilter': 'RefPtrWillBeRawPtr<NodeFilter>',
112 'Promise': 'ScriptPromise',
113 'ScriptValue': 'ScriptValue',
114 # FIXME: Eliminate custom bindings for XPathNSResolver http://crbug.com/345529
115 'XPathNSResolver': 'RefPtrWillBeRawPtr<XPathNSResolver>',
117 'unrestricted double': 'double',
118 'unrestricted float': 'float',
122 def cpp_type(idl_type, extended_attributes=None, raw_type=False, used_as_rvalue_type=False, used_as_variadic_argument=False, used_in_cpp_sequence=False):
123 """Returns C++ type corresponding to IDL type.
125 |idl_type| argument is of type IdlType, while return value is a string
131 bool, True if idl_type's raw/primitive C++ type should be returned.
133 bool, True if the C++ type is used as an argument or the return
135 used_as_variadic_argument:
136 bool, True if the C++ type is used as a variadic argument of a method.
137 used_in_cpp_sequence:
138 bool, True if the C++ type is used as an element of a container.
139 Containers can be an array, a sequence or a dictionary.
142 if extended_attributes.get('TreatNullAs') == 'EmptyString':
143 return 'TreatNullAsEmptyString'
144 if idl_type.is_nullable or extended_attributes.get('TreatNullAs') == 'NullString':
145 if extended_attributes.get('TreatUndefinedAs') == 'NullString':
146 return 'TreatNullAndUndefinedAsNullString'
147 return 'TreatNullAsNullString'
150 extended_attributes = extended_attributes or {}
151 idl_type = idl_type.preprocessed_type
153 # Array or sequence types
154 if used_as_variadic_argument:
155 native_array_element_type = idl_type
157 native_array_element_type = idl_type.native_array_element_type
158 if native_array_element_type:
159 vector_type = cpp_ptr_type('Vector', 'HeapVector', native_array_element_type.gc_type)
160 vector_template_type = cpp_template_type(vector_type, native_array_element_type.cpp_type_args(used_in_cpp_sequence=True))
161 if used_as_rvalue_type:
162 return 'const %s&' % vector_template_type
163 return vector_template_type
166 base_idl_type = idl_type.base_type
168 if base_idl_type in CPP_TYPE_SAME_AS_IDL_TYPE:
170 if base_idl_type in CPP_INT_TYPES:
172 if base_idl_type in CPP_UNSIGNED_TYPES:
174 if base_idl_type in CPP_SPECIAL_CONVERSION_RULES:
175 return CPP_SPECIAL_CONVERSION_RULES[base_idl_type]
177 if base_idl_type in NON_WRAPPER_TYPES:
178 return ('PassRefPtr<%s>' if used_as_rvalue_type else 'RefPtr<%s>') % base_idl_type
179 if idl_type.is_string_type:
182 return 'V8StringResource<%s>' % string_mode()
184 if idl_type.is_array_buffer_or_view and raw_type:
185 return idl_type.implemented_as + '*'
186 if idl_type.is_interface_type:
187 implemented_as_class = idl_type.implemented_as
189 return implemented_as_class + '*'
190 new_type = 'Member' if used_in_cpp_sequence else 'RawPtr'
191 ptr_type = cpp_ptr_type(('PassRefPtr' if used_as_rvalue_type else 'RefPtr'), new_type, idl_type.gc_type)
192 return cpp_template_type(ptr_type, implemented_as_class)
193 if idl_type.is_dictionary:
195 if idl_type.is_union_type:
198 # Default, assume native type is a pointer with same type name as idl type
199 return base_idl_type + '*'
202 def cpp_type_initializer(idl_type):
203 """Returns a string containing a C++ initialization statement for the
206 |idl_type| argument is of type IdlType.
209 base_idl_type = idl_type.base_type
211 if idl_type.native_array_element_type:
213 if idl_type.is_numeric_type:
215 if base_idl_type == 'boolean':
217 if (base_idl_type in NON_WRAPPER_TYPES or
218 base_idl_type in CPP_SPECIAL_CONVERSION_RULES or
219 base_idl_type == 'any' or
220 idl_type.is_string_type or
226 # Allow access as idl_type.cpp_type if no arguments
227 IdlTypeBase.cpp_type = property(cpp_type)
228 IdlTypeBase.cpp_type_initializer = property(cpp_type_initializer)
229 IdlTypeBase.cpp_type_args = cpp_type
230 IdlUnionType.cpp_type_initializer = ''
233 IdlArrayOrSequenceType.native_array_element_type = property(
234 lambda self: self.element_type)
237 def cpp_template_type(template, inner_type):
238 """Returns C++ template specialized to type, with space added if needed."""
239 if inner_type.endswith('>'):
240 format_string = '{template}<{inner_type} >'
242 format_string = '{template}<{inner_type}>'
243 return format_string.format(template=template, inner_type=inner_type)
246 def cpp_ptr_type(old_type, new_type, gc_type):
247 if gc_type == 'GarbageCollectedObject':
249 if gc_type == 'WillBeGarbageCollectedObject':
250 if old_type == 'Vector':
251 return 'WillBe' + new_type
252 return old_type + 'WillBe' + new_type
256 def v8_type(interface_name):
257 return 'V8' + interface_name
261 # This handles [ImplementedAs] on interface types, not [ImplementedAs] in the
262 # interface being generated. e.g., given:
263 # Foo.idl: interface Foo {attribute Bar bar};
264 # Bar.idl: [ImplementedAs=Zork] interface Bar {};
265 # when generating bindings for Foo, the [ImplementedAs] on Bar is needed.
266 # This data is external to Foo.idl, and hence computed as global information in
267 # compute_interfaces_info.py to avoid having to parse IDLs of all used interfaces.
268 IdlType.implemented_as_interfaces = {}
271 def implemented_as(idl_type):
272 base_idl_type = idl_type.base_type
273 if base_idl_type in IdlType.implemented_as_interfaces:
274 return IdlType.implemented_as_interfaces[base_idl_type]
278 IdlType.implemented_as = property(implemented_as)
280 IdlType.set_implemented_as_interfaces = classmethod(
281 lambda cls, new_implemented_as_interfaces:
282 cls.implemented_as_interfaces.update(new_implemented_as_interfaces))
286 IdlType.garbage_collected_types = set()
288 IdlType.is_garbage_collected = property(
289 lambda self: self.base_type in IdlType.garbage_collected_types)
291 IdlType.set_garbage_collected_types = classmethod(
292 lambda cls, new_garbage_collected_types:
293 cls.garbage_collected_types.update(new_garbage_collected_types))
296 # [WillBeGarbageCollected]
297 IdlType.will_be_garbage_collected_types = set()
299 IdlType.is_will_be_garbage_collected = property(
300 lambda self: self.base_type in IdlType.will_be_garbage_collected_types)
302 IdlType.set_will_be_garbage_collected_types = classmethod(
303 lambda cls, new_will_be_garbage_collected_types:
304 cls.will_be_garbage_collected_types.update(new_will_be_garbage_collected_types))
307 def gc_type(idl_type):
308 if idl_type.is_garbage_collected:
309 return 'GarbageCollectedObject'
310 if idl_type.is_will_be_garbage_collected:
311 return 'WillBeGarbageCollectedObject'
312 return 'RefCountedObject'
314 IdlTypeBase.gc_type = property(gc_type)
317 def is_traceable(idl_type):
318 return (idl_type.is_garbage_collected
319 or idl_type.is_will_be_garbage_collected)
321 IdlTypeBase.is_traceable = property(is_traceable)
324 ################################################################################
326 ################################################################################
328 def includes_for_cpp_class(class_name, relative_dir_posix):
329 return set([posixpath.join('bindings', relative_dir_posix, class_name + '.h')])
332 INCLUDES_FOR_TYPE = {
334 'Dictionary': set(['bindings/core/v8/Dictionary.h']),
335 'EventHandler': set(['bindings/core/v8/V8AbstractEventListener.h',
336 'bindings/core/v8/V8EventListenerList.h']),
337 'EventListener': set(['bindings/core/v8/BindingSecurity.h',
338 'bindings/core/v8/V8EventListenerList.h',
339 'core/frame/LocalDOMWindow.h']),
340 'HTMLCollection': set(['bindings/core/v8/V8HTMLCollection.h',
341 'core/dom/ClassCollection.h',
342 'core/dom/TagCollection.h',
343 'core/html/HTMLCollection.h',
344 'core/html/HTMLDataListOptionsCollection.h',
345 'core/html/HTMLFormControlsCollection.h',
346 'core/html/HTMLTableRowsCollection.h']),
347 'NodeList': set(['bindings/core/v8/V8NodeList.h',
348 'core/dom/NameNodeList.h',
349 'core/dom/NodeList.h',
350 'core/dom/StaticNodeList.h',
351 'core/html/LabelsNodeList.h']),
352 'Promise': set(['bindings/core/v8/ScriptPromise.h']),
353 'SerializedScriptValue': set(['bindings/core/v8/SerializedScriptValue.h']),
354 'ScriptValue': set(['bindings/core/v8/ScriptValue.h']),
358 def includes_for_type(idl_type):
359 idl_type = idl_type.preprocessed_type
362 base_idl_type = idl_type.base_type
363 if base_idl_type in INCLUDES_FOR_TYPE:
364 return INCLUDES_FOR_TYPE[base_idl_type]
365 if idl_type.is_basic_type:
367 if base_idl_type.endswith('ConstructorConstructor'):
368 # FIXME: rename to NamedConstructor
369 # FIXME: replace with a [NamedConstructorAttribute] extended attribute
370 # Ending with 'ConstructorConstructor' indicates a named constructor,
371 # and these do not have header files, as they are part of the generated
372 # bindings for the interface
374 if base_idl_type.endswith('Constructor'):
375 # FIXME: replace with a [ConstructorAttribute] extended attribute
376 base_idl_type = idl_type.constructor_type_name
377 if base_idl_type not in component_dir:
379 return set(['bindings/%s/v8/V8%s.h' % (component_dir[base_idl_type],
382 IdlType.includes_for_type = property(includes_for_type)
383 IdlUnionType.includes_for_type = property(
384 lambda self: set.union(*[member_type.includes_for_type
385 for member_type in self.member_types]))
386 IdlArrayOrSequenceType.includes_for_type = property(
387 lambda self: self.element_type.includes_for_type)
390 def add_includes_for_type(idl_type):
391 includes.update(idl_type.includes_for_type)
393 IdlTypeBase.add_includes_for_type = add_includes_for_type
396 def includes_for_interface(interface_name):
397 return IdlType(interface_name).includes_for_type
400 def add_includes_for_interface(interface_name):
401 includes.update(includes_for_interface(interface_name))
404 def impl_should_use_nullable_container(idl_type):
405 return not(idl_type.cpp_type_has_null_value)
407 IdlTypeBase.impl_should_use_nullable_container = property(
408 impl_should_use_nullable_container)
411 def impl_includes_for_type(idl_type, interfaces_info):
412 includes_for_type = set()
413 if idl_type.impl_should_use_nullable_container:
414 includes_for_type.add('bindings/core/v8/Nullable.h')
416 idl_type = idl_type.preprocessed_type
417 native_array_element_type = idl_type.native_array_element_type
418 if native_array_element_type:
419 includes_for_type.update(impl_includes_for_type(
420 native_array_element_type, interfaces_info))
421 includes_for_type.add('wtf/Vector.h')
423 base_idl_type = idl_type.base_type
424 if idl_type.is_string_type:
425 includes_for_type.add('wtf/text/WTFString.h')
426 if base_idl_type in interfaces_info:
427 interface_info = interfaces_info[idl_type.base_type]
428 includes_for_type.add(interface_info['include_path'])
429 if base_idl_type in INCLUDES_FOR_TYPE:
430 includes_for_type.update(INCLUDES_FOR_TYPE[base_idl_type])
431 return includes_for_type
433 IdlTypeBase.impl_includes_for_type = impl_includes_for_type
439 def set_component_dirs(new_component_dirs):
440 component_dir.update(new_component_dirs)
443 ################################################################################
445 ################################################################################
447 V8_VALUE_TO_CPP_VALUE = {
449 'Date': 'toCoreDate({v8_value})',
450 'DOMString': '{v8_value}',
451 'ByteString': 'toByteString({arguments})',
452 'USVString': 'toUSVString({arguments})',
453 'boolean': '{v8_value}->BooleanValue()',
454 'float': 'toFloat({arguments})',
455 'unrestricted float': 'toFloat({arguments})',
456 'double': 'toDouble({arguments})',
457 'unrestricted double': 'toDouble({arguments})',
458 'byte': 'toInt8({arguments})',
459 'octet': 'toUInt8({arguments})',
460 'short': 'toInt16({arguments})',
461 'unsigned short': 'toUInt16({arguments})',
462 'long': 'toInt32({arguments})',
463 'unsigned long': 'toUInt32({arguments})',
464 'long long': 'toInt64({arguments})',
465 'unsigned long long': 'toUInt64({arguments})',
467 'Dictionary': 'Dictionary({v8_value}, {isolate})',
468 'EventTarget': 'V8DOMWrapper::isDOMWrapper({v8_value}) ? toWrapperTypeInfo(v8::Handle<v8::Object>::Cast({v8_value}))->toEventTarget(v8::Handle<v8::Object>::Cast({v8_value})) : 0',
469 'NodeFilter': 'toNodeFilter({v8_value}, info.Holder(), ScriptState::current({isolate}))',
470 'Promise': 'ScriptPromise::cast(ScriptState::current({isolate}), {v8_value})',
471 'SerializedScriptValue': 'SerializedScriptValue::create({v8_value}, 0, 0, exceptionState, {isolate})',
472 'ScriptValue': 'ScriptValue(ScriptState::current({isolate}), {v8_value})',
473 'Window': 'toDOMWindow({v8_value}, {isolate})',
474 'XPathNSResolver': 'toXPathNSResolver({isolate}, {v8_value})',
478 def v8_conversion_needs_exception_state(idl_type):
479 return (idl_type.is_numeric_type or
480 idl_type.is_dictionary or
481 idl_type.name in ('ByteString', 'USVString', 'SerializedScriptValue'))
483 IdlType.v8_conversion_needs_exception_state = property(v8_conversion_needs_exception_state)
484 IdlArrayOrSequenceType.v8_conversion_needs_exception_state = True
485 IdlUnionType.v8_conversion_needs_exception_state = True
488 TRIVIAL_CONVERSIONS = frozenset([
499 def v8_conversion_is_trivial(idl_type):
500 # The conversion is a simple expression that returns the converted value and
501 # cannot raise an exception.
502 return (idl_type.base_type in TRIVIAL_CONVERSIONS or
503 idl_type.is_wrapper_type)
505 IdlType.v8_conversion_is_trivial = property(v8_conversion_is_trivial)
508 def v8_value_to_cpp_value(idl_type, extended_attributes, v8_value, variable_name, needs_type_check, index, isolate):
509 if idl_type.name == 'void':
512 # Array or sequence types
513 native_array_element_type = idl_type.native_array_element_type
514 if native_array_element_type:
515 return v8_value_to_cpp_value_array_or_sequence(native_array_element_type, v8_value, index)
518 idl_type = idl_type.preprocessed_type
519 add_includes_for_type(idl_type)
520 base_idl_type = idl_type.name if idl_type.is_union_type else idl_type.base_type
522 if 'EnforceRange' in extended_attributes:
523 arguments = ', '.join([v8_value, 'EnforceRange', 'exceptionState'])
524 elif 'Clamp' in extended_attributes:
525 arguments = ', '.join([v8_value, 'Clamp', 'exceptionState'])
526 elif idl_type.v8_conversion_needs_exception_state:
527 arguments = ', '.join([v8_value, 'exceptionState'])
531 if base_idl_type in V8_VALUE_TO_CPP_VALUE:
532 cpp_expression_format = V8_VALUE_TO_CPP_VALUE[base_idl_type]
533 elif idl_type.is_array_buffer_or_view:
534 cpp_expression_format = (
535 '{v8_value}->Is{idl_type}() ? '
536 'V8{idl_type}::toImpl(v8::Handle<v8::{idl_type}>::Cast({v8_value})) : 0')
537 elif idl_type.is_dictionary or idl_type.is_union_type:
538 cpp_expression_format = 'V8{idl_type}::toImpl({isolate}, {v8_value}, {variable_name}, exceptionState)'
539 elif needs_type_check:
540 cpp_expression_format = (
541 'V8{idl_type}::toImplWithTypeCheck({isolate}, {v8_value})')
543 cpp_expression_format = (
544 'V8{idl_type}::toImpl(v8::Handle<v8::Object>::Cast({v8_value}))')
546 return cpp_expression_format.format(arguments=arguments, idl_type=base_idl_type, v8_value=v8_value, variable_name=variable_name, isolate=isolate)
549 def v8_value_to_cpp_value_array_or_sequence(native_array_element_type, v8_value, index, isolate='info.GetIsolate()'):
550 # Index is None for setters, index (starting at 0) for method arguments,
551 # and is used to provide a human-readable exception message
553 index = 0 # special case, meaning "setter"
555 index += 1 # human-readable index
556 if (native_array_element_type.is_interface_type and
557 native_array_element_type.name != 'Dictionary'):
559 ref_ptr_type = cpp_ptr_type('RefPtr', 'Member', native_array_element_type.gc_type)
560 expression_format = '(to{ref_ptr_type}NativeArray<{native_array_element_type}, V8{native_array_element_type}>({v8_value}, {index}, {isolate}, exceptionState))'
561 add_includes_for_type(native_array_element_type)
564 this_cpp_type = native_array_element_type.cpp_type
565 expression_format = 'toImplArray<{cpp_type}>({v8_value}, {index}, {isolate}, exceptionState)'
566 expression = expression_format.format(native_array_element_type=native_array_element_type.name, cpp_type=this_cpp_type, index=index, ref_ptr_type=ref_ptr_type, v8_value=v8_value, isolate=isolate)
570 # FIXME: this function should be refactored, as this takes too many flags.
571 def v8_value_to_local_cpp_value(idl_type, extended_attributes, v8_value, variable_name=None, needs_type_check=True, index=None, declare_variable=True, isolate='info.GetIsolate()', used_in_private_script=False, return_promise=False, needs_exception_state_for_string=False):
572 """Returns an expression that converts a V8 value to a C++ value and stores it as a local value."""
574 this_cpp_type = idl_type.cpp_type_args(extended_attributes=extended_attributes, raw_type=True)
575 idl_type = idl_type.preprocessed_type
577 if idl_type.base_type in ('void', 'object', 'EventHandler', 'EventListener'):
578 return '/* no V8 -> C++ conversion for IDL type: %s */' % idl_type.name
580 cpp_value = v8_value_to_cpp_value(idl_type, extended_attributes, v8_value, variable_name, needs_type_check, index, isolate)
582 if idl_type.is_dictionary or idl_type.is_union_type:
583 return 'TONATIVE_VOID_EXCEPTIONSTATE_ARGINTERNAL(%s, exceptionState)' % cpp_value
585 if idl_type.is_string_type or idl_type.v8_conversion_needs_exception_state:
586 # Types that need error handling and use one of a group of (C++) macros
587 # to take care of this.
589 args = [variable_name, cpp_value]
591 if idl_type.v8_conversion_needs_exception_state:
592 macro = 'TONATIVE_DEFAULT_EXCEPTIONSTATE' if used_in_private_script else 'TONATIVE_VOID_EXCEPTIONSTATE'
593 elif return_promise or needs_exception_state_for_string:
594 macro = 'TOSTRING_VOID_EXCEPTIONSTATE'
596 macro = 'TOSTRING_DEFAULT' if used_in_private_script else 'TOSTRING_VOID'
598 if macro.endswith('_EXCEPTIONSTATE'):
599 args.append('exceptionState')
601 if used_in_private_script:
609 if macro.endswith('_EXCEPTIONSTATE'):
610 args.append('ScriptState::current(%s)' % isolate)
613 args.insert(0, this_cpp_type)
615 suffix += '_INTERNAL'
617 return '%s(%s)' % (macro + suffix, ', '.join(args))
619 # Types that don't need error handling, and simply assign a value to the
622 if not idl_type.v8_conversion_is_trivial:
623 raise Exception('unclassified V8 -> C++ conversion for IDL type: %s' % idl_type.name)
625 assignment = '%s = %s' % (variable_name, cpp_value)
627 return '%s %s' % (this_cpp_type, assignment)
631 IdlTypeBase.v8_value_to_local_cpp_value = v8_value_to_local_cpp_value
634 def use_output_parameter_for_result(idl_type):
635 """True when methods/getters which return the given idl_type should
636 take the output argument.
638 return idl_type.is_dictionary or idl_type.is_union_type
640 IdlTypeBase.use_output_parameter_for_result = property(use_output_parameter_for_result)
643 ################################################################################
645 ################################################################################
647 def preprocess_idl_type(idl_type):
649 # Enumerations are internally DOMStrings
650 return IdlType('DOMString')
651 if (idl_type.name in ['Any', 'Object'] or idl_type.is_callback_function):
652 return IdlType('ScriptValue')
655 IdlTypeBase.preprocessed_type = property(preprocess_idl_type)
658 def preprocess_idl_type_and_value(idl_type, cpp_value, extended_attributes):
659 """Returns IDL type and value, with preliminary type conversions applied."""
660 idl_type = idl_type.preprocessed_type
661 if idl_type.name == 'Promise':
662 idl_type = IdlType('ScriptValue')
663 if idl_type.base_type in ['long long', 'unsigned long long']:
664 # long long and unsigned long long are not representable in ECMAScript;
665 # we represent them as doubles.
666 is_nullable = idl_type.is_nullable
667 idl_type = IdlType('double')
669 idl_type = IdlNullableType(idl_type)
670 cpp_value = 'static_cast<double>(%s)' % cpp_value
671 # HTML5 says that unsigned reflected attributes should be in the range
672 # [0, 2^31). When a value isn't in this range, a default value (or 0)
673 # should be returned instead.
674 extended_attributes = extended_attributes or {}
675 if ('Reflect' in extended_attributes and
676 idl_type.base_type in ['unsigned long', 'unsigned short']):
677 cpp_value = cpp_value.replace('getUnsignedIntegralAttribute',
678 'getIntegralAttribute')
679 cpp_value = 'std::max(0, static_cast<int>(%s))' % cpp_value
680 return idl_type, cpp_value
683 def v8_conversion_type(idl_type, extended_attributes):
684 """Returns V8 conversion type, adding any additional includes.
686 The V8 conversion type is used to select the C++ -> V8 conversion function
687 or v8SetReturnValue* function; it can be an idl_type, a cpp_type, or a
688 separate name for the type of conversion (e.g., 'DOMWrapper').
690 extended_attributes = extended_attributes or {}
692 if idl_type.is_dictionary or idl_type.is_union_type:
693 return 'DictionaryOrUnion'
695 # Array or sequence types
696 native_array_element_type = idl_type.native_array_element_type
697 if native_array_element_type:
698 if native_array_element_type.is_interface_type:
699 add_includes_for_type(native_array_element_type)
703 base_idl_type = idl_type.base_type
704 # Basic types, without additional includes
705 if base_idl_type in CPP_INT_TYPES:
707 if base_idl_type in CPP_UNSIGNED_TYPES:
709 if idl_type.is_string_type:
710 if idl_type.is_nullable:
711 return 'StringOrNull'
712 if 'TreatReturnedNullStringAs' not in extended_attributes:
714 treat_returned_null_string_as = extended_attributes['TreatReturnedNullStringAs']
715 if treat_returned_null_string_as == 'Null':
716 return 'StringOrNull'
717 if treat_returned_null_string_as == 'Undefined':
718 return 'StringOrUndefined'
719 raise 'Unrecognized TreatReturnedNullStringAs value: "%s"' % treat_returned_null_string_as
720 if idl_type.is_basic_type or base_idl_type == 'ScriptValue':
723 # Data type with potential additional includes
724 add_includes_for_type(idl_type)
725 if base_idl_type in V8_SET_RETURN_VALUE: # Special v8SetReturnValue treatment
731 IdlTypeBase.v8_conversion_type = v8_conversion_type
734 V8_SET_RETURN_VALUE = {
735 'boolean': 'v8SetReturnValueBool(info, {cpp_value})',
736 'int': 'v8SetReturnValueInt(info, {cpp_value})',
737 'unsigned': 'v8SetReturnValueUnsigned(info, {cpp_value})',
738 'DOMString': 'v8SetReturnValueString(info, {cpp_value}, info.GetIsolate())',
739 'ByteString': 'v8SetReturnValueString(info, {cpp_value}, info.GetIsolate())',
740 'USVString': 'v8SetReturnValueString(info, {cpp_value}, info.GetIsolate())',
741 # [TreatReturnedNullStringAs]
742 'StringOrNull': 'v8SetReturnValueStringOrNull(info, {cpp_value}, info.GetIsolate())',
743 'StringOrUndefined': 'v8SetReturnValueStringOrUndefined(info, {cpp_value}, info.GetIsolate())',
745 # No special v8SetReturnValue* function (set value directly)
746 'float': 'v8SetReturnValue(info, {cpp_value})',
747 'unrestricted float': 'v8SetReturnValue(info, {cpp_value})',
748 'double': 'v8SetReturnValue(info, {cpp_value})',
749 'unrestricted double': 'v8SetReturnValue(info, {cpp_value})',
750 # No special v8SetReturnValue* function, but instead convert value to V8
751 # and then use general v8SetReturnValue.
752 'array': 'v8SetReturnValue(info, {cpp_value})',
753 'Date': 'v8SetReturnValue(info, {cpp_value})',
754 'EventHandler': 'v8SetReturnValue(info, {cpp_value})',
755 'ScriptValue': 'v8SetReturnValue(info, {cpp_value})',
756 'SerializedScriptValue': 'v8SetReturnValue(info, {cpp_value})',
758 'DOMWrapperForMainWorld': 'v8SetReturnValueForMainWorld(info, WTF::getPtr({cpp_value}))',
759 'DOMWrapperFast': 'v8SetReturnValueFast(info, WTF::getPtr({cpp_value}), {script_wrappable})',
760 'DOMWrapperDefault': 'v8SetReturnValue(info, {cpp_value})',
761 # Union types or dictionaries
762 'DictionaryOrUnion': 'v8SetReturnValue(info, result)',
766 def v8_set_return_value(idl_type, cpp_value, extended_attributes=None, script_wrappable='', release=False, for_main_world=False):
767 """Returns a statement that converts a C++ value to a V8 value and sets it as a return value.
770 def dom_wrapper_conversion_type():
771 if not script_wrappable:
772 return 'DOMWrapperDefault'
774 return 'DOMWrapperForMainWorld'
775 return 'DOMWrapperFast'
777 idl_type, cpp_value = preprocess_idl_type_and_value(idl_type, cpp_value, extended_attributes)
778 this_v8_conversion_type = idl_type.v8_conversion_type(extended_attributes)
779 # SetReturn-specific overrides
780 if this_v8_conversion_type in ['Date', 'EventHandler', 'ScriptValue', 'SerializedScriptValue', 'array']:
781 # Convert value to V8 and then use general v8SetReturnValue
782 cpp_value = idl_type.cpp_value_to_v8_value(cpp_value, extended_attributes=extended_attributes)
783 if this_v8_conversion_type == 'DOMWrapper':
784 this_v8_conversion_type = dom_wrapper_conversion_type()
786 format_string = V8_SET_RETURN_VALUE[this_v8_conversion_type]
787 # FIXME: oilpan: Remove .release() once we remove all RefPtrs from generated code.
789 cpp_value = '%s.release()' % cpp_value
790 statement = format_string.format(cpp_value=cpp_value, script_wrappable=script_wrappable)
794 IdlTypeBase.v8_set_return_value = v8_set_return_value
796 IdlType.release = property(lambda self: self.is_interface_type)
797 IdlUnionType.release = False
800 CPP_VALUE_TO_V8_VALUE = {
802 'Date': 'v8DateOrNaN({cpp_value}, {isolate})',
803 'DOMString': 'v8String({isolate}, {cpp_value})',
804 'ByteString': 'v8String({isolate}, {cpp_value})',
805 'USVString': 'v8String({isolate}, {cpp_value})',
806 'boolean': 'v8Boolean({cpp_value}, {isolate})',
807 'int': 'v8::Integer::New({isolate}, {cpp_value})',
808 'unsigned': 'v8::Integer::NewFromUnsigned({isolate}, {cpp_value})',
809 'float': 'v8::Number::New({isolate}, {cpp_value})',
810 'unrestricted float': 'v8::Number::New({isolate}, {cpp_value})',
811 'double': 'v8::Number::New({isolate}, {cpp_value})',
812 'unrestricted double': 'v8::Number::New({isolate}, {cpp_value})',
813 'void': 'v8Undefined()',
814 # [TreatReturnedNullStringAs]
815 'StringOrNull': '{cpp_value}.isNull() ? v8::Handle<v8::Value>(v8::Null({isolate})) : v8String({isolate}, {cpp_value})',
816 'StringOrUndefined': '{cpp_value}.isNull() ? v8Undefined() : v8String({isolate}, {cpp_value})',
818 'EventHandler': '{cpp_value} ? v8::Handle<v8::Value>(V8AbstractEventListener::cast({cpp_value})->getListenerObject(impl->executionContext())) : v8::Handle<v8::Value>(v8::Null({isolate}))',
819 'ScriptValue': '{cpp_value}.v8Value()',
820 'SerializedScriptValue': '{cpp_value} ? {cpp_value}->deserialize() : v8::Handle<v8::Value>(v8::Null({isolate}))',
822 'array': 'v8Array({cpp_value}, {creation_context}, {isolate})',
823 'DOMWrapper': 'toV8({cpp_value}, {creation_context}, {isolate})',
824 # Union types or dictionaries
825 'DictionaryOrUnion': 'toV8({cpp_value}, {creation_context}, {isolate})',
829 def cpp_value_to_v8_value(idl_type, cpp_value, isolate='info.GetIsolate()', creation_context='info.Holder()', extended_attributes=None):
830 """Returns an expression that converts a C++ value to a V8 value."""
831 # the isolate parameter is needed for callback interfaces
832 idl_type, cpp_value = preprocess_idl_type_and_value(idl_type, cpp_value, extended_attributes)
833 this_v8_conversion_type = idl_type.v8_conversion_type(extended_attributes)
834 format_string = CPP_VALUE_TO_V8_VALUE[this_v8_conversion_type]
835 statement = format_string.format(cpp_value=cpp_value, isolate=isolate, creation_context=creation_context)
838 IdlTypeBase.cpp_value_to_v8_value = cpp_value_to_v8_value
841 def literal_cpp_value(idl_type, idl_literal):
842 """Converts an expression that is a valid C++ literal for this type."""
843 # FIXME: add validation that idl_type and idl_literal are compatible
844 literal_value = str(idl_literal)
845 if idl_type.base_type in CPP_UNSIGNED_TYPES:
846 return literal_value + 'u'
849 IdlType.literal_cpp_value = literal_cpp_value
852 ################################################################################
853 # Utility properties for nullable types
854 ################################################################################
857 def cpp_type_has_null_value(idl_type):
858 # - String types (String/AtomicString) represent null as a null string,
859 # i.e. one for which String::isNull() returns true.
860 # - Enum types, as they are implemented as Strings.
861 # - Wrapper types (raw pointer or RefPtr/PassRefPtr) represent null as
863 # - 'Object' type. We use ScriptValue for object type.
864 return (idl_type.is_string_type or idl_type.is_wrapper_type or
865 idl_type.is_enum or idl_type.base_type == 'object')
867 IdlTypeBase.cpp_type_has_null_value = property(cpp_type_has_null_value)
870 def is_implicit_nullable(idl_type):
871 # Nullable type where the corresponding C++ type supports a null value.
872 return idl_type.is_nullable and idl_type.cpp_type_has_null_value
875 def is_explicit_nullable(idl_type):
876 # Nullable type that isn't implicit nullable (see above.) For such types,
877 # we use Nullable<T> or similar explicit ways to represent a null value.
878 return idl_type.is_nullable and not idl_type.is_implicit_nullable
880 IdlTypeBase.is_implicit_nullable = property(is_implicit_nullable)
881 IdlUnionType.is_implicit_nullable = False
882 IdlTypeBase.is_explicit_nullable = property(is_explicit_nullable)