JintNewExpression.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. JsValue[] arguments;
  34. if (_jintArguments.Length == 0)
  35. {
  36. arguments = Array.Empty<JsValue>();
  37. }
  38. else if (_hasSpreads)
  39. {
  40. arguments = BuildArgumentsWithSpreads(_jintArguments);
  41. }
  42. else
  43. {
  44. arguments = _engine._jsValueArrayPool.RentArray(_jintArguments.Length);
  45. BuildArguments(_jintArguments, arguments);
  46. }
  47. // todo: optimize by defining a common abstract class or interface
  48. var jsValue = _calleeExpression.GetValue();
  49. if (!(jsValue is IConstructor callee))
  50. {
  51. return ExceptionHelper.ThrowTypeError<object>(_engine, "The object can't be used as constructor.");
  52. }
  53. // construct the new instance using the Function's constructor method
  54. var instance = callee.Construct(arguments, jsValue);
  55. _engine._jsValueArrayPool.ReturnArray(arguments);
  56. return instance;
  57. }
  58. }
  59. }