entity_name.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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, or
  25. // for a symbolic binding, like `.Self`, that does not correspond to a generic
  26. // parameter (and therefore has no index).
  27. CompileTimeBindIndex bind_index;
  28. };
  29. // Hashing for EntityName. See common/hashing.h.
  30. inline auto CarbonHashValue(const EntityName& value, uint64_t seed)
  31. -> HashCode {
  32. Hasher hasher(seed);
  33. hasher.HashRaw(value);
  34. return static_cast<HashCode>(hasher);
  35. }
  36. // Value store for EntityName. In addition to the regular ValueStore
  37. // functionality, this can provide optional canonical IDs for EntityNames.
  38. struct EntityNameStore : public ValueStore<EntityNameId> {
  39. public:
  40. // Convert an ID to a canonical ID. All calls to this with equivalent
  41. // `EntityName`s will return the same `EntityNameId`.
  42. auto MakeCanonical(EntityNameId id) -> EntityNameId;
  43. private:
  44. class KeyContext;
  45. Set<EntityNameId, /*SmallSize=*/0, KeyContext> canonical_ids_;
  46. };
  47. class EntityNameStore::KeyContext : public TranslatingKeyContext<KeyContext> {
  48. public:
  49. explicit KeyContext(const EntityNameStore* store) : store_(store) {}
  50. // Note that it is safe to return a `const` reference here as the underlying
  51. // object's lifetime is provided by the `store_`.
  52. auto TranslateKey(EntityNameId id) const -> const EntityName& {
  53. return store_->Get(id);
  54. }
  55. private:
  56. const EntityNameStore* store_;
  57. };
  58. inline auto EntityNameStore::MakeCanonical(EntityNameId id) -> EntityNameId {
  59. return canonical_ids_.Insert(id, KeyContext(this)).key();
  60. }
  61. } // namespace Carbon::SemIR
  62. #endif // CARBON_TOOLCHAIN_SEM_IR_ENTITY_NAME_H_