NullishCoalescingExpression.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System.Runtime.CompilerServices;
  2. using Jint.Native;
  3. namespace Jint.Runtime.Interpreter.Expressions
  4. {
  5. internal sealed class NullishCoalescingExpression : JintExpression
  6. {
  7. private readonly JintExpression _left;
  8. private readonly JintExpression? _right;
  9. private readonly JsValue? _constant;
  10. public NullishCoalescingExpression(BinaryExpression expression) : base(expression)
  11. {
  12. _left = Build(expression.Left);
  13. // we can create a fast path for common literal case like variable ?? 0
  14. if (expression.Right is Literal l)
  15. {
  16. _constant = JintLiteralExpression.ConvertToJsValue(l);
  17. }
  18. else
  19. {
  20. _right = Build(expression.Right);
  21. }
  22. }
  23. public override JsValue GetValue(EvaluationContext context)
  24. {
  25. // need to notify correct node when taking shortcut
  26. context.LastSyntaxElement = _expression;
  27. return EvaluateConstantOrExpression(context);
  28. }
  29. protected override object EvaluateInternal(EvaluationContext context)
  30. {
  31. return EvaluateConstantOrExpression(context);
  32. }
  33. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  34. private JsValue EvaluateConstantOrExpression(EvaluationContext context)
  35. {
  36. var left = _left.GetValue(context);
  37. return !left.IsNullOrUndefined()
  38. ? left
  39. : _constant ?? _right!.GetValue(context);
  40. }
  41. }
  42. }