2
0

JintNewExpression.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using Esprima.Ast;
  3. using Jint.Native;
  4. namespace Jint.Runtime.Interpreter.Expressions
  5. {
  6. internal sealed class JintNewExpression : JintExpression
  7. {
  8. private JintExpression _calleeExpression;
  9. private JintExpression[] _jintArguments = Array.Empty<JintExpression>();
  10. private bool _hasSpreads;
  11. public JintNewExpression(Engine engine, NewExpression expression) : base(engine, expression)
  12. {
  13. _initialized = false;
  14. }
  15. protected override void Initialize()
  16. {
  17. var expression = (NewExpression) _expression;
  18. _calleeExpression = Build(_engine, expression.Callee);
  19. if (expression.Arguments.Count <= 0)
  20. {
  21. return;
  22. }
  23. _jintArguments = new JintExpression[expression.Arguments.Count];
  24. for (var i = 0; i < _jintArguments.Length; i++)
  25. {
  26. var argument = expression.Arguments[i];
  27. _jintArguments[i] = Build(_engine, argument);
  28. _hasSpreads |= argument.Type == Nodes.SpreadElement;
  29. }
  30. }
  31. protected override object EvaluateInternal()
  32. {
  33. // todo: optimize by defining a common abstract class or interface
  34. var jsValue = _calleeExpression.GetValue();
  35. JsValue[] arguments;
  36. if (_jintArguments.Length == 0)
  37. {
  38. arguments = Array.Empty<JsValue>();
  39. }
  40. else if (_hasSpreads)
  41. {
  42. arguments = BuildArgumentsWithSpreads(_jintArguments);
  43. }
  44. else
  45. {
  46. arguments = _engine._jsValueArrayPool.RentArray(_jintArguments.Length);
  47. BuildArguments(_jintArguments, arguments);
  48. }
  49. if (!jsValue.IsConstructor)
  50. {
  51. ExceptionHelper.ThrowTypeError(_engine.Realm, _calleeExpression.SourceText + " is not a constructor");
  52. }
  53. // construct the new instance using the Function's constructor method
  54. var instance = _engine.Construct((IConstructor) jsValue, arguments, jsValue, _calleeExpression);
  55. _engine._jsValueArrayPool.ReturnArray(arguments);
  56. return instance;
  57. }
  58. }
  59. }