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

Side by Side Diff: sdk/lib/js/dart2js/js_dart2js.dart

Issue 27514003: A few API changes: (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: More tests, especially for illegal arguments Created 7 years, 2 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 | « no previous file | tests/html/js_test.dart » ('j') | tests/html/js_test.dart » ('J')
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a 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. 3 // BSD-style license that can be found in the LICENSE file.
4 4
5 library dart.js; 5 library dart.js;
6 6
7 import 'dart:html' show Blob, ImageData, Node;
alexandre.ardhuin 2013/10/18 08:09:36 When we started dart:js, we saw a big impact on js
justinfagnani 2013/10/18 22:38:41 Replied in CL-level comment, but I'm going to take
8 import 'dart:indexed_db' show KeyRange;
9 import 'dart:collection' show HashMap;
7 import 'dart:_foreign_helper' show JS, DART_CLOSURE_TO_JS; 10 import 'dart:_foreign_helper' show JS, DART_CLOSURE_TO_JS;
11 import 'dart:_interceptors' show JavaScriptObject, UnknownJavaScriptObject;
8 import 'dart:_js_helper' show Primitives, convertDartClosureToJS; 12 import 'dart:_js_helper' show Primitives, convertDartClosureToJS;
9 13
10 final JsObject context = new JsObject._fromJs(Primitives.computeGlobalThis()); 14 final JsObject context = new JsObject._fromJs(Primitives.computeGlobalThis());
11 15
12 JsObject jsify(dynamic data) => data == null ? null : new JsObject._json(data);
13
14 class Callback implements Serializable<JsFunction> {
15 final Function _f; // here to allow capture in closure
16 final bool _withThis; // here to allow capture in closure
17 dynamic _jsFunction;
18
19 Callback._(this._f, this._withThis) {
20 _jsFunction = JS('', r'''
21 (function(){
22 var f = #;
23 return function(){
24 return f(this, Array.prototype.slice.apply(arguments));
25 };
26 }).apply(this)''', convertDartClosureToJS(_call, 2));
27 }
28
29 factory Callback(Function f) => new Callback._(f, false);
30 factory Callback.withThis(Function f) => new Callback._(f, true);
31
32 _call(thisArg, List args) {
33 final arguments = new List.from(args);
34 if (_withThis) arguments.insert(0, thisArg);
35 final dartArgs = arguments.map(_convertToDart).toList();
36 return _convertToJS(Function.apply(_f, dartArgs));
37 }
38
39 JsFunction toJs() => new JsFunction._fromJs(_jsFunction);
40 }
41
42 /*
43 * TODO(justinfagnani): add tests and make public when we remove Callback.
44 *
45 * Returns a [JsFunction] that captures its 'this' binding and calls [f]
46 * with the value of this passed as the first argument.
47 */
48 JsFunction _captureThis(Function f) =>
49 new JsFunction._fromJs(_convertDartFunction(f, captureThis: true));
50
51 _convertDartFunction(Function f, {bool captureThis: false}) { 16 _convertDartFunction(Function f, {bool captureThis: false}) {
52 return JS('', 17 return JS('',
53 'function(_call, f, captureThis) {' 18 'function(_call, f, captureThis) {'
54 'return function() {' 19 'return function() {'
55 'return _call(f, captureThis, this, ' 20 'return _call(f, captureThis, this, '
56 'Array.prototype.slice.apply(arguments));' 21 'Array.prototype.slice.apply(arguments));'
57 '}' 22 '}'
58 '}(#, #, #)', DART_CLOSURE_TO_JS(_callDartFunction), f, captureThis); 23 '}(#, #, #)', DART_CLOSURE_TO_JS(_callDartFunction), f, captureThis);
59 } 24 }
60 25
61 _callDartFunction(callback, bool captureThis, self, List arguments) { 26 _callDartFunction(callback, bool captureThis, self, List arguments) {
62 if (captureThis) { 27 if (captureThis) {
63 arguments = [self]..addAll(arguments); 28 arguments = [self]..addAll(arguments);
64 } 29 }
65 var dartArgs = arguments.map(_convertToDart).toList(); 30 var dartArgs = arguments.map(_convertToDart).toList();
66 return _convertToJS(Function.apply(callback, dartArgs)); 31 return _convertToJS(Function.apply(callback, dartArgs));
67 } 32 }
68 33
69 34
70 class JsObject implements Serializable<JsObject> { 35 class JsObject {
71 // The wrapped JS object. 36 // The wrapped JS object.
72 final dynamic _jsObject; 37 final dynamic _jsObject;
73 38
74 JsObject._fromJs(this._jsObject) { 39 JsObject._fromJs(this._jsObject) {
40 assert(_jsObject != null);
75 // Remember this proxy for the JS object 41 // Remember this proxy for the JS object
76 _getDartProxy(_jsObject, _DART_OBJECT_PROPERTY_NAME, (o) => this); 42 _getDartProxy(_jsObject, _DART_OBJECT_PROPERTY_NAME, (o) => this);
77 } 43 }
78 44
79 // TODO(vsm): Type constructor as Serializable<JsFunction> when 45 /**
80 // dartbug.com/11854 is fixed. 46 * Expert use only:
81 factory JsObject(constructor, [List arguments]) { 47 *
48 * Use this constructor only if you wish to get access to JS properties
49 * attached to a browser host object such as a Node or Blob. This constructor
50 * will return a JsObject proxy on [object], even though the object would
51 * normally be returned as a native Dart object.
52 *
53 * An exception will be thrown if [object] is a primitive type or null.
54 */
55 factory JsObject.fromBrowserObject(Object object) {
56 if (object is num || object is String || object is bool || object == null) {
57 throw new ArgumentError(
58 "object cannot be a num, string, bool, or null");
59 }
60 return new JsObject._fromJs(_convertToJS(object));
61 }
62
63 /**
64 * Converts a json-like [data] to a JavaScript map or array and return a
65 * [JsObject] to it.
66 */
67 factory JsObject.jsify(Object object) {
68 if ((object is! Map) && (object is! Iterable)) {
69 throw new ArgumentError("object must be a Map or Iterable");
70 }
71 return new JsObject._fromJs(_convertDataTree(object));
72 }
73
74 factory JsObject(JsFunction constructor, [List arguments]) {
82 var constr = _convertToJS(constructor); 75 var constr = _convertToJS(constructor);
83 if (arguments == null) { 76 if (arguments == null) {
84 return new JsObject._fromJs(JS('', 'new #()', constr)); 77 return new JsObject._fromJs(JS('', 'new #()', constr));
85 } 78 }
86 // The following code solves the problem of invoking a JavaScript 79 // The following code solves the problem of invoking a JavaScript
87 // constructor with an unknown number arguments. 80 // constructor with an unknown number arguments.
88 // First bind the constructor to the argument list using bind.apply(). 81 // First bind the constructor to the argument list using bind.apply().
89 // The first argument to bind() is the binding of 'this', so add 'null' to 82 // The first argument to bind() is the binding of 'this', so add 'null' to
90 // the arguments list passed to apply(). 83 // the arguments list passed to apply().
91 // After that, use the JavaScript 'new' operator which overrides any binding 84 // After that, use the JavaScript 'new' operator which overrides any binding
92 // of 'this' with the new instance. 85 // of 'this' with the new instance.
93 var args = [null]..addAll(arguments.map(_convertToJS)); 86 var args = [null]..addAll(arguments.map(_convertToJS));
94 var factoryFunction = JS('', '#.bind.apply(#, #)', constr, constr, args); 87 var factoryFunction = JS('', '#.bind.apply(#, #)', constr, constr, args);
95 // Without this line, calling factoryFunction as a constructor throws 88 // Without this line, calling factoryFunction as a constructor throws
96 JS('String', 'String(#)', factoryFunction); 89 JS('String', 'String(#)', factoryFunction);
97 return new JsObject._fromJs(JS('', 'new #()', factoryFunction)); 90 // This could return an UnknownJavaScriptObject, or a native
91 // object for which there is an interceptor
92 var jsObj = JS('JavaScriptObject', 'new #()', factoryFunction);
93 return new JsObject._fromJs(jsObj);
98 } 94 }
99 95
100 factory JsObject._json(data) => new JsObject._fromJs(_convertDataTree(data)); 96 // TODO: handle cycles
97 static _convertDataTree(data) {
98 var _convertedObjects = new HashMap.identity();
101 99
102 static _convertDataTree(data) { 100 _convert(o) {
103 if (data is Map) { 101 if (_convertedObjects.containsKey(o)) {
104 final convertedData = JS('=Object', '{}'); 102 return _convertedObjects[o];
105 for (var key in data.keys) {
106 JS('=Object', '#[#]=#', convertedData, key,
107 _convertDataTree(data[key]));
108 } 103 }
109 return convertedData; 104 if (o is Map) {
110 } else if (data is Iterable) { 105 final convertedMap = JS('=Object', '{}');
111 return data.map(_convertDataTree).toList(); 106 _convertedObjects[o] = convertedMap;
112 } else { 107 for (var key in o.keys) {
113 return _convertToJS(data); 108 JS('=Object', '#[#]=#', convertedMap, key, _convert(o[key]));
109 }
110 return convertedMap;
111 } else if (o is Iterable) {
112 var convertedList = [];
113 _convertedObjects[o] = convertedList;
114 convertedList.addAll(o.map(_convert));
115 return convertedList;
116 } else {
117 return _convertToJS(o);
118 }
114 } 119 }
120
121 return _convert(data);
115 } 122 }
116 123
117 JsObject toJs() => this;
118
119 /** 124 /**
120 * Returns the value associated with [key] from the proxied JavaScript 125 * Returns the value associated with [key] from the proxied JavaScript
121 * object. 126 * object.
122 * 127 *
123 * [key] must either be a [String] or [int]. 128 * [key] must either be a [String] or [num].
124 */ 129 */
125 // TODO(justinfagnani): rename key/name to property 130 // TODO(justinfagnani): rename key/name to property
126 dynamic operator[](key) { 131 dynamic operator[](key) {
127 if (key is! String && key is! int) { 132 if (key is! String && key is! num) {
128 throw new ArgumentError("key is not a String or int"); 133 throw new ArgumentError("key is not a String or num");
129 } 134 }
130 return _convertToDart(JS('', '#[#]', _jsObject, key)); 135 return _convertToDart(JS('', '#[#]', _jsObject, key));
131 } 136 }
132 137
133 /** 138 /**
134 * Sets the value associated with [key] from the proxied JavaScript 139 * Sets the value associated with [key] from the proxied JavaScript
135 * object. 140 * object.
136 * 141 *
137 * [key] must either be a [String] or [int]. 142 * [key] must either be a [String] or [num].
138 */ 143 */
139 operator[]=(key, value) { 144 operator[]=(key, value) {
140 if (key is! String && key is! int) { 145 if (key is! String && key is! num) {
141 throw new ArgumentError("key is not a String or int"); 146 throw new ArgumentError("key is not a String or num");
142 } 147 }
143 JS('', '#[#]=#', _jsObject, key, _convertToJS(value)); 148 JS('', '#[#]=#', _jsObject, key, _convertToJS(value));
144 } 149 }
145 150
146 int get hashCode => 0; 151 int get hashCode => 0;
147 152
148 bool operator==(other) => other is JsObject && 153 bool operator==(other) => other is JsObject &&
149 JS('bool', '# === #', _jsObject, other._jsObject); 154 JS('bool', '# === #', _jsObject, other._jsObject);
150 155
151 bool hasProperty(name) { 156 bool hasProperty(name) {
152 if (name is! String && name is! int) { 157 if (name is! String && name is! num) {
153 throw new ArgumentError("name is not a String or int"); 158 throw new ArgumentError("name is not a String or num");
154 } 159 }
155 return JS('bool', '# in #', name, _jsObject); 160 return JS('bool', '# in #', name, _jsObject);
156 } 161 }
157 162
158 void deleteProperty(name) { 163 void deleteProperty(name) {
159 if (name is! String && name is! int) { 164 if (name is! String && name is! num) {
160 throw new ArgumentError("name is not a String or int"); 165 throw new ArgumentError("name is not a String or num");
161 } 166 }
162 JS('bool', 'delete #[#]', _jsObject, name); 167 JS('bool', 'delete #[#]', _jsObject, name);
163 } 168 }
164 169
165 // TODO(vsm): Type type as Serializable<JsFunction> when
166 // dartbug.com/11854 is fixed.
167 bool instanceof(type) { 170 bool instanceof(type) {
168 return JS('bool', '# instanceof #', _jsObject, _convertToJS(type)); 171 return JS('bool', '# instanceof #', _jsObject, _convertToJS(type));
169 } 172 }
170 173
171 String toString() { 174 String toString() {
172 try { 175 try {
173 return JS('String', 'String(#)', _jsObject); 176 return JS('String', 'String(#)', _jsObject);
174 } catch(e) { 177 } catch(e) {
175 return super.toString(); 178 return super.toString();
176 } 179 }
177 } 180 }
178 181
179 dynamic callMethod(name, [List args]) { 182 dynamic callMethod(name, [List args]) {
180 if (name is! String && name is! int) { 183 if (name is! String && name is! num) {
181 throw new ArgumentError("name is not a String or int"); 184 throw new ArgumentError("name is not a String or num");
182 } 185 }
183 return _convertToDart(JS('', '#[#].apply(#, #)', _jsObject, name, 186 return _convertToDart(JS('', '#[#].apply(#, #)', _jsObject, name,
184 _jsObject, 187 _jsObject,
185 args == null ? null : args.map(_convertToJS).toList())); 188 args == null ? null : args.map(_convertToJS).toList()));
186 } 189 }
187 } 190 }
188 191
189 class JsFunction extends JsObject implements Serializable<JsFunction> { 192 class JsFunction extends JsObject {
193
194 /*
195 * Returns a [JsFunction] that captures its 'this' binding and calls [f]
196 * with the value of this passed as the first argument.
197 */
198 factory JsFunction.withThis(Function f) {
199 var jsFunc = _convertDartFunction(f, captureThis: true);
200 return new JsFunction._fromJs(jsFunc);
201 }
190 202
191 JsFunction._fromJs(jsObject) : super._fromJs(jsObject); 203 JsFunction._fromJs(jsObject) : super._fromJs(jsObject);
192 204
193 dynamic apply(thisArg, [List args]) => 205 dynamic apply([thisArg, List args]) =>
194 _convertToDart(JS('', '#.apply(#, #)', _jsObject, 206 _convertToDart(JS('', '#.apply(#, #)', _jsObject,
195 _convertToJS(thisArg), 207 _convertToJS(thisArg),
196 args == null ? null : args.map(_convertToJS).toList())); 208 args == null ? null : args.map(_convertToJS).toList()));
197 } 209 }
198 210
199 abstract class Serializable<T> {
200 T toJs();
201 }
202
203 // property added to a Dart object referencing its JS-side DartObject proxy 211 // property added to a Dart object referencing its JS-side DartObject proxy
204 const _DART_OBJECT_PROPERTY_NAME = r'_$dart_dartObject'; 212 const _DART_OBJECT_PROPERTY_NAME = r'_$dart_dartObject';
205 const _DART_CLOSURE_PROPERTY_NAME = r'_$dart_dartClosure'; 213 const _DART_CLOSURE_PROPERTY_NAME = r'_$dart_dartClosure';
206 214
207 // property added to a JS object referencing its Dart-side JsObject proxy 215 // property added to a JS object referencing its Dart-side JsObject proxy
208 const _JS_OBJECT_PROPERTY_NAME = r'_$dart_jsObject'; 216 const _JS_OBJECT_PROPERTY_NAME = r'_$dart_jsObject';
209 const _JS_FUNCTION_PROPERTY_NAME = r'$dart_jsFunction'; 217 const _JS_FUNCTION_PROPERTY_NAME = r'$dart_jsFunction';
210 218
211 bool _defineProperty(o, String name, value) { 219 bool _defineProperty(o, String name, value) {
212 if (JS('bool', 'Object.isExtensible(#)', o)) { 220 if (JS('bool', 'Object.isExtensible(#)', o)) {
213 try { 221 try {
214 JS('void', 'Object.defineProperty(#, #, { value: #})', o, name, value); 222 JS('void', 'Object.defineProperty(#, #, { value: #})', o, name, value);
215 return true; 223 return true;
216 } catch(e) { 224 } catch(e) {
217 // object is native and lies about being extensible 225 // object is native and lies about being extensible
218 // see https://bugzilla.mozilla.org/show_bug.cgi?id=775185 226 // see https://bugzilla.mozilla.org/show_bug.cgi?id=775185
219 } 227 }
220 } 228 }
221 return false; 229 return false;
222 } 230 }
223 231
224 dynamic _convertToJS(dynamic o) { 232 dynamic _convertToJS(dynamic o) {
225 if (o == null) { 233 if (o == null) {
226 return null; 234 return null;
227 } else if (o is String || o is num || o is bool) { 235 } else if (o is String || o is num || o is bool
236 || o is Blob || o is KeyRange || o is ImageData || o is Node ) {
228 return o; 237 return o;
238 } else if (o is DateTime) {
239 return Primitives.lazyAsJsDate(o);
229 } else if (o is JsObject) { 240 } else if (o is JsObject) {
230 return o._jsObject; 241 return o._jsObject;
231 } else if (o is Serializable) {
232 return _convertToJS(o.toJs());
233 } else if (o is Function) { 242 } else if (o is Function) {
234 return _getJsProxy(o, _JS_FUNCTION_PROPERTY_NAME, (o) { 243 return _getJsProxy(o, _JS_FUNCTION_PROPERTY_NAME, (o) {
235 var jsFunction = _convertDartFunction(o); 244 var jsFunction = _convertDartFunction(o);
236 // set a property on the JS closure referencing the Dart closure 245 // set a property on the JS closure referencing the Dart closure
237 _defineProperty(jsFunction, _DART_CLOSURE_PROPERTY_NAME, o); 246 _defineProperty(jsFunction, _DART_CLOSURE_PROPERTY_NAME, o);
238 return jsFunction; 247 return jsFunction;
239 }); 248 });
240 } else { 249 } else {
241 return _getJsProxy(o, _JS_OBJECT_PROPERTY_NAME, 250 return _getJsProxy(o, _JS_OBJECT_PROPERTY_NAME,
242 (o) => JS('', 'new DartObject(#)', o)); 251 (o) => JS('', 'new DartObject(#)', o));
(...skipping 10 matching lines...) Expand all
253 } 262 }
254 263
255 // converts a Dart object to a reference to a native JS object 264 // converts a Dart object to a reference to a native JS object
256 // which might be a DartObject JS->Dart proxy 265 // which might be a DartObject JS->Dart proxy
257 Object _convertToDart(o) { 266 Object _convertToDart(o) {
258 if (JS('bool', '# == null', o) || 267 if (JS('bool', '# == null', o) ||
259 JS('bool', 'typeof # == "string"', o) || 268 JS('bool', 'typeof # == "string"', o) ||
260 JS('bool', 'typeof # == "number"', o) || 269 JS('bool', 'typeof # == "number"', o) ||
261 JS('bool', 'typeof # == "boolean"', o)) { 270 JS('bool', 'typeof # == "boolean"', o)) {
262 return o; 271 return o;
272 } else if (o is Blob || o is DateTime || o is KeyRange || o is ImageData || o is Node) {
273 return JS('Blob|DateTime|KeyRange|ImageData|Node', '#', o);
263 } else if (JS('bool', 'typeof # == "function"', o)) { 274 } else if (JS('bool', 'typeof # == "function"', o)) {
264 return _getDartProxy(o, _DART_CLOSURE_PROPERTY_NAME, 275 return _getDartProxy(o, _DART_CLOSURE_PROPERTY_NAME,
265 (o) => new JsFunction._fromJs(o)); 276 (o) => new JsFunction._fromJs(o));
266 } else if (JS('bool', '#.constructor === DartObject', o)) { 277 } else if (JS('bool', '#.constructor === DartObject', o)) {
267 return JS('', '#.o', o); 278 return JS('', '#.o', o);
268 } else { 279 } else {
269 return _getDartProxy(o, _DART_OBJECT_PROPERTY_NAME, 280 return _getDartProxy(o, _DART_OBJECT_PROPERTY_NAME,
270 (o) => new JsObject._fromJs(o)); 281 (o) => new JsObject._fromJs(o));
271 } 282 }
272 } 283 }
273 284
274 Object _getDartProxy(o, String propertyName, createProxy(o)) { 285 Object _getDartProxy(o, String propertyName, createProxy(o)) {
275 var dartProxy = JS('', '#[#]', o, propertyName); 286 var dartProxy = JS('', '#[#]', o, propertyName);
276 if (dartProxy == null) { 287 if (dartProxy == null) {
277 dartProxy = createProxy(o); 288 dartProxy = createProxy(o);
278 _defineProperty(o, propertyName, dartProxy); 289 _defineProperty(o, propertyName, dartProxy);
279 } 290 }
280 return dartProxy; 291 return dartProxy;
281 } 292 }
OLDNEW
« no previous file with comments | « no previous file | tests/html/js_test.dart » ('j') | tests/html/js_test.dart » ('J')

Powered by Google App Engine
This is Rietveld 408576698