scope_stack.h 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. #ifndef CARBON_TOOLCHAIN_CHECK_SCOPE_STACK_H_
  5. #define CARBON_TOOLCHAIN_CHECK_SCOPE_STACK_H_
  6. #include "llvm/ADT/DenseSet.h"
  7. #include "llvm/ADT/SmallVector.h"
  8. #include "toolchain/check/lexical_lookup.h"
  9. #include "toolchain/check/scope_index.h"
  10. #include "toolchain/sem_ir/file.h"
  11. #include "toolchain/sem_ir/ids.h"
  12. namespace Carbon::Check {
  13. // A stack of lexical and semantic scopes that we are currently performing
  14. // checking within.
  15. class ScopeStack {
  16. public:
  17. explicit ScopeStack(const StringStoreWrapper<IdentifierId>& identifiers)
  18. : lexical_lookup_(identifiers) {}
  19. // A scope in which `break` and `continue` can be used.
  20. struct BreakContinueScope {
  21. SemIR::InstBlockId break_target;
  22. SemIR::InstBlockId continue_target;
  23. };
  24. // A scope in which `return` can be used.
  25. struct ReturnScope {
  26. // The declaration from which we can return. Inside a function, this will
  27. // be a `FunctionDecl`.
  28. SemIR::InstId decl_id;
  29. // The value corresponding to the current `returned var`, if any. Will be
  30. // set and unset as `returned var`s are declared and go out of scope.
  31. SemIR::InstId returned_var = SemIR::InstId::Invalid;
  32. };
  33. // A non-lexical scope in which unqualified lookup may be required.
  34. struct NonLexicalScope {
  35. // The index of the scope in the scope stack.
  36. ScopeIndex scope_index;
  37. // The corresponding name scope.
  38. SemIR::NameScopeId name_scope_id;
  39. };
  40. // Information about a scope that has been temporarily removed from the stack.
  41. struct SuspendedScope;
  42. // Pushes a scope onto scope_stack_. NameScopeId::Invalid is used for new
  43. // scopes. lexical_lookup_has_load_error is used to limit diagnostics when a
  44. // given namespace may contain a mix of both successful and failed name
  45. // imports.
  46. auto Push(SemIR::InstId scope_inst_id = SemIR::InstId::Invalid,
  47. SemIR::NameScopeId scope_id = SemIR::NameScopeId::Invalid,
  48. bool lexical_lookup_has_load_error = false) -> void;
  49. // Pops the top scope from scope_stack_, cleaning up names from
  50. // lexical_lookup_.
  51. auto Pop() -> void;
  52. // Pops the top scope from scope_stack_ if it contains no names.
  53. auto PopIfEmpty() -> void {
  54. if (scope_stack_.back().names.empty()) {
  55. Pop();
  56. }
  57. }
  58. // Pops scopes until we return to the specified scope index.
  59. auto PopTo(ScopeIndex index) -> void;
  60. // Returns the scope index associated with the current scope.
  61. auto PeekIndex() const -> ScopeIndex { return Peek().index; }
  62. // Returns the name scope associated with the current lexical scope, if any.
  63. auto PeekNameScopeId() const -> SemIR::NameScopeId { return Peek().scope_id; }
  64. // Returns the instruction associated with the current scope, or Invalid if
  65. // there is no such instruction, such as for a block scope.
  66. auto PeekInstId() const -> SemIR::InstId { return Peek().scope_inst_id; }
  67. // Returns the current scope, if it is of the specified kind. Otherwise,
  68. // returns nullopt.
  69. template <typename InstT>
  70. auto GetCurrentScopeAs(const SemIR::File& sem_ir) -> std::optional<InstT> {
  71. auto inst_id = PeekInstId();
  72. if (!inst_id.is_valid()) {
  73. return std::nullopt;
  74. }
  75. return sem_ir.insts().TryGetAs<InstT>(inst_id);
  76. }
  77. // If there is no `returned var` in scope, sets the given instruction to be
  78. // the current `returned var` and returns an invalid instruction ID. If there
  79. // is already a `returned var`, returns it instead.
  80. auto SetReturnedVarOrGetExisting(SemIR::InstId inst_id) -> SemIR::InstId;
  81. // Looks up the name `name_id` in the current scope. Returns the existing
  82. // lookup result, if any.
  83. auto LookupInCurrentScope(SemIR::NameId name_id) -> SemIR::InstId;
  84. // Looks up the name `name_id` in the current scope and related lexical
  85. // scopes. Returns the innermost lexical lookup result, if any, along with a
  86. // list of non-lexical scopes in which lookup should also be performed,
  87. // ordered from outermost to innermost.
  88. auto LookupInLexicalScopes(SemIR::NameId name_id)
  89. -> std::pair<SemIR::InstId, llvm::ArrayRef<NonLexicalScope>>;
  90. // Looks up the name `name_id` in the current scope. Returns the existing
  91. // instruction if any, and otherwise adds the name with the value `target_id`
  92. // and returns Invalid.
  93. auto LookupOrAddName(SemIR::NameId name_id, SemIR::InstId target_id)
  94. -> SemIR::InstId;
  95. // Prepares to add a compile-time binding in the current scope, and returns
  96. // its index. The added binding must then be pushed using
  97. // `PushCompileTimeBinding`.
  98. auto AddCompileTimeBinding() -> SemIR::CompileTimeBindIndex {
  99. auto index = scope_stack_.back().next_compile_time_bind_index;
  100. ++scope_stack_.back().next_compile_time_bind_index.index;
  101. return index;
  102. }
  103. // Pushes a compile-time binding into the current scope.
  104. auto PushCompileTimeBinding(SemIR::InstId bind_id) -> void {
  105. compile_time_binding_stack_.push_back(bind_id);
  106. }
  107. // Temporarily removes the top of the stack and its lexical lookup results.
  108. auto Suspend() -> SuspendedScope;
  109. // Restores a suspended scope stack entry.
  110. auto Restore(SuspendedScope scope) -> void;
  111. // Runs verification that the processing cleanly finished.
  112. auto VerifyOnFinish() -> void;
  113. auto return_scope_stack() -> llvm::SmallVector<ReturnScope>& {
  114. return return_scope_stack_;
  115. }
  116. auto break_continue_stack() -> llvm::SmallVector<BreakContinueScope>& {
  117. return break_continue_stack_;
  118. }
  119. auto compile_time_binding_stack() -> llvm::SmallVector<SemIR::InstId>& {
  120. return compile_time_binding_stack_;
  121. }
  122. private:
  123. // An entry in scope_stack_.
  124. struct ScopeStackEntry {
  125. // The sequential index of this scope entry within the file.
  126. ScopeIndex index;
  127. // The instruction associated with this entry, if any. This can be one of:
  128. //
  129. // - A `ClassDecl`, for a class definition scope.
  130. // - A `FunctionDecl`, for the outermost scope in a function
  131. // definition.
  132. // - Invalid, for any other scope.
  133. SemIR::InstId scope_inst_id;
  134. // The name scope associated with this entry, if any.
  135. SemIR::NameScopeId scope_id;
  136. // The next compile-time binding index to allocate in this scope.
  137. SemIR::CompileTimeBindIndex next_compile_time_bind_index;
  138. // Whether lexical_lookup_ has load errors from this scope or an ancestor
  139. // scope.
  140. bool lexical_lookup_has_load_error;
  141. // Whether a `returned var` was introduced in this scope, and needs to be
  142. // unregistered when the scope ends.
  143. bool has_returned_var = false;
  144. // Names which are registered with lexical_lookup_, and will need to be
  145. // unregistered when the scope ends.
  146. llvm::DenseSet<SemIR::NameId> names = {};
  147. // TODO: This likely needs to track things which need to be destructed.
  148. };
  149. auto Peek() const -> const ScopeStackEntry& { return scope_stack_.back(); }
  150. // Returns whether lexical lookup currently has any load errors.
  151. auto LexicalLookupHasLoadError() const -> bool {
  152. return !scope_stack_.empty() &&
  153. scope_stack_.back().lexical_lookup_has_load_error;
  154. }
  155. // A stack of scopes from which we can `return`.
  156. llvm::SmallVector<ReturnScope> return_scope_stack_;
  157. // A stack of `break` and `continue` targets.
  158. llvm::SmallVector<BreakContinueScope> break_continue_stack_;
  159. // A stack for scope context.
  160. llvm::SmallVector<ScopeStackEntry> scope_stack_;
  161. // Information about non-lexical scopes. This is a subset of the entries and
  162. // the information in scope_stack_.
  163. llvm::SmallVector<NonLexicalScope> non_lexical_scope_stack_;
  164. // A stack of the current compile time bindings.
  165. llvm::SmallVector<SemIR::InstId> compile_time_binding_stack_;
  166. // The index of the next scope that will be pushed onto scope_stack_. The
  167. // first is always the package scope.
  168. ScopeIndex next_scope_index_ = ScopeIndex::Package;
  169. // Tracks lexical lookup results.
  170. LexicalLookup lexical_lookup_;
  171. };
  172. struct ScopeStack::SuspendedScope {
  173. // An item that was suspended within this scope. This represents either a
  174. // lexical lookup entry in this scope, or a compile time binding entry in this
  175. // scope.
  176. //
  177. // TODO: For compile-time bindings, the common case is that they will both
  178. // have a suspended lexical lookup entry and a suspended compile time binding
  179. // entry. We should be able to store that as a single ScopeItem rather than
  180. // two.
  181. struct ScopeItem {
  182. static constexpr uint32_t IndexForCompileTimeBinding = -1;
  183. // The scope index for a LexicalLookup::SuspendedResult, or
  184. // CompileTimeBindingIndex for a suspended compile time binding.
  185. uint32_t index;
  186. // The instruction within the scope.
  187. SemIR::InstId inst_id;
  188. };
  189. // The suspended scope stack entry.
  190. ScopeStackEntry entry;
  191. // The list of items that were within this scope when it was suspended. The
  192. // inline size is an attempt to keep the size of a `SuspendedFunction`
  193. // reasonable while avoiding heap allocations most of the time.
  194. llvm::SmallVector<ScopeItem, 8> suspended_items;
  195. };
  196. } // namespace Carbon::Check
  197. #endif // CARBON_TOOLCHAIN_CHECK_SCOPE_STACK_H_