经过一些重新测试后,我发现我的实现无法处理很多递归。虽然在 Firefox 中运行了一些测试后,我发现这可能比我最初想象的更常见。我相信基本问题是我的实现需要 3 次调用才能进行函数调用。第一次调用是对一个名为的方法进行的,该方法Call
确保调用是对一个可调用对象并获取任何引用的参数的值。第二次调用一个名为的方法,该方法Call
定义在ICallable
界面。此方法创建新的执行上下文并构建 lambda 表达式(如果尚未创建)。最后调用函数对象封装的 lambda。显然,进行函数调用非常繁重,但我确信通过一些调整,我可以在使用此实现时使递归成为一个可行的工具。
public static object Call(ExecutionContext context, object value, object[] args)
{
var func = Reference.GetValue(value) as ICallable;
if (func == null)
{
throw new TypeException();
}
if (args != null && args.Length > 0)
{
for (int i = 0; i < args.Length; i++)
{
args[i] = Reference.GetValue(args[i]);
}
}
var reference = value as Reference;
if (reference != null)
{
if (reference.IsProperty)
{
return func.Call(reference.Value, args);
}
else
{
return func.Call(((EnviromentRecord)reference.Value).ImplicitThisValue(), args);
}
}
return func.Call(Undefined.Value, args);
}
public object Call(object thisObject, object[] arguments)
{
var lexicalEnviroment = Scope.NewDeclarativeEnviroment();
var variableEnviroment = Scope.NewDeclarativeEnviroment();
var thisBinding = thisObject ?? Engine.GlobalEnviroment.GlobalObject;
var newContext = new ExecutionContext(Engine, lexicalEnviroment, variableEnviroment, thisBinding);
Engine.EnterContext(newContext);
var result = Function.Value(newContext, arguments);
Engine.LeaveContext();
return result;
}