name_scope.h 12 KB

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