heap.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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_HEAP_H_
  5. #define EXECUTABLE_SEMANTICS_INTERPRETER_HEAP_H_
  6. #include <vector>
  7. #include "common/ostream.h"
  8. #include "executable_semantics/ast/source_location.h"
  9. #include "executable_semantics/common/nonnull.h"
  10. #include "executable_semantics/interpreter/address.h"
  11. #include "executable_semantics/interpreter/heap_allocation_interface.h"
  12. #include "executable_semantics/interpreter/value.h"
  13. namespace Carbon {
  14. // A Heap represents the abstract machine's dynamically allocated memory.
  15. class Heap : public HeapAllocationInterface {
  16. public:
  17. // Constructs an empty Heap.
  18. explicit Heap(Nonnull<Arena*> arena) : arena_(arena){};
  19. Heap(const Heap&) = delete;
  20. auto operator=(const Heap&) -> Heap& = delete;
  21. // Returns the value at the given address in the heap after
  22. // checking that it is alive.
  23. auto Read(const Address& a, SourceLocation source_loc) const
  24. -> Nonnull<const Value*>;
  25. // Writes the given value at the address in the heap after
  26. // checking that the address is alive.
  27. void Write(const Address& a, Nonnull<const Value*> v,
  28. SourceLocation source_loc);
  29. // Put the given value on the heap and mark it as alive.
  30. auto AllocateValue(Nonnull<const Value*> v) -> AllocationId override;
  31. // Marks this allocation, and all of its sub-objects, as dead.
  32. void Deallocate(AllocationId allocation) override;
  33. // Print all the values on the heap to the stream `out`.
  34. void Print(llvm::raw_ostream& out) const;
  35. LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
  36. auto arena() const -> Arena& override { return *arena_; }
  37. private:
  38. // Signal an error if the allocation is no longer alive.
  39. void CheckAlive(AllocationId allocation, SourceLocation source_loc) const;
  40. Nonnull<Arena*> arena_;
  41. std::vector<Nonnull<const Value*>> values_;
  42. std::vector<bool> alive_;
  43. };
  44. } // namespace Carbon
  45. #endif // EXECUTABLE_SEMANTICS_INTERPRETER_HEAP_H_