Factor Heap class out of State (#491)

Additional miscellaneous cleanup:

- Use the term "deallocate" instead of "kill" in function names, for symmetry with "allocate".
- Drop an unnecessary memory allocation in `AllocateValue`.
- Implement `PrintHeap` in terms of `PrintAddress`, so that dead values are flagged with `!!`.
This commit is contained in:
Geoff Romer
2021-04-23 13:25:51 -07:00
committed by GitHub
parent a13cecccc6
commit e022ff106f
4 changed files with 127 additions and 109 deletions
+31 -12
View File
@@ -59,30 +59,49 @@ struct Frame {
continuation(UINT_MAX) {}
};
// TODO(geoffromer): Make this a class, with all members private
struct State {
Stack<Frame*> stack;
std::vector<bool> alive;
// A Heap represents the abstract machine's dynamically allocated memory.
class Heap {
public:
// Constructs an empty Heap.
Heap() = default;
Heap(const Heap&) = delete;
Heap& operator=(const Heap&) = delete;
// Returns the value at the given address in the heap after
// checking that it is alive.
auto ReadFromMemory(Address a, int line_num) -> const Value*;
auto Read(Address a, int line_num) -> const Value*;
// Writes the given value at the address in the heap after
// checking that the address is alive.
auto WriteToMemory(Address a, const Value* v, int line_num) -> void;
// Print the value at the given address to the stream `out`.
auto PrintAddress(Address a, std::ostream& out) -> void;
// Signal an error if the address is no longer alive.
void CheckAlive(Address address, int line_num);
auto Write(Address a, const Value* v, int line_num) -> void;
// Put the given value on the heap and mark it as alive.
auto AllocateValue(const Value* v) -> Address;
// Marks the object at this address, and all of its sub-objects, as dead.
auto KillObject(Address address) -> void;
auto Deallocate(Address address) -> void;
// Print the value at the given address to the stream `out`.
auto PrintAddress(Address a, std::ostream& out) -> void;
// Print all the values on the heap to the stream `out`.
auto PrintHeap(std::ostream& out) -> void;
private:
std::vector<const Value*> heap;
// Signal an error if the address is no longer alive.
void CheckAlive(Address address, int line_num);
// Marks all sub-objects of this value as dead.
void DeallocateSubObjects(const Value* val);
std::vector<const Value*> values_;
std::vector<bool> alive_;
};
struct State {
Stack<Frame*> stack;
Heap heap;
};
extern State* state;