name_scope.h 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. } // namespace Carbon::SemIR
  17. template <>
  18. struct llvm::format_provider<Carbon::SemIR::AccessKind> {
  19. using AccessKind = Carbon::SemIR::AccessKind;
  20. static void format(const AccessKind& loc, raw_ostream& out,
  21. StringRef /*style*/) {
  22. switch (loc) {
  23. case AccessKind::Private:
  24. out << "private";
  25. break;
  26. case AccessKind::Protected:
  27. out << "protected";
  28. break;
  29. case AccessKind::Public:
  30. out << "public";
  31. break;
  32. }
  33. }
  34. };
  35. namespace Carbon::SemIR {
  36. struct NameScope : Printable<NameScope> {
  37. struct Entry {
  38. NameId name_id;
  39. InstId inst_id;
  40. AccessKind access_kind;
  41. };
  42. auto Print(llvm::raw_ostream& out) const -> void {
  43. out << "{inst: " << inst_id << ", parent_scope: " << parent_scope_id
  44. << ", has_error: " << (has_error ? "true" : "false");
  45. out << ", extended_scopes: [";
  46. llvm::ListSeparator scope_sep;
  47. for (auto id : extended_scopes) {
  48. out << scope_sep << id;
  49. }
  50. out << "]";
  51. out << ", names: {";
  52. llvm::ListSeparator sep;
  53. for (auto entry : names) {
  54. out << sep << entry.name_id << ": " << entry.inst_id;
  55. }
  56. out << "}";
  57. out << "}";
  58. }
  59. // Adds a name to the scope that must not already exist.
  60. auto AddRequired(Entry name_entry) -> void {
  61. auto add_name = [&] {
  62. int index = names.size();
  63. names.push_back(name_entry);
  64. return index;
  65. };
  66. auto result = name_map.Insert(name_entry.name_id, add_name);
  67. CARBON_CHECK(result.is_inserted(), "Failed to add required name: {0}",
  68. name_entry.name_id);
  69. }
  70. // Returns true if this name scope describes an imported package.
  71. auto is_imported_package() const -> bool {
  72. return is_closed_import && parent_scope_id == NameScopeId::Package;
  73. }
  74. // Names in the scope. We store both an insertion-ordered vector for iterating
  75. // and a map from `NameId` to the index of that vector for name lookup.
  76. //
  77. // Optimization notes: this is somewhat memory inefficient. If this ends up
  78. // either hot or a significant source of memory allocation, we should consider
  79. // switching to a SOA model where the `AccessKind` is stored in a separate
  80. // vector so that these can pack densely. If this ends up both cold and memory
  81. // intensive, we can also switch the lookup to a set of indices into the
  82. // vector rather than a map from `NameId` to index.
  83. llvm::SmallVector<Entry> names;
  84. Map<NameId, int> name_map;
  85. // Scopes extended by this scope.
  86. //
  87. // TODO: A `NameScopeId` is currently insufficient to describe an extended
  88. // scope in general. For example:
  89. //
  90. // class A(T:! type) {
  91. // extend base: B(T*);
  92. // }
  93. //
  94. // needs to describe the `T*` argument.
  95. //
  96. // Small vector size is set to 1: we expect that there will rarely be more
  97. // than a single extended scope. Currently the only kind of extended scope is
  98. // a base class, and there can be only one of those per scope.
  99. // TODO: Revisit this once we have more kinds of extended scope and data.
  100. // TODO: Consider using something like `TinyPtrVector` for this.
  101. llvm::SmallVector<NameScopeId, 1> extended_scopes;
  102. // The instruction which owns the scope.
  103. InstId inst_id;
  104. // When the scope is a namespace, the name. Otherwise, invalid.
  105. NameId name_id;
  106. // The parent scope.
  107. NameScopeId parent_scope_id;
  108. // Whether we have diagnosed an error in a construct that would have added
  109. // names to this scope. For example, this can happen if an `import` failed or
  110. // an `extend` declaration was ill-formed. If true, the `names` map is assumed
  111. // to be missing names as a result of the error, and no further errors are
  112. // produced for lookup failures in this scope.
  113. bool has_error = false;
  114. // True if this is a closed namespace created by importing a package.
  115. bool is_closed_import = false;
  116. // Imported IR scopes that compose this namespace. This will be empty for
  117. // scopes that correspond to the current package.
  118. llvm::SmallVector<std::pair<SemIR::ImportIRId, SemIR::NameScopeId>, 0>
  119. import_ir_scopes;
  120. };
  121. // Provides a ValueStore wrapper for an API specific to name scopes.
  122. class NameScopeStore {
  123. public:
  124. explicit NameScopeStore(InstStore* insts) : insts_(insts) {}
  125. // Adds a name scope, returning an ID to reference it.
  126. auto Add(InstId inst_id, NameId name_id, NameScopeId parent_scope_id)
  127. -> NameScopeId {
  128. return values_.Add({.inst_id = inst_id,
  129. .name_id = name_id,
  130. .parent_scope_id = parent_scope_id});
  131. }
  132. // Adds a name that is required to exist in a name scope, such as `Self`.
  133. // These must never conflict.
  134. auto AddRequiredName(NameScopeId scope_id, NameId name_id, InstId inst_id)
  135. -> void {
  136. Get(scope_id).AddRequired({.name_id = name_id,
  137. .inst_id = inst_id,
  138. .access_kind = AccessKind::Public});
  139. }
  140. // Returns the requested name scope.
  141. auto Get(NameScopeId scope_id) -> NameScope& { return values_.Get(scope_id); }
  142. // Returns the requested name scope.
  143. auto Get(NameScopeId scope_id) const -> const NameScope& {
  144. return values_.Get(scope_id);
  145. }
  146. // Returns the instruction owning the requested name scope, or Invalid with
  147. // nullopt if the scope is either invalid or has no associated instruction.
  148. auto GetInstIfValid(NameScopeId scope_id) const
  149. -> std::pair<InstId, std::optional<Inst>> {
  150. if (!scope_id.is_valid()) {
  151. return {InstId::Invalid, std::nullopt};
  152. }
  153. auto inst_id = Get(scope_id).inst_id;
  154. if (!inst_id.is_valid()) {
  155. return {InstId::Invalid, std::nullopt};
  156. }
  157. return {inst_id, insts_->Get(inst_id)};
  158. }
  159. auto OutputYaml() const -> Yaml::OutputMapping {
  160. return values_.OutputYaml();
  161. }
  162. // Collects memory usage of members.
  163. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  164. -> void {
  165. mem_usage.Collect(label, values_);
  166. }
  167. private:
  168. InstStore* insts_;
  169. ValueStore<NameScopeId> values_;
  170. };
  171. } // namespace Carbon::SemIR
  172. #endif // CARBON_TOOLCHAIN_SEM_IR_NAME_SCOPE_H_