heap.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. #include "executable_semantics/interpreter/heap.h"
  5. namespace Carbon {
  6. auto Heap::AllocateValue(const Value* v) -> Address {
  7. // Putting the following two side effects together in this function
  8. // ensures that we don't do anything else in between, which is really bad!
  9. // Consider whether to include a copy of the input v in this function
  10. // or to leave it up to the caller.
  11. CHECK(v != nullptr);
  12. Address a(values_.size());
  13. values_.push_back(v);
  14. alive_.push_back(true);
  15. return a;
  16. }
  17. auto Heap::Read(const Address& a, int line_num) -> const Value* {
  18. this->CheckAlive(a, line_num);
  19. return values_[a.index]->GetField(a.field_path, line_num);
  20. }
  21. auto Heap::Write(const Address& a, const Value* v, int line_num) -> void {
  22. CHECK(v != nullptr);
  23. this->CheckAlive(a, line_num);
  24. values_[a.index] = values_[a.index]->SetField(a.field_path, v, line_num);
  25. }
  26. void Heap::CheckAlive(const Address& address, int line_num) {
  27. if (!alive_[address.index]) {
  28. std::cerr << line_num << ": undefined behavior: access to dead value ";
  29. PrintValue(values_[address.index], std::cerr);
  30. std::cerr << std::endl;
  31. exit(-1);
  32. }
  33. }
  34. void Heap::Deallocate(const Address& address) {
  35. CHECK(address.field_path.IsEmpty());
  36. if (alive_[address.index]) {
  37. alive_[address.index] = false;
  38. } else {
  39. std::cerr << "runtime error, deallocating an already dead value"
  40. << std::endl;
  41. exit(-1);
  42. }
  43. }
  44. void Heap::PrintHeap(std::ostream& out) {
  45. for (size_t i = 0; i < values_.size(); ++i) {
  46. PrintAddress(Address(i), out);
  47. out << ", ";
  48. }
  49. }
  50. auto Heap::PrintAddress(const Address& a, std::ostream& out) -> void {
  51. if (!alive_[a.index]) {
  52. out << "!!";
  53. }
  54. PrintValue(values_[a.index], out);
  55. }
  56. } // namespace Carbon