RefStack.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using Jint.Runtime.Environments;
  4. namespace Jint.Runtime
  5. {
  6. internal sealed class ExecutionContextStack
  7. {
  8. private ExecutionContext[] _array;
  9. private int _size;
  10. private const int DefaultCapacity = 4;
  11. public ExecutionContextStack()
  12. {
  13. _array = new ExecutionContext[4];
  14. _size = 0;
  15. }
  16. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  17. public ref readonly ExecutionContext Peek()
  18. {
  19. if (_size == 0)
  20. {
  21. ThrowEmptyStackException();
  22. }
  23. return ref _array[_size - 1];
  24. }
  25. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  26. public void Pop()
  27. {
  28. if (_size == 0)
  29. {
  30. ThrowEmptyStackException();
  31. }
  32. _size--;
  33. }
  34. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  35. public void Push(in ExecutionContext item)
  36. {
  37. if (_size == _array.Length)
  38. {
  39. var newSize = 2 * _array.Length;
  40. var newArray = new ExecutionContext[newSize];
  41. Array.Copy(_array, 0, newArray, 0, _size);
  42. _array = newArray;
  43. }
  44. _array[_size++] = item;
  45. }
  46. private static void ThrowEmptyStackException()
  47. {
  48. throw new InvalidOperationException("stack is empty");
  49. }
  50. public void ReplaceTopLexicalEnvironment(LexicalEnvironment newEnv)
  51. {
  52. _array[_size - 1] = _array[_size - 1].UpdateLexicalEnvironment(newEnv);
  53. }
  54. }
  55. }