ScriptFunctionInstance.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using Jint.Native;
  4. using Jint.Native.Function;
  5. using Jint.Native.Object;
  6. using Jint.Parser.Ast;
  7. using Jint.Runtime.Descriptors;
  8. using Jint.Runtime.Environments;
  9. namespace Jint.Runtime
  10. {
  11. /// <summary>
  12. ///
  13. /// </summary>
  14. public class ScriptFunctionInstance : FunctionInstance
  15. {
  16. private readonly Engine _engine;
  17. private readonly Statement _body;
  18. private readonly IEnumerable<Identifier> _parameters;
  19. public ScriptFunctionInstance(Engine engine, Statement body, string name, Identifier[] parameters, ObjectInstance instancePrototype, ObjectInstance functionPrototype, LexicalEnvironment scope)
  20. : base(engine, instancePrototype, parameters, scope)
  21. {
  22. // http://www.ecma-international.org/ecma-262/5.1/#sec-13.2
  23. _engine = engine;
  24. _body = body;
  25. _parameters = parameters;
  26. Extensible = true;
  27. var len = parameters.Count();
  28. DefineOwnProperty("length", new DataDescriptor(len) { Writable = false, Enumerable = false, Configurable = false }, false);
  29. DefineOwnProperty("name", new DataDescriptor(name), false);
  30. instancePrototype.DefineOwnProperty("constructor", new DataDescriptor(this) { Writable = true, Enumerable = true, Configurable = true }, false);
  31. DefineOwnProperty("prototype", new DataDescriptor(functionPrototype) { Writable = true, Enumerable = true, Configurable = true }, false);
  32. }
  33. public override dynamic Call(object thisObject, dynamic[] arguments)
  34. {
  35. // todo: http://www.ecma-international.org/ecma-262/5.1/#sec-13.2.1
  36. // setup new execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.3
  37. var localEnv = LexicalEnvironment.NewDeclarativeEnvironment(Scope);
  38. object thisArg;
  39. if (thisObject == Undefined.Instance || thisObject == Null.Instance)
  40. {
  41. thisArg = _engine.Global;
  42. }
  43. else
  44. {
  45. thisArg = thisObject;
  46. }
  47. _engine.EnterExecutionContext(localEnv, localEnv, thisArg);
  48. var env = localEnv.Record;
  49. int i = 0;
  50. foreach (var parameter in _parameters)
  51. {
  52. env.SetMutableBinding(parameter.Name, i < arguments.Length ? arguments[i++] : Undefined.Instance, false);
  53. }
  54. _engine.ExecuteStatement(_body);
  55. var result = _engine.CurrentExecutionContext.Return;
  56. _engine.LeaveExecutionContext();
  57. return result;
  58. }
  59. public virtual ObjectInstance Construct(dynamic[] arguments)
  60. {
  61. /// todo: http://www.ecma-international.org/ecma-262/5.1/#sec-13.2.2
  62. var instance = new FunctionShim(_engine, this.Prototype, null, null);
  63. return instance;
  64. }
  65. }
  66. }