stack.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef EXECUTABLE_SEMANTICS_INTERPRETER_STACK_H_
  5. #define EXECUTABLE_SEMANTICS_INTERPRETER_STACK_H_
  6. #include <cstddef>
  7. #include <iterator>
  8. #include <vector>
  9. #include "common/check.h"
  10. namespace Carbon {
  11. // A stack data structure.
  12. template <class T>
  13. struct Stack {
  14. using const_iterator = typename std::vector<T>::const_reverse_iterator;
  15. // Creates an empty instance.
  16. Stack() = default;
  17. // Creates an instance containing just `x`.
  18. explicit Stack(T x) : Stack() { Push(std::move(x)); }
  19. // Pushes `x` onto the top of the stack.
  20. void Push(T x) { elements.push_back(std::move(x)); }
  21. // Removes and returns the top element of the stack.
  22. //
  23. // - Requires: !this->IsEmpty()
  24. auto Pop() -> T {
  25. CHECK(!IsEmpty()) << "Can't pop from empty stack.";
  26. auto r = std::move(elements.back());
  27. elements.pop_back();
  28. return r;
  29. }
  30. // Removes the top `n` elements of the stack.
  31. //
  32. // - Requires: n >= 0 && n <= Count()
  33. void Pop(int n) {
  34. CHECK(n >= 0) << "Negative pop count disallowed.";
  35. CHECK(static_cast<size_t>(n) <= elements.size())
  36. << "Can only pop as many elements as stack has.";
  37. elements.erase(elements.end() - n, elements.end());
  38. }
  39. // Returns the top element of the stack.
  40. //
  41. // - Requires: !this->IsEmpty()
  42. auto Top() const -> T {
  43. CHECK(!IsEmpty()) << "Empty stack has no Top().";
  44. return elements.back();
  45. }
  46. // Returns `true` iff `Count() > 0`.
  47. auto IsEmpty() const -> bool { return elements.empty(); }
  48. // Returns the number of elements in `*this`.
  49. auto Count() const -> int { return elements.size(); }
  50. // Iterates over the Stack from top to bottom.
  51. const_iterator begin() const { return elements.crbegin(); }
  52. const_iterator end() const { return elements.crend(); }
  53. private:
  54. std::vector<T> elements;
  55. };
  56. } // namespace Carbon
  57. #endif // EXECUTABLE_SEMANTICS_INTERPRETER_CONS_LIST_H_