scope_stack.cpp 10 KB

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