name_scope.h 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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_NAME_SCOPE_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_NAME_SCOPE_H_
  6. #include "common/map.h"
  7. #include "toolchain/sem_ir/ids.h"
  8. #include "toolchain/sem_ir/inst.h"
  9. namespace Carbon::SemIR {
  10. // Access control for an entity.
  11. enum class AccessKind : int8_t {
  12. Public,
  13. Protected,
  14. Private,
  15. };
  16. class NameScope : public Printable<NameScope> {
  17. public:
  18. struct Entry {
  19. NameId name_id;
  20. InstId inst_id;
  21. AccessKind access_kind;
  22. bool is_poisoned = false;
  23. };
  24. static_assert(sizeof(Entry) == 12);
  25. struct EntryId : public IdBase<EntryId> {
  26. static constexpr llvm::StringLiteral Label = "name_scope_entry";
  27. using IdBase::IdBase;
  28. };
  29. explicit NameScope(InstId inst_id, NameId name_id,
  30. NameScopeId parent_scope_id)
  31. : inst_id_(inst_id),
  32. name_id_(name_id),
  33. parent_scope_id_(parent_scope_id) {}
  34. auto Print(llvm::raw_ostream& out) const -> void;
  35. auto entries() const -> llvm::ArrayRef<Entry> { return names_; }
  36. // Get a specific Name entry based on an EntryId that return from a lookup.
  37. //
  38. // The Entry could become invalidated if the scope object is invalidated or if
  39. // a name is added.
  40. auto GetEntry(EntryId entry_id) const -> const Entry& {
  41. return names_[entry_id.index];
  42. }
  43. auto GetEntry(EntryId entry_id) -> Entry& { return names_[entry_id.index]; }
  44. // Searches for the given name and returns an EntryId if found or nullopt if
  45. // not. The returned entry may be poisoned.
  46. auto Lookup(NameId name_id) const -> std::optional<EntryId> {
  47. auto lookup = name_map_.Lookup(name_id);
  48. if (!lookup) {
  49. return std::nullopt;
  50. }
  51. return lookup.value();
  52. }
  53. // Adds a new name known to not exist. Must not be poisoned.
  54. auto AddRequired(Entry name_entry) -> void;
  55. // If the given name already exists, return true with the EntryId; the entry
  56. // might be poisoned. Otherwise, adds the name using inst_id and access_kind
  57. // and returns false with the new EntryId.
  58. //
  59. // This cannot be used to add poisoned entries; use AddPoison instead.
  60. auto LookupOrAdd(SemIR::NameId name_id, InstId inst_id,
  61. AccessKind access_kind) -> std::pair<bool, EntryId>;
  62. // Adds a new poisoned name.
  63. auto AddPoison(NameId name_id) -> void;
  64. auto extended_scopes() const -> llvm::ArrayRef<InstId> {
  65. return extended_scopes_;
  66. }
  67. auto AddExtendedScope(SemIR::InstId extended_scope) -> void {
  68. extended_scopes_.push_back(extended_scope);
  69. }
  70. auto inst_id() const -> InstId { return inst_id_; }
  71. auto name_id() const -> NameId { return name_id_; }
  72. auto parent_scope_id() const -> NameScopeId { return parent_scope_id_; }
  73. auto has_error() const -> bool { return has_error_; }
  74. // Mark that we have diagnosed an error in a construct that would have added
  75. // names to this scope.
  76. auto set_has_error() -> void { has_error_ = true; }
  77. auto is_closed_import() const -> bool { return is_closed_import_; }
  78. auto set_is_closed_import(bool is_closed_import) -> void {
  79. is_closed_import_ = is_closed_import;
  80. }
  81. // Returns true if this name scope describes an imported package.
  82. auto is_imported_package() const -> bool {
  83. return is_closed_import() && parent_scope_id() == NameScopeId::Package;
  84. }
  85. auto import_ir_scopes() const
  86. -> llvm::ArrayRef<std::pair<SemIR::ImportIRId, SemIR::NameScopeId>> {
  87. return import_ir_scopes_;
  88. }
  89. auto AddImportIRScope(
  90. const std::pair<SemIR::ImportIRId, SemIR::NameScopeId>& import_ir_scope)
  91. -> void {
  92. import_ir_scopes_.push_back(import_ir_scope);
  93. }
  94. private:
  95. // Names in the scope, including poisoned names.
  96. //
  97. // Entries could become invalidated if the scope object is invalidated or if a
  98. // name is added.
  99. //
  100. // We store both an insertion-ordered vector for iterating
  101. // and a map from `NameId` to the index of that vector for name lookup.
  102. //
  103. // Optimization notes: this is somewhat memory inefficient. If this ends up
  104. // either hot or a significant source of memory allocation, we should consider
  105. // switching to a SOA model where the `AccessKind` is stored in a separate
  106. // vector so that these can pack densely. If this ends up both cold and memory
  107. // intensive, we can also switch the lookup to a set of indices into the
  108. // vector rather than a map from `NameId` to index.
  109. llvm::SmallVector<Entry> names_;
  110. Map<NameId, EntryId> name_map_;
  111. // Instructions returning values that are extended by this scope.
  112. //
  113. // Small vector size is set to 1: we expect that there will rarely be more
  114. // than a single extended scope.
  115. // TODO: Revisit this once we have more kinds of extended scope and data.
  116. // TODO: Consider using something like `TinyPtrVector` for this.
  117. llvm::SmallVector<InstId, 1> extended_scopes_;
  118. // The instruction which owns the scope.
  119. InstId inst_id_;
  120. // When the scope is a namespace, the name. Otherwise, invalid.
  121. NameId name_id_;
  122. // The parent scope.
  123. NameScopeId parent_scope_id_;
  124. // Whether we have diagnosed an error in a construct that would have added
  125. // names to this scope. For example, this can happen if an `import` failed or
  126. // an `extend` declaration was ill-formed. If true, names are assumed to be
  127. // missing as a result of the error, and no further errors are produced for
  128. // lookup failures in this scope.
  129. bool has_error_ = false;
  130. // True if this is a closed namespace created by importing a package.
  131. bool is_closed_import_ = false;
  132. // Imported IR scopes that compose this namespace. This will be empty for
  133. // scopes that correspond to the current package.
  134. llvm::SmallVector<std::pair<SemIR::ImportIRId, SemIR::NameScopeId>, 0>
  135. import_ir_scopes_;
  136. };
  137. // Provides a ValueStore wrapper for an API specific to name scopes.
  138. class NameScopeStore {
  139. public:
  140. explicit NameScopeStore(const File* file) : file_(file) {}
  141. // Adds a name scope, returning an ID to reference it.
  142. auto Add(InstId inst_id, NameId name_id, NameScopeId parent_scope_id)
  143. -> NameScopeId {
  144. return values_.Add(NameScope(inst_id, name_id, parent_scope_id));
  145. }
  146. // Adds a name that is required to exist in a name scope, such as `Self`.
  147. // The name must never conflict. inst_id must not be poisoned.
  148. auto AddRequiredName(NameScopeId scope_id, NameId name_id, InstId inst_id)
  149. -> void {
  150. Get(scope_id).AddRequired({.name_id = name_id,
  151. .inst_id = inst_id,
  152. .access_kind = AccessKind::Public});
  153. }
  154. // Returns the requested name scope.
  155. auto Get(NameScopeId scope_id) -> NameScope& { return values_.Get(scope_id); }
  156. // Returns the requested name scope.
  157. auto Get(NameScopeId scope_id) const -> const NameScope& {
  158. return values_.Get(scope_id);
  159. }
  160. // Returns the instruction owning the requested name scope, or Invalid with
  161. // nullopt if the scope is either invalid or has no associated instruction.
  162. auto GetInstIfValid(NameScopeId scope_id) const
  163. -> std::pair<InstId, std::optional<Inst>>;
  164. // Returns whether the provided scope ID is for a package scope.
  165. auto IsPackage(NameScopeId scope_id) const -> bool {
  166. if (!scope_id.is_valid()) {
  167. return false;
  168. }
  169. // A package is either the current package or an imported package.
  170. return scope_id == SemIR::NameScopeId::Package ||
  171. Get(scope_id).is_imported_package();
  172. }
  173. // Returns whether the provided scope ID is for the Core package.
  174. auto IsCorePackage(NameScopeId scope_id) const -> bool;
  175. auto OutputYaml() const -> Yaml::OutputMapping {
  176. return values_.OutputYaml();
  177. }
  178. // Collects memory usage of members.
  179. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  180. -> void {
  181. mem_usage.Collect(std::string(label), values_);
  182. }
  183. private:
  184. const File* file_;
  185. ValueStore<NameScopeId> values_;
  186. };
  187. } // namespace Carbon::SemIR
  188. #endif // CARBON_TOOLCHAIN_SEM_IR_NAME_SCOPE_H_