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

Side by Side Diff: tool/input_sdk/private/operations.dart

Issue 1530563003: Generate all runtime files from dart. (Closed) Base URL: git@github.com:dart-lang/dev_compiler.git@master
Patch Set: simplify diff in js_codegen.dart Created 4 years, 11 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
OLDNEW
(Empty)
1 // Copyright (c) 2015, 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 /// This library defines runtime operations on objects used by the code
6 /// generator.
7 part of dart._runtime;
8
9 _canonicalFieldName(obj, name, args, displayName) => JS('', '''(() => {
10 $name = $canonicalMember($obj, $name);
11 if ($name) return $name;
12 // TODO(jmesserly): in the future we might have types that "overlay" Dart
13 // methods while also exposing the full native API, e.g. dart:html vs
14 // dart:dom. To support that we'd need to fall back to the normal name
15 // if an extension method wasn't found.
16 $throwNoSuchMethodFunc($obj, $displayName, $args);
17 })()''');
18
19 dload(obj, field) => JS('', '''(() => {
20 $field = $_canonicalFieldName($obj, $field, [], $field);
21 if ($hasMethod($obj, $field)) {
22 return $bind($obj, $field);
23 }
24 // TODO(vsm): Implement NSM robustly. An 'in' check breaks on certain
25 // types. hasOwnProperty doesn't chase the proto chain.
26 // Also, do we want an NSM on regular JS objects?
27 // See: https://github.com/dart-lang/dev_compiler/issues/169
28 let result = $obj[$field];
29 return result;
30 })()''');
31
32 dput(obj, field, value) => JS('', '''(() => {
33 $field = $_canonicalFieldName($obj, $field, [$value], $field);
34 // TODO(vsm): Implement NSM and type checks.
35 // See: https://github.com/dart-lang/dev_compiler/issues/170
36 $obj[$field] = $value;
37 return $value;
38 })()''');
39
40 /// Check that a function of a given type can be applied to
41 /// actuals.
42 checkApply(type, actuals) => JS('', '''(() => {
43 if ($actuals.length < $type.args.length) return false;
44 let index = 0;
45 for(let i = 0; i < $type.args.length; ++i) {
46 if (!$instanceOfOrNull($actuals[i], $type.args[i])) return false;
47 ++index;
48 }
49 if ($actuals.length == $type.args.length) return true;
50 let extras = $actuals.length - $type.args.length;
51 if ($type.optionals.length > 0) {
52 if (extras > $type.optionals.length) return false;
53 for(let i = 0, j=index; i < extras; ++i, ++j) {
54 if (!$instanceOfOrNull($actuals[j], $type.optionals[i])) return false;
55 }
56 return true;
57 }
58 // TODO(leafp): We can't tell when someone might be calling
59 // something expecting an optional argument with named arguments
60
61 if (extras != 1) return false;
62 // An empty named list means no named arguments
63 if ($getOwnPropertyNames($type.named).length == 0) return false;
64 let opts = $actuals[index];
65 let names = $getOwnPropertyNames(opts);
66 // Type is something other than a map
67 if (names.length == 0) return false;
68 for (var name of names) {
69 if (!($hasOwnProperty.call($type.named, name))) {
70 return false;
71 }
72 if (!$instanceOfOrNull(opts[name], $type.named[name])) return false;
73 }
74 return true;
75 })()''');
76
77
78 throwNoSuchMethod(obj, name, pArgs, nArgs, extras) => JS('', '''(() => {
79 $throw_(new $NoSuchMethodError($obj, $name, $pArgs, $nArgs, $extras));
80 })()''');
81
82 throwNoSuchMethodFunc(obj, name, pArgs, opt_func) => JS('', '''(() => {
83 if ($obj === void 0) $obj = $opt_func;
84 $throwNoSuchMethod($obj, $name, $pArgs);
85 })()''');
86
87 checkAndCall(f, ftype, obj, args, name) => JS('', '''(() => {
88 if (!($f instanceof Function)) {
89 // We're not a function (and hence not a method either)
90 // Grab the `call` method if it's not a function.
91 if ($f != null) {
92 $ftype = $getMethodType($f, 'call');
93 $f = $f.call;
94 }
95 if (!($f instanceof Function)) {
96 $throwNoSuchMethodFunc($obj, $name, $args);
97 }
98 }
99 // If f is a function, but not a method (no method type)
100 // then it should have been a function valued field, so
101 // get the type from the function.
102 if ($ftype === void 0) {
103 $ftype = $read($f);
104 }
105
106 if (!$ftype) {
107 // TODO(leafp): Allow JS objects to go through?
108 // This includes the DOM.
109 return $f.apply($obj, $args);
110 }
111
112 if ($checkApply($ftype, $args)) {
113 return $f.apply($obj, $args);
114 }
115
116 // TODO(leafp): throw a type error (rather than NSM)
117 // if the arity matches but the types are wrong.
118 $throwNoSuchMethodFunc($obj, $name, $args, $f);
119 })()''');
120
121 dcall(f, @rest args) => JS('', '''(() => {
122 let ftype = $read($f);
123 return $checkAndCall($f, ftype, void 0, $args, 'call');
124 })()''');
125
126 /// Shared code for dsend, dindex, and dsetindex. */
127 callMethod(obj, name, args, displayName) => JS('', '''(() => {
128 let symbol = $_canonicalFieldName($obj, $name, $args, $displayName);
129 let f = $obj != null ? $obj[symbol] : null;
130 let ftype = $getMethodType($obj, $name);
131 return $checkAndCall(f, ftype, $obj, $args, $displayName);
132 })()''');
133
134 dsend(obj, method, @rest args) => JS('', '''(() => {
135 return $callMethod($obj, $method, $args, $method);
136 })()''');
137
138 dindex(obj, index) => JS('', '''(() => {
139 return $callMethod($obj, 'get', [$index], '[]');
140 })()''');
141
142 dsetindex(obj, index, value) => JS('', '''(() => {
143 $callMethod($obj, 'set', [$index, $value], '[]=');
144 return $value;
145 })()''');
146
147 _ignoreTypeFailure(actual, type) => JS('', '''(() => {
148 // TODO(vsm): Remove this hack ...
149 // This is primarily due to the lack of generic methods,
150 // but we need to triage all the types.
151 if (isSubtype($type, $Iterable) && isSubtype($actual, $Iterable) ||
152 isSubtype($type, $Future) && isSubtype($actual, $Future) ||
153 isSubtype($type, $Map) && isSubtype($actual, $Map) ||
154 isSubtype($type, $Function) && isSubtype($actual, $Function) ||
155 isSubtype($type, $Stream) && isSubtype($actual, $Stream) ||
156 isSubtype($type, $StreamSubscription) &&
157 isSubtype($actual, $StreamSubscription)) {
158 console.warn('Ignoring cast fail from ' + $typeName($actual) +
159 ' to ' + $typeName($type));
160 return true;
161 }
162 return false;
163 })()''');
164
165 strongInstanceOf(obj, type, ignoreFromWhiteList) => JS('', '''(() => {
166 let actual = $realRuntimeType($obj);
167 if ($isSubtype(actual, $type) || actual == $jsobject) return true;
168 if ($ignoreFromWhiteList == void 0) return false;
169 if ($isGroundType($type)) return false;
170 if ($_ignoreTypeFailure(actual, $type)) return true;
171 return false;
172 })()''');
173
174 instanceOfOrNull(obj, type) => JS('', '''(() => {
175 if (($obj == null) || $strongInstanceOf($obj, $type, true)) return true;
176 return false;
177 })()''');
178
179 instanceOf(obj, type) => JS('', '''(() => {
180 if ($strongInstanceOf($obj, $type)) return true;
181 // TODO(#296): This is perhaps too eager to throw a StrongModeError?
182 // It will throw on <int>[] is List<String>.
183 // TODO(vsm): We can statically detect many cases where this
184 // check is unnecessary.
185 if ($isGroundType($type)) return false;
186 let actual = $realRuntimeType($obj);
187 $throwStrongModeError('Strong mode is check failure: ' +
188 $typeName(actual) + ' does not soundly subtype ' +
189 $typeName($type));
190 })()''');
191
192 cast(obj, type) => JS('', '''(() => {
193 // TODO(#296): This is perhaps too eager to throw a StrongModeError?
194 // TODO(vsm): handle non-nullable types
195 if ($instanceOfOrNull($obj, $type)) return $obj;
196 let actual = $realRuntimeType($obj);
197 if ($isGroundType($type)) $throwCastError(actual, $type);
198
199 if ($_ignoreTypeFailure(actual, $type)) return $obj;
200
201 $throwStrongModeError('Strong mode cast failure from ' +
202 $typeName(actual) + ' to ' + $typeName($type));
203 })()''');
204
205 asInt(obj) => JS('', '''(() => {
206 if ($obj == null) {
207 return null;
208 }
209 if (Math.floor($obj) != $obj) {
210 // Note: null will also be caught by this check
211 $throwCastError($realRuntimeType($obj), $int);
212 }
213 return $obj;
214 })()''');
215
216 arity(f) => JS('', '''(() => {
217 // TODO(jmesserly): need to parse optional params.
218 // In ES6, length is the number of required arguments.
219 return { min: $f.length, max: $f.length };
220 })()''');
221
222 equals(x, y) => JS('', '''(() => {
223 if ($x == null || $y == null) return $x == $y;
224 let eq = $x['=='];
225 return eq ? eq.call($x, $y) : $x === $y;
226 })()''');
227
228 /// Checks that `x` is not null or undefined. */
229 notNull(x) => JS('', '''(() => {
230 if ($x == null) $throwNullValueError();
231 return $x;
232 })()''');
233
234 ///
235 /// Creates a dart:collection LinkedHashMap.
236 ///
237 /// For a map with string keys an object literal can be used, for example
238 /// `map({'hi': 1, 'there': 2})`.
239 ///
240 /// Otherwise an array should be used, for example `map([1, 2, 3, 4])` will
241 /// create a map with keys [1, 3] and values [2, 4]. Each key-value pair
242 /// should be adjacent entries in the array.
243 ///
244 /// For a map with no keys the function can be called with no arguments, for
245 /// example `map()`.
246 ///
247 // TODO(jmesserly): this could be faster
248 map(values) => JS('', '''(() => {
249 let map = $LinkedHashMap.new();
250 if (Array.isArray($values)) {
251 for (let i = 0, end = $values.length - 1; i < end; i += 2) {
252 let key = $values[i];
253 let value = $values[i + 1];
254 map.set(key, value);
255 }
256 } else if (typeof $values === 'object') {
257 for (let key of $getOwnPropertyNames($values)) {
258 map.set(key, $values[key]);
259 }
260 }
261 return map;
262 })()''');
263
264 @JSExportName('assert')
265 assert_(condition) => JS('', '''(() => {
266 if (!$condition) $throwAssertionError();
267 })()''');
268
269 final _stack = JS('', 'new WeakMap()');
270 @JSExportName('throw')
271 throw_(obj) => JS('', '''(() => {
272 if ($obj != null && (typeof $obj == 'object' || typeof $obj == 'function')) {
273 // TODO(jmesserly): couldn't we store the most recent stack in a single
274 // variable? There should only be one active stack trace. That would
275 // allow it to work for things like strings and numbers.
276 _stack.set($obj, new Error());
277 }
278 throw $obj;
279 })()''');
280
281 getError(exception) => JS('', '''(() => {
282 var stack = _stack.get($exception);
283 return stack !== void 0 ? stack : $exception;
284 })()''');
285
286 // This is a utility function: it is only intended to be called from dev
287 // tools.
288 stackPrint(exception) => JS('', '''(() => {
289 var error = $getError($exception);
290 console.log(error.stack ? error.stack : 'No stack trace for: ' + error);
291 })()''');
292
293 stackTrace(exception) => JS('', '''(() => {
294 var error = $getError($exception);
295 return $getTraceFromException(error);
296 })()''');
297
298 ///
299 /// Implements a sequence of .? operations.
300 ///
301 /// Will call each successive callback, unless one returns null, which stops
302 /// the sequence.
303 ///
304 nullSafe(obj, @rest callbacks) => JS('', '''(() => {
305 if ($obj == null) return $obj;
306 for (const callback of $callbacks) {
307 $obj = callback($obj);
308 if ($obj == null) break;
309 }
310 return $obj;
311 })()''');
312
313 final _value = JS('', 'Symbol("_value")');
314 ///
315 /// Looks up a sequence of [keys] in [map], recursively, and
316 /// returns the result. If the value is not found, [valueFn] will be called to
317 /// add it. For example:
318 ///
319 /// let map = new Map();
320 /// putIfAbsent(map, [1, 2, 'hi ', 'there '], () => 'world');
321 ///
322 /// ... will create a Map with a structure like:
323 ///
324 /// { 1: { 2: { 'hi ': { 'there ': 'world' } } } }
325 ///
326 multiKeyPutIfAbsent(map, keys, valueFn) => JS('', '''(() => {
327 for (let k of $keys) {
328 let value = $map.get(k);
329 if (!value) {
330 // TODO(jmesserly): most of these maps are very small (e.g. 1 item),
331 // so it may be worth optimizing for that.
332 $map.set(k, value = new Map());
333 }
334 $map = value;
335 }
336 if ($map.has(_value)) return $map.get(_value);
337 let value = $valueFn();
338 $map.set(_value, value);
339 return value;
340 })()''');
341
342 /// The global constant table. */
343 final constants = JS('', 'new Map()');
344
345 ///
346 /// Canonicalize a constant object.
347 ///
348 /// Preconditions:
349 /// - `obj` is an objects or array, not a primitive.
350 /// - nested values of the object are themselves already canonicalized.
351 ///
352 @JSExportName('const')
353 const_(obj) => JS('', '''(() => {
354 let objectKey = [$realRuntimeType($obj)];
355 // TODO(jmesserly): there's no guarantee in JS that names/symbols are
356 // returned in the same order.
357 //
358 // We could probably get the same order if we're judicious about
359 // initializing fields in a consistent order across all const constructors.
360 // Alternatively we need a way to sort them to make consistent.
361 //
362 // Right now we use the (name,value) pairs in sequence, which prevents
363 // an object with incorrect field values being returned, but won't
364 // canonicalize correctly if key order is different.
365 for (let name of $getOwnNamesAndSymbols($obj)) {
366 objectKey.push(name);
367 objectKey.push($obj[name]);
368 }
369 return $multiKeyPutIfAbsent($constants, objectKey, () => $obj);
370 })()''');
371
372
373 // The following are helpers for Object methods when the receiver
374 // may be null or primitive. These should only be generated by
375 // the compiler.
376 hashCode(obj) => JS('', '''(() => {
377 if ($obj == null) {
378 return 0;
379 }
380 // TODO(vsm): What should we do for primitives and non-Dart objects?
381 switch (typeof $obj) {
382 case "number":
383 case "boolean":
384 return $obj & 0x1FFFFFFF;
385 case "string":
386 // TODO(vsm): Call the JSString hashCode?
387 return $obj.length;
388 }
389 return $obj.hashCode;
390 })()''');
391
392 toString(obj) => JS('', '''(() => {
393 if ($obj == null) {
394 return "null";
395 }
396 return $obj.toString();
397 })()''');
398
399 noSuchMethod(obj, invocation) => JS('', '''(() => {
400 if ($obj == null) {
401 $throwNoSuchMethod($obj, $invocation.memberName,
402 $invocation.positionalArguments, $invocation.namedArguments);
403 }
404 switch (typeof $obj) {
405 case "number":
406 case "boolean":
407 case "string":
408 $throwNoSuchMethod($obj, $invocation.memberName,
409 $invocation.positionalArguments, $invocation.namedArguments);
410 }
411 return $obj.noSuchMethod($invocation);
412 })()''');
413
414 final JsIterator = JS('', '''
415 class JsIterator {
416 constructor(dartIterator) {
417 this.dartIterator = dartIterator;
418 }
419 next() {
420 let i = this.dartIterator;
421 let done = !i.moveNext();
422 return { done: done, value: done ? void 0 : i.current };
423 }
424 }
425 ''');
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698