name_scope.h 7.6 KB

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