scope_stack.cpp 7.9 KB

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