name_scope.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. // Represents the result of a name lookup.
  17. //
  18. // Lookup results are constructed through the `Make()` factory functions. Each
  19. // result takes one of a few forms, depending on the function used:
  20. // - Found when the lookup was successful returning an existing `InstId`. Can be
  21. // constructed using `MakeFound()` or `MakeWrappedLookupResult()` with an
  22. // existing `inst_id`.
  23. // - Not found when the name wasn't declared or nor poisoned. Can be constructed
  24. // using `MakeNotFound()` or using `MakeWrappedLookupResult()` with a `None`
  25. // `inst_id`.
  26. // - Poisoned when the name wasn't declared but was poisoned and so also
  27. // considered to not be found in that scope. Can be constructed using
  28. // `MakePoisoned()`.
  29. // - Represent that an error has occurred during lookup. This is still
  30. // considered found and the error `InstId` is considered existing. Can be
  31. // constructed using `MakeError()` or using `MakeWrappedLookupResult()` with
  32. // `ErrorInst::SingletonInstId`.
  33. class ScopeLookupResult {
  34. public:
  35. static auto MakeFound(InstId inst_id, AccessKind access_kind)
  36. -> ScopeLookupResult {
  37. CARBON_CHECK(inst_id.has_value());
  38. return MakeWrappedLookupResult(inst_id, access_kind);
  39. }
  40. static auto MakeNotFound() -> ScopeLookupResult {
  41. return MakeWrappedLookupResult(InstId::None, AccessKind::Public);
  42. }
  43. static auto MakePoisoned() -> ScopeLookupResult {
  44. return ScopeLookupResult(InstId::None, AccessKind::Public,
  45. /*is_poisoned=*/true);
  46. }
  47. static auto MakeError() -> ScopeLookupResult {
  48. return MakeFound(ErrorInst::SingletonInstId, AccessKind::Public);
  49. }
  50. static auto MakeWrappedLookupResult(InstId inst_id, AccessKind access_kind)
  51. -> ScopeLookupResult {
  52. return ScopeLookupResult(inst_id, access_kind, /*is_poisoned=*/false);
  53. }
  54. // True iff CreatePoisoned() was used.
  55. auto is_poisoned() const -> bool { return is_poisoned_; }
  56. // True when lookup was successful or resulted with an error. False for
  57. // poisoned or not found.
  58. auto is_found() const -> bool {
  59. return !is_poisoned() && inst_id_.has_value();
  60. }
  61. // The `InstId` of the result of the lookup. Must only be called when lookup
  62. // was successful e.g. `is_found()` returns true. Always returns an existing
  63. // `InstId`.
  64. auto target_inst_id() const -> InstId {
  65. CARBON_CHECK(is_found());
  66. return inst_id_;
  67. }
  68. auto access_kind() const -> AccessKind { return access_kind_; }
  69. // Equality means either:
  70. // - Both are not poisoned and have the same `InstId` and `AccessKind`.
  71. // - Both are poisoned.
  72. friend auto operator==(const ScopeLookupResult&, const ScopeLookupResult&)
  73. -> bool = default;
  74. private:
  75. explicit ScopeLookupResult(InstId inst_id, AccessKind access_kind,
  76. bool is_poisoned)
  77. : inst_id_(inst_id),
  78. access_kind_(access_kind),
  79. is_poisoned_(is_poisoned) {}
  80. InstId inst_id_;
  81. AccessKind access_kind_;
  82. bool is_poisoned_;
  83. };
  84. static_assert(sizeof(ScopeLookupResult) == 8);
  85. class NameScope : public Printable<NameScope> {
  86. public:
  87. struct Entry {
  88. NameId name_id;
  89. ScopeLookupResult result;
  90. // Equality means they have the same `name_id` and equal `result`.
  91. friend auto operator==(const Entry&, const Entry&) -> bool = default;
  92. };
  93. static_assert(sizeof(Entry) == 12);
  94. struct EntryId : public IdBase<EntryId> {
  95. static constexpr llvm::StringLiteral Label = "name_scope_entry";
  96. using IdBase::IdBase;
  97. };
  98. explicit NameScope(InstId inst_id, NameId name_id,
  99. NameScopeId parent_scope_id)
  100. : inst_id_(inst_id),
  101. name_id_(name_id),
  102. parent_scope_id_(parent_scope_id) {}
  103. auto Print(llvm::raw_ostream& out) const -> void;
  104. auto entries() const -> llvm::ArrayRef<Entry> { return names_; }
  105. // Get a specific Name entry based on an EntryId that return from a lookup.
  106. //
  107. // The Entry could become invalidated if the scope object is invalidated or if
  108. // a name is added.
  109. auto GetEntry(EntryId entry_id) const -> const Entry& {
  110. return names_[entry_id.index];
  111. }
  112. auto GetEntry(EntryId entry_id) -> Entry& { return names_[entry_id.index]; }
  113. // Searches for the given name and returns an EntryId if found or nullopt if
  114. // not. The returned entry may be poisoned.
  115. auto Lookup(NameId name_id) const -> std::optional<EntryId> {
  116. auto lookup = name_map_.Lookup(name_id);
  117. if (!lookup) {
  118. return std::nullopt;
  119. }
  120. return lookup.value();
  121. }
  122. // Adds a new name that is known to not exist. The new entry is not allowed to
  123. // be poisoned. An existing poisoned entry can be overwritten.
  124. auto AddRequired(Entry name_entry) -> void;
  125. // Searches for the given name. If found, including if a poisoned entry is
  126. // found, returns true with the existing EntryId. Otherwise, adds the name
  127. // using inst_id and access_kind and returns false with the new EntryId.
  128. //
  129. // This cannot be used to add poisoned entries; use LookupOrPoison instead.
  130. auto LookupOrAdd(NameId name_id, InstId inst_id, AccessKind access_kind)
  131. -> std::pair<bool, EntryId>;
  132. // Searches for the given name. If found, including if a poisoned entry is
  133. // found, returns the corresponding EntryId. Otherwise, returns nullopt and
  134. // poisons the name so it can't be declared later.
  135. auto LookupOrPoison(NameId name_id) -> std::optional<EntryId>;
  136. auto extended_scopes() const -> llvm::ArrayRef<InstId> {
  137. return extended_scopes_;
  138. }
  139. auto AddExtendedScope(InstId extended_scope) -> void {
  140. extended_scopes_.push_back(extended_scope);
  141. }
  142. auto inst_id() const -> InstId { return inst_id_; }
  143. auto name_id() const -> NameId { return name_id_; }
  144. auto parent_scope_id() const -> NameScopeId { return parent_scope_id_; }
  145. auto has_error() const -> bool { return has_error_; }
  146. // Mark that we have diagnosed an error in a construct that would have added
  147. // names to this scope.
  148. auto set_has_error() -> void { has_error_ = true; }
  149. auto is_closed_import() const -> bool { return is_closed_import_; }
  150. auto set_is_closed_import(bool is_closed_import) -> void {
  151. is_closed_import_ = is_closed_import;
  152. }
  153. // Returns true if this name scope describes an imported package.
  154. auto is_imported_package() const -> bool {
  155. return is_closed_import() && parent_scope_id() == NameScopeId::Package;
  156. }
  157. auto import_ir_scopes() const
  158. -> llvm::ArrayRef<std::pair<ImportIRId, NameScopeId>> {
  159. return import_ir_scopes_;
  160. }
  161. auto AddImportIRScope(
  162. const std::pair<ImportIRId, NameScopeId>& import_ir_scope) -> void {
  163. import_ir_scopes_.push_back(import_ir_scope);
  164. }
  165. private:
  166. // Names in the scope, including poisoned names.
  167. //
  168. // Entries could become invalidated if the scope object is invalidated or if a
  169. // name is added.
  170. //
  171. // We store both an insertion-ordered vector for iterating
  172. // and a map from `NameId` to the index of that vector for name lookup.
  173. //
  174. // Optimization notes: this is somewhat memory inefficient. If this ends up
  175. // either hot or a significant source of memory allocation, we should consider
  176. // switching to a SOA model where the `AccessKind` is stored in a separate
  177. // vector so that these can pack densely. If this ends up both cold and memory
  178. // intensive, we can also switch the lookup to a set of indices into the
  179. // vector rather than a map from `NameId` to index.
  180. llvm::SmallVector<Entry> names_;
  181. Map<NameId, EntryId> name_map_;
  182. // Instructions returning values that are extended by this scope.
  183. //
  184. // Small vector size is set to 1: we expect that there will rarely be more
  185. // than a single extended scope.
  186. // TODO: Revisit this once we have more kinds of extended scope and data.
  187. // TODO: Consider using something like `TinyPtrVector` for this.
  188. llvm::SmallVector<InstId, 1> extended_scopes_;
  189. // The instruction which owns the scope.
  190. InstId inst_id_;
  191. // When the scope is a namespace, the name. Otherwise, `None`.
  192. NameId name_id_;
  193. // The parent scope.
  194. NameScopeId parent_scope_id_;
  195. // Whether we have diagnosed an error in a construct that would have added
  196. // names to this scope. For example, this can happen if an `import` failed or
  197. // an `extend` declaration was ill-formed. If true, names are assumed to be
  198. // missing as a result of the error, and no further errors are produced for
  199. // lookup failures in this scope.
  200. bool has_error_ = false;
  201. // True if this is a closed namespace created by importing a package.
  202. bool is_closed_import_ = false;
  203. // Imported IR scopes that compose this namespace. This will be empty for
  204. // scopes that correspond to the current package.
  205. llvm::SmallVector<std::pair<ImportIRId, NameScopeId>, 0> import_ir_scopes_;
  206. };
  207. // Provides a ValueStore wrapper for an API specific to name scopes.
  208. class NameScopeStore {
  209. public:
  210. explicit NameScopeStore(const File* file) : file_(file) {}
  211. // Adds a name scope, returning an ID to reference it.
  212. auto Add(InstId inst_id, NameId name_id, NameScopeId parent_scope_id)
  213. -> NameScopeId {
  214. return values_.Add(NameScope(inst_id, name_id, parent_scope_id));
  215. }
  216. // Adds a name that is required to exist in a name scope, such as `Self`.
  217. // The name must never conflict.
  218. auto AddRequiredName(NameScopeId scope_id, NameId name_id, InstId inst_id)
  219. -> void {
  220. Get(scope_id).AddRequired(
  221. {.name_id = name_id,
  222. .result = ScopeLookupResult::MakeFound(inst_id, AccessKind::Public)});
  223. }
  224. // Returns the requested name scope.
  225. auto Get(NameScopeId scope_id) -> NameScope& { return values_.Get(scope_id); }
  226. // Returns the requested name scope.
  227. auto Get(NameScopeId scope_id) const -> const NameScope& {
  228. return values_.Get(scope_id);
  229. }
  230. // Returns the instruction owning the requested name scope, or `None` with
  231. // nullopt if the scope is either `None` or has no associated instruction.
  232. auto GetInstIfValid(NameScopeId scope_id) const
  233. -> std::pair<InstId, std::optional<Inst>>;
  234. // Returns whether the provided scope ID is for a package scope.
  235. auto IsPackage(NameScopeId scope_id) const -> bool {
  236. if (!scope_id.has_value()) {
  237. return false;
  238. }
  239. // A package is either the current package or an imported package.
  240. return scope_id == NameScopeId::Package ||
  241. Get(scope_id).is_imported_package();
  242. }
  243. // Returns whether the provided scope ID is for the Core package.
  244. auto IsCorePackage(NameScopeId scope_id) const -> bool;
  245. auto OutputYaml() const -> Yaml::OutputMapping {
  246. return values_.OutputYaml();
  247. }
  248. // Collects memory usage of members.
  249. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  250. -> void {
  251. mem_usage.Collect(std::string(label), values_);
  252. }
  253. private:
  254. const File* file_;
  255. ValueStore<NameScopeId> values_;
  256. };
  257. } // namespace Carbon::SemIR
  258. #endif // CARBON_TOOLCHAIN_SEM_IR_NAME_SCOPE_H_