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 /** |
| 6 * Convert top-level or static functions to objects that can be sent to |
| 7 * other isolates. |
| 8 * |
| 9 * This package is only needed until such functions can be sent directly |
| 10 * through send-ports. |
| 11 */ |
| 12 library pkg.isolate.functionref; |
| 13 |
| 14 import "dart:mirrors"; |
| 15 |
| 16 abstract class FunctionRef { |
| 17 static FunctionRef from(Function function) { |
| 18 var cm = reflect(function); |
| 19 if (cm is ClosureMirror) { |
| 20 MethodMirror fm = cm.function; |
| 21 if (fm.isRegularMethod && fm.isStatic) { |
| 22 Symbol functionName = fm.simpleName; |
| 23 Symbol className; |
| 24 DeclarationMirror owner = fm.owner; |
| 25 if (owner is ClassMirror) { |
| 26 className = owner.simpleName; |
| 27 owner = owner.owner; |
| 28 } |
| 29 if (owner is LibraryMirror) { |
| 30 LibraryMirror ownerLibrary = owner; |
| 31 Uri libraryUri = ownerLibrary.uri; |
| 32 return new _FunctionRef(libraryUri, className, functionName); |
| 33 } |
| 34 } |
| 35 throw new ArgumentError.value(function, "function", |
| 36 "Not a static or top-level function"); |
| 37 } |
| 38 // It's a Function but not a closure, so it's a callable object. |
| 39 return new _CallableObjectRef(function); |
| 40 } |
| 41 |
| 42 Function get function; |
| 43 } |
| 44 |
| 45 class _FunctionRef implements FunctionRef { |
| 46 final Uri libraryUri; |
| 47 final Symbol className; |
| 48 final Symbol functionName; |
| 49 |
| 50 _FunctionRef(this.libraryUri, this.className, this.functionName); |
| 51 |
| 52 Function get function { |
| 53 LibraryMirror lm = currentMirrorSystem().libraries[libraryUri]; |
| 54 if (lm != null) { |
| 55 ObjectMirror owner = lm; |
| 56 if (className != null) { |
| 57 ClassMirror cm = lm.declarations[className]; |
| 58 owner = cm; |
| 59 } |
| 60 if (owner != null) { |
| 61 ClosureMirror function = owner.getField(this.functionName); |
| 62 if (function != null) return function.reflectee; |
| 63 } |
| 64 } |
| 65 String functionName = MirrorSystem.getName(this.functionName); |
| 66 String classQualifier = ""; |
| 67 if (this.className != null) { |
| 68 classQualifier = " in class ${MirrorSystem.getName(this.className)}"; |
| 69 } |
| 70 throw new UnsupportedError( |
| 71 "Function $functionName${classQualifier} not found in library $libraryUri" |
| 72 ); |
| 73 } |
| 74 } |
| 75 |
| 76 class _CallableObjectRef implements FunctionRef { |
| 77 final Function object; |
| 78 _CallableObjectRef(this.object); |
| 79 Function get function => object; |
| 80 } |
OLD | NEW |