name_scope.h 14 KB

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