context.h 15 KB

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