0

eval这是在 Dart 平台中使用此方法的代码。

这是通过反射完成的。

运行时/lib/mirrors_impl.dart

_getFieldSlow(unwrapped) {
      // ..... Skipped  
      var atPosition = unwrapped.indexOf('@');
      if (atPosition == -1) {
        // Public symbol.
        f = _eval('(x) => x.$unwrapped', null);
      } else {
        // Private symbol.
        var withoutKey = unwrapped.substring(0, atPosition);
        var privateKey = unwrapped.substring(atPosition);
        f = _eval('(x) => x.$withoutKey', privateKey);
      }
      // ..... Skipped
  }
  static _eval(expression, privateKey)
      native "Mirrors_evalInLibraryWithPrivateKey";

运行时/lib/mirrors.cc

DEFINE_NATIVE_ENTRY(Mirrors_evalInLibraryWithPrivateKey, 2) {
  GET_NON_NULL_NATIVE_ARGUMENT(String, expression, arguments->NativeArgAt(0));
  GET_NATIVE_ARGUMENT(String, private_key, arguments->NativeArgAt(1));

  const GrowableObjectArray& libraries =
      GrowableObjectArray::Handle(isolate->object_store()->libraries());
  const int num_libraries = libraries.Length();
  Library& each_library = Library::Handle();
  Library& ctxt_library = Library::Handle();
  String& library_key = String::Handle();

  if (library_key.IsNull()) {
    ctxt_library = Library::CoreLibrary();
  } else {
    for (int i = 0; i < num_libraries; i++) {
      each_library ^= libraries.At(i);
      library_key = each_library.private_key();
      if (library_key.Equals(private_key)) {
        ctxt_library = each_library.raw();
        break;
      }
    }
  }
  ASSERT(!ctxt_library.IsNull());
  return ctxt_library.Evaluate(expression);

运行时/vm/bootstrap_natives.h

V(Mirrors_evalInLibraryWithPrivateKey, 2)                                    \

附言

我在这里提问是因为我不能在 Dart 邮件列表中提问。

附言

正如我们在中看到static private method的那样mirrors_impl.dart

static _eval(expression, privateKey) native "Mirrors_evalInLibraryWithPrivateKey";

有人希望这种方法应该公开吗?( this is not a question but just a thought aloud)。

4

1 回答 1

7

根据Dart 常见问题解答,即使可能会添加其他动态功能,像这样的纯字符串 eval 也不太可能进入该语言:

因此,例如,Dart 不太可能支持在当前上下文中将字符串评估为代码,但它可能支持将该代码动态加载到新的隔离中。Dart 不太可能支持向值添加字段,但它可能(通过镜像系统)支持向类添加字段,并且您可以使用 noSuchMethod() 有效地添加方法。使用这些功能将产生运行时成本;将不使用它们的程序的成本降至最低对我们来说很重要。

该领域仍在开发中,因此我们欢迎您对运行时动态的需求提出想法。

于 2014-02-07T15:53:33.353 回答