heap.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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/common/nonnull.h"
  9. #include "executable_semantics/common/source_location.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. -> ErrorOr<Nonnull<const Value*>>;
  25. // Writes the given value at the address in the heap after
  26. // checking that the address is alive.
  27. auto Write(const Address& a, Nonnull<const Value*> v,
  28. SourceLocation source_loc) -> ErrorOr<Success>;
  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. auto CheckAlive(AllocationId allocation, SourceLocation source_loc) const
  40. -> ErrorOr<Success>;
  41. Nonnull<Arena*> arena_;
  42. std::vector<Nonnull<const Value*>> values_;
  43. std::vector<bool> alive_;
  44. };
  45. } // namespace Carbon
  46. #endif // EXECUTABLE_SEMANTICS_INTERPRETER_HEAP_H_