scope_stack.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. #include "toolchain/check/scope_stack.h"
  5. #include "common/check.h"
  6. #include "toolchain/sem_ir/ids.h"
  7. namespace Carbon::Check {
  8. auto ScopeStack::VerifyOnFinish() const -> void {
  9. CARBON_CHECK(scope_stack_.empty(), "{0}", scope_stack_.size());
  10. full_pattern_stack_.VerifyOnFinish();
  11. }
  12. auto ScopeStack::VerifyNextCompileTimeBindIndex(llvm::StringLiteral label,
  13. const ScopeStackEntry& scope)
  14. -> void {
  15. CARBON_CHECK(
  16. static_cast<int32_t>(compile_time_binding_stack_.all_values_size()) ==
  17. scope.next_compile_time_bind_index.index,
  18. "Wrong number of entries in compile-time binding stack after {0}: have "
  19. "{1}, expected {2}",
  20. label, compile_time_binding_stack_.all_values_size(),
  21. scope.next_compile_time_bind_index.index);
  22. }
  23. auto ScopeStack::Push(SemIR::InstId scope_inst_id, SemIR::NameScopeId scope_id,
  24. SemIR::SpecificId specific_id,
  25. bool lexical_lookup_has_load_error) -> void {
  26. // If this scope doesn't have a specific of its own, it lives in the enclosing
  27. // scope's specific, if any.
  28. auto enclosing_specific_id = specific_id;
  29. if (!specific_id.has_value() && !scope_stack_.empty()) {
  30. enclosing_specific_id = PeekSpecificId();
  31. }
  32. compile_time_binding_stack_.PushArray();
  33. scope_stack_.push_back(
  34. {.index = next_scope_index_,
  35. .scope_inst_id = scope_inst_id,
  36. .scope_id = scope_id,
  37. .specific_id = enclosing_specific_id,
  38. .next_compile_time_bind_index = SemIR::CompileTimeBindIndex(
  39. compile_time_binding_stack_.all_values_size()),
  40. .lexical_lookup_has_load_error =
  41. LexicalLookupHasLoadError() || lexical_lookup_has_load_error});
  42. if (scope_id.has_value()) {
  43. non_lexical_scope_stack_.push_back({.scope_index = next_scope_index_,
  44. .name_scope_id = scope_id,
  45. .specific_id = enclosing_specific_id});
  46. } else {
  47. // For lexical lookups, unqualified lookup doesn't know how to find the
  48. // associated specific, so if we start adding lexical scopes associated with
  49. // specifics, we'll need to somehow track them in lookup.
  50. CARBON_CHECK(!specific_id.has_value(),
  51. "Lexical scope should not have an associated specific.");
  52. }
  53. // TODO: Handle this case more gracefully.
  54. CARBON_CHECK(next_scope_index_.index != std::numeric_limits<int32_t>::max(),
  55. "Ran out of scopes");
  56. ++next_scope_index_.index;
  57. VerifyNextCompileTimeBindIndex("Push", scope_stack_.back());
  58. }
  59. auto ScopeStack::Pop() -> void {
  60. auto scope = scope_stack_.pop_back_val();
  61. scope.names.ForEach([&](SemIR::NameId str_id) {
  62. auto& lexical_results = lexical_lookup_.Get(str_id);
  63. CARBON_CHECK(lexical_results.back().scope_index == scope.index,
  64. "Inconsistent scope index for name {0}", str_id);
  65. lexical_results.pop_back();
  66. });
  67. if (scope.scope_id.has_value()) {
  68. CARBON_CHECK(non_lexical_scope_stack_.back().scope_index == scope.index);
  69. non_lexical_scope_stack_.pop_back();
  70. }
  71. if (scope.has_returned_var) {
  72. CARBON_CHECK(!return_scope_stack_.empty());
  73. CARBON_CHECK(return_scope_stack_.back().returned_var.has_value());
  74. return_scope_stack_.back().returned_var = SemIR::InstId::None;
  75. }
  76. VerifyNextCompileTimeBindIndex("Pop", scope);
  77. compile_time_binding_stack_.PopArray();
  78. }
  79. auto ScopeStack::PopTo(ScopeIndex index) -> void {
  80. while (PeekIndex() > index) {
  81. Pop();
  82. }
  83. CARBON_CHECK(PeekIndex() == index,
  84. "Scope index {0} does not enclose the current scope {1}", index,
  85. PeekIndex());
  86. }
  87. auto ScopeStack::LookupInLexicalScopesWithin(SemIR::NameId name_id,
  88. ScopeIndex scope_index)
  89. -> SemIR::InstId {
  90. auto& lexical_results = lexical_lookup_.Get(name_id);
  91. if (lexical_results.empty()) {
  92. return SemIR::InstId::None;
  93. }
  94. auto result = lexical_results.back();
  95. if (result.scope_index < scope_index) {
  96. return SemIR::InstId::None;
  97. }
  98. return result.inst_id;
  99. }
  100. auto ScopeStack::LookupInLexicalScopes(SemIR::NameId name_id)
  101. -> std::pair<SemIR::InstId, llvm::ArrayRef<NonLexicalScope>> {
  102. // Find the results from lexical scopes. These will be combined with results
  103. // from non-lexical scopes such as namespaces and classes.
  104. llvm::ArrayRef<LexicalLookup::Result> lexical_results =
  105. lexical_lookup_.Get(name_id);
  106. // If we have no lexical results, check all non-lexical scopes.
  107. if (lexical_results.empty()) {
  108. return {LexicalLookupHasLoadError() ? SemIR::ErrorInst::SingletonInstId
  109. : SemIR::InstId::None,
  110. non_lexical_scope_stack_};
  111. }
  112. // Find the first non-lexical scope that is within the scope of the lexical
  113. // lookup result.
  114. auto* first_non_lexical_scope = llvm::lower_bound(
  115. non_lexical_scope_stack_, lexical_results.back().scope_index,
  116. [](const NonLexicalScope& scope, ScopeIndex index) {
  117. return scope.scope_index < index;
  118. });
  119. return {
  120. lexical_results.back().inst_id,
  121. llvm::ArrayRef(first_non_lexical_scope, non_lexical_scope_stack_.end())};
  122. }
  123. auto ScopeStack::LookupOrAddName(SemIR::NameId name_id, SemIR::InstId target_id,
  124. ScopeIndex scope_index) -> SemIR::InstId {
  125. // Find the corresponding scope depth.
  126. //
  127. // TODO: Consider passing in the depth rather than performing a scan for it.
  128. // We only do this scan when declaring an entity such as a class within a
  129. // function, so it should be relatively rare, but it's still not necesasry to
  130. // recompute this.
  131. int scope_depth = scope_stack_.size() - 1;
  132. if (scope_index.has_value()) {
  133. scope_depth =
  134. std::lower_bound(scope_stack_.begin(), scope_stack_.end(), scope_index,
  135. [](const ScopeStackEntry& entry, ScopeIndex index) {
  136. return entry.index < index;
  137. }) -
  138. scope_stack_.begin();
  139. CARBON_CHECK(scope_stack_[scope_depth].index == scope_index,
  140. "Declaring name in scope that has already ended");
  141. } else {
  142. scope_index = scope_stack_[scope_depth].index;
  143. }
  144. // If this name has already been declared in this scope or an inner scope,
  145. // return the existing result.
  146. auto& lexical_results = lexical_lookup_.Get(name_id);
  147. if (!lexical_results.empty() &&
  148. lexical_results.back().scope_index >= scope_index) {
  149. return lexical_results.back().inst_id;
  150. }
  151. // Add the name into the scope.
  152. bool inserted = scope_stack_[scope_depth].names.Insert(name_id).is_inserted();
  153. CARBON_CHECK(inserted, "Name in scope but not in lexical lookups");
  154. ++scope_stack_[scope_depth].num_names;
  155. // Add a corresponding lexical lookup result.
  156. lexical_results.push_back({.inst_id = target_id, .scope_index = scope_index});
  157. return SemIR::InstId::None;
  158. }
  159. auto ScopeStack::SetReturnedVarOrGetExisting(SemIR::InstId inst_id)
  160. -> SemIR::InstId {
  161. CARBON_CHECK(!return_scope_stack_.empty(), "`returned var` in no function");
  162. auto& returned_var = return_scope_stack_.back().returned_var;
  163. if (returned_var.has_value()) {
  164. return returned_var;
  165. }
  166. returned_var = inst_id;
  167. CARBON_CHECK(!scope_stack_.back().has_returned_var,
  168. "Scope has returned var but none is set");
  169. if (inst_id.has_value()) {
  170. scope_stack_.back().has_returned_var = true;
  171. }
  172. return SemIR::InstId::None;
  173. }
  174. auto ScopeStack::Suspend() -> SuspendedScope {
  175. CARBON_CHECK(!scope_stack_.empty(), "No scope to suspend");
  176. SuspendedScope result = {.entry = scope_stack_.pop_back_val(),
  177. .suspended_items = {}};
  178. if (result.entry.scope_id.has_value()) {
  179. non_lexical_scope_stack_.pop_back();
  180. }
  181. auto peek_compile_time_bindings = compile_time_binding_stack_.PeekArray();
  182. result.suspended_items.reserve(result.entry.num_names +
  183. peek_compile_time_bindings.size());
  184. result.entry.names.ForEach([&](SemIR::NameId name_id) {
  185. auto [index, inst_id] = lexical_lookup_.Suspend(name_id);
  186. CARBON_CHECK(index !=
  187. SuspendedScope::ScopeItem::IndexForCompileTimeBinding);
  188. result.suspended_items.push_back({.index = index, .inst_id = inst_id});
  189. });
  190. CARBON_CHECK(static_cast<int>(result.suspended_items.size()) ==
  191. result.entry.num_names);
  192. // Move any compile-time bindings into the suspended scope.
  193. for (auto inst_id : peek_compile_time_bindings) {
  194. result.suspended_items.push_back(
  195. {.index = SuspendedScope::ScopeItem::IndexForCompileTimeBinding,
  196. .inst_id = inst_id});
  197. }
  198. compile_time_binding_stack_.PopArray();
  199. // This would be easy to support if we had a need, but currently we do not.
  200. CARBON_CHECK(!result.entry.has_returned_var,
  201. "Should not suspend a scope with a returned var.");
  202. return result;
  203. }
  204. auto ScopeStack::Restore(SuspendedScope scope) -> void {
  205. compile_time_binding_stack_.PushArray();
  206. for (auto [index, inst_id] : scope.suspended_items) {
  207. if (index == SuspendedScope::ScopeItem::IndexForCompileTimeBinding) {
  208. compile_time_binding_stack_.AppendToTop(inst_id);
  209. } else {
  210. lexical_lookup_.Restore({.index = index, .inst_id = inst_id},
  211. scope.entry.index);
  212. }
  213. }
  214. VerifyNextCompileTimeBindIndex("Restore", scope.entry);
  215. if (scope.entry.scope_id.has_value()) {
  216. non_lexical_scope_stack_.push_back(
  217. {.scope_index = scope.entry.index,
  218. .name_scope_id = scope.entry.scope_id,
  219. .specific_id = scope.entry.specific_id});
  220. }
  221. scope_stack_.push_back(std::move(scope.entry));
  222. }
  223. } // namespace Carbon::Check