scope_stack.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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()) << scope_stack_.size();
  10. }
  11. auto ScopeStack::Push(SemIR::InstId scope_inst_id, SemIR::NameScopeId scope_id,
  12. bool lexical_lookup_has_load_error) -> void {
  13. scope_stack_.push_back(
  14. {.index = next_scope_index_,
  15. .scope_inst_id = scope_inst_id,
  16. .scope_id = scope_id,
  17. .next_compile_time_bind_index =
  18. scope_stack_.empty()
  19. ? SemIR::CompileTimeBindIndex(0)
  20. : scope_stack_.back().next_compile_time_bind_index,
  21. .lexical_lookup_has_load_error =
  22. LexicalLookupHasLoadError() || lexical_lookup_has_load_error});
  23. if (scope_id.is_valid()) {
  24. non_lexical_scope_stack_.push_back(
  25. {.scope_index = next_scope_index_, .name_scope_id = scope_id});
  26. }
  27. // TODO: Handle this case more gracefully.
  28. CARBON_CHECK(next_scope_index_.index != std::numeric_limits<int32_t>::max())
  29. << "Ran out of scopes";
  30. ++next_scope_index_.index;
  31. }
  32. auto ScopeStack::Pop() -> void {
  33. auto scope = scope_stack_.pop_back_val();
  34. for (const auto& str_id : scope.names) {
  35. auto& lexical_results = lexical_lookup_.Get(str_id);
  36. CARBON_CHECK(lexical_results.back().scope_index == scope.index)
  37. << "Inconsistent scope index for name " << str_id;
  38. lexical_results.pop_back();
  39. }
  40. if (scope.scope_id.is_valid()) {
  41. CARBON_CHECK(non_lexical_scope_stack_.back().scope_index == scope.index);
  42. non_lexical_scope_stack_.pop_back();
  43. }
  44. if (scope.has_returned_var) {
  45. CARBON_CHECK(!return_scope_stack_.empty());
  46. CARBON_CHECK(return_scope_stack_.back().returned_var.is_valid());
  47. return_scope_stack_.back().returned_var = SemIR::InstId::Invalid;
  48. }
  49. CARBON_CHECK(scope.next_compile_time_bind_index.index ==
  50. static_cast<int32_t>(compile_time_binding_stack_.size()))
  51. << "Wrong number of entries in compile-time binding stack, have "
  52. << compile_time_binding_stack_.size() << ", expected "
  53. << scope.next_compile_time_bind_index.index;
  54. compile_time_binding_stack_.truncate(
  55. scope_stack_.empty()
  56. ? 0
  57. : scope_stack_.back().next_compile_time_bind_index.index);
  58. }
  59. auto ScopeStack::PopTo(ScopeIndex index) -> void {
  60. while (PeekIndex() > index) {
  61. Pop();
  62. }
  63. CARBON_CHECK(PeekIndex() == index)
  64. << "Scope index " << index << " does not enclose the current scope "
  65. << PeekIndex();
  66. }
  67. auto ScopeStack::LookupInCurrentScope(SemIR::NameId name_id) -> SemIR::InstId {
  68. auto& lexical_results = lexical_lookup_.Get(name_id);
  69. if (lexical_results.empty()) {
  70. return SemIR::InstId::Invalid;
  71. }
  72. auto result = lexical_results.back();
  73. if (result.scope_index != PeekIndex()) {
  74. return SemIR::InstId::Invalid;
  75. }
  76. return result.inst_id;
  77. }
  78. auto ScopeStack::LookupInLexicalScopes(SemIR::NameId name_id)
  79. -> std::pair<SemIR::InstId, llvm::ArrayRef<NonLexicalScope>> {
  80. // Find the results from lexical scopes. These will be combined with results
  81. // from non-lexical scopes such as namespaces and classes.
  82. llvm::ArrayRef<LexicalLookup::Result> lexical_results =
  83. lexical_lookup_.Get(name_id);
  84. // If we have no lexical results, check all non-lexical scopes.
  85. if (lexical_results.empty()) {
  86. return {LexicalLookupHasLoadError() ? SemIR::InstId::BuiltinError
  87. : SemIR::InstId::Invalid,
  88. non_lexical_scope_stack_};
  89. }
  90. // Find the first non-lexical scope that is within the scope of the lexical
  91. // lookup result.
  92. auto* first_non_lexical_scope = std::lower_bound(
  93. non_lexical_scope_stack_.begin(), non_lexical_scope_stack_.end(),
  94. lexical_results.back().scope_index,
  95. [](const NonLexicalScope& scope, ScopeIndex index) {
  96. return scope.scope_index < index;
  97. });
  98. return {
  99. lexical_results.back().inst_id,
  100. llvm::ArrayRef(first_non_lexical_scope, non_lexical_scope_stack_.end())};
  101. }
  102. auto ScopeStack::LookupOrAddName(SemIR::NameId name_id, SemIR::InstId target_id)
  103. -> SemIR::InstId {
  104. if (!scope_stack_.back().names.insert(name_id).second) {
  105. auto existing = lexical_lookup_.Get(name_id).back().inst_id;
  106. CARBON_CHECK(existing.is_valid())
  107. << "Name in scope but not in lexical lookups";
  108. return existing;
  109. }
  110. // TODO: Reject if we previously performed a failed lookup for this name
  111. // in this scope or a scope nested within it.
  112. auto& lexical_results = lexical_lookup_.Get(name_id);
  113. CARBON_CHECK(lexical_results.empty() ||
  114. lexical_results.back().scope_index < PeekIndex())
  115. << "Failed to clean up after scope nested within the current scope";
  116. lexical_results.push_back({.inst_id = target_id, .scope_index = PeekIndex()});
  117. return SemIR::InstId::Invalid;
  118. }
  119. auto ScopeStack::SetReturnedVarOrGetExisting(SemIR::InstId inst_id)
  120. -> SemIR::InstId {
  121. CARBON_CHECK(!return_scope_stack_.empty()) << "`returned var` in no function";
  122. auto& returned_var = return_scope_stack_.back().returned_var;
  123. if (returned_var.is_valid()) {
  124. return returned_var;
  125. }
  126. returned_var = inst_id;
  127. CARBON_CHECK(!scope_stack_.back().has_returned_var)
  128. << "Scope has returned var but none is set";
  129. if (inst_id.is_valid()) {
  130. scope_stack_.back().has_returned_var = true;
  131. }
  132. return SemIR::InstId::Invalid;
  133. }
  134. auto ScopeStack::Suspend() -> SuspendedScope {
  135. CARBON_CHECK(!scope_stack_.empty()) << "No scope to suspend";
  136. SuspendedScope result = {.entry = scope_stack_.pop_back_val(),
  137. .suspended_items = {}};
  138. if (result.entry.scope_id.is_valid()) {
  139. non_lexical_scope_stack_.pop_back();
  140. }
  141. auto remaining_compile_time_bindings =
  142. scope_stack_.empty()
  143. ? 0
  144. : scope_stack_.back().next_compile_time_bind_index.index;
  145. result.suspended_items.reserve(result.entry.names.size() +
  146. compile_time_binding_stack_.size() -
  147. remaining_compile_time_bindings);
  148. for (auto name_id : result.entry.names) {
  149. auto [index, inst_id] = lexical_lookup_.Suspend(name_id);
  150. CARBON_CHECK(index !=
  151. SuspendedScope::ScopeItem::IndexForCompileTimeBinding);
  152. result.suspended_items.push_back({.index = index, .inst_id = inst_id});
  153. }
  154. // Move any compile-time bindings into the suspended scope.
  155. for (auto inst_id : llvm::ArrayRef(compile_time_binding_stack_)
  156. .drop_back(remaining_compile_time_bindings)) {
  157. result.suspended_items.push_back(
  158. {.index = SuspendedScope::ScopeItem::IndexForCompileTimeBinding,
  159. .inst_id = inst_id});
  160. }
  161. compile_time_binding_stack_.truncate(remaining_compile_time_bindings);
  162. // This would be easy to support if we had a need, but currently we do not.
  163. CARBON_CHECK(!result.entry.has_returned_var)
  164. << "Should not suspend a scope with a returned var.";
  165. return result;
  166. }
  167. auto ScopeStack::Restore(SuspendedScope scope) -> void {
  168. for (auto [index, inst_id] : scope.suspended_items) {
  169. if (index == SuspendedScope::ScopeItem::IndexForCompileTimeBinding) {
  170. compile_time_binding_stack_.push_back(inst_id);
  171. } else {
  172. lexical_lookup_.Restore({.index = index, .inst_id = inst_id},
  173. scope.entry.index);
  174. }
  175. }
  176. CARBON_CHECK(scope.entry.next_compile_time_bind_index.index ==
  177. static_cast<int32_t>(compile_time_binding_stack_.size()))
  178. << "Wrong number of entries in compile-time binding stack "
  179. "when restoring, have "
  180. << compile_time_binding_stack_.size() << ", expected "
  181. << scope.entry.next_compile_time_bind_index.index;
  182. if (scope.entry.scope_id.is_valid()) {
  183. non_lexical_scope_stack_.push_back({.scope_index = scope.entry.index,
  184. .name_scope_id = scope.entry.scope_id});
  185. }
  186. scope_stack_.push_back(std::move(scope.entry));
  187. }
  188. } // namespace Carbon::Check