context.h 27 KB

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