name_scope.h 7.9 KB

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