context.h 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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/scope_index.h"
  19. #include "toolchain/check/scope_stack.h"
  20. #include "toolchain/parse/node_ids.h"
  21. #include "toolchain/parse/tree.h"
  22. #include "toolchain/parse/tree_and_subtrees.h"
  23. #include "toolchain/sem_ir/file.h"
  24. #include "toolchain/sem_ir/ids.h"
  25. #include "toolchain/sem_ir/import_ir.h"
  26. #include "toolchain/sem_ir/inst.h"
  27. #include "toolchain/sem_ir/name_scope.h"
  28. #include "toolchain/sem_ir/typed_insts.h"
  29. namespace Carbon::Check {
  30. // Information about a scope in which we can perform name lookup.
  31. struct LookupScope {
  32. // The name scope in which names are searched.
  33. SemIR::NameScopeId name_scope_id;
  34. // The specific for the name scope, or `None` if the name scope is not
  35. // defined by a generic or we should perform lookup into the generic itself.
  36. SemIR::SpecificId specific_id;
  37. };
  38. // A result produced by name lookup.
  39. struct LookupResult {
  40. // The specific in which the lookup result was found. `None` if the result
  41. // was not found in a specific.
  42. SemIR::SpecificId specific_id;
  43. // The result from the lookup in the scope.
  44. SemIR::ScopeLookupResult scope_result;
  45. };
  46. // Information about an access.
  47. struct AccessInfo {
  48. // The constant being accessed.
  49. SemIR::ConstantId constant_id;
  50. // The highest allowed access for a lookup. For example, `Protected` allows
  51. // access to `Public` and `Protected` names, but not `Private`.
  52. SemIR::AccessKind highest_allowed_access;
  53. };
  54. // Context and shared functionality for semantics handlers.
  55. class Context {
  56. public:
  57. using DiagnosticEmitter = Carbon::DiagnosticEmitter<SemIRLoc>;
  58. using DiagnosticBuilder = DiagnosticEmitter::DiagnosticBuilder;
  59. // A function that forms a diagnostic for some kind of problem. The
  60. // DiagnosticBuilder is returned rather than emitted so that the caller can
  61. // add contextual notes as appropriate.
  62. using BuildDiagnosticFn =
  63. llvm::function_ref<auto()->Context::DiagnosticBuilder>;
  64. // Stores references for work.
  65. explicit Context(DiagnosticEmitter* emitter,
  66. Parse::GetTreeAndSubtreesFn get_parse_tree_and_subtrees,
  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 current scope, if it is of the specified kind. Otherwise,
  247. // returns nullopt.
  248. template <typename InstT>
  249. auto GetCurrentScopeAs() -> std::optional<InstT> {
  250. return scope_stack().GetCurrentScopeAs<InstT>(sem_ir());
  251. }
  252. // Mark the start of a new single-entry region with the given entry block.
  253. auto PushRegion(SemIR::InstBlockId entry_block_id) -> void {
  254. region_stack_.PushArray();
  255. region_stack_.AppendToTop(entry_block_id);
  256. }
  257. // Add `block_id` to the most recently pushed single-entry region. To preserve
  258. // the single-entry property, `block_id` must not be directly reachable from
  259. // any block outside the region. To ensure the region's blocks are in lexical
  260. // order, this should be called when the first parse node associated with this
  261. // block is handled, or as close as possible.
  262. auto AddToRegion(SemIR::InstBlockId block_id, SemIR::LocId loc_id) -> void;
  263. // Complete creation of the most recently pushed single-entry region, and
  264. // return a list of its blocks.
  265. auto PopRegion() -> llvm::SmallVector<SemIR::InstBlockId> {
  266. llvm::SmallVector<SemIR::InstBlockId> result(region_stack_.PeekArray());
  267. region_stack_.PopArray();
  268. return result;
  269. }
  270. // Adds a `Branch` instruction branching to a new instruction block, and
  271. // returns the ID of the new block. All paths to the branch target must go
  272. // through the current block, though not necessarily through this branch.
  273. auto AddDominatedBlockAndBranch(Parse::NodeId node_id) -> SemIR::InstBlockId;
  274. // Adds a `Branch` instruction branching to a new instruction block with a
  275. // value, and returns the ID of the new block. All paths to the branch target
  276. // must go through the current block.
  277. auto AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  278. SemIR::InstId arg_id)
  279. -> SemIR::InstBlockId;
  280. // Adds a `BranchIf` instruction branching to a new instruction block, and
  281. // returns the ID of the new block. All paths to the branch target must go
  282. // through the current block.
  283. auto AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  284. SemIR::InstId cond_id)
  285. -> SemIR::InstBlockId;
  286. // Handles recovergence of control flow. Adds branches from the top
  287. // `num_blocks` on the instruction block stack to a new block, pops the
  288. // existing blocks, pushes the new block onto the instruction block stack,
  289. // and adds it to the most recently pushed region.
  290. auto AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  291. -> void;
  292. // Handles recovergence of control flow with a result value. Adds branches
  293. // from the top few blocks on the instruction block stack to a new block, pops
  294. // the existing blocks, pushes the new block onto the instruction block
  295. // stack, and adds it to the most recently pushed region. The number of blocks
  296. // popped is the size of `block_args`, and the corresponding result values are
  297. // the elements of `block_args`. Returns an instruction referring to the
  298. // result value.
  299. auto AddConvergenceBlockWithArgAndPush(
  300. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  301. -> SemIR::InstId;
  302. // Sets the constant value of a block argument created as the result of a
  303. // branch. `select_id` should be a `BlockArg` that selects between two
  304. // values. `cond_id` is the condition, `if_false` is the value to use if the
  305. // condition is false, and `if_true` is the value to use if the condition is
  306. // true. We don't track enough information in the `BlockArg` inst for
  307. // `TryEvalInst` to do this itself.
  308. auto SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  309. SemIR::InstId cond_id,
  310. SemIR::InstId if_true,
  311. SemIR::InstId if_false) -> void;
  312. // Returns whether the current position in the current block is reachable.
  313. auto is_current_position_reachable() -> bool;
  314. // Returns the type ID for a constant of type `type`.
  315. auto GetTypeIdForTypeConstant(SemIR::ConstantId constant_id) -> SemIR::TypeId;
  316. // Returns the type ID for an instruction whose constant value is of type
  317. // `type`.
  318. auto GetTypeIdForTypeInst(SemIR::InstId inst_id) -> SemIR::TypeId {
  319. return GetTypeIdForTypeConstant(constant_values().Get(inst_id));
  320. }
  321. // Attempts to complete the type `type_id`. Returns `true` if the type is
  322. // complete, or `false` if it could not be completed. A complete type has
  323. // known object and value representations. Returns `true` if the type is
  324. // symbolic.
  325. //
  326. // Avoid calling this where possible, as it can lead to coherence issues.
  327. // However, it's important that we use it during monomorphization, where we
  328. // don't want to trigger a request for more monomorphization.
  329. // TODO: Remove the other call to this function.
  330. auto TryToCompleteType(SemIR::TypeId type_id, SemIRLoc loc,
  331. BuildDiagnosticFn diagnoser = nullptr) -> bool;
  332. // Completes the type `type_id`. CHECK-fails if it can't be completed.
  333. auto CompleteTypeOrCheckFail(SemIR::TypeId type_id) -> void;
  334. // Like `TryToCompleteType`, but for cases where it is an error for the type
  335. // to be incomplete.
  336. //
  337. // If the type is not complete, `diagnoser` is invoked to diagnose the issue,
  338. // if a `diagnoser` is provided. The builder it returns will be annotated to
  339. // describe the reason why the type is not complete.
  340. //
  341. // `diagnoser` should build an error diagnostic. If `type_id` is dependent,
  342. // the completeness of the type will be enforced during monomorphization, and
  343. // `loc_id` is used as the location for a diagnostic produced at that time.
  344. auto RequireCompleteType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  345. BuildDiagnosticFn diagnoser) -> bool;
  346. // Like `RequireCompleteType`, but also require the type to not be an abstract
  347. // class type. If it is, `abstract_diagnoser` is used to diagnose the problem,
  348. // and this function returns false.
  349. auto RequireConcreteType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  350. BuildDiagnosticFn diagnoser,
  351. BuildDiagnosticFn abstract_diagnoser) -> bool;
  352. // Like `RequireCompleteType`, but also require the type to be defined. A
  353. // defined type has known members. If the type is not defined, `diagnoser` is
  354. // used to diagnose the problem, and this function returns false.
  355. //
  356. // This is the same as `RequireCompleteType` except for facet types, which are
  357. // complete before they are fully defined.
  358. auto RequireDefinedType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  359. BuildDiagnosticFn diagnoser) -> bool;
  360. // Returns the type `type_id` if it is a complete type, or produces an
  361. // incomplete type error and returns an error type. This is a convenience
  362. // wrapper around `RequireCompleteType`.
  363. auto AsCompleteType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  364. BuildDiagnosticFn diagnoser) -> SemIR::TypeId {
  365. return RequireCompleteType(type_id, loc_id, diagnoser)
  366. ? type_id
  367. : SemIR::ErrorInst::SingletonTypeId;
  368. }
  369. // Returns the type `type_id` if it is a concrete type, or produces an
  370. // incomplete or abstract type error and returns an error type. This is a
  371. // convenience wrapper around `RequireConcreteType`.
  372. auto AsConcreteType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  373. BuildDiagnosticFn diagnoser,
  374. BuildDiagnosticFn abstract_diagnoser) -> SemIR::TypeId {
  375. return RequireConcreteType(type_id, loc_id, diagnoser, abstract_diagnoser)
  376. ? type_id
  377. : SemIR::ErrorInst::SingletonTypeId;
  378. }
  379. // Returns whether `type_id` represents a facet type.
  380. auto IsFacetType(SemIR::TypeId type_id) -> bool {
  381. return type_id == SemIR::TypeType::SingletonTypeId ||
  382. types().Is<SemIR::FacetType>(type_id);
  383. }
  384. // Create a FacetType typed instruction object consisting of a single
  385. // interface.
  386. auto FacetTypeFromInterface(SemIR::InterfaceId interface_id,
  387. SemIR::SpecificId specific_id)
  388. -> SemIR::FacetType;
  389. // TODO: Consider moving these `Get*Type` functions to a separate class.
  390. // Gets the type to use for an unbound associated entity declared in this
  391. // interface. For example, this is the type of `I.T` after
  392. // `interface I { let T:! type; }`.
  393. // The name of the interface is used for diagnostics.
  394. // TODO: Should we use a different type for each such entity, or the same type
  395. // for all associated entities?
  396. auto GetAssociatedEntityType(SemIR::TypeId interface_type_id)
  397. -> SemIR::TypeId;
  398. // Gets a singleton type. The returned type will be complete. Requires that
  399. // `singleton_id` is already validated to be a singleton.
  400. auto GetSingletonType(SemIR::InstId singleton_id) -> SemIR::TypeId;
  401. // Gets a class type.
  402. auto GetClassType(SemIR::ClassId class_id, SemIR::SpecificId specific_id)
  403. -> SemIR::TypeId;
  404. // Gets a function type. The returned type will be complete.
  405. auto GetFunctionType(SemIR::FunctionId fn_id, SemIR::SpecificId specific_id)
  406. -> SemIR::TypeId;
  407. // Gets the type of an associated function with the `Self` parameter bound to
  408. // a particular value. The returned type will be complete.
  409. auto GetFunctionTypeWithSelfType(SemIR::InstId interface_function_type_id,
  410. SemIR::InstId self_id) -> SemIR::TypeId;
  411. // Gets a generic class type, which is the type of a name of a generic class,
  412. // such as the type of `Vector` given `class Vector(T:! type)`. The returned
  413. // type will be complete.
  414. auto GetGenericClassType(SemIR::ClassId class_id,
  415. SemIR::SpecificId enclosing_specific_id)
  416. -> SemIR::TypeId;
  417. // Gets a generic interface type, which is the type of a name of a generic
  418. // interface, such as the type of `AddWith` given
  419. // `interface AddWith(T:! type)`. The returned type will be complete.
  420. auto GetGenericInterfaceType(SemIR::InterfaceId interface_id,
  421. SemIR::SpecificId enclosing_specific_id)
  422. -> SemIR::TypeId;
  423. // Gets the facet type corresponding to a particular interface.
  424. auto GetInterfaceType(SemIR::InterfaceId interface_id,
  425. SemIR::SpecificId specific_id) -> SemIR::TypeId;
  426. // Returns a pointer type whose pointee type is `pointee_type_id`.
  427. auto GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId;
  428. // Returns a struct type with the given fields.
  429. auto GetStructType(SemIR::StructTypeFieldsId fields_id) -> SemIR::TypeId;
  430. // Returns a tuple type with the given element types.
  431. auto GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids) -> SemIR::TypeId;
  432. // Returns an unbound element type.
  433. auto GetUnboundElementType(SemIR::TypeId class_type_id,
  434. SemIR::TypeId element_type_id) -> SemIR::TypeId;
  435. // Adds an exported name.
  436. auto AddExport(SemIR::InstId inst_id) -> void { exports_.push_back(inst_id); }
  437. auto Finalize() -> void;
  438. // Returns the imported IR ID for an IR, or `None` if not imported.
  439. auto GetImportIRId(const SemIR::File& sem_ir) -> SemIR::ImportIRId& {
  440. return check_ir_map_[sem_ir.check_ir_id().index];
  441. }
  442. // True if the current file is an impl file.
  443. auto IsImplFile() -> bool {
  444. return sem_ir_->import_irs().Get(SemIR::ImportIRId::ApiForImpl).sem_ir !=
  445. nullptr;
  446. }
  447. // Prints information for a stack dump.
  448. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  449. // Prints the the formatted sem_ir to stderr.
  450. LLVM_DUMP_METHOD auto DumpFormattedFile() const -> void;
  451. // Get the Lex::TokenKind of a node for diagnostics.
  452. auto token_kind(Parse::NodeId node_id) -> Lex::TokenKind {
  453. return tokens().GetKind(parse_tree().node_token(node_id));
  454. }
  455. auto emitter() -> DiagnosticEmitter& { return *emitter_; }
  456. auto parse_tree_and_subtrees() -> const Parse::TreeAndSubtrees& {
  457. return get_parse_tree_and_subtrees_();
  458. }
  459. auto sem_ir() -> SemIR::File& { return *sem_ir_; }
  460. auto sem_ir() const -> const SemIR::File& { return *sem_ir_; }
  461. auto parse_tree() const -> const Parse::Tree& {
  462. return sem_ir_->parse_tree();
  463. }
  464. auto tokens() const -> const Lex::TokenizedBuffer& {
  465. return parse_tree().tokens();
  466. }
  467. auto node_stack() -> NodeStack& { return node_stack_; }
  468. auto inst_block_stack() -> InstBlockStack& { return inst_block_stack_; }
  469. auto pattern_block_stack() -> InstBlockStack& { return pattern_block_stack_; }
  470. auto param_and_arg_refs_stack() -> ParamAndArgRefsStack& {
  471. return param_and_arg_refs_stack_;
  472. }
  473. auto args_type_info_stack() -> InstBlockStack& {
  474. return args_type_info_stack_;
  475. }
  476. auto struct_type_fields_stack() -> ArrayStack<SemIR::StructTypeField>& {
  477. return struct_type_fields_stack_;
  478. }
  479. auto field_decls_stack() -> ArrayStack<SemIR::InstId>& {
  480. return field_decls_stack_;
  481. }
  482. auto decl_name_stack() -> DeclNameStack& { return decl_name_stack_; }
  483. auto decl_introducer_state_stack() -> DeclIntroducerStateStack& {
  484. return decl_introducer_state_stack_;
  485. }
  486. auto scope_stack() -> ScopeStack& { return scope_stack_; }
  487. auto return_scope_stack() -> llvm::SmallVector<ScopeStack::ReturnScope>& {
  488. return scope_stack().return_scope_stack();
  489. }
  490. auto break_continue_stack()
  491. -> llvm::SmallVector<ScopeStack::BreakContinueScope>& {
  492. return scope_stack().break_continue_stack();
  493. }
  494. auto generic_region_stack() -> GenericRegionStack& {
  495. return generic_region_stack_;
  496. }
  497. auto vtable_stack() -> InstBlockStack& { return vtable_stack_; }
  498. auto import_ir_constant_values()
  499. -> llvm::SmallVector<SemIR::ConstantValueStore, 0>& {
  500. return import_ir_constant_values_;
  501. }
  502. // Directly expose SemIR::File data accessors for brevity in calls.
  503. auto identifiers() -> SharedValueStores::IdentifierStore& {
  504. return sem_ir().identifiers();
  505. }
  506. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  507. auto reals() -> SharedValueStores::RealStore& { return sem_ir().reals(); }
  508. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  509. auto string_literal_values() -> SharedValueStores::StringLiteralStore& {
  510. return sem_ir().string_literal_values();
  511. }
  512. auto entity_names() -> SemIR::EntityNameStore& {
  513. return sem_ir().entity_names();
  514. }
  515. auto functions() -> ValueStore<SemIR::FunctionId>& {
  516. return sem_ir().functions();
  517. }
  518. auto classes() -> ValueStore<SemIR::ClassId>& { return sem_ir().classes(); }
  519. auto interfaces() -> ValueStore<SemIR::InterfaceId>& {
  520. return sem_ir().interfaces();
  521. }
  522. auto associated_constants() -> ValueStore<SemIR::AssociatedConstantId>& {
  523. return sem_ir().associated_constants();
  524. }
  525. auto facet_types() -> CanonicalValueStore<SemIR::FacetTypeId>& {
  526. return sem_ir().facet_types();
  527. }
  528. auto impls() -> SemIR::ImplStore& { return sem_ir().impls(); }
  529. auto generics() -> SemIR::GenericStore& { return sem_ir().generics(); }
  530. auto specifics() -> SemIR::SpecificStore& { return sem_ir().specifics(); }
  531. auto import_irs() -> ValueStore<SemIR::ImportIRId>& {
  532. return sem_ir().import_irs();
  533. }
  534. auto import_ir_insts() -> ValueStore<SemIR::ImportIRInstId>& {
  535. return sem_ir().import_ir_insts();
  536. }
  537. auto names() -> SemIR::NameStoreWrapper { return sem_ir().names(); }
  538. auto name_scopes() -> SemIR::NameScopeStore& {
  539. return sem_ir().name_scopes();
  540. }
  541. auto struct_type_fields() -> SemIR::StructTypeFieldsStore& {
  542. return sem_ir().struct_type_fields();
  543. }
  544. auto types() -> SemIR::TypeStore& { return sem_ir().types(); }
  545. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  546. return sem_ir().type_blocks();
  547. }
  548. // Instructions should be added with `AddInst` or `AddInstInNoBlock`. This is
  549. // `const` to prevent accidental misuse.
  550. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  551. auto constant_values() -> SemIR::ConstantValueStore& {
  552. return sem_ir().constant_values();
  553. }
  554. auto inst_blocks() -> SemIR::InstBlockStore& {
  555. return sem_ir().inst_blocks();
  556. }
  557. auto constants() -> SemIR::ConstantStore& { return sem_ir().constants(); }
  558. auto definitions_required() -> llvm::SmallVector<SemIR::InstId>& {
  559. return definitions_required_;
  560. }
  561. auto global_init() -> GlobalInit& { return global_init_; }
  562. // Marks the start of a region of insts in a pattern context that might
  563. // represent an expression or a pattern. Typically this is called when
  564. // handling a parse node that can immediately precede a subpattern (such
  565. // as `let` or a `,` in a pattern list), and the handler for the subpattern
  566. // node makes the matching `EndSubpatternAs*` call.
  567. auto BeginSubpattern() -> void;
  568. // Ends a region started by BeginSubpattern (in stack order), treating it as
  569. // an expression with the given result, and returns the ID of the region. The
  570. // region will not yet have any control-flow edges into or out of it.
  571. auto EndSubpatternAsExpr(SemIR::InstId result_id) -> SemIR::ExprRegionId;
  572. // Ends a region started by BeginSubpattern (in stack order), asserting that
  573. // it was empty.
  574. auto EndSubpatternAsEmpty() -> void;
  575. // TODO: Add EndSubpatternAsPattern, when needed.
  576. // Inserts the given region into the current code block. If the region
  577. // consists of a single block, this will be implemented as a `splice_block`
  578. // inst. Otherwise, this will end the current block with a branch to the entry
  579. // block of the region, and add future insts to a new block which is the
  580. // immediate successor of the region's exit block. As a result, this cannot be
  581. // called more than once for the same region.
  582. auto InsertHere(SemIR::ExprRegionId region_id) -> SemIR::InstId;
  583. auto import_ref_ids() -> llvm::SmallVector<SemIR::InstId>& {
  584. return import_ref_ids_;
  585. }
  586. // Map from an AnyBindingPattern inst to precomputed parts of the
  587. // pattern-match SemIR for it.
  588. //
  589. // TODO: Consider putting this behind a narrower API to guard against emitting
  590. // multiple times.
  591. struct BindingPatternInfo {
  592. // The corresponding AnyBindName inst.
  593. SemIR::InstId bind_name_id;
  594. // The region of insts that computes the type of the binding.
  595. SemIR::ExprRegionId type_expr_region_id;
  596. };
  597. auto bind_name_map() -> Map<SemIR::InstId, BindingPatternInfo>& {
  598. return bind_name_map_;
  599. }
  600. auto var_storage_map() -> Map<SemIR::InstId, SemIR::InstId>& {
  601. return var_storage_map_;
  602. }
  603. auto full_pattern_stack() -> FullPatternStack& {
  604. return scope_stack_.full_pattern_stack();
  605. }
  606. private:
  607. // A FoldingSet node for a type.
  608. class TypeNode : public llvm::FastFoldingSetNode {
  609. public:
  610. explicit TypeNode(const llvm::FoldingSetNodeID& node_id,
  611. SemIR::TypeId type_id)
  612. : llvm::FastFoldingSetNode(node_id), type_id_(type_id) {}
  613. auto type_id() -> SemIR::TypeId { return type_id_; }
  614. private:
  615. SemIR::TypeId type_id_;
  616. };
  617. // Checks that the provided imported location has a node kind that is
  618. // compatible with that of the given instruction.
  619. auto CheckCompatibleImportedNodeKind(SemIR::ImportIRInstId imported_loc_id,
  620. SemIR::InstKind kind) -> void;
  621. // Finish producing an instruction. Set its constant value, and register it in
  622. // any applicable instruction lists.
  623. auto FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void;
  624. // Handles diagnostics.
  625. DiagnosticEmitter* emitter_;
  626. // Returns a lazily constructed TreeAndSubtrees.
  627. Parse::GetTreeAndSubtreesFn get_parse_tree_and_subtrees_;
  628. // The SemIR::File being added to.
  629. SemIR::File* sem_ir_;
  630. // Whether to print verbose output.
  631. llvm::raw_ostream* vlog_stream_;
  632. // The stack during Build. Will contain file-level parse nodes on return.
  633. NodeStack node_stack_;
  634. // The stack of instruction blocks being used for general IR generation.
  635. InstBlockStack inst_block_stack_;
  636. // The stack of instruction blocks that contain pattern instructions.
  637. InstBlockStack pattern_block_stack_;
  638. // The stack of instruction blocks being used for param and arg ref blocks.
  639. ParamAndArgRefsStack param_and_arg_refs_stack_;
  640. // The stack of instruction blocks being used for type information while
  641. // processing arguments. This is used in parallel with
  642. // param_and_arg_refs_stack_. It's currently only used for struct literals,
  643. // where we need to track names for a type separate from the literal
  644. // arguments.
  645. InstBlockStack args_type_info_stack_;
  646. // The stack of StructTypeFields for in-progress StructTypeLiterals.
  647. ArrayStack<SemIR::StructTypeField> struct_type_fields_stack_;
  648. // The stack of FieldDecls for in-progress Class definitions.
  649. ArrayStack<SemIR::InstId> field_decls_stack_;
  650. // The stack used for qualified declaration name construction.
  651. DeclNameStack decl_name_stack_;
  652. // The stack of declarations that could have modifiers.
  653. DeclIntroducerStateStack decl_introducer_state_stack_;
  654. // The stack of scopes we are currently within.
  655. ScopeStack scope_stack_;
  656. // The stack of generic regions we are currently within.
  657. GenericRegionStack generic_region_stack_;
  658. // Contains a vtable block for each `class` scope which is currently being
  659. // defined, regardless of whether the class can have virtual functions.
  660. InstBlockStack vtable_stack_;
  661. // Cache of reverse mapping from type constants to types.
  662. //
  663. // TODO: Instead of mapping to a dense `TypeId` space, we could make `TypeId`
  664. // be a thin wrapper around `ConstantId` and only perform the lookup only when
  665. // we want to access the completeness and value representation of a type. It's
  666. // not clear whether that would result in more or fewer lookups.
  667. //
  668. // TODO: Should this be part of the `TypeStore`?
  669. Map<SemIR::ConstantId, SemIR::TypeId> type_ids_for_type_constants_;
  670. // The list which will form NodeBlockId::Exports.
  671. llvm::SmallVector<SemIR::InstId> exports_;
  672. // Maps CheckIRId to ImportIRId.
  673. llvm::SmallVector<SemIR::ImportIRId> check_ir_map_;
  674. // Per-import constant values. These refer to the main IR and mainly serve as
  675. // a lookup table for quick access.
  676. //
  677. // Inline 0 elements because it's expected to require heap allocation.
  678. llvm::SmallVector<SemIR::ConstantValueStore, 0> import_ir_constant_values_;
  679. // Declaration instructions of entities that should have definitions by the
  680. // end of the current source file.
  681. llvm::SmallVector<SemIR::InstId> definitions_required_;
  682. // State for global initialization.
  683. GlobalInit global_init_;
  684. // A list of import refs which can't be inserted into their current context.
  685. // They're typically added during name lookup or import ref resolution, where
  686. // the current block on inst_block_stack_ is unrelated.
  687. //
  688. // These are instead added here because they're referenced by other
  689. // instructions and needs to be visible in textual IR.
  690. // FinalizeImportRefBlock() will produce an inst block for them.
  691. llvm::SmallVector<SemIR::InstId> import_ref_ids_;
  692. Map<SemIR::InstId, BindingPatternInfo> bind_name_map_;
  693. // Map from VarPattern insts to the corresponding VarStorage insts. The
  694. // VarStorage insts are allocated, emitted, and stored in the map after
  695. // processing the enclosing full-pattern.
  696. Map<SemIR::InstId, SemIR::InstId> var_storage_map_;
  697. // Stack of single-entry regions being built.
  698. ArrayStack<SemIR::InstBlockId> region_stack_;
  699. };
  700. } // namespace Carbon::Check
  701. #endif // CARBON_TOOLCHAIN_CHECK_CONTEXT_H_