name_scope.h 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 that is known to not exist. The new entry is not allowed to
  54. // be poisoned. An existing poisoned entry can be overwritten.
  55. auto AddRequired(Entry name_entry) -> void;
  56. // Searches for the given name. If found, including if a poisoned entry is
  57. // found, returns true with the existing EntryId. Otherwise, adds the name
  58. // using inst_id and access_kind and returns false with the new EntryId.
  59. //
  60. // This cannot be used to add poisoned entries; use LookupOrPoison instead.
  61. auto LookupOrAdd(SemIR::NameId name_id, InstId inst_id,
  62. AccessKind access_kind) -> std::pair<bool, EntryId>;
  63. // Searches for the given name. If found, including if a poisoned entry is
  64. // found, returns the corresponding EntryId. Otherwise, returns nullopt and
  65. // poisons the name so it can't be declared later.
  66. auto LookupOrPoison(NameId name_id) -> std::optional<EntryId>;
  67. auto extended_scopes() const -> llvm::ArrayRef<InstId> {
  68. return extended_scopes_;
  69. }
  70. auto AddExtendedScope(SemIR::InstId extended_scope) -> void {
  71. extended_scopes_.push_back(extended_scope);
  72. }
  73. auto inst_id() const -> InstId { return inst_id_; }
  74. auto name_id() const -> NameId { return name_id_; }
  75. auto parent_scope_id() const -> NameScopeId { return parent_scope_id_; }
  76. auto has_error() const -> bool { return has_error_; }
  77. // Mark that we have diagnosed an error in a construct that would have added
  78. // names to this scope.
  79. auto set_has_error() -> void { has_error_ = true; }
  80. auto is_closed_import() const -> bool { return is_closed_import_; }
  81. auto set_is_closed_import(bool is_closed_import) -> void {
  82. is_closed_import_ = is_closed_import;
  83. }
  84. // Returns true if this name scope describes an imported package.
  85. auto is_imported_package() const -> bool {
  86. return is_closed_import() && parent_scope_id() == NameScopeId::Package;
  87. }
  88. auto import_ir_scopes() const
  89. -> llvm::ArrayRef<std::pair<SemIR::ImportIRId, SemIR::NameScopeId>> {
  90. return import_ir_scopes_;
  91. }
  92. auto AddImportIRScope(
  93. const std::pair<SemIR::ImportIRId, SemIR::NameScopeId>& import_ir_scope)
  94. -> void {
  95. import_ir_scopes_.push_back(import_ir_scope);
  96. }
  97. private:
  98. // Names in the scope, including poisoned names.
  99. //
  100. // Entries could become invalidated if the scope object is invalidated or if a
  101. // name is added.
  102. //
  103. // We store both an insertion-ordered vector for iterating
  104. // and a map from `NameId` to the index of that vector for name lookup.
  105. //
  106. // Optimization notes: this is somewhat memory inefficient. If this ends up
  107. // either hot or a significant source of memory allocation, we should consider
  108. // switching to a SOA model where the `AccessKind` is stored in a separate
  109. // vector so that these can pack densely. If this ends up both cold and memory
  110. // intensive, we can also switch the lookup to a set of indices into the
  111. // vector rather than a map from `NameId` to index.
  112. llvm::SmallVector<Entry> names_;
  113. Map<NameId, EntryId> name_map_;
  114. // Instructions returning values that are extended by this scope.
  115. //
  116. // Small vector size is set to 1: we expect that there will rarely be more
  117. // than a single extended scope.
  118. // TODO: Revisit this once we have more kinds of extended scope and data.
  119. // TODO: Consider using something like `TinyPtrVector` for this.
  120. llvm::SmallVector<InstId, 1> extended_scopes_;
  121. // The instruction which owns the scope.
  122. InstId inst_id_;
  123. // When the scope is a namespace, the name. Otherwise, invalid.
  124. NameId name_id_;
  125. // The parent scope.
  126. NameScopeId parent_scope_id_;
  127. // Whether we have diagnosed an error in a construct that would have added
  128. // names to this scope. For example, this can happen if an `import` failed or
  129. // an `extend` declaration was ill-formed. If true, names are assumed to be
  130. // missing as a result of the error, and no further errors are produced for
  131. // lookup failures in this scope.
  132. bool has_error_ = false;
  133. // True if this is a closed namespace created by importing a package.
  134. bool is_closed_import_ = false;
  135. // Imported IR scopes that compose this namespace. This will be empty for
  136. // scopes that correspond to the current package.
  137. llvm::SmallVector<std::pair<SemIR::ImportIRId, SemIR::NameScopeId>, 0>
  138. import_ir_scopes_;
  139. };
  140. // Provides a ValueStore wrapper for an API specific to name scopes.
  141. class NameScopeStore {
  142. public:
  143. explicit NameScopeStore(const File* file) : file_(file) {}
  144. // Adds a name scope, returning an ID to reference it.
  145. auto Add(InstId inst_id, NameId name_id, NameScopeId parent_scope_id)
  146. -> NameScopeId {
  147. return values_.Add(NameScope(inst_id, name_id, parent_scope_id));
  148. }
  149. // Adds a name that is required to exist in a name scope, such as `Self`.
  150. // The name must never conflict. inst_id must not be poisoned.
  151. auto AddRequiredName(NameScopeId scope_id, NameId name_id, InstId inst_id)
  152. -> void {
  153. Get(scope_id).AddRequired({.name_id = name_id,
  154. .inst_id = inst_id,
  155. .access_kind = AccessKind::Public});
  156. }
  157. // Returns the requested name scope.
  158. auto Get(NameScopeId scope_id) -> NameScope& { return values_.Get(scope_id); }
  159. // Returns the requested name scope.
  160. auto Get(NameScopeId scope_id) const -> const NameScope& {
  161. return values_.Get(scope_id);
  162. }
  163. // Returns the instruction owning the requested name scope, or Invalid with
  164. // nullopt if the scope is either invalid or has no associated instruction.
  165. auto GetInstIfValid(NameScopeId scope_id) const
  166. -> std::pair<InstId, std::optional<Inst>>;
  167. // Returns whether the provided scope ID is for a package scope.
  168. auto IsPackage(NameScopeId scope_id) const -> bool {
  169. if (!scope_id.is_valid()) {
  170. return false;
  171. }
  172. // A package is either the current package or an imported package.
  173. return scope_id == SemIR::NameScopeId::Package ||
  174. Get(scope_id).is_imported_package();
  175. }
  176. // Returns whether the provided scope ID is for the Core package.
  177. auto IsCorePackage(NameScopeId scope_id) const -> bool;
  178. auto OutputYaml() const -> Yaml::OutputMapping {
  179. return values_.OutputYaml();
  180. }
  181. // Collects memory usage of members.
  182. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  183. -> void {
  184. mem_usage.Collect(std::string(label), values_);
  185. }
  186. private:
  187. const File* file_;
  188. ValueStore<NameScopeId> values_;
  189. };
  190. } // namespace Carbon::SemIR
  191. #endif // CARBON_TOOLCHAIN_SEM_IR_NAME_SCOPE_H_