OLD | NEW |
| (Empty) |
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++ <-> Dart:HTML). | |
30 | |
31 Extends IdlType and IdlUnionType with C++-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 from idl_types import IdlTypeBase, IdlType, IdlUnionType, TYPE_NAMES, IdlArrayOr
SequenceType, IdlSequenceType | |
42 | |
43 import dart_attributes | |
44 from dart_utilities import DartUtilities | |
45 from v8_globals import includes | |
46 | |
47 | |
48 ################################################################################ | |
49 # CPP -specific handling of IDL types for Dart:Blink | |
50 ################################################################################ | |
51 | |
52 NON_WRAPPER_TYPES = frozenset([ | |
53 'Dictionary', | |
54 'EventHandler', | |
55 'EventListener', | |
56 'NodeFilter', | |
57 'SerializedScriptValue', | |
58 ]) | |
59 TYPED_ARRAYS = { | |
60 # (cpp_type, dart_type), used by constructor templates | |
61 'ArrayBuffer': (None, 'ByteBuffer'), | |
62 'ArrayBufferView': (None, 'ByteData'), | |
63 'Float32Array': ('float', 'Float32List'), | |
64 'Float64Array': ('double', 'Float64List'), | |
65 'Int8Array': ('signed char', 'Int8List'), | |
66 'Int16Array': ('short', 'Int16List'), | |
67 'Int32Array': ('int', 'Int32List'), | |
68 'Uint8Array': ('unsigned char', 'Uint8List'), | |
69 'Uint8ClampedArray': ('unsigned char', 'Uint8ClampedList'), | |
70 'Uint16Array': ('unsigned short', 'Uint16List'), | |
71 'Uint32Array': ('unsigned int', 'Uint32List'), | |
72 } | |
73 | |
74 | |
75 IdlTypeBase.is_typed_array_type = property( | |
76 lambda self: self.base_type in TYPED_ARRAYS) | |
77 | |
78 | |
79 IdlType.is_wrapper_type = property( | |
80 lambda self: (self.is_interface_type and | |
81 self.base_type not in NON_WRAPPER_TYPES)) | |
82 | |
83 | |
84 ################################################################################ | |
85 # C++ types | |
86 ################################################################################ | |
87 | |
88 CPP_TYPE_SAME_AS_IDL_TYPE = set([ | |
89 'double', | |
90 'float', | |
91 'long long', | |
92 'unsigned long long', | |
93 ]) | |
94 CPP_INT_TYPES = set([ | |
95 'byte', | |
96 'long', | |
97 'short', | |
98 ]) | |
99 CPP_UNSIGNED_TYPES = set([ | |
100 'octet', | |
101 'unsigned int', | |
102 'unsigned long', | |
103 'unsigned short', | |
104 ]) | |
105 CPP_SPECIAL_CONVERSION_RULES = { | |
106 'Date': 'double', | |
107 'Dictionary': 'Dictionary', | |
108 'EventHandler': 'EventListener*', | |
109 'NodeFilter': 'RefPtrWillBeRawPtr<NodeFilter>', | |
110 'Promise': 'ScriptPromise', | |
111 'ScriptValue': 'ScriptValue', | |
112 # FIXME: Eliminate custom bindings for XPathNSResolver http://crbug.com/345
529 | |
113 'XPathNSResolver': 'RefPtrWillBeRawPtr<XPathNSResolver>', | |
114 'boolean': 'bool', | |
115 'unrestricted double': 'double', | |
116 'unrestricted float': 'float', | |
117 } | |
118 | |
119 | |
120 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): | |
121 """Returns C++ type corresponding to IDL type. | |
122 | |
123 |idl_type| argument is of type IdlType, while return value is a string | |
124 | |
125 Args: | |
126 idl_type: | |
127 IdlType | |
128 raw_type: | |
129 bool, True if idl_type's raw/primitive C++ type should be returned. | |
130 used_as_rvalue_type: | |
131 bool, True if the C++ type is used as an argument or the return | |
132 type of a method. | |
133 used_as_variadic_argument: | |
134 bool, True if the C++ type is used as a variadic argument of a metho
d. | |
135 used_in_cpp_sequence: | |
136 bool, True if the C++ type is used as an element of a container. | |
137 Containers can be an array, a sequence or a dictionary. | |
138 """ | |
139 extended_attributes = extended_attributes or {} | |
140 idl_type = idl_type.preprocessed_type | |
141 | |
142 # Composite types | |
143 native_array_element_type = idl_type.native_array_element_type | |
144 if native_array_element_type: | |
145 vector_type = cpp_ptr_type('Vector', 'HeapVector', native_array_element_
type.gc_type) | |
146 return cpp_template_type(vector_type, native_array_element_type.cpp_type
_args(used_in_cpp_sequence=True)) | |
147 | |
148 # Simple types | |
149 base_idl_type = idl_type.base_type | |
150 | |
151 if base_idl_type in CPP_TYPE_SAME_AS_IDL_TYPE: | |
152 return base_idl_type | |
153 if base_idl_type in CPP_INT_TYPES: | |
154 return 'int' | |
155 if base_idl_type in CPP_UNSIGNED_TYPES: | |
156 return 'unsigned' | |
157 if base_idl_type in CPP_SPECIAL_CONVERSION_RULES: | |
158 return CPP_SPECIAL_CONVERSION_RULES[base_idl_type] | |
159 | |
160 if base_idl_type in NON_WRAPPER_TYPES: | |
161 return ('PassRefPtr<%s>' if used_as_rvalue_type else 'RefPtr<%s>') % bas
e_idl_type | |
162 if base_idl_type in ('DOMString', 'ByteString', 'ScalarValueString'): | |
163 if not raw_type: | |
164 return 'String' | |
165 return 'DartStringAdapter' | |
166 | |
167 if idl_type.is_typed_array_type and raw_type: | |
168 return 'RefPtr<%s>' % base_idl_type | |
169 if idl_type.is_interface_type: | |
170 implemented_as_class = idl_type.implemented_as | |
171 if raw_type: | |
172 return implemented_as_class + '*' | |
173 new_type = 'Member' if used_in_cpp_sequence else 'RawPtr' | |
174 ptr_type = cpp_ptr_type(('PassRefPtr' if used_as_rvalue_type else 'RefPt
r'), new_type, idl_type.gc_type) | |
175 return cpp_template_type(ptr_type, implemented_as_class) | |
176 | |
177 # Default, assume native type is a pointer with same type name as idl type | |
178 | |
179 # FIXME: How to handle sequence<WebGLShader>? | |
180 if base_idl_type is None: | |
181 base_idl_type = idl_type.inner_type.element_type.base_type | |
182 | |
183 return base_idl_type + '*' | |
184 | |
185 | |
186 def cpp_type_union(idl_type, extended_attributes=None, used_as_rvalue_type=False
, will_be_in_heap_object=False): | |
187 return (member_type.cpp_type for member_type in idl_type.member_types) | |
188 | |
189 | |
190 # Allow access as idl_type.cpp_type if no arguments | |
191 IdlTypeBase.cpp_type = property(cpp_type) | |
192 IdlTypeBase.cpp_type_args = cpp_type | |
193 IdlUnionType.cpp_type = property(cpp_type_union) | |
194 IdlUnionType.cpp_type_args = cpp_type_union | |
195 | |
196 | |
197 IdlTypeBase.native_array_element_type = None | |
198 IdlArrayOrSequenceType.native_array_element_type = property( | |
199 lambda self: self.element_type) | |
200 | |
201 IdlTypeBase.enum_validation_expression = property(DartUtilities.enum_validation_
expression) | |
202 | |
203 | |
204 def cpp_template_type(template, inner_type): | |
205 """Returns C++ template specialized to type, with space added if needed.""" | |
206 if inner_type.endswith('>'): | |
207 format_string = '{template}<{inner_type} >' | |
208 else: | |
209 format_string = '{template}<{inner_type}>' | |
210 return format_string.format(template=template, inner_type=inner_type) | |
211 | |
212 | |
213 def cpp_ptr_type(old_type, new_type, gc_type): | |
214 if gc_type == 'GarbageCollectedObject': | |
215 return new_type | |
216 if gc_type == 'WillBeGarbageCollectedObject': | |
217 if old_type == 'Vector': | |
218 return 'WillBe' + new_type | |
219 return old_type + 'WillBe' + new_type | |
220 return old_type | |
221 | |
222 | |
223 def v8_type(interface_name): | |
224 return 'V8' + interface_name | |
225 | |
226 | |
227 def dart_type(interface_name): | |
228 return 'Dart' + str(interface_name) | |
229 | |
230 | |
231 # [ImplementedAs] | |
232 # This handles [ImplementedAs] on interface types, not [ImplementedAs] in the | |
233 # interface being generated. e.g., given: | |
234 # Foo.idl: interface Foo {attribute Bar bar}; | |
235 # Bar.idl: [ImplementedAs=Zork] interface Bar {}; | |
236 # when generating bindings for Foo, the [ImplementedAs] on Bar is needed. | |
237 # This data is external to Foo.idl, and hence computed as global information in | |
238 # compute_interfaces_info.py to avoid having to parse IDLs of all used interface
s. | |
239 IdlType.implemented_as_interfaces = {} | |
240 | |
241 | |
242 def implemented_as(idl_type): | |
243 base_idl_type = idl_type.base_type | |
244 if base_idl_type in IdlType.implemented_as_interfaces: | |
245 return IdlType.implemented_as_interfaces[base_idl_type] | |
246 return base_idl_type | |
247 | |
248 | |
249 IdlType.implemented_as = property(implemented_as) | |
250 | |
251 IdlType.set_implemented_as_interfaces = classmethod( | |
252 lambda cls, new_implemented_as_interfaces: | |
253 cls.implemented_as_interfaces.update(new_implemented_as_interfaces)) | |
254 | |
255 | |
256 # [GarbageCollected] | |
257 IdlType.garbage_collected_types = set() | |
258 | |
259 IdlTypeBase.is_garbage_collected = False | |
260 IdlType.is_garbage_collected = property( | |
261 lambda self: self.base_type in IdlType.garbage_collected_types) | |
262 | |
263 IdlType.set_garbage_collected_types = classmethod( | |
264 lambda cls, new_garbage_collected_types: | |
265 cls.garbage_collected_types.update(new_garbage_collected_types)) | |
266 | |
267 | |
268 # [WillBeGarbageCollected] | |
269 IdlType.will_be_garbage_collected_types = set() | |
270 | |
271 IdlTypeBase.is_will_be_garbage_collected = False | |
272 IdlType.is_will_be_garbage_collected = property( | |
273 lambda self: self.base_type in IdlType.will_be_garbage_collected_types) | |
274 | |
275 IdlType.set_will_be_garbage_collected_types = classmethod( | |
276 lambda cls, new_will_be_garbage_collected_types: | |
277 cls.will_be_garbage_collected_types.update(new_will_be_garbage_collected
_types)) | |
278 | |
279 | |
280 def gc_type(idl_type): | |
281 if idl_type.is_garbage_collected: | |
282 return 'GarbageCollectedObject' | |
283 if idl_type.is_will_be_garbage_collected: | |
284 return 'WillBeGarbageCollectedObject' | |
285 return 'RefCountedObject' | |
286 | |
287 IdlTypeBase.gc_type = property(gc_type) | |
288 | |
289 | |
290 ################################################################################ | |
291 # Includes | |
292 ################################################################################ | |
293 | |
294 def includes_for_cpp_class(class_name, relative_dir_posix): | |
295 return set([posixpath.join('bindings', relative_dir_posix, class_name + '.h'
)]) | |
296 | |
297 # TODO(terry): Will we need this group header for dart:blink? | |
298 INCLUDES_FOR_TYPE = { | |
299 'object': set(), | |
300 'Dictionary': set(['bindings/core/v8/Dictionary.h']), | |
301 'EventHandler': set(), | |
302 'EventListener': set(), | |
303 'HTMLCollection': set(['bindings/core/dart/DartHTMLCollection.h', | |
304 'core/dom/ClassCollection.h', | |
305 'core/dom/TagCollection.h', | |
306 'core/html/HTMLCollection.h', | |
307 'core/html/HTMLDataListOptionsCollection.h', | |
308 'core/html/HTMLFormControlsCollection.h', | |
309 'core/html/HTMLTableRowsCollection.h']), | |
310 'NodeList': set(['bindings/core/dart/DartNodeList.h', | |
311 'core/dom/NameNodeList.h', | |
312 'core/dom/NodeList.h', | |
313 'core/dom/StaticNodeList.h', | |
314 'core/html/LabelsNodeList.h']), | |
315 'Promise': set(['bindings/core/dart/DartScriptPromise.h']), | |
316 'SerializedScriptValue': set(), | |
317 'ScriptValue': set(['bindings/core/dart/DartScriptValue.h']), | |
318 } | |
319 | |
320 | |
321 def includes_for_type(idl_type): | |
322 idl_type = idl_type.preprocessed_type | |
323 | |
324 # Composite types | |
325 if idl_type.native_array_element_type: | |
326 return includes_for_type(idl_type) | |
327 | |
328 # Simple types | |
329 base_idl_type = idl_type.base_type | |
330 if base_idl_type in INCLUDES_FOR_TYPE: | |
331 return INCLUDES_FOR_TYPE[base_idl_type] | |
332 if idl_type.is_basic_type: | |
333 return set() | |
334 if idl_type.is_typed_array_type: | |
335 # Typed array factory methods are already provided by DartUtilities.h. | |
336 return set([]) | |
337 if base_idl_type.endswith('ConstructorConstructor'): | |
338 # FIXME: rename to NamedConstructor | |
339 # FIXME: replace with a [NamedConstructorAttribute] extended attribute | |
340 # Ending with 'ConstructorConstructor' indicates a named constructor, | |
341 # and these do not have header files, as they are part of the generated | |
342 # bindings for the interface | |
343 return set() | |
344 if base_idl_type.endswith('Constructor'): | |
345 # FIXME: replace with a [ConstructorAttribute] extended attribute | |
346 base_idl_type = idl_type.constructor_type_name | |
347 if base_idl_type not in component_dir: | |
348 return set() | |
349 return set(['bindings/%s/dart/Dart%s.h' % (component_dir[base_idl_type], | |
350 base_idl_type)]) | |
351 | |
352 IdlType.includes_for_type = property(includes_for_type) | |
353 IdlUnionType.includes_for_type = property( | |
354 lambda self: set.union(*[includes_for_type(member_type) | |
355 for member_type in self.member_types])) | |
356 | |
357 | |
358 def add_includes_for_type(idl_type): | |
359 includes.update(idl_type.includes_for_type) | |
360 | |
361 IdlTypeBase.add_includes_for_type = add_includes_for_type | |
362 IdlUnionType.add_includes_for_type = add_includes_for_type | |
363 | |
364 | |
365 def includes_for_interface(interface_name): | |
366 return IdlType(interface_name).includes_for_type | |
367 | |
368 | |
369 def add_includes_for_interface(interface_name): | |
370 includes.update(includes_for_interface(interface_name)) | |
371 | |
372 | |
373 component_dir = {} | |
374 | |
375 | |
376 def set_component_dirs(new_component_dirs): | |
377 component_dir.update(new_component_dirs) | |
378 | |
379 | |
380 ################################################################################ | |
381 # Dart -> C++ | |
382 ################################################################################ | |
383 | |
384 # TODO(terry): Need to fix to handle getter/setters for onEvent. | |
385 DART_FIX_ME = 'DART_UNIMPLEMENTED(/* Conversion unimplemented*/);' | |
386 | |
387 # For a given IDL type, the DartHandle to C++ conversion. | |
388 DART_TO_CPP_VALUE = { | |
389 # Basic | |
390 'Date': 'DartUtilities::dartToDate(args, {index}, exception)', | |
391 'DOMString': 'DartUtilities::dartToString{null_check}(args, {index}, excepti
on, {auto_scope})', | |
392 'ByteString': 'DartUtilities::dartToByteString{null_check}(args, {index}, ex
ception, {auto_scope})', | |
393 'ScalarValueString': 'DartUtilities::dartToScalarValueString{null_check}(arg
s, {index}, exception, {auto_scope})', | |
394 'boolean': 'DartUtilities::dartToBool{null_check}(args, {index}, exception)'
, | |
395 'float': 'static_cast<float>(DartUtilities::dartToDouble(args, {index}, exce
ption))', | |
396 'unrestricted float': 'static_cast<float>(DartUtilities::dartToDouble(args,
{index}, exception))', | |
397 'double': 'DartUtilities::dartToDouble(args, {index}, exception)', | |
398 'unrestricted double': 'DartUtilities::dartToDouble(args, {index}, exception
)', | |
399 # FIXME(vsm): Inconsistent with V8. | |
400 'byte': 'DartUtilities::dartToUnsigned(args, {index}, exception)', | |
401 'octet': 'DartUtilities::dartToUnsigned(args, {index}, exception)', | |
402 'short': 'DartUtilities::dartToInt(args, {index}, exception)', | |
403 'unsigned short': 'DartUtilities::dartToUnsigned(args, {index}, exception)', | |
404 'long': 'DartUtilities::dartToInt(args, {index}, exception)', | |
405 'unsigned long': 'DartUtilities::dartToUnsignedLongLong(args, {index}, excep
tion)', | |
406 'long long': 'DartUtilities::dartToLongLong(args, {index}, exception)', | |
407 'unsigned long long': 'DartUtilities::dartToUnsignedLongLong(args, {index},
exception)', | |
408 # Interface types | |
409 'Dictionary': 'DartUtilities::dartToDictionary{null_check}(args, {index}, ex
ception)', | |
410 'EventTarget': '0 /* FIXME, DART_TO_CPP_VALUE[EventTarget] */', | |
411 'NodeFilter': 'nullptr /* FIXME, DART_TO_CPP_VALUE[NodeFilter] */', | |
412 'Promise': 'DartUtilities::dartToScriptPromise{null_check}(args, {index})', | |
413 'SerializedScriptValue': 'nullptr /* FIXME, DART_TO_CPP_VALUE[SerializedScri
ptValue] */', | |
414 'ScriptValue': 'DartUtilities::dartToScriptValue{null_check}(args, {index})'
, | |
415 # FIXME(vsm): Why don't we have an entry for Window? V8 does. | |
416 # I think I removed this as the Window object is more special in V8 - it's t
he | |
417 # global context as well. Do we need to special case it? | |
418 'XPathNSResolver': 'nullptr /* FIXME, DART_TO_CPP_VALUE[XPathNSResolver] */'
, | |
419 # FIXME(vsm): This is an enum type (defined in StorageQuota.idl). | |
420 # We should handle it automatically, but map to a String for now. | |
421 'StorageType': 'DartUtilities::dartToString(args, {index}, exception, {auto_
scope})', | |
422 } | |
423 | |
424 | |
425 def dart_dictionary_value_argument(idl_type, index): | |
426 if idl_type.is_dictionary: | |
427 argument_expression_format = 'DartUtilities::dartToDictionaryWithNullChe
ck(args, {index}, exception)' | |
428 return argument_expression_format.format(index=index) | |
429 | |
430 return None | |
431 | |
432 | |
433 def dart_dictionary_to_local_cpp_value(idl_type, index=None): | |
434 """Returns an expression that converts a Dictionary value as a local value."
"" | |
435 idl_type = idl_type.preprocessed_type | |
436 | |
437 cpp_value = dart_dictionary_value_argument(idl_type, index) | |
438 | |
439 return cpp_value | |
440 | |
441 IdlTypeBase.dart_dictionary_to_local_cpp_value = dart_dictionary_to_local_cpp_va
lue | |
442 | |
443 | |
444 def dart_value_to_cpp_value(idl_type, extended_attributes, variable_name, | |
445 null_check, has_type_checking_interface, | |
446 index, auto_scope=True): | |
447 # Composite types | |
448 native_array_element_type = idl_type.native_array_element_type | |
449 if native_array_element_type: | |
450 return dart_value_to_cpp_value_array_or_sequence(native_array_element_ty
pe, variable_name, index) | |
451 | |
452 # Simple types | |
453 idl_type = idl_type.preprocessed_type | |
454 add_includes_for_type(idl_type) | |
455 base_idl_type = idl_type.base_type | |
456 | |
457 if 'EnforceRange' in extended_attributes: | |
458 arguments = ', '.join([variable_name, 'EnforceRange', 'exceptionState']) | |
459 elif idl_type.is_integer_type: # NormalConversion | |
460 arguments = ', '.join([variable_name, 'es']) | |
461 else: | |
462 arguments = variable_name | |
463 | |
464 if base_idl_type in DART_TO_CPP_VALUE: | |
465 cpp_expression_format = DART_TO_CPP_VALUE[base_idl_type] | |
466 elif idl_type.is_typed_array_type: | |
467 # FIXME(vsm): V8 generates a type check here as well. Do we need one? | |
468 # FIXME(vsm): When do we call the externalized version? E.g., see | |
469 # bindings/dart/custom/DartWaveShaperNodeCustom.cpp - it calls | |
470 # DartUtilities::dartToExternalizedArrayBufferView instead. | |
471 # V8 always converts null here | |
472 cpp_expression_format = ('DartUtilities::dartTo{idl_type}WithNullCheck(a
rgs, {index}, exception)') | |
473 elif idl_type.is_callback_interface: | |
474 cpp_expression_format = ('Dart{idl_type}::create{null_check}(args, {inde
x}, exception)') | |
475 elif idl_type.is_dictionary: | |
476 # Value of dictionary is defined in method dart_dictionary_value_argumen
t. | |
477 cpp_expression_format = 'Dart{idl_type}::toImpl(dictionary, es)' | |
478 else: | |
479 cpp_expression_format = ('Dart{idl_type}::toNative{null_check}(args, {in
dex}, exception)') | |
480 | |
481 # We allow the calling context to force a null check to handle | |
482 # some cases that require calling context info. V8 handles all | |
483 # of this differently, and we may wish to reconsider this approach | |
484 check_string = '' | |
485 if null_check or allow_null(idl_type, extended_attributes, | |
486 has_type_checking_interface): | |
487 check_string = 'WithNullCheck' | |
488 elif allow_empty(idl_type, extended_attributes): | |
489 check_string = 'WithEmptyCheck' | |
490 return cpp_expression_format.format(null_check=check_string, | |
491 arguments=arguments, | |
492 index=index, | |
493 idl_type=base_idl_type, | |
494 auto_scope=DartUtilities.bool_to_cpp(aut
o_scope)) | |
495 | |
496 | |
497 def dart_value_to_cpp_value_array_or_sequence(native_array_element_type, variabl
e_name, index): | |
498 # Index is None for setters, index (starting at 0) for method arguments, | |
499 # and is used to provide a human-readable exception message | |
500 if index is None: | |
501 index = 0 # special case, meaning "setter" | |
502 # else: | |
503 # index += 1 # human-readable index | |
504 if (native_array_element_type.is_interface_type and | |
505 native_array_element_type.name != 'Dictionary'): | |
506 this_cpp_type = None | |
507 ref_ptr_type = cpp_ptr_type('RefPtr', 'Member', native_array_element_typ
e.gc_type) | |
508 # FIXME(vsm): We're not using ref_ptr_type.... | |
509 expression_format = 'DartUtilities::toNativeVector<{native_array_element
_type} >(args, {index}, {variable_name}, exception)' | |
510 add_includes_for_type(native_array_element_type) | |
511 else: | |
512 ref_ptr_type = None | |
513 this_cpp_type = native_array_element_type.cpp_type | |
514 expression_format = 'DartUtilities::toNativeVector<{cpp_type}>(args, {in
dex}, {variable_name}, exception)' | |
515 | |
516 expression = expression_format.format(native_array_element_type=native_array
_element_type.name, | |
517 cpp_type=this_cpp_type, index=index, r
ef_ptr_type=ref_ptr_type, | |
518 variable_name=variable_name) | |
519 return expression | |
520 | |
521 | |
522 def dart_value_to_local_cpp_value(idl_type, extended_attributes, variable_name, | |
523 null_check, has_type_checking_interface, | |
524 index=None, auto_scope=True): | |
525 """Returns an expression that converts a Dart value to a C++ value as a loca
l value.""" | |
526 idl_type = idl_type.preprocessed_type | |
527 | |
528 cpp_value = dart_value_to_cpp_value( | |
529 idl_type, extended_attributes, variable_name, | |
530 null_check, has_type_checking_interface, | |
531 index, auto_scope) | |
532 | |
533 return cpp_value | |
534 | |
535 IdlTypeBase.dart_value_to_local_cpp_value = dart_value_to_local_cpp_value | |
536 #IdlUnionType.dart_value_to_local_cpp_value = dart_value_to_local_cpp_value | |
537 | |
538 | |
539 # Insure that we don't use C++ reserved names. Today on default is a problem. | |
540 def check_reserved_name(name): | |
541 return 'default_value' if (name == 'default') else name | |
542 | |
543 | |
544 ################################################################################ | |
545 # C++ -> V8 | |
546 ################################################################################ | |
547 | |
548 def preprocess_idl_type(idl_type): | |
549 if idl_type.is_enum: | |
550 # Enumerations are internally DOMStrings | |
551 return IdlType('DOMString') | |
552 if (idl_type.name == 'Any' or idl_type.is_callback_function): | |
553 return IdlType('ScriptValue') | |
554 return idl_type | |
555 | |
556 IdlTypeBase.preprocessed_type = property(preprocess_idl_type) | |
557 IdlUnionType.preprocessed_type = property(preprocess_idl_type) | |
558 | |
559 | |
560 def preprocess_idl_type_and_value(idl_type, cpp_value, extended_attributes): | |
561 """Returns IDL type and value, with preliminary type conversions applied.""" | |
562 idl_type = idl_type.preprocessed_type | |
563 if idl_type.name == 'Promise': | |
564 idl_type = IdlType('ScriptPromise') | |
565 | |
566 # FIXME(vsm): V8 maps 'long long' and 'unsigned long long' to double | |
567 # as they are not representable in ECMAScript. Should we do the same? | |
568 | |
569 # HTML5 says that unsigned reflected attributes should be in the range | |
570 # [0, 2^31). When a value isn't in this range, a default value (or 0) | |
571 # should be returned instead. | |
572 extended_attributes = extended_attributes or {} | |
573 if ('Reflect' in extended_attributes and | |
574 idl_type.base_type in ['unsigned long', 'unsigned short']): | |
575 cpp_value = cpp_value.replace('getUnsignedIntegralAttribute', | |
576 'getIntegralAttribute') | |
577 cpp_value = 'std::max(0, %s)' % cpp_value | |
578 return idl_type, cpp_value | |
579 | |
580 | |
581 def dart_conversion_type(idl_type, extended_attributes): | |
582 """Returns Dart conversion type, adding any additional includes. | |
583 | |
584 The Dart conversion type is used to select the C++ -> Dart conversion functi
on | |
585 or setDart*ReturnValue function; it can be an idl_type, a cpp_type, or a | |
586 separate name for the type of conversion (e.g., 'DOMWrapper'). | |
587 """ | |
588 extended_attributes = extended_attributes or {} | |
589 | |
590 # Composite types | |
591 native_array_element_type = idl_type.native_array_element_type | |
592 | |
593 # FIXME: Work around sequence behaving like an array. | |
594 if (not native_array_element_type) and type(idl_type.inner_type) is IdlSeque
nceType: | |
595 native_array_element_type = idl_type.inner_type.native_array_element_typ
e | |
596 | |
597 if native_array_element_type: | |
598 if native_array_element_type.is_interface_type: | |
599 add_includes_for_type(native_array_element_type) | |
600 return 'array' | |
601 | |
602 # Simple types | |
603 base_idl_type = idl_type.base_type | |
604 # Basic types, without additional includes | |
605 if base_idl_type in CPP_INT_TYPES or base_idl_type == 'long long': | |
606 return 'int' | |
607 if base_idl_type in CPP_UNSIGNED_TYPES or base_idl_type == 'unsigned long lo
ng': | |
608 return 'unsigned' | |
609 if idl_type.is_string_type: | |
610 if idl_type.is_nullable: | |
611 return 'StringOrNull' | |
612 if 'TreatReturnedNullStringAs' not in extended_attributes: | |
613 return 'DOMString' | |
614 treat_returned_null_string_as = extended_attributes['TreatReturnedNullSt
ringAs'] | |
615 if treat_returned_null_string_as == 'Null': | |
616 return 'StringOrNull' | |
617 if treat_returned_null_string_as == 'Undefined': | |
618 return 'StringOrUndefined' | |
619 raise 'Unrecognized TreatReturnNullStringAs value: "%s"' % treat_returne
d_null_string_as | |
620 if idl_type.is_basic_type or base_idl_type == 'ScriptValue': | |
621 return base_idl_type | |
622 | |
623 # Data type with potential additional includes | |
624 add_includes_for_type(idl_type) | |
625 if base_idl_type in DART_SET_RETURN_VALUE: # Special dartSetReturnValue tre
atment | |
626 return base_idl_type | |
627 | |
628 # Typed arrays don't have special Dart* classes for Dart. | |
629 if idl_type.is_typed_array_type: | |
630 if base_idl_type == 'ArrayBuffer': | |
631 return 'ArrayBuffer' | |
632 else: | |
633 return 'TypedList' | |
634 | |
635 # Pointer type | |
636 return 'DOMWrapper' | |
637 | |
638 IdlTypeBase.dart_conversion_type = dart_conversion_type | |
639 | |
640 | |
641 DART_SET_RETURN_VALUE = { | |
642 'boolean': 'Dart_SetBooleanReturnValue(args, {cpp_value})', | |
643 'int': 'DartUtilities::setDartIntegerReturnValue(args, {cpp_value})', | |
644 'unsigned': 'DartUtilities::setDartUnsignedLongLongReturnValue(args, {cpp_va
lue})', | |
645 'DOMString': 'DartUtilities::setDartStringReturnValue(args, {cpp_value}, {au
to_scope})', | |
646 # FIXME(terry): Need to handle checking to byte values > 255 throwing except
ion. | |
647 'ByteString': 'DartUtilities::setDartByteStringReturnValue(args, {cpp_value}
, {auto_scope})', | |
648 # FIXME(terry): Need to make valid unicode; match UTF-16 to U+FFFD REPLACEM
ENT CHARACTER. | |
649 'ScalarValueString': 'DartUtilities::setDartScalarValueStringReturnValue(arg
s, {cpp_value}, {auto_scope})', | |
650 # [TreatNullReturnValueAs] | |
651 'StringOrNull': 'DartUtilities::setDartStringReturnValueWithNullCheck(args,
{cpp_value}, {auto_scope})', | |
652 # FIXME(vsm): How should we handle undefined? | |
653 'StringOrUndefined': 'DartUtilities::setDartStringReturnValue(args, {cpp_val
ue}, {auto_scope})', | |
654 'void': '', | |
655 # We specialize these as well in Dart. | |
656 'float': 'Dart_SetDoubleReturnValue(args, {cpp_value})', | |
657 'unrestricted float': 'Dart_SetDoubleReturnValue(args, {cpp_value})', | |
658 'double': 'Dart_SetDoubleReturnValue(args, {cpp_value})', | |
659 'unrestricted double': 'Dart_SetDoubleReturnValue(args, {cpp_value})', | |
660 # No special function, but instead convert value to Dart_Handle | |
661 # and then use general Dart_SetReturnValue. | |
662 'array': 'Dart_SetReturnValue(args, {cpp_value})', | |
663 'Date': 'Dart_SetReturnValue(args, {cpp_value})', | |
664 'EventHandler': DART_FIX_ME, | |
665 'ScriptPromise': 'Dart_SetReturnValue(args, {cpp_value})', | |
666 'ScriptValue': 'Dart_SetReturnValue(args, {cpp_value})', | |
667 'SerializedScriptValue': DART_FIX_ME, | |
668 # DOMWrapper | |
669 # TODO(terry): Remove ForMainWorld stuff. | |
670 'DOMWrapperForMainWorld': DART_FIX_ME, | |
671 # FIXME(vsm): V8 has a fast path. Do we? | |
672 'DOMWrapperFast': 'Dart{type_name}::returnToDart(args, WTF::getPtr({cpp_valu
e}), {auto_scope})', | |
673 'DOMWrapperDefault': 'Dart{type_name}::returnToDart(args, {cpp_value}, {auto
_scope})', | |
674 # Typed arrays don't have special Dart* classes for Dart. | |
675 'ArrayBuffer': 'Dart_SetReturnValue(args, DartUtilities::arrayBufferToDart({
cpp_value}))', | |
676 'TypedList': 'Dart_SetReturnValue(args, DartUtilities::arrayBufferViewToDart
({cpp_value}))', | |
677 'Dictionary': DART_FIX_ME, | |
678 } | |
679 | |
680 | |
681 def dart_set_return_value(idl_type, cpp_value, | |
682 extended_attributes=None, script_wrappable='', | |
683 release=False, for_main_world=False, | |
684 auto_scope=True): | |
685 """Returns a statement that converts a C++ value to a Dart value and sets it
as a return value. | |
686 | |
687 """ | |
688 def dom_wrapper_conversion_type(): | |
689 if not script_wrappable: | |
690 return 'DOMWrapperDefault' | |
691 if for_main_world: | |
692 return 'DOMWrapperForMainWorld' | |
693 return 'DOMWrapperFast' | |
694 | |
695 idl_type, cpp_value = preprocess_idl_type_and_value(idl_type, cpp_value, ext
ended_attributes) | |
696 this_dart_conversion_type = idl_type.dart_conversion_type(extended_attribute
s) | |
697 # SetReturn-specific overrides | |
698 if this_dart_conversion_type in ['Date', 'EventHandler', 'ScriptPromise', 'S
criptValue', 'SerializedScriptValue', 'array']: | |
699 # Convert value to Dart and then use general Dart_SetReturnValue | |
700 # FIXME(vsm): Why do we differ from V8 here? It doesn't have a | |
701 # creation_context. | |
702 creation_context = '' | |
703 if this_dart_conversion_type == 'array': | |
704 # FIXME: This is not right if the base type is a primitive, DOMStrin
g, etc. | |
705 # What is the right check for base type? | |
706 base_type = str(idl_type.element_type) | |
707 if base_type not in DART_TO_CPP_VALUE: | |
708 if base_type == 'None': | |
709 raise Exception('Unknown base type for ' + str(idl_type)) | |
710 creation_context = '<Dart%s>' % base_type | |
711 if idl_type.is_nullable: | |
712 creation_context = 'Nullable' + creation_context | |
713 | |
714 cpp_value = idl_type.cpp_value_to_dart_value(cpp_value, creation_context
=creation_context, | |
715 extended_attributes=extende
d_attributes) | |
716 if this_dart_conversion_type == 'DOMWrapper': | |
717 this_dart_conversion_type = dom_wrapper_conversion_type() | |
718 | |
719 format_string = DART_SET_RETURN_VALUE[this_dart_conversion_type] | |
720 | |
721 if release: | |
722 cpp_value = '%s.release()' % cpp_value | |
723 statement = format_string.format(cpp_value=cpp_value, | |
724 type_name=idl_type.name, | |
725 script_wrappable=script_wrappable, | |
726 auto_scope=DartUtilities.bool_to_cpp(auto_s
cope)) | |
727 return statement | |
728 | |
729 | |
730 def dart_set_return_value_union(idl_type, cpp_value, extended_attributes=None, | |
731 script_wrappable='', release=False, for_main_world
=False, | |
732 auto_scope=True): | |
733 """ | |
734 release: can be either False (False for all member types) or | |
735 a sequence (list or tuple) of booleans (if specified individually). | |
736 """ | |
737 return [ | |
738 # FIXME(vsm): Why do we use 'result' instead of cpp_value as V8? | |
739 member_type.dart_set_return_value('result' + str(i), | |
740 extended_attributes, | |
741 script_wrappable, | |
742 release and release[i], | |
743 for_main_world, | |
744 auto_scope) | |
745 for i, member_type in | |
746 enumerate(idl_type.member_types)] | |
747 | |
748 IdlTypeBase.dart_set_return_value = dart_set_return_value | |
749 IdlUnionType.dart_set_return_value = dart_set_return_value_union | |
750 | |
751 IdlType.release = property(lambda self: self.is_interface_type) | |
752 IdlUnionType.release = property( | |
753 lambda self: [member_type.is_interface_type | |
754 for member_type in self.member_types]) | |
755 | |
756 | |
757 CPP_VALUE_TO_DART_VALUE = { | |
758 # Built-in types | |
759 # FIXME(vsm): V8 uses DateOrNull - do we need a null check? | |
760 'Date': 'DartUtilities::dateToDart({cpp_value})', | |
761 'DOMString': 'DartUtilities::stringToDartString({cpp_value})', | |
762 'boolean': 'DartUtilities::boolToDart({cpp_value})', | |
763 'int': 'DartUtilities::intToDart({cpp_value})', | |
764 'unsigned': 'DartUtilities::unsignedLongLongToDart({cpp_value})', | |
765 'float': 'DartUtilities::doubleToDart({cpp_value})', | |
766 'unrestricted float': 'DartUtilities::doubleToDart({cpp_value})', | |
767 'double': 'DartUtilities::doubleToDart({cpp_value})', | |
768 'unrestricted double': 'DartUtilities::doubleToDart({cpp_value})', | |
769 # FIXME(vsm): Dart_Null? | |
770 'void': '', | |
771 # Special cases | |
772 'EventHandler': '-----OOPS TO DART-EVENT---', | |
773 # We need to generate the NullCheck version in some cases. | |
774 'ScriptPromise': 'DartUtilities::scriptPromiseToDart({cpp_value})', | |
775 'ScriptValue': 'DartUtilities::scriptValueToDart({cpp_value})', | |
776 'SerializedScriptValue': 'DartUtilities::serializedScriptValueToDart({cpp_va
lue})', | |
777 # General | |
778 'array': 'DartDOMWrapper::vectorToDart{creation_context}({cpp_value})', | |
779 'DOMWrapper': 'Dart{idl_type}::toDart({cpp_value})', | |
780 } | |
781 | |
782 | |
783 def cpp_value_to_dart_value(idl_type, cpp_value, creation_context='', extended_a
ttributes=None): | |
784 """Returns an expression that converts a C++ value to a Dart value.""" | |
785 # the isolate parameter is needed for callback interfaces | |
786 idl_type, cpp_value = preprocess_idl_type_and_value(idl_type, cpp_value, ext
ended_attributes) | |
787 this_dart_conversion_type = idl_type.dart_conversion_type(extended_attribute
s) | |
788 format_string = CPP_VALUE_TO_DART_VALUE[this_dart_conversion_type] | |
789 statement = format_string.format( | |
790 cpp_value=cpp_value, creation_context=creation_context, | |
791 idl_type=idl_type.base_type) | |
792 return statement | |
793 | |
794 IdlTypeBase.cpp_value_to_dart_value = cpp_value_to_dart_value | |
795 | |
796 # FIXME(leafp) This is horrible, we should do better, but currently this is hard
to do | |
797 # in a nice way. Best solution might be to extend DartStringAdapter to accomoda
te | |
798 # initialization from constant strings, but better to do that once we're stable | |
799 # on the bots so we can track any performance regression | |
800 CPP_LITERAL_TO_DART_VALUE = { | |
801 'DOMString': {'nullptr': 'DartStringAdapter(DartStringPeer::nullString())', | |
802 'String("")': 'DartStringAdapter(DartStringPeer::emptyString()
)', | |
803 '*': 'DartUtilities::dartToString(DartUtilities::stringToDart(
{cpp_literal}), exception)'}, | |
804 'ScalarValueString': {'nullptr': 'DartStringAdapter(DartStringPeer::nullStri
ng())', | |
805 'String("")': 'DartStringAdapter(DartStringPeer::empty
String())', | |
806 '*': 'DartUtilities::dartToScalarValueString(DartUtili
ties::stringToDart({cpp_literal}), exception)'}, | |
807 } | |
808 | |
809 | |
810 def literal_cpp_value(idl_type, idl_literal): | |
811 """Converts an expression that is a valid C++ literal for this type.""" | |
812 # FIXME: add validation that idl_type and idl_literal are compatible | |
813 literal_value = str(idl_literal) | |
814 base_type = idl_type.preprocessed_type.base_type | |
815 if base_type in CPP_UNSIGNED_TYPES: | |
816 return literal_value + 'u' | |
817 if base_type in CPP_LITERAL_TO_DART_VALUE: | |
818 if literal_value in CPP_LITERAL_TO_DART_VALUE[base_type]: | |
819 format_string = CPP_LITERAL_TO_DART_VALUE[base_type][literal_value] | |
820 else: | |
821 format_string = CPP_LITERAL_TO_DART_VALUE[base_type]['*'] | |
822 return format_string.format(cpp_literal=literal_value) | |
823 return literal_value | |
824 | |
825 IdlType.literal_cpp_value = literal_cpp_value | |
826 | |
827 | |
828 CPP_DEFAULT_VALUE_FOR_CPP_TYPE = { | |
829 'DOMString': 'DartStringAdapter(DartStringPeer::emptyString())', | |
830 'ByteString': 'DartStringAdapter(DartStringPeer::emptyString())', | |
831 'ScalarValueString': 'DartStringAdapter(DartStringPeer::emptyString())', | |
832 'boolean': 'false', | |
833 'float': '0.0f', | |
834 'unrestricted float': '0.0f', | |
835 'double': '0.0', | |
836 'unrestricted double': '0.0', | |
837 'byte': '0', | |
838 'octet': '0', | |
839 'short': '0', | |
840 'unsigned short': '0', | |
841 'long': '0', | |
842 'unsigned long': '0', | |
843 'long long': '0', | |
844 'unsigned long long': '0', | |
845 'Dictionary': 'Dictionary()', | |
846 'ScriptValue': 'DartUtilities::dartToScriptValueWithNullCheck(Dart_Null())', | |
847 'MediaQueryListListener': 'nullptr', | |
848 'NodeFilter': 'nullptr', | |
849 'SerializedScriptValue': 'nullptr', | |
850 'XPathNSResolver': 'nullptr', | |
851 } | |
852 | |
853 | |
854 def default_cpp_value_for_cpp_type(idl_type): | |
855 idl_type = idl_type.preprocessed_type | |
856 add_includes_for_type(idl_type) | |
857 base_idl_type = idl_type.base_type | |
858 if base_idl_type in CPP_DEFAULT_VALUE_FOR_CPP_TYPE: | |
859 return CPP_DEFAULT_VALUE_FOR_CPP_TYPE[base_idl_type] | |
860 if base_idl_type in NON_WRAPPER_TYPES: | |
861 return 'nullptr' | |
862 format_str = 'Dart{idl_type}::toNativeWithNullCheck(Dart_Null(), exception)' | |
863 return format_str.format(idl_type=idl_type) | |
864 | |
865 | |
866 # Override idl_type.name to not suffix orNull to the name, in Dart we always | |
867 # test for null e.g., | |
868 # | |
869 # bool isNull = false; | |
870 # TYPE* result = receiver->GETTER(isNull); | |
871 # if (isNull) | |
872 # return; | |
873 # | |
874 def dart_name(idl_type): | |
875 """Return type name. | |
876 | |
877 http://heycam.github.io/webidl/#dfn-type-name | |
878 """ | |
879 base_type = idl_type.base_type | |
880 base_type_name = TYPE_NAMES.get(base_type, base_type) | |
881 if idl_type.native_array_element_type: | |
882 return idl_type.inner_name() | |
883 return base_type_name | |
884 | |
885 IdlType.name = property(dart_name) | |
886 IdlUnionType.name = property(dart_name) | |
887 | |
888 | |
889 # If True use the WithNullCheck version when converting. | |
890 def allow_null(idl_type, extended_attributes, has_type_checking_interface): | |
891 if idl_type.base_type in ('DOMString', 'ByteString', 'ScalarValueString'): | |
892 # This logic is in cpp_types in v8_types.py, since they handle | |
893 # this using the V8StringResource type. We handle it here | |
894 if (extended_attributes.get('TreatNullAs') == 'NullString' or | |
895 extended_attributes.get('TreatUndefinedAs') == 'NullString'): | |
896 return True | |
897 | |
898 if extended_attributes.get('Default') == 'NullString': | |
899 return True | |
900 | |
901 if extended_attributes.get('Default') == 'Undefined': | |
902 return True | |
903 | |
904 if idl_type.is_nullable: | |
905 return True | |
906 | |
907 return False | |
908 else: | |
909 # This logic is implemented in the methods.cpp template in V8 | |
910 if (idl_type.is_nullable or not has_type_checking_interface): | |
911 return True | |
912 | |
913 if extended_attributes.get('Default') == 'Undefined': | |
914 return True | |
915 | |
916 return False | |
917 | |
918 | |
919 # If True use the WithEmptyCheck version when converting. | |
920 def allow_empty(idl_type, extended_attributes): | |
921 if idl_type.base_type in ('DOMString', 'ByteString', 'ScalarValueString'): | |
922 # This logic is in cpp_types in v8_types.py, since they handle | |
923 # this using the V8StringResource type. We handle it here | |
924 if (extended_attributes.get('TreatNullAs') == 'EmptyString' or | |
925 extended_attributes.get('TreatUndefinedAs') == 'EmptyString'): | |
926 return True | |
927 | |
928 if extended_attributes.get('Default') == 'EmptyString': | |
929 return True | |
930 | |
931 return False | |
OLD | NEW |