1. /**
    
  2.  * Copyright (c) Meta Platforms, Inc. and affiliates.
    
  3.  *
    
  4.  * This source code is licensed under the MIT license found in the
    
  5.  * LICENSE file in the root directory of this source tree.
    
  6.  *
    
  7.  * @flow
    
  8.  */
    
  9. 
    
  10. import type {Fiber} from './ReactInternalTypes';
    
  11. 
    
  12. export type StackCursor<T> = {current: T};
    
  13. 
    
  14. const valueStack: Array<any> = [];
    
  15. 
    
  16. let fiberStack: Array<Fiber | null>;
    
  17. 
    
  18. if (__DEV__) {
    
  19.   fiberStack = [];
    
  20. }
    
  21. 
    
  22. let index = -1;
    
  23. 
    
  24. function createCursor<T>(defaultValue: T): StackCursor<T> {
    
  25.   return {
    
  26.     current: defaultValue,
    
  27.   };
    
  28. }
    
  29. 
    
  30. function isEmpty(): boolean {
    
  31.   return index === -1;
    
  32. }
    
  33. 
    
  34. function pop<T>(cursor: StackCursor<T>, fiber: Fiber): void {
    
  35.   if (index < 0) {
    
  36.     if (__DEV__) {
    
  37.       console.error('Unexpected pop.');
    
  38.     }
    
  39.     return;
    
  40.   }
    
  41. 
    
  42.   if (__DEV__) {
    
  43.     if (fiber !== fiberStack[index]) {
    
  44.       console.error('Unexpected Fiber popped.');
    
  45.     }
    
  46.   }
    
  47. 
    
  48.   cursor.current = valueStack[index];
    
  49. 
    
  50.   valueStack[index] = null;
    
  51. 
    
  52.   if (__DEV__) {
    
  53.     fiberStack[index] = null;
    
  54.   }
    
  55. 
    
  56.   index--;
    
  57. }
    
  58. 
    
  59. function push<T>(cursor: StackCursor<T>, value: T, fiber: Fiber): void {
    
  60.   index++;
    
  61. 
    
  62.   valueStack[index] = cursor.current;
    
  63. 
    
  64.   if (__DEV__) {
    
  65.     fiberStack[index] = fiber;
    
  66.   }
    
  67. 
    
  68.   cursor.current = value;
    
  69. }
    
  70. 
    
  71. function checkThatStackIsEmpty() {
    
  72.   if (__DEV__) {
    
  73.     if (index !== -1) {
    
  74.       console.error(
    
  75.         'Expected an empty stack. Something was not reset properly.',
    
  76.       );
    
  77.     }
    
  78.   }
    
  79. }
    
  80. 
    
  81. function resetStackAfterFatalErrorInDev() {
    
  82.   if (__DEV__) {
    
  83.     index = -1;
    
  84.     valueStack.length = 0;
    
  85.     fiberStack.length = 0;
    
  86.   }
    
  87. }
    
  88. 
    
  89. export {
    
  90.   createCursor,
    
  91.   isEmpty,
    
  92.   pop,
    
  93.   push,
    
  94.   // DEV only:
    
  95.   checkThatStackIsEmpty,
    
  96.   resetStackAfterFatalErrorInDev,
    
  97. };