name_scope.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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) -> 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 inst_id() const -> InstId { return inst_id_; }
  166. auto name_id() const -> NameId { return name_id_; }
  167. auto parent_scope_id() const -> NameScopeId { return parent_scope_id_; }
  168. auto has_error() const -> bool { return has_error_; }
  169. // Mark that we have diagnosed an error in a construct that would have added
  170. // names to this scope.
  171. auto set_has_error() -> void { has_error_ = true; }
  172. auto is_closed_import() const -> bool { return is_closed_import_; }
  173. auto set_is_closed_import(bool is_closed_import) -> void {
  174. is_closed_import_ = is_closed_import;
  175. }
  176. auto is_cpp_scope() const -> bool { return cpp_decl_context(); }
  177. auto cpp_decl_context() const -> const clang::DeclContext* {
  178. return cpp_decl_context_;
  179. }
  180. auto cpp_decl_context() -> clang::DeclContext* { return cpp_decl_context_; }
  181. auto set_cpp_decl_context(clang::DeclContext* cpp_decl_context) -> void {
  182. cpp_decl_context_ = cpp_decl_context;
  183. }
  184. // Returns true if this name scope describes an imported package.
  185. auto is_imported_package() const -> bool {
  186. return is_closed_import() && parent_scope_id() == NameScopeId::Package;
  187. }
  188. auto import_ir_scopes() const
  189. -> llvm::ArrayRef<std::pair<ImportIRId, NameScopeId>> {
  190. return import_ir_scopes_;
  191. }
  192. auto AddImportIRScope(
  193. const std::pair<ImportIRId, NameScopeId>& import_ir_scope) -> void {
  194. import_ir_scopes_.push_back(import_ir_scope);
  195. }
  196. auto is_interface_definition() const -> bool {
  197. return is_interface_definition_;
  198. }
  199. // TODO: Figure out a better way of setting this and is_cpp_scope() than
  200. // calling a function immediately after construction.
  201. auto set_is_interface_definition() -> void {
  202. is_interface_definition_ = true;
  203. }
  204. private:
  205. // Names in the scope, including poisoned names.
  206. //
  207. // Entries could become invalidated if the scope object is invalidated or if a
  208. // name is added.
  209. //
  210. // We store both an insertion-ordered vector for iterating
  211. // and a map from `NameId` to the index of that vector for name lookup.
  212. //
  213. // Optimization notes: this is somewhat memory inefficient. If this ends up
  214. // either hot or a significant source of memory allocation, we should consider
  215. // switching to a SOA model where the `AccessKind` is stored in a separate
  216. // vector so that these can pack densely. If this ends up both cold and memory
  217. // intensive, we can also switch the lookup to a set of indices into the
  218. // vector rather than a map from `NameId` to index.
  219. llvm::SmallVector<Entry> names_;
  220. Map<NameId, EntryId> name_map_;
  221. // Instructions returning values that are extended by this scope.
  222. //
  223. // Small vector size is set to 1: we expect that there will rarely be more
  224. // than a single extended scope.
  225. // TODO: Revisit this once we have more kinds of extended scope and data.
  226. // TODO: Consider using something like `TinyPtrVector` for this.
  227. llvm::SmallVector<InstId, 1> extended_scopes_;
  228. // The instruction which owns the scope.
  229. InstId inst_id_;
  230. // When the scope is a namespace, the name. Otherwise, `None`.
  231. NameId name_id_;
  232. // The parent scope.
  233. NameScopeId parent_scope_id_;
  234. // Whether we have diagnosed an error in a construct that would have added
  235. // names to this scope. For example, this can happen if an `import` failed or
  236. // an `extend` declaration was ill-formed. If true, names are assumed to be
  237. // missing as a result of the error, and no further errors are produced for
  238. // lookup failures in this scope.
  239. bool has_error_ = false;
  240. // True if this is a closed namespace created by importing a package.
  241. bool is_closed_import_ = false;
  242. // Set if this is the `Cpp` scope or a scope inside `Cpp`. Points to the
  243. // matching Clang declaration context to look for names. This is mutable since
  244. // `clang::Sema::LookupQualifiedName()` requires a mutable `DeclContext`.
  245. // TODO: Ensure we can easily serialize/deserialize this. Consider decl ID to
  246. // point into the AST. This is related to:
  247. // https://github.com/carbon-language/carbon-lang/issues/4666.
  248. clang::DeclContext* cpp_decl_context_ = nullptr;
  249. // True if this is the scope of an interface definition, where associated
  250. // entities will be bound to the interface's `Self` symbolic type.
  251. bool is_interface_definition_ = false;
  252. // Imported IR scopes that compose this namespace. This will be empty for
  253. // scopes that correspond to the current package.
  254. llvm::SmallVector<std::pair<ImportIRId, NameScopeId>, 0> import_ir_scopes_;
  255. };
  256. // Provides a ValueStore wrapper for an API specific to name scopes.
  257. class NameScopeStore {
  258. public:
  259. explicit NameScopeStore(const File* file) : file_(file) {}
  260. // Adds a name scope, returning an ID to reference it.
  261. auto Add(InstId inst_id, NameId name_id, NameScopeId parent_scope_id)
  262. -> NameScopeId {
  263. return values_.Add(NameScope(inst_id, name_id, parent_scope_id));
  264. }
  265. // Adds a name that is required to exist in a name scope, such as `Self`.
  266. // The name must never conflict.
  267. auto AddRequiredName(NameScopeId scope_id, NameId name_id, InstId inst_id)
  268. -> void {
  269. Get(scope_id).AddRequired(
  270. {.name_id = name_id,
  271. .result = ScopeLookupResult::MakeFound(inst_id, AccessKind::Public)});
  272. }
  273. // Returns the requested name scope.
  274. auto Get(NameScopeId scope_id) -> NameScope& { return values_.Get(scope_id); }
  275. // Returns the requested name scope.
  276. auto Get(NameScopeId scope_id) const -> const NameScope& {
  277. return values_.Get(scope_id);
  278. }
  279. // Returns the instruction owning the requested name scope, or `None` with
  280. // nullopt if the scope is either `None` or has no associated instruction.
  281. auto GetInstIfValid(NameScopeId scope_id) const
  282. -> std::pair<InstId, std::optional<Inst>>;
  283. // Returns whether the provided scope ID is for a package scope.
  284. auto IsPackage(NameScopeId scope_id) const -> bool {
  285. if (!scope_id.has_value()) {
  286. return false;
  287. }
  288. // A package is either the current package or an imported package.
  289. return scope_id == NameScopeId::Package ||
  290. Get(scope_id).is_imported_package();
  291. }
  292. // Returns whether the provided scope ID is for the Core package.
  293. auto IsCorePackage(NameScopeId scope_id) const -> bool;
  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> values_;
  305. };
  306. } // namespace Carbon::SemIR
  307. #endif // CARBON_TOOLCHAIN_SEM_IR_NAME_SCOPE_H_