Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / scripts / v8_types.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 """Functions for type handling and type conversion (Blink/C++ <-> V8/JS).
30
31 Extends IdlType and IdlUnionType with V8-specific properties, methods, and
32 class methods.
33
34 Spec:
35 http://www.w3.org/TR/WebIDL/#es-type-mapping
36
37 Design doc: http://www.chromium.org/developers/design-documents/idl-compiler
38 """
39
40 import posixpath
41
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
45
46
47 ################################################################################
48 # V8-specific handling of IDL types
49 ################################################################################
50
51 NON_WRAPPER_TYPES = frozenset([
52     'Dictionary',
53     'EventHandler',
54     'EventListener',
55     'NodeFilter',
56     'SerializedScriptValue',
57 ])
58 TYPED_ARRAY_TYPES = frozenset([
59     'Float32Array',
60     'Float64Array',
61     'Int8Array',
62     'Int16Array',
63     'Int32Array',
64     'Uint8Array',
65     'Uint8ClampedArray',
66     'Uint16Array',
67     'Uint32Array',
68 ])
69 ARRAY_BUFFER_AND_VIEW_TYPES = TYPED_ARRAY_TYPES.union(frozenset([
70     'ArrayBuffer',
71     'ArrayBufferView',
72     'DataView',
73 ]))
74
75 IdlType.is_array_buffer_or_view = property(
76     lambda self: self.base_type in ARRAY_BUFFER_AND_VIEW_TYPES)
77
78 IdlType.is_typed_array = property(
79     lambda self: self.base_type in TYPED_ARRAY_TYPES)
80
81 IdlType.is_wrapper_type = property(
82     lambda self: (self.is_interface_type and
83                   self.base_type not in NON_WRAPPER_TYPES))
84
85
86 ################################################################################
87 # C++ types
88 ################################################################################
89
90 CPP_TYPE_SAME_AS_IDL_TYPE = set([
91     'double',
92     'float',
93     'long long',
94     'unsigned long long',
95 ])
96 CPP_INT_TYPES = set([
97     'byte',
98     'long',
99     'short',
100 ])
101 CPP_UNSIGNED_TYPES = set([
102     'octet',
103     'unsigned int',
104     'unsigned long',
105     'unsigned short',
106 ])
107 CPP_SPECIAL_CONVERSION_RULES = {
108     'Date': 'double',
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>',
116     'boolean': 'bool',
117     'unrestricted double': 'double',
118     'unrestricted float': 'float',
119 }
120
121
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.
124
125     |idl_type| argument is of type IdlType, while return value is a string
126
127     Args:
128         idl_type:
129             IdlType
130         raw_type:
131             bool, True if idl_type's raw/primitive C++ type should be returned.
132         used_as_rvalue_type:
133             bool, True if the C++ type is used as an argument or the return
134             type of a method.
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.
140     """
141     def string_mode():
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'
148         return ''
149
150     extended_attributes = extended_attributes or {}
151     idl_type = idl_type.preprocessed_type
152
153     # Array or sequence types
154     if used_as_variadic_argument:
155         native_array_element_type = idl_type
156     else:
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
164
165     # Simple types
166     base_idl_type = idl_type.base_type
167
168     if base_idl_type in CPP_TYPE_SAME_AS_IDL_TYPE:
169         return base_idl_type
170     if base_idl_type in CPP_INT_TYPES:
171         return 'int'
172     if base_idl_type in CPP_UNSIGNED_TYPES:
173         return 'unsigned'
174     if base_idl_type in CPP_SPECIAL_CONVERSION_RULES:
175         return CPP_SPECIAL_CONVERSION_RULES[base_idl_type]
176
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:
180         if not raw_type:
181             return 'String'
182         return 'V8StringResource<%s>' % string_mode()
183
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
188         if raw_type:
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:
194         return base_idl_type
195     if idl_type.is_union_type:
196         return idl_type.name
197
198     # Default, assume native type is a pointer with same type name as idl type
199     return base_idl_type + '*'
200
201
202 def cpp_type_initializer(idl_type):
203     """Returns a string containing a C++ initialization statement for the
204     corresponding type.
205
206     |idl_type| argument is of type IdlType.
207     """
208
209     base_idl_type = idl_type.base_type
210
211     if idl_type.native_array_element_type:
212         return ''
213     if idl_type.is_numeric_type:
214         return ' = 0'
215     if base_idl_type == 'boolean':
216         return ' = false'
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
221         idl_type.is_enum):
222         return ''
223     return ' = nullptr'
224
225
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 = ''
231
232
233 IdlArrayOrSequenceType.native_array_element_type = property(
234     lambda self: self.element_type)
235
236
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} >'
241     else:
242         format_string = '{template}<{inner_type}>'
243     return format_string.format(template=template, inner_type=inner_type)
244
245
246 def cpp_ptr_type(old_type, new_type, gc_type):
247     if gc_type == 'GarbageCollectedObject':
248         return new_type
249     if gc_type == 'WillBeGarbageCollectedObject':
250         if old_type == 'Vector':
251             return 'WillBe' + new_type
252         return old_type + 'WillBe' + new_type
253     return old_type
254
255
256 def v8_type(interface_name):
257     return 'V8' + interface_name
258
259
260 # [ImplementedAs]
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 = {}
269
270
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]
275     return base_idl_type
276
277
278 IdlType.implemented_as = property(implemented_as)
279
280 IdlType.set_implemented_as_interfaces = classmethod(
281     lambda cls, new_implemented_as_interfaces:
282         cls.implemented_as_interfaces.update(new_implemented_as_interfaces))
283
284
285 # [GarbageCollected]
286 IdlType.garbage_collected_types = set()
287
288 IdlType.is_garbage_collected = property(
289     lambda self: self.base_type in IdlType.garbage_collected_types)
290
291 IdlType.set_garbage_collected_types = classmethod(
292     lambda cls, new_garbage_collected_types:
293         cls.garbage_collected_types.update(new_garbage_collected_types))
294
295
296 # [WillBeGarbageCollected]
297 IdlType.will_be_garbage_collected_types = set()
298
299 IdlType.is_will_be_garbage_collected = property(
300     lambda self: self.base_type in IdlType.will_be_garbage_collected_types)
301
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))
305
306
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'
313
314 IdlTypeBase.gc_type = property(gc_type)
315
316
317 def is_traceable(idl_type):
318     return (idl_type.is_garbage_collected
319             or idl_type.is_will_be_garbage_collected)
320
321 IdlTypeBase.is_traceable = property(is_traceable)
322
323
324 ################################################################################
325 # Includes
326 ################################################################################
327
328 def includes_for_cpp_class(class_name, relative_dir_posix):
329     return set([posixpath.join('bindings', relative_dir_posix, class_name + '.h')])
330
331
332 INCLUDES_FOR_TYPE = {
333     'object': set(),
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']),
355 }
356
357
358 def includes_for_type(idl_type):
359     idl_type = idl_type.preprocessed_type
360
361     # Simple types
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:
366         return set()
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
373         return set()
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:
378         return set()
379     return set(['bindings/%s/v8/V8%s.h' % (component_dir[base_idl_type],
380                                            base_idl_type)])
381
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)
388
389
390 def add_includes_for_type(idl_type):
391     includes.update(idl_type.includes_for_type)
392
393 IdlTypeBase.add_includes_for_type = add_includes_for_type
394
395
396 def includes_for_interface(interface_name):
397     return IdlType(interface_name).includes_for_type
398
399
400 def add_includes_for_interface(interface_name):
401     includes.update(includes_for_interface(interface_name))
402
403
404 def impl_should_use_nullable_container(idl_type):
405     return not(idl_type.cpp_type_has_null_value)
406
407 IdlTypeBase.impl_should_use_nullable_container = property(
408     impl_should_use_nullable_container)
409
410
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')
415
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')
422
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
432
433 IdlTypeBase.impl_includes_for_type = impl_includes_for_type
434
435
436 component_dir = {}
437
438
439 def set_component_dirs(new_component_dirs):
440     component_dir.update(new_component_dirs)
441
442
443 ################################################################################
444 # V8 -> C++
445 ################################################################################
446
447 V8_VALUE_TO_CPP_VALUE = {
448     # Basic
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})',
466     # Interface types
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})',
475 }
476
477
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'))
482
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
486
487
488 TRIVIAL_CONVERSIONS = frozenset([
489     'any',
490     'boolean',
491     'Date',
492     'Dictionary',
493     'NodeFilter',
494     'XPathNSResolver',
495     'Promise'
496 ])
497
498
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)
504
505 IdlType.v8_conversion_is_trivial = property(v8_conversion_is_trivial)
506
507
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':
510         return ''
511
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)
516
517     # Simple types
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
521
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'])
528     else:
529         arguments = v8_value
530
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})')
542     else:
543         cpp_expression_format = (
544             'V8{idl_type}::toImpl(v8::Handle<v8::Object>::Cast({v8_value}))')
545
546     return cpp_expression_format.format(arguments=arguments, idl_type=base_idl_type, v8_value=v8_value, variable_name=variable_name, isolate=isolate)
547
548
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
552     if index is None:
553         index = 0  # special case, meaning "setter"
554     else:
555         index += 1  # human-readable index
556     if (native_array_element_type.is_interface_type and
557         native_array_element_type.name != 'Dictionary'):
558         this_cpp_type = None
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)
562     else:
563         ref_ptr_type = None
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)
567     return expression
568
569
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."""
573
574     this_cpp_type = idl_type.cpp_type_args(extended_attributes=extended_attributes, raw_type=True)
575     idl_type = idl_type.preprocessed_type
576
577     if idl_type.base_type in ('void', 'object', 'EventHandler', 'EventListener'):
578         return '/* no V8 -> C++ conversion for IDL type: %s */' % idl_type.name
579
580     cpp_value = v8_value_to_cpp_value(idl_type, extended_attributes, v8_value, variable_name, needs_type_check, index, isolate)
581
582     if idl_type.is_dictionary or idl_type.is_union_type:
583         return 'TONATIVE_VOID_EXCEPTIONSTATE_ARGINTERNAL(%s, exceptionState)' % cpp_value
584
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.
588
589         args = [variable_name, cpp_value]
590
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'
595         else:
596             macro = 'TOSTRING_DEFAULT' if used_in_private_script else 'TOSTRING_VOID'
597
598         if macro.endswith('_EXCEPTIONSTATE'):
599             args.append('exceptionState')
600
601         if used_in_private_script:
602             args.append('false')
603
604         suffix = ''
605
606         if return_promise:
607             suffix += '_PROMISE'
608             args.append('info')
609             if macro.endswith('_EXCEPTIONSTATE'):
610                 args.append('ScriptState::current(%s)' % isolate)
611
612         if declare_variable:
613             args.insert(0, this_cpp_type)
614         else:
615             suffix += '_INTERNAL'
616
617         return '%s(%s)' % (macro + suffix, ', '.join(args))
618
619     # Types that don't need error handling, and simply assign a value to the
620     # local variable.
621
622     if not idl_type.v8_conversion_is_trivial:
623         raise Exception('unclassified V8 -> C++ conversion for IDL type: %s' % idl_type.name)
624
625     assignment = '%s = %s' % (variable_name, cpp_value)
626     if declare_variable:
627         return '%s %s' % (this_cpp_type, assignment)
628     return assignment
629
630
631 IdlTypeBase.v8_value_to_local_cpp_value = v8_value_to_local_cpp_value
632
633
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.
637     """
638     return idl_type.is_dictionary or idl_type.is_union_type
639
640 IdlTypeBase.use_output_parameter_for_result = property(use_output_parameter_for_result)
641
642
643 ################################################################################
644 # C++ -> V8
645 ################################################################################
646
647 def preprocess_idl_type(idl_type):
648     if idl_type.is_enum:
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')
653     return idl_type
654
655 IdlTypeBase.preprocessed_type = property(preprocess_idl_type)
656
657
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')
668         if is_nullable:
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
681
682
683 def v8_conversion_type(idl_type, extended_attributes):
684     """Returns V8 conversion type, adding any additional includes.
685
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').
689     """
690     extended_attributes = extended_attributes or {}
691
692     if idl_type.is_dictionary or idl_type.is_union_type:
693         return 'DictionaryOrUnion'
694
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)
700         return 'array'
701
702     # Simple types
703     base_idl_type = idl_type.base_type
704     # Basic types, without additional includes
705     if base_idl_type in CPP_INT_TYPES:
706         return 'int'
707     if base_idl_type in CPP_UNSIGNED_TYPES:
708         return 'unsigned'
709     if idl_type.is_string_type:
710         if idl_type.is_nullable:
711             return 'StringOrNull'
712         if 'TreatReturnedNullStringAs' not in extended_attributes:
713             return base_idl_type
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':
721         return base_idl_type
722
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
726         return base_idl_type
727
728     # Pointer type
729     return 'DOMWrapper'
730
731 IdlTypeBase.v8_conversion_type = v8_conversion_type
732
733
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())',
744     'void': '',
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})',
757     # DOMWrapper
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)',
763 }
764
765
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.
768
769     """
770     def dom_wrapper_conversion_type():
771         if not script_wrappable:
772             return 'DOMWrapperDefault'
773         if for_main_world:
774             return 'DOMWrapperForMainWorld'
775         return 'DOMWrapperFast'
776
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()
785
786     format_string = V8_SET_RETURN_VALUE[this_v8_conversion_type]
787     # FIXME: oilpan: Remove .release() once we remove all RefPtrs from generated code.
788     if release:
789         cpp_value = '%s.release()' % cpp_value
790     statement = format_string.format(cpp_value=cpp_value, script_wrappable=script_wrappable)
791     return statement
792
793
794 IdlTypeBase.v8_set_return_value = v8_set_return_value
795
796 IdlType.release = property(lambda self: self.is_interface_type)
797 IdlUnionType.release = False
798
799
800 CPP_VALUE_TO_V8_VALUE = {
801     # Built-in types
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})',
817     # Special cases
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}))',
821     # General
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})',
826 }
827
828
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)
836     return statement
837
838 IdlTypeBase.cpp_value_to_v8_value = cpp_value_to_v8_value
839
840
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'
847     return literal_value
848
849 IdlType.literal_cpp_value = literal_cpp_value
850
851
852 ################################################################################
853 # Utility properties for nullable types
854 ################################################################################
855
856
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
862     #   a null pointer.
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')
866
867 IdlTypeBase.cpp_type_has_null_value = property(cpp_type_has_null_value)
868
869
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
873
874
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
879
880 IdlTypeBase.is_implicit_nullable = property(is_implicit_nullable)
881 IdlUnionType.is_implicit_nullable = False
882 IdlTypeBase.is_explicit_nullable = property(is_explicit_nullable)