entity_name.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 CARBON_TOOLCHAIN_SEM_IR_ENTITY_NAME_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_ENTITY_NAME_H_
  6. #include "common/hashing.h"
  7. #include "common/set.h"
  8. #include "toolchain/base/value_store.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. namespace Carbon::SemIR {
  11. struct EntityName : public Printable<EntityName> {
  12. auto Print(llvm::raw_ostream& out) const -> void {
  13. out << "{name: " << name_id << ", parent_scope: " << parent_scope_id
  14. << ", index: " << bind_index << "}";
  15. }
  16. friend auto CarbonHashtableEq(const EntityName& lhs, const EntityName& rhs)
  17. -> bool {
  18. return std::memcmp(&lhs, &rhs, sizeof(EntityName)) == 0;
  19. }
  20. // The name.
  21. NameId name_id;
  22. // The parent scope.
  23. NameScopeId parent_scope_id;
  24. // The index for a compile-time binding. Invalid for a runtime binding.
  25. CompileTimeBindIndex bind_index;
  26. };
  27. // Hashing for EntityName. See common/hashing.h.
  28. inline auto CarbonHashValue(const EntityName& value, uint64_t seed)
  29. -> HashCode {
  30. Hasher hasher(seed);
  31. hasher.HashRaw(value);
  32. return static_cast<HashCode>(hasher);
  33. }
  34. // Value store for EntityName. In addition to the regular ValueStore
  35. // functionality, this can provide optional canonical IDs for EntityNames.
  36. struct EntityNameStore : public ValueStore<EntityNameId> {
  37. public:
  38. // Convert an ID to a canonical ID. All calls to this with equivalent
  39. // `EntityName`s will return the same `EntityNameId`.
  40. auto MakeCanonical(EntityNameId id) -> EntityNameId;
  41. private:
  42. class KeyContext;
  43. Set<EntityNameId, /*SmallSize=*/0, KeyContext> canonical_ids_;
  44. };
  45. class EntityNameStore::KeyContext : public TranslatingKeyContext<KeyContext> {
  46. public:
  47. explicit KeyContext(const EntityNameStore* store) : store_(store) {}
  48. // Note that it is safe to return a `const` reference here as the underlying
  49. // object's lifetime is provided by the `store_`.
  50. auto TranslateKey(EntityNameId id) const -> const EntityName& {
  51. return store_->Get(id);
  52. }
  53. private:
  54. const EntityNameStore* store_;
  55. };
  56. inline auto EntityNameStore::MakeCanonical(EntityNameId id) -> EntityNameId {
  57. return canonical_ids_.Insert(id, KeyContext(this)).key();
  58. }
  59. } // namespace Carbon::SemIR
  60. #endif // CARBON_TOOLCHAIN_SEM_IR_ENTITY_NAME_H_