scope_stack.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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.is_valid() && !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.is_valid()) {
  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.is_valid(),
  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.is_valid()) {
  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.is_valid());
  73. return_scope_stack_.back().returned_var = SemIR::InstId::Invalid;
  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::LookupInCurrentScope(SemIR::NameId name_id) -> SemIR::InstId {
  87. auto& lexical_results = lexical_lookup_.Get(name_id);
  88. if (lexical_results.empty()) {
  89. return SemIR::InstId::Invalid;
  90. }
  91. auto result = lexical_results.back();
  92. if (result.scope_index != PeekIndex()) {
  93. return SemIR::InstId::Invalid;
  94. }
  95. return result.inst_id;
  96. }
  97. auto ScopeStack::LookupInLexicalScopes(SemIR::NameId name_id)
  98. -> std::pair<SemIR::InstId, llvm::ArrayRef<NonLexicalScope>> {
  99. // Find the results from lexical scopes. These will be combined with results
  100. // from non-lexical scopes such as namespaces and classes.
  101. llvm::ArrayRef<LexicalLookup::Result> lexical_results =
  102. lexical_lookup_.Get(name_id);
  103. // If we have no lexical results, check all non-lexical scopes.
  104. if (lexical_results.empty()) {
  105. return {LexicalLookupHasLoadError() ? SemIR::InstId::BuiltinError
  106. : SemIR::InstId::Invalid,
  107. non_lexical_scope_stack_};
  108. }
  109. // Find the first non-lexical scope that is within the scope of the lexical
  110. // lookup result.
  111. auto* first_non_lexical_scope = std::lower_bound(
  112. non_lexical_scope_stack_.begin(), non_lexical_scope_stack_.end(),
  113. lexical_results.back().scope_index,
  114. [](const NonLexicalScope& scope, ScopeIndex index) {
  115. return scope.scope_index < index;
  116. });
  117. return {
  118. lexical_results.back().inst_id,
  119. llvm::ArrayRef(first_non_lexical_scope, non_lexical_scope_stack_.end())};
  120. }
  121. auto ScopeStack::LookupOrAddName(SemIR::NameId name_id, SemIR::InstId target_id)
  122. -> SemIR::InstId {
  123. if (!scope_stack_.back().names.Insert(name_id).is_inserted()) {
  124. auto existing = lexical_lookup_.Get(name_id).back().inst_id;
  125. CARBON_CHECK(existing.is_valid(),
  126. "Name in scope but not in lexical lookups");
  127. return existing;
  128. }
  129. ++scope_stack_.back().num_names;
  130. // TODO: Reject if we previously performed a failed lookup for this name
  131. // in this scope or a scope nested within it.
  132. auto& lexical_results = lexical_lookup_.Get(name_id);
  133. CARBON_CHECK(
  134. lexical_results.empty() ||
  135. lexical_results.back().scope_index < PeekIndex(),
  136. "Failed to clean up after scope nested within the current scope");
  137. lexical_results.push_back({.inst_id = target_id, .scope_index = PeekIndex()});
  138. return SemIR::InstId::Invalid;
  139. }
  140. auto ScopeStack::SetReturnedVarOrGetExisting(SemIR::InstId inst_id)
  141. -> SemIR::InstId {
  142. CARBON_CHECK(!return_scope_stack_.empty(), "`returned var` in no function");
  143. auto& returned_var = return_scope_stack_.back().returned_var;
  144. if (returned_var.is_valid()) {
  145. return returned_var;
  146. }
  147. returned_var = inst_id;
  148. CARBON_CHECK(!scope_stack_.back().has_returned_var,
  149. "Scope has returned var but none is set");
  150. if (inst_id.is_valid()) {
  151. scope_stack_.back().has_returned_var = true;
  152. }
  153. return SemIR::InstId::Invalid;
  154. }
  155. auto ScopeStack::Suspend() -> SuspendedScope {
  156. CARBON_CHECK(!scope_stack_.empty(), "No scope to suspend");
  157. SuspendedScope result = {.entry = scope_stack_.pop_back_val(),
  158. .suspended_items = {}};
  159. if (result.entry.scope_id.is_valid()) {
  160. non_lexical_scope_stack_.pop_back();
  161. }
  162. auto peek_compile_time_bindings = compile_time_binding_stack_.PeekArray();
  163. result.suspended_items.reserve(result.entry.num_names +
  164. peek_compile_time_bindings.size());
  165. result.entry.names.ForEach([&](SemIR::NameId name_id) {
  166. auto [index, inst_id] = lexical_lookup_.Suspend(name_id);
  167. CARBON_CHECK(index !=
  168. SuspendedScope::ScopeItem::IndexForCompileTimeBinding);
  169. result.suspended_items.push_back({.index = index, .inst_id = inst_id});
  170. });
  171. CARBON_CHECK(static_cast<int>(result.suspended_items.size()) ==
  172. result.entry.num_names);
  173. // Move any compile-time bindings into the suspended scope.
  174. for (auto inst_id : peek_compile_time_bindings) {
  175. result.suspended_items.push_back(
  176. {.index = SuspendedScope::ScopeItem::IndexForCompileTimeBinding,
  177. .inst_id = inst_id});
  178. }
  179. compile_time_binding_stack_.PopArray();
  180. // This would be easy to support if we had a need, but currently we do not.
  181. CARBON_CHECK(!result.entry.has_returned_var,
  182. "Should not suspend a scope with a returned var.");
  183. return result;
  184. }
  185. auto ScopeStack::Restore(SuspendedScope scope) -> void {
  186. compile_time_binding_stack_.PushArray();
  187. for (auto [index, inst_id] : scope.suspended_items) {
  188. if (index == SuspendedScope::ScopeItem::IndexForCompileTimeBinding) {
  189. compile_time_binding_stack_.AppendToTop(inst_id);
  190. } else {
  191. lexical_lookup_.Restore({.index = index, .inst_id = inst_id},
  192. scope.entry.index);
  193. }
  194. }
  195. VerifyNextCompileTimeBindIndex("Restore", scope.entry);
  196. if (scope.entry.scope_id.is_valid()) {
  197. non_lexical_scope_stack_.push_back(
  198. {.scope_index = scope.entry.index,
  199. .name_scope_id = scope.entry.scope_id,
  200. .specific_id = scope.entry.specific_id});
  201. }
  202. scope_stack_.push_back(std::move(scope.entry));
  203. }
  204. } // namespace Carbon::Check