context.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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 "common/map.h"
  7. #include "llvm/ADT/FoldingSet.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "toolchain/check/decl_introducer_state.h"
  10. #include "toolchain/check/decl_name_stack.h"
  11. #include "toolchain/check/diagnostic_helpers.h"
  12. #include "toolchain/check/generic_region_stack.h"
  13. #include "toolchain/check/global_init.h"
  14. #include "toolchain/check/inst_block_stack.h"
  15. #include "toolchain/check/node_stack.h"
  16. #include "toolchain/check/param_and_arg_refs_stack.h"
  17. #include "toolchain/check/scope_stack.h"
  18. #include "toolchain/parse/node_ids.h"
  19. #include "toolchain/parse/tree.h"
  20. #include "toolchain/parse/tree_and_subtrees.h"
  21. #include "toolchain/sem_ir/file.h"
  22. #include "toolchain/sem_ir/ids.h"
  23. #include "toolchain/sem_ir/import_ir.h"
  24. #include "toolchain/sem_ir/inst.h"
  25. #include "toolchain/sem_ir/name_scope.h"
  26. #include "toolchain/sem_ir/typed_insts.h"
  27. namespace Carbon::Check {
  28. // Information about a scope in which we can perform name lookup.
  29. struct LookupScope {
  30. // The name scope in which names are searched.
  31. SemIR::NameScopeId name_scope_id;
  32. // The specific for the name scope, or `Invalid` if the name scope is not
  33. // defined by a generic or we should perform lookup into the generic itself.
  34. SemIR::SpecificId specific_id;
  35. };
  36. // A result produced by name lookup.
  37. struct LookupResult {
  38. // The specific in which the lookup result was found. `Invalid` if the result
  39. // was not found in a specific.
  40. SemIR::SpecificId specific_id;
  41. // The declaration that was found by name lookup.
  42. SemIR::InstId inst_id;
  43. };
  44. // Information about an access.
  45. struct AccessInfo {
  46. // The constant being accessed.
  47. SemIR::ConstantId constant_id;
  48. // The highest allowed access for a lookup. For example, `Protected` allows
  49. // access to `Public` and `Protected` names, but not `Private`.
  50. SemIR::AccessKind highest_allowed_access;
  51. };
  52. // Context and shared functionality for semantics handlers.
  53. class Context {
  54. public:
  55. using DiagnosticEmitter = Carbon::DiagnosticEmitter<SemIRLoc>;
  56. using DiagnosticBuilder = DiagnosticEmitter::DiagnosticBuilder;
  57. // A function that forms a diagnostic for some kind of problem. The
  58. // DiagnosticBuilder is returned rather than emitted so that the caller can
  59. // add contextual notes as appropriate.
  60. using BuildDiagnosticFn =
  61. llvm::function_ref<auto()->Context::DiagnosticBuilder>;
  62. // Stores references for work.
  63. explicit Context(const Lex::TokenizedBuffer& tokens,
  64. DiagnosticEmitter& emitter, const Parse::Tree& parse_tree,
  65. llvm::function_ref<const Parse::TreeAndSubtrees&()>
  66. get_parse_tree_and_subtrees,
  67. SemIR::File& sem_ir, llvm::raw_ostream* vlog_stream);
  68. // Marks an implementation TODO. Always returns false.
  69. auto TODO(SemIRLoc loc, std::string label) -> bool;
  70. // Runs verification that the processing cleanly finished.
  71. auto VerifyOnFinish() -> void;
  72. // Adds an instruction to the current block, returning the produced ID.
  73. auto AddInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId;
  74. // Convenience for AddInst with typed nodes.
  75. template <typename InstT, typename LocT>
  76. auto AddInst(LocT loc, InstT inst)
  77. -> decltype(AddInst(SemIR::LocIdAndInst(loc, inst))) {
  78. return AddInst(SemIR::LocIdAndInst(loc, inst));
  79. }
  80. // Returns a LocIdAndInst for an instruction with an imported location. Checks
  81. // that the imported location is compatible with the kind of instruction being
  82. // created.
  83. template <typename InstT>
  84. requires SemIR::Internal::HasNodeId<InstT>
  85. auto MakeImportedLocAndInst(SemIR::ImportIRInstId imported_loc_id, InstT inst)
  86. -> SemIR::LocIdAndInst {
  87. if constexpr (!SemIR::Internal::HasUntypedNodeId<InstT>) {
  88. CheckCompatibleImportedNodeKind(imported_loc_id, InstT::Kind);
  89. }
  90. return SemIR::LocIdAndInst::UncheckedLoc(imported_loc_id, inst);
  91. }
  92. // Adds an instruction in no block, returning the produced ID. Should be used
  93. // rarely.
  94. auto AddInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId;
  95. // Convenience for AddInstInNoBlock with typed nodes.
  96. template <typename InstT, typename LocT>
  97. auto AddInstInNoBlock(LocT loc, InstT inst)
  98. -> decltype(AddInstInNoBlock(SemIR::LocIdAndInst(loc, inst))) {
  99. return AddInstInNoBlock(SemIR::LocIdAndInst(loc, inst));
  100. }
  101. // Adds an instruction to the current block, returning the produced ID. The
  102. // instruction is a placeholder that is expected to be replaced by
  103. // `ReplaceInstBeforeConstantUse`.
  104. auto AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId;
  105. // Adds an instruction in no block, returning the produced ID. Should be used
  106. // rarely. The instruction is a placeholder that is expected to be replaced by
  107. // `ReplaceInstBeforeConstantUse`.
  108. auto AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  109. -> SemIR::InstId;
  110. // Adds an instruction to the constants block, returning the produced ID.
  111. auto AddConstant(SemIR::Inst inst, bool is_symbolic) -> SemIR::ConstantId;
  112. // Pushes a parse tree node onto the stack, storing the SemIR::Inst as the
  113. // result.
  114. template <typename InstT>
  115. requires(SemIR::Internal::HasNodeId<InstT>)
  116. auto AddInstAndPush(decltype(InstT::Kind)::TypedNodeId node_id, InstT inst)
  117. -> void {
  118. node_stack_.Push(node_id, AddInst(node_id, inst));
  119. }
  120. // Replaces the instruction `inst_id` with `loc_id_and_inst`. The instruction
  121. // is required to not have been used in any constant evaluation, either
  122. // because it's newly created and entirely unused, or because it's only used
  123. // in a position that constant evaluation ignores, such as a return slot.
  124. auto ReplaceLocIdAndInstBeforeConstantUse(SemIR::InstId inst_id,
  125. SemIR::LocIdAndInst loc_id_and_inst)
  126. -> void;
  127. // Replaces the instruction `inst_id` with `inst`, not affecting location.
  128. // The instruction is required to not have been used in any constant
  129. // evaluation, either because it's newly created and entirely unused, or
  130. // because it's only used in a position that constant evaluation ignores, such
  131. // as a return slot.
  132. auto ReplaceInstBeforeConstantUse(SemIR::InstId inst_id, SemIR::Inst inst)
  133. -> void;
  134. // Sets only the parse node of an instruction. This is only used when setting
  135. // the parse node of an imported namespace. Versus
  136. // ReplaceInstBeforeConstantUse, it is safe to use after the namespace is used
  137. // in constant evaluation. It's exposed this way mainly so that `insts()` can
  138. // remain const.
  139. auto SetNamespaceNodeId(SemIR::InstId inst_id, Parse::NodeId node_id)
  140. -> void {
  141. sem_ir().insts().SetLocId(inst_id, SemIR::LocId(node_id));
  142. }
  143. // Adds a name to name lookup. Prints a diagnostic for name conflicts.
  144. auto AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id) -> void;
  145. // Performs name lookup in a specified scope for a name appearing in a
  146. // declaration, returning the referenced instruction. If scope_id is invalid,
  147. // uses the current contextual scope.
  148. auto LookupNameInDecl(SemIR::LocId loc_id, SemIR::NameId name_id,
  149. SemIR::NameScopeId scope_id) -> SemIR::InstId;
  150. // Performs an unqualified name lookup, returning the referenced instruction.
  151. auto LookupUnqualifiedName(Parse::NodeId node_id, SemIR::NameId name_id,
  152. bool required = true) -> LookupResult;
  153. // Performs a name lookup in a specified scope, returning the referenced
  154. // instruction. Does not look into extended scopes. Returns an invalid
  155. // instruction if the name is not found.
  156. auto LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
  157. SemIR::NameScopeId scope_id,
  158. const SemIR::NameScope& scope)
  159. -> std::pair<SemIR::InstId, SemIR::AccessKind>;
  160. // Performs a qualified name lookup in a specified scope and in scopes that
  161. // it extends, returning the referenced instruction.
  162. auto LookupQualifiedName(SemIRLoc loc, SemIR::NameId name_id,
  163. LookupScope scope, bool required = true,
  164. std::optional<AccessInfo> access_info = std::nullopt)
  165. -> LookupResult;
  166. // Returns the instruction corresponding to a name in the core package, or
  167. // BuiltinError if not found.
  168. auto LookupNameInCore(SemIRLoc loc, llvm::StringRef name) -> SemIR::InstId;
  169. // Prints a diagnostic for a duplicate name.
  170. auto DiagnoseDuplicateName(SemIRLoc dup_def, SemIRLoc prev_def) -> void;
  171. // Prints a diagnostic for a missing name.
  172. auto DiagnoseNameNotFound(SemIRLoc loc, SemIR::NameId name_id) -> void;
  173. // Adds a note to a diagnostic explaining that a class is incomplete.
  174. auto NoteIncompleteClass(SemIR::ClassId class_id, DiagnosticBuilder& builder)
  175. -> void;
  176. // Adds a note to a diagnostic explaining that an interface is not defined.
  177. auto NoteUndefinedInterface(SemIR::InterfaceId interface_id,
  178. DiagnosticBuilder& builder) -> void;
  179. // Returns the current scope, if it is of the specified kind. Otherwise,
  180. // returns nullopt.
  181. template <typename InstT>
  182. auto GetCurrentScopeAs() -> std::optional<InstT> {
  183. return scope_stack().GetCurrentScopeAs<InstT>(sem_ir());
  184. }
  185. // Adds a `Branch` instruction branching to a new instruction block, and
  186. // returns the ID of the new block. All paths to the branch target must go
  187. // through the current block, though not necessarily through this branch.
  188. auto AddDominatedBlockAndBranch(Parse::NodeId node_id) -> SemIR::InstBlockId;
  189. // Adds a `Branch` instruction branching to a new instruction block with a
  190. // value, and returns the ID of the new block. All paths to the branch target
  191. // must go through the current block.
  192. auto AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  193. SemIR::InstId arg_id)
  194. -> SemIR::InstBlockId;
  195. // Adds a `BranchIf` instruction branching to a new instruction block, and
  196. // returns the ID of the new block. All paths to the branch target must go
  197. // through the current block.
  198. auto AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  199. SemIR::InstId cond_id)
  200. -> SemIR::InstBlockId;
  201. // Handles recovergence of control flow. Adds branches from the top
  202. // `num_blocks` on the instruction block stack to a new block, pops the
  203. // existing blocks, and pushes the new block onto the instruction block stack.
  204. auto AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  205. -> void;
  206. // Handles recovergence of control flow with a result value. Adds branches
  207. // from the top few blocks on the instruction block stack to a new block, pops
  208. // the existing blocks, and pushes the new block onto the instruction block
  209. // stack. The number of blocks popped is the size of `block_args`, and the
  210. // corresponding result values are the elements of `block_args`. Returns an
  211. // instruction referring to the result value.
  212. auto AddConvergenceBlockWithArgAndPush(
  213. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  214. -> SemIR::InstId;
  215. // Sets the constant value of a block argument created as the result of a
  216. // branch. `select_id` should be a `BlockArg` that selects between two
  217. // values. `cond_id` is the condition, `if_false` is the value to use if the
  218. // condition is false, and `if_true` is the value to use if the condition is
  219. // true. We don't track enough information in the `BlockArg` inst for
  220. // `TryEvalInst` to do this itself.
  221. auto SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  222. SemIR::InstId cond_id,
  223. SemIR::InstId if_true,
  224. SemIR::InstId if_false) -> void;
  225. // Add the current code block to the enclosing function.
  226. // TODO: The node_id is taken for expressions, which can occur in
  227. // non-function contexts. This should be refactored to support non-function
  228. // contexts, and node_id removed.
  229. auto AddCurrentCodeBlockToFunction(
  230. Parse::NodeId node_id = Parse::NodeId::Invalid) -> void;
  231. // Returns whether the current position in the current block is reachable.
  232. auto is_current_position_reachable() -> bool;
  233. // Returns the type ID for a constant of type `type`.
  234. auto GetTypeIdForTypeConstant(SemIR::ConstantId constant_id) -> SemIR::TypeId;
  235. // Returns the type ID for an instruction whose constant value is of type
  236. // `type`.
  237. auto GetTypeIdForTypeInst(SemIR::InstId inst_id) -> SemIR::TypeId {
  238. return GetTypeIdForTypeConstant(constant_values().Get(inst_id));
  239. }
  240. // Attempts to complete the type `type_id`. Returns `true` if the type is
  241. // complete, or `false` if it could not be completed. A complete type has
  242. // known object and value representations.
  243. //
  244. // If the type is not complete, `diagnoser` is invoked to diagnose the issue,
  245. // if a `diagnoser` is provided. The builder it returns will be annotated to
  246. // describe the reason why the type is not complete.
  247. auto TryToCompleteType(
  248. SemIR::TypeId type_id,
  249. std::optional<BuildDiagnosticFn> diagnoser = std::nullopt) -> bool;
  250. // Attempts to complete and define the type `type_id`. Returns `true` if the
  251. // type is defined, or `false` if no definition is available. A defined type
  252. // has known members.
  253. //
  254. // This is the same as `TryToCompleteType` except for interfaces, which are
  255. // complete before they are fully defined.
  256. auto TryToDefineType(
  257. SemIR::TypeId type_id,
  258. std::optional<BuildDiagnosticFn> diagnoser = std::nullopt) -> bool;
  259. // Returns the type `type_id` as a complete type, or produces an incomplete
  260. // type error and returns an error type. This is a convenience wrapper around
  261. // TryToCompleteType.
  262. auto AsCompleteType(SemIR::TypeId type_id, BuildDiagnosticFn diagnoser)
  263. -> SemIR::TypeId {
  264. return TryToCompleteType(type_id, diagnoser) ? type_id
  265. : SemIR::TypeId::Error;
  266. }
  267. // TODO: Consider moving these `Get*Type` functions to a separate class.
  268. // Gets the type for the name of an associated entity.
  269. auto GetAssociatedEntityType(SemIR::TypeId interface_type_id,
  270. SemIR::TypeId entity_type_id) -> SemIR::TypeId;
  271. // Gets a builtin type. The returned type will be complete.
  272. auto GetBuiltinType(SemIR::BuiltinInstKind kind) -> SemIR::TypeId;
  273. // Gets a function type. The returned type will be complete.
  274. auto GetFunctionType(SemIR::FunctionId fn_id, SemIR::SpecificId specific_id)
  275. -> SemIR::TypeId;
  276. // Gets a generic class type, which is the type of a name of a generic class,
  277. // such as the type of `Vector` given `class Vector(T:! type)`. The returned
  278. // type will be complete.
  279. auto GetGenericClassType(SemIR::ClassId class_id,
  280. SemIR::SpecificId enclosing_specific_id)
  281. -> SemIR::TypeId;
  282. // Gets a generic interface type, which is the type of a name of a generic
  283. // interface, such as the type of `AddWith` given
  284. // `interface AddWith(T:! type)`. The returned type will be complete.
  285. auto GetGenericInterfaceType(SemIR::InterfaceId interface_id,
  286. SemIR::SpecificId enclosing_specific_id)
  287. -> SemIR::TypeId;
  288. // Returns a pointer type whose pointee type is `pointee_type_id`.
  289. auto GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId;
  290. // Returns a struct type with the given fields, which should be a block of
  291. // `StructTypeField`s.
  292. auto GetStructType(SemIR::InstBlockId refs_id) -> SemIR::TypeId;
  293. // Returns a tuple type with the given element types.
  294. auto GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids) -> SemIR::TypeId;
  295. // Returns an unbound element type.
  296. auto GetUnboundElementType(SemIR::TypeId class_type_id,
  297. SemIR::TypeId element_type_id) -> SemIR::TypeId;
  298. // Removes any top-level `const` qualifiers from a type.
  299. auto GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId;
  300. // Adds an exported name.
  301. auto AddExport(SemIR::InstId inst_id) -> void { exports_.push_back(inst_id); }
  302. auto Finalize() -> void;
  303. // Sets the total number of IRs which exist. This is used to prepare a map
  304. // from IR to imported IR.
  305. auto SetTotalIRCount(int num_irs) -> void {
  306. CARBON_CHECK(check_ir_map_.empty(), "SetTotalIRCount is only called once");
  307. check_ir_map_.resize(num_irs, SemIR::ImportIRId::Invalid);
  308. }
  309. // Returns the imported IR ID for an IR, or invalid if not imported.
  310. auto GetImportIRId(const SemIR::File& sem_ir) -> SemIR::ImportIRId& {
  311. return check_ir_map_[sem_ir.check_ir_id().index];
  312. }
  313. // True if the current file is an impl file.
  314. auto IsImplFile() -> bool {
  315. return sem_ir_->import_irs().Get(SemIR::ImportIRId::ApiForImpl).sem_ir !=
  316. nullptr;
  317. }
  318. // Prints information for a stack dump.
  319. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  320. // Prints the the formatted sem_ir to stderr.
  321. LLVM_DUMP_METHOD auto DumpFormattedFile() const -> void;
  322. // Get the Lex::TokenKind of a node for diagnostics.
  323. auto token_kind(Parse::NodeId node_id) -> Lex::TokenKind {
  324. return tokens().GetKind(parse_tree().node_token(node_id));
  325. }
  326. auto tokens() -> const Lex::TokenizedBuffer& { return *tokens_; }
  327. auto emitter() -> DiagnosticEmitter& { return *emitter_; }
  328. auto parse_tree() -> const Parse::Tree& { return *parse_tree_; }
  329. auto parse_tree_and_subtrees() -> const Parse::TreeAndSubtrees& {
  330. return get_parse_tree_and_subtrees_();
  331. }
  332. auto sem_ir() -> SemIR::File& { return *sem_ir_; }
  333. auto node_stack() -> NodeStack& { return node_stack_; }
  334. auto inst_block_stack() -> InstBlockStack& { return inst_block_stack_; }
  335. auto param_and_arg_refs_stack() -> ParamAndArgRefsStack& {
  336. return param_and_arg_refs_stack_;
  337. }
  338. auto args_type_info_stack() -> InstBlockStack& {
  339. return args_type_info_stack_;
  340. }
  341. auto decl_name_stack() -> DeclNameStack& { return decl_name_stack_; }
  342. auto decl_introducer_state_stack() -> DeclIntroducerStateStack& {
  343. return decl_introducer_state_stack_;
  344. }
  345. auto scope_stack() -> ScopeStack& { return scope_stack_; }
  346. auto return_scope_stack() -> llvm::SmallVector<ScopeStack::ReturnScope>& {
  347. return scope_stack().return_scope_stack();
  348. }
  349. auto break_continue_stack()
  350. -> llvm::SmallVector<ScopeStack::BreakContinueScope>& {
  351. return scope_stack().break_continue_stack();
  352. }
  353. auto generic_region_stack() -> GenericRegionStack& {
  354. return generic_region_stack_;
  355. }
  356. auto import_ir_constant_values()
  357. -> llvm::SmallVector<SemIR::ConstantValueStore, 0>& {
  358. return import_ir_constant_values_;
  359. }
  360. // Directly expose SemIR::File data accessors for brevity in calls.
  361. auto identifiers() -> CanonicalValueStore<IdentifierId>& {
  362. return sem_ir().identifiers();
  363. }
  364. auto ints() -> CanonicalValueStore<IntId>& { return sem_ir().ints(); }
  365. auto reals() -> ValueStore<RealId>& { return sem_ir().reals(); }
  366. auto floats() -> FloatValueStore& { return sem_ir().floats(); }
  367. auto string_literal_values() -> CanonicalValueStore<StringLiteralValueId>& {
  368. return sem_ir().string_literal_values();
  369. }
  370. auto entity_names() -> SemIR::EntityNameStore& {
  371. return sem_ir().entity_names();
  372. }
  373. auto functions() -> ValueStore<SemIR::FunctionId>& {
  374. return sem_ir().functions();
  375. }
  376. auto classes() -> ValueStore<SemIR::ClassId>& { return sem_ir().classes(); }
  377. auto interfaces() -> ValueStore<SemIR::InterfaceId>& {
  378. return sem_ir().interfaces();
  379. }
  380. auto impls() -> SemIR::ImplStore& { return sem_ir().impls(); }
  381. auto generics() -> SemIR::GenericStore& { return sem_ir().generics(); }
  382. auto specifics() -> SemIR::SpecificStore& { return sem_ir().specifics(); }
  383. auto import_irs() -> ValueStore<SemIR::ImportIRId>& {
  384. return sem_ir().import_irs();
  385. }
  386. auto import_ir_insts() -> ValueStore<SemIR::ImportIRInstId>& {
  387. return sem_ir().import_ir_insts();
  388. }
  389. auto names() -> SemIR::NameStoreWrapper { return sem_ir().names(); }
  390. auto name_scopes() -> SemIR::NameScopeStore& {
  391. return sem_ir().name_scopes();
  392. }
  393. auto types() -> SemIR::TypeStore& { return sem_ir().types(); }
  394. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  395. return sem_ir().type_blocks();
  396. }
  397. // Instructions should be added with `AddInst` or `AddInstInNoBlock`. This is
  398. // `const` to prevent accidental misuse.
  399. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  400. auto constant_values() -> SemIR::ConstantValueStore& {
  401. return sem_ir().constant_values();
  402. }
  403. auto inst_blocks() -> SemIR::InstBlockStore& {
  404. return sem_ir().inst_blocks();
  405. }
  406. auto constants() -> SemIR::ConstantStore& { return sem_ir().constants(); }
  407. auto definitions_required() -> llvm::SmallVector<SemIR::InstId>& {
  408. return definitions_required_;
  409. }
  410. auto global_init() -> GlobalInit& { return global_init_; }
  411. auto import_ref_ids() -> llvm::SmallVector<SemIR::InstId>& {
  412. return import_ref_ids_;
  413. }
  414. private:
  415. // A FoldingSet node for a type.
  416. class TypeNode : public llvm::FastFoldingSetNode {
  417. public:
  418. explicit TypeNode(const llvm::FoldingSetNodeID& node_id,
  419. SemIR::TypeId type_id)
  420. : llvm::FastFoldingSetNode(node_id), type_id_(type_id) {}
  421. auto type_id() -> SemIR::TypeId { return type_id_; }
  422. private:
  423. SemIR::TypeId type_id_;
  424. };
  425. // Checks that the provided imported location has a node kind that is
  426. // compatible with that of the given instruction.
  427. auto CheckCompatibleImportedNodeKind(SemIR::ImportIRInstId imported_loc_id,
  428. SemIR::InstKind kind) -> void;
  429. // Finish producing an instruction. Set its constant value, and register it in
  430. // any applicable instruction lists.
  431. auto FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void;
  432. // Tokens for getting data on literals.
  433. const Lex::TokenizedBuffer* tokens_;
  434. // Handles diagnostics.
  435. DiagnosticEmitter* emitter_;
  436. // The file's parse tree.
  437. const Parse::Tree* parse_tree_;
  438. // Returns a lazily constructed TreeAndSubtrees.
  439. llvm::function_ref<const Parse::TreeAndSubtrees&()>
  440. get_parse_tree_and_subtrees_;
  441. // The SemIR::File being added to.
  442. SemIR::File* sem_ir_;
  443. // Whether to print verbose output.
  444. llvm::raw_ostream* vlog_stream_;
  445. // The stack during Build. Will contain file-level parse nodes on return.
  446. NodeStack node_stack_;
  447. // The stack of instruction blocks being used for general IR generation.
  448. InstBlockStack inst_block_stack_;
  449. // The stack of instruction blocks being used for param and arg ref blocks.
  450. ParamAndArgRefsStack param_and_arg_refs_stack_;
  451. // The stack of instruction blocks being used for type information while
  452. // processing arguments. This is used in parallel with
  453. // param_and_arg_refs_stack_. It's currently only used for struct literals,
  454. // where we need to track names for a type separate from the literal
  455. // arguments.
  456. InstBlockStack args_type_info_stack_;
  457. // The stack used for qualified declaration name construction.
  458. DeclNameStack decl_name_stack_;
  459. // The stack of declarations that could have modifiers.
  460. DeclIntroducerStateStack decl_introducer_state_stack_;
  461. // The stack of scopes we are currently within.
  462. ScopeStack scope_stack_;
  463. // The stack of generic regions we are currently within.
  464. GenericRegionStack generic_region_stack_;
  465. // Cache of reverse mapping from type constants to types.
  466. //
  467. // TODO: Instead of mapping to a dense `TypeId` space, we could make `TypeId`
  468. // be a thin wrapper around `ConstantId` and only perform the lookup only when
  469. // we want to access the completeness and value representation of a type. It's
  470. // not clear whether that would result in more or fewer lookups.
  471. //
  472. // TODO: Should this be part of the `TypeStore`?
  473. Map<SemIR::ConstantId, SemIR::TypeId> type_ids_for_type_constants_;
  474. // The list which will form NodeBlockId::Exports.
  475. llvm::SmallVector<SemIR::InstId> exports_;
  476. // Maps CheckIRId to ImportIRId.
  477. llvm::SmallVector<SemIR::ImportIRId> check_ir_map_;
  478. // Per-import constant values. These refer to the main IR and mainly serve as
  479. // a lookup table for quick access.
  480. //
  481. // Inline 0 elements because it's expected to require heap allocation.
  482. llvm::SmallVector<SemIR::ConstantValueStore, 0> import_ir_constant_values_;
  483. // Declaration instructions of entities that should have definitions by the
  484. // end of the current source file.
  485. llvm::SmallVector<SemIR::InstId> definitions_required_;
  486. // State for global initialization.
  487. GlobalInit global_init_;
  488. // A list of import refs which can't be inserted into their current context.
  489. // They're typically added during name lookup or import ref resolution, where
  490. // the current block on inst_block_stack_ is unrelated.
  491. //
  492. // These are instead added here because they're referenced by other
  493. // instructions and needs to be visible in textual IR.
  494. // FinalizeImportRefBlock() will produce an inst block for them.
  495. llvm::SmallVector<SemIR::InstId> import_ref_ids_;
  496. };
  497. } // namespace Carbon::Check
  498. #endif // CARBON_TOOLCHAIN_CHECK_CONTEXT_H_