address.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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_ADDRESS_H_
  5. #define EXECUTABLE_SEMANTICS_INTERPRETER_ADDRESS_H_
  6. #include <cstdint>
  7. #include <iostream>
  8. #include <string>
  9. #include <vector>
  10. #include "executable_semantics/interpreter/field_path.h"
  11. namespace Carbon {
  12. // An Address represents a memory address in the Carbon virtual machine.
  13. // Addresses are used to access values stored in a Heap, and are obtained
  14. // from a Heap (or by deriving them from other Addresses).
  15. class Address {
  16. public:
  17. Address(const Address&) = default;
  18. Address(Address&&) = default;
  19. auto operator=(const Address&) -> Address& = default;
  20. auto operator=(Address&&) -> Address& = default;
  21. // Returns true if the two addresses refer to the same memory location.
  22. friend auto operator==(const Address& lhs, const Address& rhs) -> bool {
  23. return lhs.index == rhs.index;
  24. }
  25. friend auto operator!=(const Address& lhs, const Address& rhs) -> bool {
  26. return !(lhs == rhs);
  27. }
  28. // Prints a human-readable representation of `a` to `out`.
  29. //
  30. // Currently, that representation consists of an integer index identifying
  31. // the whole memory allocation, and an optional FieldPath specifying a
  32. // particular field within that allocation.
  33. friend auto operator<<(std::ostream& out, const Address& a) -> std::ostream& {
  34. out << "Address(" << a.index << ")" << a.field_path;
  35. return out;
  36. }
  37. // If *this represents the address of an object with a field named
  38. // `field_name`, this method returns the address of that field.
  39. auto SubobjectAddress(std::string field_name) const -> Address {
  40. Address result = *this;
  41. result.field_path.Append(std::move(field_name));
  42. return result;
  43. }
  44. private:
  45. // The representation of Address describes how to locate an object within
  46. // the Heap, so its implementation details are tied to the implementation
  47. // details of the Heap.
  48. friend class Heap;
  49. explicit Address(uint64_t index) : index(index) {}
  50. uint64_t index;
  51. FieldPath field_path;
  52. };
  53. } // namespace Carbon
  54. #endif // EXECUTABLE_SEMANTICS_INTERPRETER_ADDRESS_H_