Files
carbon-lang/executable_semantics/interpreter/stack.h
T
Jon Meow 47325be112 Switch interpreter Stacks to Ptr (#763)
This also eliminates the ctad wrapper for Stack: I think the leaning is to remove it. It felt worth keeping the constructor because constructing with a single element is a common use-case.

Adds a single-argument constructor for Scope because the `std::list<std::string>()` is common, and eliding it is consistent with what we've done for things like tuples.

I was considering a vector constructor due to the double-Push on line 1139, but thought the Push() semantics may mean that it's better not to provide.
2021-08-19 11:34:03 -07:00

75 lines
2.0 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef EXECUTABLE_SEMANTICS_INTERPRETER_STACK_H_
#define EXECUTABLE_SEMANTICS_INTERPRETER_STACK_H_
#include <cstddef>
#include <iterator>
#include <vector>
#include "common/check.h"
namespace Carbon {
// A stack data structure.
template <class T>
struct Stack {
using const_iterator = typename std::vector<T>::const_reverse_iterator;
// Creates an empty instance.
Stack() = default;
// Creates an instance containing just `x`.
explicit Stack(T x) : Stack() { Push(std::move(x)); }
// Pushes `x` onto the top of the stack.
void Push(T x) { elements.push_back(std::move(x)); }
// Removes and returns the top element of the stack.
//
// - Requires: !this->IsEmpty()
auto Pop() -> T {
CHECK(!IsEmpty()) << "Can't pop from empty stack.";
auto r = std::move(elements.back());
elements.pop_back();
return r;
}
// Removes the top `n` elements of the stack.
//
// - Requires: n >= 0 && n <= Count()
void Pop(int n) {
CHECK(n >= 0) << "Negative pop count disallowed.";
CHECK(static_cast<size_t>(n) <= elements.size())
<< "Can only pop as many elements as stack has.";
elements.erase(elements.end() - n, elements.end());
}
// Returns the top element of the stack.
//
// - Requires: !this->IsEmpty()
auto Top() const -> T {
CHECK(!IsEmpty()) << "Empty stack has no Top().";
return elements.back();
}
// Returns `true` iff `Count() > 0`.
auto IsEmpty() const -> bool { return elements.empty(); }
// Returns the number of elements in `*this`.
auto Count() const -> int { return elements.size(); }
// Iterates over the Stack from top to bottom.
const_iterator begin() const { return elements.crbegin(); }
const_iterator end() const { return elements.crend(); }
private:
std::vector<T> elements;
};
} // namespace Carbon
#endif // EXECUTABLE_SEMANTICS_INTERPRETER_CONS_LIST_H_