name_scope.h 13 KB

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