scope_stack.cpp 8.8 KB

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