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