NullishCoalescingExpression.cs 1.4 KB

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