context.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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/full_pattern_stack.h"
  13. #include "toolchain/check/generic_region_stack.h"
  14. #include "toolchain/check/global_init.h"
  15. #include "toolchain/check/inst_block_stack.h"
  16. #include "toolchain/check/node_stack.h"
  17. #include "toolchain/check/param_and_arg_refs_stack.h"
  18. #include "toolchain/check/region_stack.h"
  19. #include "toolchain/check/scope_index.h"
  20. #include "toolchain/check/scope_stack.h"
  21. #include "toolchain/parse/node_ids.h"
  22. #include "toolchain/parse/tree.h"
  23. #include "toolchain/parse/tree_and_subtrees.h"
  24. #include "toolchain/sem_ir/file.h"
  25. #include "toolchain/sem_ir/ids.h"
  26. #include "toolchain/sem_ir/import_ir.h"
  27. #include "toolchain/sem_ir/inst.h"
  28. #include "toolchain/sem_ir/name_scope.h"
  29. #include "toolchain/sem_ir/typed_insts.h"
  30. namespace Carbon::Check {
  31. // Information about a scope in which we can perform name lookup.
  32. struct LookupScope {
  33. // The name scope in which names are searched.
  34. SemIR::NameScopeId name_scope_id;
  35. // The specific for the name scope, or `None` if the name scope is not
  36. // defined by a generic or we should perform lookup into the generic itself.
  37. SemIR::SpecificId specific_id;
  38. };
  39. // A result produced by name lookup.
  40. struct LookupResult {
  41. // The specific in which the lookup result was found. `None` if the result
  42. // was not found in a specific.
  43. SemIR::SpecificId specific_id;
  44. // The result from the lookup in the scope.
  45. SemIR::ScopeLookupResult scope_result;
  46. };
  47. // Information about an access.
  48. struct AccessInfo {
  49. // The constant being accessed.
  50. SemIR::ConstantId constant_id;
  51. // The highest allowed access for a lookup. For example, `Protected` allows
  52. // access to `Public` and `Protected` names, but not `Private`.
  53. SemIR::AccessKind highest_allowed_access;
  54. };
  55. // Context and shared functionality for semantics handlers.
  56. class Context {
  57. public:
  58. using DiagnosticEmitter = Carbon::DiagnosticEmitter<SemIRLoc>;
  59. using DiagnosticBuilder = DiagnosticEmitter::DiagnosticBuilder;
  60. // A function that forms a diagnostic for some kind of problem. The
  61. // DiagnosticBuilder is returned rather than emitted so that the caller can
  62. // add contextual notes as appropriate.
  63. using BuildDiagnosticFn = llvm::function_ref<auto()->DiagnosticBuilder>;
  64. // Stores references for work.
  65. explicit Context(DiagnosticEmitter* emitter,
  66. Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter,
  67. SemIR::File* sem_ir, int imported_ir_count,
  68. int total_ir_count, llvm::raw_ostream* vlog_stream);
  69. // Marks an implementation TODO. Always returns false.
  70. auto TODO(SemIRLoc loc, std::string label) -> bool;
  71. // Runs verification that the processing cleanly finished.
  72. auto VerifyOnFinish() -> void;
  73. // Adds an instruction to the current block, returning the produced ID.
  74. auto AddInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId {
  75. auto inst_id = AddInstInNoBlock(loc_id_and_inst);
  76. inst_block_stack_.AddInstId(inst_id);
  77. return inst_id;
  78. }
  79. // Convenience for AddInst with typed nodes.
  80. template <typename InstT, typename LocT>
  81. auto AddInst(LocT loc, InstT inst)
  82. -> decltype(AddInst(SemIR::LocIdAndInst(loc, inst))) {
  83. return AddInst(SemIR::LocIdAndInst(loc, inst));
  84. }
  85. // Returns a LocIdAndInst for an instruction with an imported location. Checks
  86. // that the imported location is compatible with the kind of instruction being
  87. // created.
  88. template <typename InstT>
  89. requires SemIR::Internal::HasNodeId<InstT>
  90. auto MakeImportedLocAndInst(SemIR::ImportIRInstId imported_loc_id, InstT inst)
  91. -> SemIR::LocIdAndInst {
  92. if constexpr (!SemIR::Internal::HasUntypedNodeId<InstT>) {
  93. CheckCompatibleImportedNodeKind(imported_loc_id, InstT::Kind);
  94. }
  95. return SemIR::LocIdAndInst::UncheckedLoc(imported_loc_id, inst);
  96. }
  97. // Adds an instruction in no block, returning the produced ID. Should be used
  98. // rarely.
  99. auto AddInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId {
  100. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  101. CARBON_VLOG("AddInst: {0}\n", loc_id_and_inst.inst);
  102. FinishInst(inst_id, loc_id_and_inst.inst);
  103. return inst_id;
  104. }
  105. // Convenience for AddInstInNoBlock with typed nodes.
  106. template <typename InstT, typename LocT>
  107. auto AddInstInNoBlock(LocT loc, InstT inst)
  108. -> decltype(AddInstInNoBlock(SemIR::LocIdAndInst(loc, inst))) {
  109. return AddInstInNoBlock(SemIR::LocIdAndInst(loc, inst));
  110. }
  111. // If the instruction has an implicit location and a constant value, returns
  112. // the constant value's instruction ID. Otherwise, same as AddInst.
  113. auto GetOrAddInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId;
  114. // Convenience for GetOrAddInst with typed nodes.
  115. template <typename InstT, typename LocT>
  116. auto GetOrAddInst(LocT loc, InstT inst)
  117. -> decltype(GetOrAddInst(SemIR::LocIdAndInst(loc, inst))) {
  118. return GetOrAddInst(SemIR::LocIdAndInst(loc, inst));
  119. }
  120. // Adds an instruction to the current block, returning the produced ID. The
  121. // instruction is a placeholder that is expected to be replaced by
  122. // `ReplaceInstBeforeConstantUse`.
  123. auto AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId;
  124. // Adds an instruction in no block, returning the produced ID. Should be used
  125. // rarely. The instruction is a placeholder that is expected to be replaced by
  126. // `ReplaceInstBeforeConstantUse`.
  127. auto AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  128. -> SemIR::InstId;
  129. // Adds an instruction to the current pattern block, returning the produced
  130. // ID.
  131. // TODO: Is it possible to remove this and pattern_block_stack, now that
  132. // we have BeginSubpattern etc. instead?
  133. auto AddPatternInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId {
  134. auto inst_id = AddInstInNoBlock(loc_id_and_inst);
  135. pattern_block_stack_.AddInstId(inst_id);
  136. return inst_id;
  137. }
  138. // Convenience for AddPatternInst with typed nodes.
  139. template <typename InstT>
  140. requires(SemIR::Internal::HasNodeId<InstT>)
  141. auto AddPatternInst(decltype(InstT::Kind)::TypedNodeId node_id, InstT inst)
  142. -> SemIR::InstId {
  143. return AddPatternInst(SemIR::LocIdAndInst(node_id, inst));
  144. }
  145. // Pushes a parse tree node onto the stack, storing the SemIR::Inst as the
  146. // result.
  147. template <typename InstT>
  148. requires(SemIR::Internal::HasNodeId<InstT>)
  149. auto AddInstAndPush(decltype(InstT::Kind)::TypedNodeId node_id, InstT inst)
  150. -> void {
  151. node_stack_.Push(node_id, AddInst(node_id, inst));
  152. }
  153. // Replaces the instruction at `inst_id` with `loc_id_and_inst`. The
  154. // instruction is required to not have been used in any constant evaluation,
  155. // either because it's newly created and entirely unused, or because it's only
  156. // used in a position that constant evaluation ignores, such as a return slot.
  157. auto ReplaceLocIdAndInstBeforeConstantUse(SemIR::InstId inst_id,
  158. SemIR::LocIdAndInst loc_id_and_inst)
  159. -> void;
  160. // Replaces the instruction at `inst_id` with `inst`, not affecting location.
  161. // The instruction is required to not have been used in any constant
  162. // evaluation, either because it's newly created and entirely unused, or
  163. // because it's only used in a position that constant evaluation ignores, such
  164. // as a return slot.
  165. auto ReplaceInstBeforeConstantUse(SemIR::InstId inst_id, SemIR::Inst inst)
  166. -> void;
  167. // Replaces the instruction at `inst_id` with `inst`, not affecting location.
  168. // The instruction is required to not change its constant value.
  169. auto ReplaceInstPreservingConstantValue(SemIR::InstId inst_id,
  170. SemIR::Inst inst) -> void;
  171. // Sets only the parse node of an instruction. This is only used when setting
  172. // the parse node of an imported namespace. Versus
  173. // ReplaceInstBeforeConstantUse, it is safe to use after the namespace is used
  174. // in constant evaluation. It's exposed this way mainly so that `insts()` can
  175. // remain const.
  176. auto SetNamespaceNodeId(SemIR::InstId inst_id, Parse::NodeId node_id)
  177. -> void {
  178. sem_ir().insts().SetLocId(inst_id, SemIR::LocId(node_id));
  179. }
  180. // Adds a name to name lookup. Prints a diagnostic for name conflicts. If
  181. // specified, `scope_index` specifies which lexical scope the name is inserted
  182. // into, otherwise the name is inserted into the current scope.
  183. auto AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id,
  184. ScopeIndex scope_index = ScopeIndex::None) -> void;
  185. // Performs name lookup in a specified scope for a name appearing in a
  186. // declaration. If scope_id is `None`, performs lookup into the lexical scope
  187. // specified by scope_index instead.
  188. auto LookupNameInDecl(SemIR::LocId loc_id, SemIR::NameId name_id,
  189. SemIR::NameScopeId scope_id, ScopeIndex scope_index)
  190. -> SemIR::ScopeLookupResult;
  191. // Performs an unqualified name lookup, returning the referenced `InstId`.
  192. auto LookupUnqualifiedName(Parse::NodeId node_id, SemIR::NameId name_id,
  193. bool required = true) -> LookupResult;
  194. // Performs a name lookup in a specified scope, returning the referenced
  195. // `InstId`. Does not look into extended scopes. Returns `InstId::None` if the
  196. // name is not found.
  197. //
  198. // If `is_being_declared` is false, then this is a regular name lookup, and
  199. // the name will be poisoned if not found so that later lookups will fail; a
  200. // poisoned name will be treated as if it is not declared. Otherwise, this is
  201. // a lookup for a name being declared, so the name will not be poisoned, but
  202. // poison will be returned if it's already been looked up.
  203. auto LookupNameInExactScope(SemIR::LocId loc_id, SemIR::NameId name_id,
  204. SemIR::NameScopeId scope_id,
  205. SemIR::NameScope& scope,
  206. bool is_being_declared = false)
  207. -> SemIR::ScopeLookupResult;
  208. // Appends the lookup scopes corresponding to `base_const_id` to `*scopes`.
  209. // Returns `false` if not a scope. On invalid scopes, prints a diagnostic, but
  210. // still updates `*scopes` and returns `true`.
  211. auto AppendLookupScopesForConstant(SemIR::LocId loc_id,
  212. SemIR::ConstantId base_const_id,
  213. llvm::SmallVector<LookupScope>* scopes)
  214. -> bool;
  215. // Performs a qualified name lookup in a specified scopes and in scopes that
  216. // they extend, returning the referenced `InstId`.
  217. auto LookupQualifiedName(SemIR::LocId loc_id, SemIR::NameId name_id,
  218. llvm::ArrayRef<LookupScope> lookup_scopes,
  219. bool required = true,
  220. std::optional<AccessInfo> access_info = std::nullopt)
  221. -> LookupResult;
  222. // Returns the `InstId` corresponding to a name in the core package, or
  223. // BuiltinErrorInst if not found.
  224. auto LookupNameInCore(SemIR::LocId loc_id, llvm::StringRef name)
  225. -> SemIR::InstId;
  226. // Prints a diagnostic for a duplicate name.
  227. auto DiagnoseDuplicateName(SemIRLoc dup_def, SemIRLoc prev_def) -> void;
  228. // Prints a diagnostic for a poisoned name when it's later declared.
  229. auto DiagnosePoisonedName(SemIR::LocId poisoning_loc_id,
  230. SemIR::InstId decl_inst_id) -> void;
  231. // Prints a diagnostic for a missing name.
  232. auto DiagnoseNameNotFound(SemIRLoc loc, SemIR::NameId name_id) -> void;
  233. // Prints a diagnostic for a missing qualified name.
  234. auto DiagnoseMemberNameNotFound(SemIRLoc loc, SemIR::NameId name_id,
  235. llvm::ArrayRef<LookupScope> lookup_scopes)
  236. -> void;
  237. // Adds a note to a diagnostic explaining that a class is incomplete.
  238. auto NoteIncompleteClass(SemIR::ClassId class_id, DiagnosticBuilder& builder)
  239. -> void;
  240. // Adds a note to a diagnostic explaining that a class is abstract.
  241. auto NoteAbstractClass(SemIR::ClassId class_id, DiagnosticBuilder& builder)
  242. -> void;
  243. // Adds a note to a diagnostic explaining that an interface is not defined.
  244. auto NoteUndefinedInterface(SemIR::InterfaceId interface_id,
  245. DiagnosticBuilder& builder) -> void;
  246. // Returns the type ID for a constant that is a type value, i.e. it is a value
  247. // of type `TypeType`.
  248. //
  249. // Facet values are of the same typishness as types, but are not themselves
  250. // types, so they can not be passed here. They should be converted to a type
  251. // through an `as type` conversion, that is, to a value of type `TypeType`.
  252. auto GetTypeIdForTypeConstant(SemIR::ConstantId constant_id) -> SemIR::TypeId;
  253. // Returns the type ID for an instruction whose constant value is a type
  254. // value, i.e. it is a value of type `TypeType`.
  255. //
  256. // Instructions whose values are facet values (see `FacetValue`) produce a
  257. // value of the same typishness as types, but which are themselves not types,
  258. // so they can not be passed here. They should be converted to a type through
  259. // an `as type` conversion, such as to a `FacetAccessType` instruction whose
  260. // value is of type `TypeType`.
  261. auto GetTypeIdForTypeInst(SemIR::InstId inst_id) -> SemIR::TypeId {
  262. return GetTypeIdForTypeConstant(constant_values().Get(inst_id));
  263. }
  264. // Returns whether `type_id` represents a facet type.
  265. auto IsFacetType(SemIR::TypeId type_id) -> bool {
  266. return type_id == SemIR::TypeType::SingletonTypeId ||
  267. types().Is<SemIR::FacetType>(type_id);
  268. }
  269. // Create a FacetType typed instruction object consisting of a single
  270. // interface.
  271. auto FacetTypeFromInterface(SemIR::InterfaceId interface_id,
  272. SemIR::SpecificId specific_id)
  273. -> SemIR::FacetType;
  274. // TODO: Consider moving these `Get*Type` functions to a separate class.
  275. // Gets the type to use for an unbound associated entity declared in this
  276. // interface. For example, this is the type of `I.T` after
  277. // `interface I { let T:! type; }`.
  278. // The name of the interface is used for diagnostics.
  279. // TODO: Should we use a different type for each such entity, or the same type
  280. // for all associated entities?
  281. auto GetAssociatedEntityType(SemIR::TypeId interface_type_id)
  282. -> SemIR::TypeId;
  283. // Gets a singleton type. The returned type will be complete. Requires that
  284. // `singleton_id` is already validated to be a singleton.
  285. auto GetSingletonType(SemIR::InstId singleton_id) -> SemIR::TypeId;
  286. // Gets a class type.
  287. auto GetClassType(SemIR::ClassId class_id, SemIR::SpecificId specific_id)
  288. -> SemIR::TypeId;
  289. // Gets a function type. The returned type will be complete.
  290. auto GetFunctionType(SemIR::FunctionId fn_id, SemIR::SpecificId specific_id)
  291. -> SemIR::TypeId;
  292. // Gets the type of an associated function with the `Self` parameter bound to
  293. // a particular value. The returned type will be complete.
  294. auto GetFunctionTypeWithSelfType(SemIR::InstId interface_function_type_id,
  295. SemIR::InstId self_id) -> SemIR::TypeId;
  296. // Gets a generic class type, which is the type of a name of a generic class,
  297. // such as the type of `Vector` given `class Vector(T:! type)`. The returned
  298. // type will be complete.
  299. auto GetGenericClassType(SemIR::ClassId class_id,
  300. SemIR::SpecificId enclosing_specific_id)
  301. -> SemIR::TypeId;
  302. // Gets a generic interface type, which is the type of a name of a generic
  303. // interface, such as the type of `AddWith` given
  304. // `interface AddWith(T:! type)`. The returned type will be complete.
  305. auto GetGenericInterfaceType(SemIR::InterfaceId interface_id,
  306. SemIR::SpecificId enclosing_specific_id)
  307. -> SemIR::TypeId;
  308. // Gets the facet type corresponding to a particular interface.
  309. auto GetInterfaceType(SemIR::InterfaceId interface_id,
  310. SemIR::SpecificId specific_id) -> SemIR::TypeId;
  311. // Returns a pointer type whose pointee type is `pointee_type_id`.
  312. auto GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId;
  313. // Returns a struct type with the given fields.
  314. auto GetStructType(SemIR::StructTypeFieldsId fields_id) -> SemIR::TypeId;
  315. // Returns a tuple type with the given element types.
  316. auto GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids) -> SemIR::TypeId;
  317. // Returns an unbound element type.
  318. auto GetUnboundElementType(SemIR::TypeId class_type_id,
  319. SemIR::TypeId element_type_id) -> SemIR::TypeId;
  320. // Adds an exported name.
  321. auto AddExport(SemIR::InstId inst_id) -> void { exports_.push_back(inst_id); }
  322. auto Finalize() -> void;
  323. // Prints information for a stack dump.
  324. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  325. // Prints the the formatted sem_ir to stderr.
  326. LLVM_DUMP_METHOD auto DumpFormattedFile() const -> void;
  327. // Get the Lex::TokenKind of a node for diagnostics.
  328. auto token_kind(Parse::NodeId node_id) -> Lex::TokenKind {
  329. return tokens().GetKind(parse_tree().node_token(node_id));
  330. }
  331. auto emitter() -> DiagnosticEmitter& { return *emitter_; }
  332. auto parse_tree_and_subtrees() -> const Parse::TreeAndSubtrees& {
  333. return tree_and_subtrees_getter_();
  334. }
  335. auto sem_ir() -> SemIR::File& { return *sem_ir_; }
  336. auto sem_ir() const -> const SemIR::File& { return *sem_ir_; }
  337. auto parse_tree() const -> const Parse::Tree& {
  338. return sem_ir_->parse_tree();
  339. }
  340. auto tokens() const -> const Lex::TokenizedBuffer& {
  341. return parse_tree().tokens();
  342. }
  343. auto vlog_stream() -> llvm::raw_ostream* { return vlog_stream_; }
  344. auto node_stack() -> NodeStack& { return node_stack_; }
  345. auto inst_block_stack() -> InstBlockStack& { return inst_block_stack_; }
  346. auto pattern_block_stack() -> InstBlockStack& { return pattern_block_stack_; }
  347. auto param_and_arg_refs_stack() -> ParamAndArgRefsStack& {
  348. return param_and_arg_refs_stack_;
  349. }
  350. auto args_type_info_stack() -> InstBlockStack& {
  351. return args_type_info_stack_;
  352. }
  353. auto struct_type_fields_stack() -> ArrayStack<SemIR::StructTypeField>& {
  354. return struct_type_fields_stack_;
  355. }
  356. auto field_decls_stack() -> ArrayStack<SemIR::InstId>& {
  357. return field_decls_stack_;
  358. }
  359. auto decl_name_stack() -> DeclNameStack& { return decl_name_stack_; }
  360. auto decl_introducer_state_stack() -> DeclIntroducerStateStack& {
  361. return decl_introducer_state_stack_;
  362. }
  363. auto scope_stack() -> ScopeStack& { return scope_stack_; }
  364. auto return_scope_stack() -> llvm::SmallVector<ScopeStack::ReturnScope>& {
  365. return scope_stack().return_scope_stack();
  366. }
  367. auto break_continue_stack()
  368. -> llvm::SmallVector<ScopeStack::BreakContinueScope>& {
  369. return scope_stack().break_continue_stack();
  370. }
  371. auto generic_region_stack() -> GenericRegionStack& {
  372. return generic_region_stack_;
  373. }
  374. auto vtable_stack() -> InstBlockStack& { return vtable_stack_; }
  375. auto check_ir_map() -> llvm::MutableArrayRef<SemIR::ImportIRId> {
  376. return check_ir_map_;
  377. }
  378. auto import_ir_constant_values()
  379. -> llvm::SmallVector<SemIR::ConstantValueStore, 0>& {
  380. return import_ir_constant_values_;
  381. }
  382. // Directly expose SemIR::File data accessors for brevity in calls.
  383. auto identifiers() -> SharedValueStores::IdentifierStore& {
  384. return sem_ir().identifiers();
  385. }
  386. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  387. auto reals() -> SharedValueStores::RealStore& { return sem_ir().reals(); }
  388. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  389. auto string_literal_values() -> SharedValueStores::StringLiteralStore& {
  390. return sem_ir().string_literal_values();
  391. }
  392. auto entity_names() -> SemIR::EntityNameStore& {
  393. return sem_ir().entity_names();
  394. }
  395. auto functions() -> ValueStore<SemIR::FunctionId>& {
  396. return sem_ir().functions();
  397. }
  398. auto classes() -> ValueStore<SemIR::ClassId>& { return sem_ir().classes(); }
  399. auto interfaces() -> ValueStore<SemIR::InterfaceId>& {
  400. return sem_ir().interfaces();
  401. }
  402. auto associated_constants() -> ValueStore<SemIR::AssociatedConstantId>& {
  403. return sem_ir().associated_constants();
  404. }
  405. auto facet_types() -> CanonicalValueStore<SemIR::FacetTypeId>& {
  406. return sem_ir().facet_types();
  407. }
  408. auto impls() -> SemIR::ImplStore& { return sem_ir().impls(); }
  409. auto generics() -> SemIR::GenericStore& { return sem_ir().generics(); }
  410. auto specifics() -> SemIR::SpecificStore& { return sem_ir().specifics(); }
  411. auto import_irs() -> ValueStore<SemIR::ImportIRId>& {
  412. return sem_ir().import_irs();
  413. }
  414. auto import_ir_insts() -> ValueStore<SemIR::ImportIRInstId>& {
  415. return sem_ir().import_ir_insts();
  416. }
  417. auto names() -> SemIR::NameStoreWrapper { return sem_ir().names(); }
  418. auto name_scopes() -> SemIR::NameScopeStore& {
  419. return sem_ir().name_scopes();
  420. }
  421. auto struct_type_fields() -> SemIR::StructTypeFieldsStore& {
  422. return sem_ir().struct_type_fields();
  423. }
  424. auto types() -> SemIR::TypeStore& { return sem_ir().types(); }
  425. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  426. return sem_ir().type_blocks();
  427. }
  428. // Instructions should be added with `AddInst` or `AddInstInNoBlock`. This is
  429. // `const` to prevent accidental misuse.
  430. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  431. auto constant_values() -> SemIR::ConstantValueStore& {
  432. return sem_ir().constant_values();
  433. }
  434. auto inst_blocks() -> SemIR::InstBlockStore& {
  435. return sem_ir().inst_blocks();
  436. }
  437. auto constants() -> SemIR::ConstantStore& { return sem_ir().constants(); }
  438. auto definitions_required() -> llvm::SmallVector<SemIR::InstId>& {
  439. return definitions_required_;
  440. }
  441. auto global_init() -> GlobalInit& { return global_init_; }
  442. auto import_ref_ids() -> llvm::SmallVector<SemIR::InstId>& {
  443. return import_ref_ids_;
  444. }
  445. // Map from an AnyBindingPattern inst to precomputed parts of the
  446. // pattern-match SemIR for it.
  447. //
  448. // TODO: Consider putting this behind a narrower API to guard against emitting
  449. // multiple times.
  450. struct BindingPatternInfo {
  451. // The corresponding AnyBindName inst.
  452. SemIR::InstId bind_name_id;
  453. // The region of insts that computes the type of the binding.
  454. SemIR::ExprRegionId type_expr_region_id;
  455. };
  456. auto bind_name_map() -> Map<SemIR::InstId, BindingPatternInfo>& {
  457. return bind_name_map_;
  458. }
  459. auto var_storage_map() -> Map<SemIR::InstId, SemIR::InstId>& {
  460. return var_storage_map_;
  461. }
  462. auto region_stack() -> RegionStack& { return region_stack_; }
  463. auto full_pattern_stack() -> FullPatternStack& {
  464. return scope_stack_.full_pattern_stack();
  465. }
  466. private:
  467. // A FoldingSet node for a type.
  468. class TypeNode : public llvm::FastFoldingSetNode {
  469. public:
  470. explicit TypeNode(const llvm::FoldingSetNodeID& node_id,
  471. SemIR::TypeId type_id)
  472. : llvm::FastFoldingSetNode(node_id), type_id_(type_id) {}
  473. auto type_id() -> SemIR::TypeId { return type_id_; }
  474. private:
  475. SemIR::TypeId type_id_;
  476. };
  477. // Checks that the provided imported location has a node kind that is
  478. // compatible with that of the given instruction.
  479. auto CheckCompatibleImportedNodeKind(SemIR::ImportIRInstId imported_loc_id,
  480. SemIR::InstKind kind) -> void;
  481. // Finish producing an instruction. Set its constant value, and register it in
  482. // any applicable instruction lists.
  483. auto FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void;
  484. // Handles diagnostics.
  485. DiagnosticEmitter* emitter_;
  486. // Returns a lazily constructed TreeAndSubtrees.
  487. Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter_;
  488. // The SemIR::File being added to.
  489. SemIR::File* sem_ir_;
  490. // Whether to print verbose output.
  491. llvm::raw_ostream* vlog_stream_;
  492. // The stack during Build. Will contain file-level parse nodes on return.
  493. NodeStack node_stack_;
  494. // The stack of instruction blocks being used for general IR generation.
  495. InstBlockStack inst_block_stack_;
  496. // The stack of instruction blocks that contain pattern instructions.
  497. InstBlockStack pattern_block_stack_;
  498. // The stack of instruction blocks being used for param and arg ref blocks.
  499. ParamAndArgRefsStack param_and_arg_refs_stack_;
  500. // The stack of instruction blocks being used for type information while
  501. // processing arguments. This is used in parallel with
  502. // param_and_arg_refs_stack_. It's currently only used for struct literals,
  503. // where we need to track names for a type separate from the literal
  504. // arguments.
  505. InstBlockStack args_type_info_stack_;
  506. // The stack of StructTypeFields for in-progress StructTypeLiterals.
  507. ArrayStack<SemIR::StructTypeField> struct_type_fields_stack_;
  508. // The stack of FieldDecls for in-progress Class definitions.
  509. ArrayStack<SemIR::InstId> field_decls_stack_;
  510. // The stack used for qualified declaration name construction.
  511. DeclNameStack decl_name_stack_;
  512. // The stack of declarations that could have modifiers.
  513. DeclIntroducerStateStack decl_introducer_state_stack_;
  514. // The stack of scopes we are currently within.
  515. ScopeStack scope_stack_;
  516. // The stack of generic regions we are currently within.
  517. GenericRegionStack generic_region_stack_;
  518. // Contains a vtable block for each `class` scope which is currently being
  519. // defined, regardless of whether the class can have virtual functions.
  520. InstBlockStack vtable_stack_;
  521. // Cache of reverse mapping from type constants to types.
  522. //
  523. // TODO: Instead of mapping to a dense `TypeId` space, we could make `TypeId`
  524. // be a thin wrapper around `ConstantId` and only perform the lookup only when
  525. // we want to access the completeness and value representation of a type. It's
  526. // not clear whether that would result in more or fewer lookups.
  527. //
  528. // TODO: Should this be part of the `TypeStore`?
  529. Map<SemIR::ConstantId, SemIR::TypeId> type_ids_for_type_constants_;
  530. // The list which will form NodeBlockId::Exports.
  531. llvm::SmallVector<SemIR::InstId> exports_;
  532. // Maps CheckIRId to ImportIRId.
  533. llvm::SmallVector<SemIR::ImportIRId> check_ir_map_;
  534. // Per-import constant values. These refer to the main IR and mainly serve as
  535. // a lookup table for quick access.
  536. //
  537. // Inline 0 elements because it's expected to require heap allocation.
  538. llvm::SmallVector<SemIR::ConstantValueStore, 0> import_ir_constant_values_;
  539. // Declaration instructions of entities that should have definitions by the
  540. // end of the current source file.
  541. llvm::SmallVector<SemIR::InstId> definitions_required_;
  542. // State for global initialization.
  543. GlobalInit global_init_;
  544. // A list of import refs which can't be inserted into their current context.
  545. // They're typically added during name lookup or import ref resolution, where
  546. // the current block on inst_block_stack_ is unrelated.
  547. //
  548. // These are instead added here because they're referenced by other
  549. // instructions and needs to be visible in textual IR.
  550. // FinalizeImportRefBlock() will produce an inst block for them.
  551. llvm::SmallVector<SemIR::InstId> import_ref_ids_;
  552. Map<SemIR::InstId, BindingPatternInfo> bind_name_map_;
  553. // Map from VarPattern insts to the corresponding VarStorage insts. The
  554. // VarStorage insts are allocated, emitted, and stored in the map after
  555. // processing the enclosing full-pattern.
  556. Map<SemIR::InstId, SemIR::InstId> var_storage_map_;
  557. // Stack of single-entry regions being built.
  558. RegionStack region_stack_;
  559. };
  560. } // namespace Carbon::Check
  561. #endif // CARBON_TOOLCHAIN_CHECK_CONTEXT_H_