scope_stack.cpp 9.7 KB

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