scope_stack.cpp 10 KB

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