context.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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_CONTEXT_H_
  5. #define CARBON_TOOLCHAIN_CHECK_CONTEXT_H_
  6. #include <string>
  7. #include "common/map.h"
  8. #include "common/ostream.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "toolchain/check/decl_introducer_state.h"
  11. #include "toolchain/check/decl_name_stack.h"
  12. #include "toolchain/check/full_pattern_stack.h"
  13. #include "toolchain/check/generic_region_stack.h"
  14. #include "toolchain/check/global_init.h"
  15. #include "toolchain/check/inst_block_stack.h"
  16. #include "toolchain/check/node_stack.h"
  17. #include "toolchain/check/param_and_arg_refs_stack.h"
  18. #include "toolchain/check/region_stack.h"
  19. #include "toolchain/check/scope_stack.h"
  20. #include "toolchain/diagnostics/diagnostic_emitter.h"
  21. #include "toolchain/parse/node_ids.h"
  22. #include "toolchain/parse/tree.h"
  23. #include "toolchain/parse/tree_and_subtrees.h"
  24. #include "toolchain/sem_ir/file.h"
  25. #include "toolchain/sem_ir/ids.h"
  26. #include "toolchain/sem_ir/import_ir.h"
  27. #include "toolchain/sem_ir/inst.h"
  28. #include "toolchain/sem_ir/name_scope.h"
  29. #include "toolchain/sem_ir/typed_insts.h"
  30. namespace Carbon::Check {
  31. // Context stored during check.
  32. //
  33. // This file stores state, and members objects may provide an API. Other files
  34. // may also have helpers that operate on Context. To keep this file manageable,
  35. // please put logic into other files.
  36. //
  37. // For example, consider the API for functions:
  38. // - `context.functions()`: Exposes storage of `SemIR::Function` objects.
  39. // - `toolchain/check/function.h`: Contains helper functions which use
  40. // `Check::Context`.
  41. // - `toolchain/sem_ir/function.h`: Contains helper functions which only need
  42. // `SemIR` objects, for which it's helpful not to depend on `Check::Context`
  43. // (for example, shared with lowering).
  44. class Context {
  45. public:
  46. // Stores references for work.
  47. explicit Context(DiagnosticEmitter<SemIRLoc>* emitter,
  48. Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter,
  49. SemIR::File* sem_ir, int imported_ir_count,
  50. int total_ir_count, llvm::raw_ostream* vlog_stream);
  51. // Marks an implementation TODO. Always returns false.
  52. auto TODO(SemIRLoc loc, std::string label) -> bool;
  53. // Runs verification that the processing cleanly finished.
  54. auto VerifyOnFinish() const -> void;
  55. // Prints information for a stack dump.
  56. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  57. // Get the Lex::TokenKind of a node for diagnostics.
  58. auto token_kind(Parse::NodeId node_id) -> Lex::TokenKind {
  59. return tokens().GetKind(parse_tree().node_token(node_id));
  60. }
  61. auto emitter() -> DiagnosticEmitter<SemIRLoc>& { return *emitter_; }
  62. auto parse_tree_and_subtrees() -> const Parse::TreeAndSubtrees& {
  63. return tree_and_subtrees_getter_();
  64. }
  65. auto sem_ir() -> SemIR::File& { return *sem_ir_; }
  66. auto sem_ir() const -> const SemIR::File& { return *sem_ir_; }
  67. // Convenience functions for major phase data.
  68. auto parse_tree() const -> const Parse::Tree& {
  69. return sem_ir_->parse_tree();
  70. }
  71. auto tokens() const -> const Lex::TokenizedBuffer& {
  72. return parse_tree().tokens();
  73. }
  74. auto vlog_stream() -> llvm::raw_ostream* { return vlog_stream_; }
  75. auto node_stack() -> NodeStack& { return node_stack_; }
  76. auto inst_block_stack() -> InstBlockStack& { return inst_block_stack_; }
  77. auto pattern_block_stack() -> InstBlockStack& { return pattern_block_stack_; }
  78. auto param_and_arg_refs_stack() -> ParamAndArgRefsStack& {
  79. return param_and_arg_refs_stack_;
  80. }
  81. auto args_type_info_stack() -> InstBlockStack& {
  82. return args_type_info_stack_;
  83. }
  84. auto struct_type_fields_stack() -> ArrayStack<SemIR::StructTypeField>& {
  85. return struct_type_fields_stack_;
  86. }
  87. auto field_decls_stack() -> ArrayStack<SemIR::InstId>& {
  88. return field_decls_stack_;
  89. }
  90. auto decl_name_stack() -> DeclNameStack& { return decl_name_stack_; }
  91. auto decl_introducer_state_stack() -> DeclIntroducerStateStack& {
  92. return decl_introducer_state_stack_;
  93. }
  94. auto scope_stack() -> ScopeStack& { return scope_stack_; }
  95. // Conveneicne functions for frequently-used `scope_stack` members.
  96. auto return_scope_stack() -> llvm::SmallVector<ScopeStack::ReturnScope>& {
  97. return scope_stack().return_scope_stack();
  98. }
  99. auto break_continue_stack()
  100. -> llvm::SmallVector<ScopeStack::BreakContinueScope>& {
  101. return scope_stack().break_continue_stack();
  102. }
  103. auto full_pattern_stack() -> FullPatternStack& {
  104. return scope_stack_.full_pattern_stack();
  105. }
  106. auto generic_region_stack() -> GenericRegionStack& {
  107. return generic_region_stack_;
  108. }
  109. auto vtable_stack() -> InstBlockStack& { return vtable_stack_; }
  110. auto exports() -> llvm::SmallVector<SemIR::InstId>& { return exports_; }
  111. auto check_ir_map() -> llvm::MutableArrayRef<SemIR::ImportIRId> {
  112. return check_ir_map_;
  113. }
  114. auto import_ir_constant_values()
  115. -> llvm::SmallVector<SemIR::ConstantValueStore, 0>& {
  116. return import_ir_constant_values_;
  117. }
  118. auto definitions_required() -> llvm::SmallVector<SemIR::InstId>& {
  119. return definitions_required_;
  120. }
  121. auto global_init() -> GlobalInit& { return global_init_; }
  122. auto import_ref_ids() -> llvm::SmallVector<SemIR::InstId>& {
  123. return import_ref_ids_;
  124. }
  125. // Pre-computed parts of a binding pattern.
  126. // TODO: Consider putting this behind a narrower API to guard against emitting
  127. // multiple times.
  128. struct BindingPatternInfo {
  129. // The corresponding AnyBindName inst.
  130. SemIR::InstId bind_name_id;
  131. // The region of insts that computes the type of the binding.
  132. SemIR::ExprRegionId type_expr_region_id;
  133. };
  134. auto bind_name_map() -> Map<SemIR::InstId, BindingPatternInfo>& {
  135. return bind_name_map_;
  136. }
  137. auto var_storage_map() -> Map<SemIR::InstId, SemIR::InstId>& {
  138. return var_storage_map_;
  139. }
  140. // During Choice typechecking, each alternative turns into a name binding on
  141. // the Choice type, but this can't be done until the full Choice type is
  142. // known. This represents each binding to be done at the end of checking the
  143. // Choice type.
  144. struct ChoiceDeferredBinding {
  145. Parse::NodeId node_id;
  146. NameComponent name_component;
  147. };
  148. auto choice_deferred_bindings() -> llvm::SmallVector<ChoiceDeferredBinding>& {
  149. return choice_deferred_bindings_;
  150. }
  151. auto region_stack() -> RegionStack& { return region_stack_; }
  152. // An ongoing impl lookup, used to ensure termination.
  153. struct ImplLookupStackEntry {
  154. SemIR::ConstantId query_self_const_id;
  155. SemIR::ConstantId query_facet_type_const_id;
  156. // The location of the impl being looked at for the stack entry.
  157. SemIR::InstId impl_loc = SemIR::InstId::None;
  158. };
  159. auto impl_lookup_stack() -> llvm::SmallVector<ImplLookupStackEntry>& {
  160. return impl_lookup_stack_;
  161. }
  162. // --------------------------------------------------------------------------
  163. // Directly expose SemIR::File data accessors for brevity in calls.
  164. // --------------------------------------------------------------------------
  165. auto identifiers() -> SharedValueStores::IdentifierStore& {
  166. return sem_ir().identifiers();
  167. }
  168. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  169. auto reals() -> SharedValueStores::RealStore& { return sem_ir().reals(); }
  170. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  171. auto string_literal_values() -> SharedValueStores::StringLiteralStore& {
  172. return sem_ir().string_literal_values();
  173. }
  174. auto entity_names() -> SemIR::EntityNameStore& {
  175. return sem_ir().entity_names();
  176. }
  177. auto functions() -> ValueStore<SemIR::FunctionId>& {
  178. return sem_ir().functions();
  179. }
  180. auto classes() -> ValueStore<SemIR::ClassId>& { return sem_ir().classes(); }
  181. auto interfaces() -> ValueStore<SemIR::InterfaceId>& {
  182. return sem_ir().interfaces();
  183. }
  184. auto associated_constants() -> ValueStore<SemIR::AssociatedConstantId>& {
  185. return sem_ir().associated_constants();
  186. }
  187. auto facet_types() -> CanonicalValueStore<SemIR::FacetTypeId>& {
  188. return sem_ir().facet_types();
  189. }
  190. auto complete_facet_types() -> SemIR::File::CompleteFacetTypeStore& {
  191. return sem_ir().complete_facet_types();
  192. }
  193. auto impls() -> SemIR::ImplStore& { return sem_ir().impls(); }
  194. auto generics() -> SemIR::GenericStore& { return sem_ir().generics(); }
  195. auto specifics() -> SemIR::SpecificStore& { return sem_ir().specifics(); }
  196. auto import_irs() -> ValueStore<SemIR::ImportIRId>& {
  197. return sem_ir().import_irs();
  198. }
  199. auto import_ir_insts() -> ValueStore<SemIR::ImportIRInstId>& {
  200. return sem_ir().import_ir_insts();
  201. }
  202. auto names() -> SemIR::NameStoreWrapper { return sem_ir().names(); }
  203. auto name_scopes() -> SemIR::NameScopeStore& {
  204. return sem_ir().name_scopes();
  205. }
  206. auto struct_type_fields() -> SemIR::StructTypeFieldsStore& {
  207. return sem_ir().struct_type_fields();
  208. }
  209. auto types() -> SemIR::TypeStore& { return sem_ir().types(); }
  210. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  211. return sem_ir().type_blocks();
  212. }
  213. // Instructions should be added with `AddInst` or `AddInstInNoBlock` from
  214. // `inst.h`. This is `const` to prevent accidental misuse.
  215. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  216. auto constant_values() -> SemIR::ConstantValueStore& {
  217. return sem_ir().constant_values();
  218. }
  219. auto inst_blocks() -> SemIR::InstBlockStore& {
  220. return sem_ir().inst_blocks();
  221. }
  222. auto constants() -> SemIR::ConstantStore& { return sem_ir().constants(); }
  223. // --------------------------------------------------------------------------
  224. // End of SemIR::File members.
  225. // --------------------------------------------------------------------------
  226. private:
  227. // Handles diagnostics.
  228. DiagnosticEmitter<SemIRLoc>* emitter_;
  229. // Returns a lazily constructed TreeAndSubtrees.
  230. Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter_;
  231. // The SemIR::File being added to.
  232. SemIR::File* sem_ir_;
  233. // Whether to print verbose output.
  234. llvm::raw_ostream* vlog_stream_;
  235. // The stack during Build. Will contain file-level parse nodes on return.
  236. NodeStack node_stack_;
  237. // The stack of instruction blocks being used for general IR generation.
  238. InstBlockStack inst_block_stack_;
  239. // The stack of instruction blocks that contain pattern instructions.
  240. InstBlockStack pattern_block_stack_;
  241. // The stack of instruction blocks being used for param and arg ref blocks.
  242. ParamAndArgRefsStack param_and_arg_refs_stack_;
  243. // The stack of instruction blocks being used for type information while
  244. // processing arguments. This is used in parallel with
  245. // param_and_arg_refs_stack_. It's currently only used for struct literals,
  246. // where we need to track names for a type separate from the literal
  247. // arguments.
  248. InstBlockStack args_type_info_stack_;
  249. // The stack of StructTypeFields for in-progress StructTypeLiterals.
  250. ArrayStack<SemIR::StructTypeField> struct_type_fields_stack_;
  251. // The stack of FieldDecls for in-progress Class definitions.
  252. ArrayStack<SemIR::InstId> field_decls_stack_;
  253. // The stack used for qualified declaration name construction.
  254. DeclNameStack decl_name_stack_;
  255. // The stack of declarations that could have modifiers.
  256. DeclIntroducerStateStack decl_introducer_state_stack_;
  257. // The stack of scopes we are currently within.
  258. ScopeStack scope_stack_;
  259. // The stack of generic regions we are currently within.
  260. GenericRegionStack generic_region_stack_;
  261. // Contains a vtable block for each `class` scope which is currently being
  262. // defined, regardless of whether the class can have virtual functions.
  263. InstBlockStack vtable_stack_;
  264. // The list which will form NodeBlockId::Exports.
  265. llvm::SmallVector<SemIR::InstId> exports_;
  266. // Maps CheckIRId to ImportIRId.
  267. llvm::SmallVector<SemIR::ImportIRId> check_ir_map_;
  268. // Per-import constant values. These refer to the main IR and mainly serve as
  269. // a lookup table for quick access.
  270. //
  271. // Inline 0 elements because it's expected to require heap allocation.
  272. llvm::SmallVector<SemIR::ConstantValueStore, 0> import_ir_constant_values_;
  273. // Declaration instructions of entities that should have definitions by the
  274. // end of the current source file.
  275. llvm::SmallVector<SemIR::InstId> definitions_required_;
  276. // State for global initialization.
  277. GlobalInit global_init_;
  278. // A list of import refs which can't be inserted into their current context.
  279. // They're typically added during name lookup or import ref resolution, where
  280. // the current block on inst_block_stack_ is unrelated.
  281. //
  282. // These are instead added here because they're referenced by other
  283. // instructions and needs to be visible in textual IR.
  284. // FinalizeImportRefBlock() will produce an inst block for them.
  285. llvm::SmallVector<SemIR::InstId> import_ref_ids_;
  286. // Map from an AnyBindingPattern inst to precomputed parts of the
  287. // pattern-match SemIR for it.
  288. Map<SemIR::InstId, BindingPatternInfo> bind_name_map_;
  289. // Map from VarPattern insts to the corresponding VarStorage insts. The
  290. // VarStorage insts are allocated, emitted, and stored in the map after
  291. // processing the enclosing full-pattern.
  292. Map<SemIR::InstId, SemIR::InstId> var_storage_map_;
  293. // Each alternative in a Choice gets an entry here, they are stored in
  294. // declaration order. The vector is consumed and emptied at the end of the
  295. // Choice definition.
  296. //
  297. // TODO: This may need to be a stack of vectors if it becomes possible to
  298. // define a Choice type inside an alternative's parameter set.
  299. llvm::SmallVector<ChoiceDeferredBinding> choice_deferred_bindings_;
  300. // Stack of single-entry regions being built.
  301. RegionStack region_stack_;
  302. // Tracks all ongoing impl lookups in order to ensure that lookup terminates
  303. // via the acyclic rule and the termination rule.
  304. llvm::SmallVector<ImplLookupStackEntry> impl_lookup_stack_;
  305. };
  306. } // namespace Carbon::Check
  307. #endif // CARBON_TOOLCHAIN_CHECK_CONTEXT_H_