ScriptFunctionInstance.cs 2.8 KB

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