heap.cpp 1.9 KB

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