context.h 25 KB

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