scope_stack.h 11 KB

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