ScriptFunctionInstance.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 Statement _body;
  17. private readonly IEnumerable<Identifier> _parameters;
  18. public ScriptFunctionInstance(Statement body, string name, Identifier[] parameters, ObjectInstance instancePrototype, ObjectInstance functionPrototype, LexicalEnvironment scope)
  19. : base(instancePrototype, parameters, scope)
  20. {
  21. // http://www.ecma-international.org/ecma-262/5.1/#sec-13.2
  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 dynamic Call(Engine engine, object thisObject, dynamic[] 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. engine.ExecuteStatement(_body);
  53. var result = engine.CurrentExecutionContext.Return;
  54. engine.LeaveExecutionContext();
  55. return result;
  56. }
  57. public virtual ObjectInstance Construct(dynamic[] arguments)
  58. {
  59. /// todo: http://www.ecma-international.org/ecma-262/5.1/#sec-13.2.2
  60. var instance = new FunctionShim(this.Prototype, null, null);
  61. return instance;
  62. }
  63. }
  64. }