scope_stack.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. scope.names.ForEach([&](SemIR::NameId str_id) {
  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).is_inserted()) {
  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. ++scope_stack_.back().num_names;
  111. // TODO: Reject if we previously performed a failed lookup for this name
  112. // in this scope or a scope nested within it.
  113. auto& lexical_results = lexical_lookup_.Get(name_id);
  114. CARBON_CHECK(lexical_results.empty() ||
  115. lexical_results.back().scope_index < PeekIndex())
  116. << "Failed to clean up after scope nested within the current scope";
  117. lexical_results.push_back({.inst_id = target_id, .scope_index = PeekIndex()});
  118. return SemIR::InstId::Invalid;
  119. }
  120. auto ScopeStack::SetReturnedVarOrGetExisting(SemIR::InstId inst_id)
  121. -> SemIR::InstId {
  122. CARBON_CHECK(!return_scope_stack_.empty()) << "`returned var` in no function";
  123. auto& returned_var = return_scope_stack_.back().returned_var;
  124. if (returned_var.is_valid()) {
  125. return returned_var;
  126. }
  127. returned_var = inst_id;
  128. CARBON_CHECK(!scope_stack_.back().has_returned_var)
  129. << "Scope has returned var but none is set";
  130. if (inst_id.is_valid()) {
  131. scope_stack_.back().has_returned_var = true;
  132. }
  133. return SemIR::InstId::Invalid;
  134. }
  135. auto ScopeStack::Suspend() -> SuspendedScope {
  136. CARBON_CHECK(!scope_stack_.empty()) << "No scope to suspend";
  137. SuspendedScope result = {.entry = scope_stack_.pop_back_val(),
  138. .suspended_items = {}};
  139. if (result.entry.scope_id.is_valid()) {
  140. non_lexical_scope_stack_.pop_back();
  141. }
  142. auto remaining_compile_time_bindings =
  143. scope_stack_.empty()
  144. ? 0
  145. : scope_stack_.back().next_compile_time_bind_index.index;
  146. result.suspended_items.reserve(result.entry.num_names +
  147. compile_time_binding_stack_.size() -
  148. remaining_compile_time_bindings);
  149. result.entry.names.ForEach([&](SemIR::NameId name_id) {
  150. auto [index, inst_id] = lexical_lookup_.Suspend(name_id);
  151. CARBON_CHECK(index !=
  152. SuspendedScope::ScopeItem::IndexForCompileTimeBinding);
  153. result.suspended_items.push_back({.index = index, .inst_id = inst_id});
  154. });
  155. CARBON_CHECK(static_cast<int>(result.suspended_items.size()) ==
  156. result.entry.num_names);
  157. // Move any compile-time bindings into the suspended scope.
  158. for (auto inst_id : llvm::ArrayRef(compile_time_binding_stack_)
  159. .drop_front(remaining_compile_time_bindings)) {
  160. result.suspended_items.push_back(
  161. {.index = SuspendedScope::ScopeItem::IndexForCompileTimeBinding,
  162. .inst_id = inst_id});
  163. }
  164. compile_time_binding_stack_.truncate(remaining_compile_time_bindings);
  165. // This would be easy to support if we had a need, but currently we do not.
  166. CARBON_CHECK(!result.entry.has_returned_var)
  167. << "Should not suspend a scope with a returned var.";
  168. return result;
  169. }
  170. auto ScopeStack::Restore(SuspendedScope scope) -> void {
  171. for (auto [index, inst_id] : scope.suspended_items) {
  172. if (index == SuspendedScope::ScopeItem::IndexForCompileTimeBinding) {
  173. compile_time_binding_stack_.push_back(inst_id);
  174. } else {
  175. lexical_lookup_.Restore({.index = index, .inst_id = inst_id},
  176. scope.entry.index);
  177. }
  178. }
  179. CARBON_CHECK(scope.entry.next_compile_time_bind_index.index ==
  180. static_cast<int32_t>(compile_time_binding_stack_.size()))
  181. << "Wrong number of entries in compile-time binding stack "
  182. "when restoring, have "
  183. << compile_time_binding_stack_.size() << ", expected "
  184. << scope.entry.next_compile_time_bind_index.index;
  185. if (scope.entry.scope_id.is_valid()) {
  186. non_lexical_scope_stack_.push_back({.scope_index = scope.entry.index,
  187. .name_scope_id = scope.entry.scope_id});
  188. }
  189. scope_stack_.push_back(std::move(scope.entry));
  190. }
  191. } // namespace Carbon::Check