Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(205)

Side by Side Diff: frog/leg/lib/native_helper.dart

Issue 9750003: Write our JS blobs for handling native classes in Dart. (Closed) Base URL: http://dart.googlecode.com/svn/branches/bleeding_edge/dart/
Patch Set: Created 8 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « frog/leg/lib/js_helper.dart ('k') | frog/leg/native_emitter.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 String typeNameInChrome(obj) {
6 String name = JS('String', "#.constructor.name", obj);
7 if (name == 'Window') return 'DOMWindow';
8 return name;
9 }
10
11 String typeNameInFirefox(obj) {
12 String name = constructorNameFallback(obj);
13 if (name == 'Window') return 'DOMWindow';
14 if (name == 'Document') return 'HTMLDocument';
15 if (name == 'XMLDocument') return 'Document';
16 return name;
17 }
18
19 String typeNameInIE(obj) {
20 String name = constructorNameFallback(obj);
21 if (name == 'Window') return 'DOMWindow';
22 // IE calls both HTML and XML documents 'Document', so we check for the
23 // xmlVersion property, which is the empty string on HTML documents.
24 if (name == 'Document' && JS('bool', '!!#.xmlVersion', obj)) return 'Document' ;
25 if (name == 'Document') return 'HTMLDocument';
26 return name;
27 }
28
29 String constructorNameFallback(obj) {
30 var constructor = JS('var', "#.constructor", obj);
31 if (JS('String', "typeof(#)", constructor) === 'function') {
32 // The constructor isn't null or undefined at this point. Try
33 // to grab hold of its name.
34 var name = JS('var', '#.name', constructor);
35 // If the name is a non-empty string, we use that as the type
36 // name of this object. On Firefox, we often get 'Object' as
37 // the constructor name even for more specialized objects so
38 // we have to fall through to the toString() based implementation
39 // below in that case.
40 if (JS('String', "typeof(#)", name) === 'string'
41 && !name.isEmpty()
42 && name !== 'Object') {
ahe 2012/03/27 09:42:08 !=
ngeoffray 2012/03/27 10:37:33 Why?
43 return name;
44 }
45 }
46 String string = JS('String', 'Object.prototype.toString.call(#)', obj);
47 return string.substring(8, string.length - 1);
48 }
49
50
51 /**
52 * Returns the function to use to get the type name of an object.
53 */
54 Function getTypeNameOfFunction() {
55 // If we're not in the browser, we're almost certainly running on v8.
56 if (JS('String', 'typeof(navigator)') !== 'object') return typeNameInChrome;
57
58 String userAgent = JS('String', "navigator.userAgent");
59 if (userAgent.contains(const RegExp('Chrome|DumpRenderTree'))) {
60 return typeNameInChrome;
61 } else if (userAgent.contains('Firefox')) {
62 return typeNameInFirefox;
63 } else if (userAgent.contains('MSIE')) {
64 return typeNameInIE;
65 } else {
66 return constructorNameFallback;
67 }
68 }
69
70
71 /**
72 * Cached value for the function to use to get the type name of an
73 * object.
74 */
75 Function _getTypeNameOf;
76
77 /**
78 * Returns the type name of [obj].
79 */
80 String getTypeNameOf(var obj) {
81 if (_getTypeNameOf === null) _getTypeNameOf = getTypeNameOfFunction();
82 return _getTypeNameOf(obj);
83 }
84
85 /**
86 * Sets a JavaScript property on an object.
87 */
88 void defineProperty(var obj, String property, var value) {
89 JS('void', """Object.defineProperty(#, #,
90 {value: #, enumerable: false, writable: false, configurable: true});""",
91 obj,
92 property,
93 value);
94 }
95
96 /**
97 * Helper method to throw a [NoSuchMethodException] for a invalid call
98 * on a native object.
99 */
100 void throwNoSuchMethod(obj, name, arguments) {
101 throw new NoSuchMethodException(obj, name, arguments);
102 }
103
104 /**
105 * This method looks up the type name of [obj] in [methods]. If it
106 * cannot find it, it looks into the [_dynamicMetadata] array. If the
107 * method can still not be found, it creates a method that will throw
108 * a [NoSuchMethodException].
109 *
110 * Once it has a method, the prototype of [obj] is patched with that
111 * method, on the property [name]. The method is then invoked.
112 *
113 * This method returns the result of invoking the found method.
114 */
115 dynamicBind(var obj,
116 String name,
117 var methods,
118 List arguments) {
119 String tag = getTypeNameOf(obj);
120 var method = JS('var', '#[#]', methods, tag);
121
122 if (method === null && _dynamicMetadata !== null) {
123 for (int i = 0; i < _dynamicMetadata.length; i++) {
124 MetaInfo entry = _dynamicMetadata[i];
125 if (entry.set.contains(tag)) {
126 method = JS('var', '#[#]', methods, entry.tag);
127 if (method !== null) break;
128 }
129 }
130 }
131
132 if (method === null) {
133 method = JS('var', "#['Object']", methods);
134 }
135
136 if (method === null) {
137 method = JS('var',
138 'function () {'
139 '#(#, #, Array.prototype.slice.call(arguments));'
140 '}',
141 DART_CLOSURE_TO_JS(throwNoSuchMethod), obj, name);
142 }
143
144 var nullCheckMethod = JS('var',
145 'function() {'
146 'var res = #.apply(this, Array.prototype.slice.call(arguments));'
147 'return res === null ? (void 0) : res;'
148 '}',
149 method);
150
151 var proto = JS('var', 'Object.getPrototypeOf(#)', obj);
152 if (JS('bool', '!#.hasOwnProperty(#)', proto, name)) {
153 defineProperty(proto, name, nullCheckMethod);
154 }
155
156 return JS('var', '#.apply(#, #)', nullCheckMethod, obj, arguments);
157 }
158
159 /**
160 * Code for doing the dynamic dispatch on JavaScript prototypes that are not
161 * available at compile-time. Each property of a native Dart class
162 * is registered through this function, which is called with the
163 * following pattern:
164 *
165 * dynamicFunction('propertyName').prototypeName = // JS code
166 *
167 * What this function does is:
168 * - Creates a map of { prototypeName: JS code }.
169 * - Attaches 'propertyName' to the JS Object prototype that will
170 * intercept at runtime all calls to propertyName.
171 * - Sets the value of 'propertyName' to the returned method from
172 * [dynamicBind].
173 *
174 */
175 dynamicFunction(name) {
176 var f = JS('var', 'Object.prototype[#]', name);
177 if (f !== null && JS('bool', '!!#.methods', f)) {
178 return JS('var', '#.methods', f);
179 }
180
181 // TODO(ngeoffray): We could make this a map if the code we
182 // generate plays well with a Dart map.
183 var methods = JS('var', '{}');
184 // If there is a method attached to the Dart Object class, use it as
185 // the method to call in case no method is registered for that type.
186 var dartMethod = JS('var', 'Object.getPrototypeOf(#)[#]', new Object(), name);
187 if (dartMethod !== null) JS('void', "#['Object'] = #", methods, dartMethod);
188
189 var bind = JS('var',
190 'function() {'
191 'return #(this, #, #, Array.prototype.slice.call(arguments));'
192 '}',
193 DART_CLOSURE_TO_JS(dynamicBind), name, methods);
194
195 JS('void', '#.methods = #', bind, methods);
196 defineProperty(JS('var', 'Object.prototype'), name, bind);
197 return methods;
198 }
199
200 /**
201 * This class encodes the class hierarchy when we need it for dynamic
202 * dispatch.
203 */
204 class MetaInfo {
205 /**
206 * The type name this [MetaInfo] relates to.
207 */
208 String tag;
209
210 /**
211 * A string containing the names of subtypes of [tag], separated by
212 * '|'.
213 */
214 String tags;
215
216 /**
217 * A list of names of subtypes of [tag].
218 */
219 Set<String> set;
220
221 MetaInfo(this.tag, this.tags, this.set);
222 }
223
224 List<MetaInfo> get _dynamicMetadata() {
ahe 2012/03/27 09:42:08 Is there a particular reason for these methods bei
ngeoffray 2012/03/27 10:37:33 The reason was that dynamicMetadata is the name of
225 return JS('var', '\$dynamicMetadata');
226 }
227
228 void set _dynamicMetadata(List<String> table) {
229 JS('void', '\$dynamicMetadata = #', table);
230 }
231
232 /**
233 * Builds the metadata used for encoding the class hierarchy of native
234 * classes. The following example:
235 *
236 * class A native "*A" {}
237 * class B native "*B" {}
238 *
239 * Will generate:
240 * ['A', 'A|B']
241 *
242 * This method turns the array into a list of [MetaInfo] objects.
243 */
244 void dynamicSetMetadata(List<List<String>> inputTable) {
ahe 2012/03/27 09:42:08 This method would be clearer if it was: _dynamicM
ngeoffray 2012/03/27 10:37:33 OK, will do in another CL.
245 _dynamicMetadata = <MetaInfo>[];
246 for (int i = 0; i < inputTable.length; i++) {
247 String tag = inputTable[i][0];
248 String tags = inputTable[i][1];
249 Set<String> set = new Set<String>();
250 List<String> tagNames = tags.split('|');
251 for (int j = 0; j < tagNames.length; j++) {
252 set.add(tagNames[j]);
253 }
254 _dynamicMetadata.add(new MetaInfo(tag, tags, set));
255 }
256 }
257
258 // Initialized by the compiler.
259 var isChecksHelper;
260
261 // This method will be called for 'is' checks on native types.
262 // It takes the object on which the 'is' check is being done, and the
263 // property name for the type check. The method patches the real
264 // prototype of the object with the value from the Dart object
265 // (see [generateNativeClass]).
266 bool dynamicIsCheck(obj, String typeName) {
267 if (isJsArray(obj)) return false;
268 // Check if the Dart object corresponding to this class has the property.
269 var res = JS('bool', '!!#[#][#]', isChecksHelper, getTypeNameOf(obj),
270 typeName);
271 var proto = JS('var', 'Object.getPrototypeOf(#)', obj);
272 defineProperty(proto, typeName, res);
273 return res;
274 }
OLDNEW
« no previous file with comments | « frog/leg/lib/js_helper.dart ('k') | frog/leg/native_emitter.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698