stack.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. // NOLINTNEXTLINE(readability-identifier-naming)
  15. using const_iterator = typename std::vector<T>::const_reverse_iterator;
  16. // Creates an empty instance.
  17. Stack() = default;
  18. // Creates an instance containing just `x`.
  19. explicit Stack(T x) : Stack() { Push(std::move(x)); }
  20. // Pushes `x` onto the top of the stack.
  21. void Push(T x) { elements_.push_back(std::move(x)); }
  22. // Removes and returns the top element of the stack.
  23. //
  24. // - Requires: !this->IsEmpty()
  25. auto Pop() -> T {
  26. CHECK(!IsEmpty()) << "Can't pop from empty stack.";
  27. auto r = std::move(elements_.back());
  28. elements_.pop_back();
  29. return r;
  30. }
  31. // Removes the top `n` elements of the stack.
  32. //
  33. // - Requires: n >= 0 && n <= Count()
  34. void Pop(int n) {
  35. CHECK(n >= 0) << "Negative pop count disallowed.";
  36. CHECK(static_cast<size_t>(n) <= elements_.size())
  37. << "Can only pop as many elements as stack has.";
  38. elements_.erase(elements_.end() - n, elements_.end());
  39. }
  40. // Returns the top element of the stack.
  41. //
  42. // - Requires: !this->IsEmpty()
  43. auto Top() const -> const T& {
  44. CHECK(!IsEmpty()) << "Empty stack has no Top().";
  45. return elements_.back();
  46. }
  47. // Returns `true` iff `Count() > 0`.
  48. auto IsEmpty() const -> bool { return elements_.empty(); }
  49. // Returns the number of elements in `*this`.
  50. auto Count() const -> int { return elements_.size(); }
  51. // Iterates over the Stack from top to bottom.
  52. auto begin() const -> const_iterator { return elements_.crbegin(); }
  53. auto end() const -> const_iterator { return elements_.crend(); }
  54. private:
  55. std::vector<T> elements_;
  56. };
  57. } // namespace Carbon
  58. #endif // EXECUTABLE_SEMANTICS_INTERPRETER_CONS_LIST_H_