context.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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(DiagnosticEmitter* emitter,
  64. llvm::function_ref<const Parse::TreeAndSubtrees&()>
  65. get_parse_tree_and_subtrees,
  66. SemIR::File* sem_ir, int imported_ir_count,
  67. int total_ir_count, 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. // If the instruction has an implicit location and a constant value, returns
  111. // the constant value's instruction ID. Otherwise, same as AddInst.
  112. auto GetOrAddInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId;
  113. // Convenience for GetOrAddInst with typed nodes.
  114. template <typename InstT, typename LocT>
  115. auto GetOrAddInst(LocT loc, InstT inst)
  116. -> decltype(GetOrAddInst(SemIR::LocIdAndInst(loc, inst))) {
  117. return GetOrAddInst(SemIR::LocIdAndInst(loc, inst));
  118. }
  119. // Adds an instruction to the current block, returning the produced ID. The
  120. // instruction is a placeholder that is expected to be replaced by
  121. // `ReplaceInstBeforeConstantUse`.
  122. auto AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId;
  123. // Adds an instruction in no block, returning the produced ID. Should be used
  124. // rarely. The instruction is a placeholder that is expected to be replaced by
  125. // `ReplaceInstBeforeConstantUse`.
  126. auto AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  127. -> SemIR::InstId;
  128. // Adds an instruction to the current pattern block, returning the produced
  129. // ID.
  130. // TODO: Is it possible to remove this and pattern_block_stack, now that
  131. // we have BeginSubpattern etc. instead?
  132. auto AddPatternInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId {
  133. auto inst_id = AddInstInNoBlock(loc_id_and_inst);
  134. pattern_block_stack_.AddInstId(inst_id);
  135. return inst_id;
  136. }
  137. // Convenience for AddPatternInst with typed nodes.
  138. template <typename InstT>
  139. requires(SemIR::Internal::HasNodeId<InstT>)
  140. auto AddPatternInst(decltype(InstT::Kind)::TypedNodeId node_id, InstT inst)
  141. -> SemIR::InstId {
  142. return AddPatternInst(SemIR::LocIdAndInst(node_id, inst));
  143. }
  144. // Pushes a parse tree node onto the stack, storing the SemIR::Inst as the
  145. // result.
  146. template <typename InstT>
  147. requires(SemIR::Internal::HasNodeId<InstT>)
  148. auto AddInstAndPush(decltype(InstT::Kind)::TypedNodeId node_id, InstT inst)
  149. -> void {
  150. node_stack_.Push(node_id, AddInst(node_id, inst));
  151. }
  152. // Replaces the instruction `inst_id` with `loc_id_and_inst`. The instruction
  153. // is required to not have been used in any constant evaluation, either
  154. // because it's newly created and entirely unused, or because it's only used
  155. // in a position that constant evaluation ignores, such as a return slot.
  156. auto ReplaceLocIdAndInstBeforeConstantUse(SemIR::InstId inst_id,
  157. SemIR::LocIdAndInst loc_id_and_inst)
  158. -> void;
  159. // Replaces the instruction `inst_id` with `inst`, not affecting location.
  160. // The instruction is required to not have been used in any constant
  161. // evaluation, either because it's newly created and entirely unused, or
  162. // because it's only used in a position that constant evaluation ignores, such
  163. // as a return slot.
  164. auto ReplaceInstBeforeConstantUse(SemIR::InstId inst_id, SemIR::Inst inst)
  165. -> void;
  166. // Replaces the instruction `inst_id` with `inst`, not affecting location.
  167. // The instruction is required to not change its constant value.
  168. auto ReplaceInstPreservingConstantValue(SemIR::InstId inst_id,
  169. SemIR::Inst inst) -> void;
  170. // Sets only the parse node of an instruction. This is only used when setting
  171. // the parse node of an imported namespace. Versus
  172. // ReplaceInstBeforeConstantUse, it is safe to use after the namespace is used
  173. // in constant evaluation. It's exposed this way mainly so that `insts()` can
  174. // remain const.
  175. auto SetNamespaceNodeId(SemIR::InstId inst_id, Parse::NodeId node_id)
  176. -> void {
  177. sem_ir().insts().SetLocId(inst_id, SemIR::LocId(node_id));
  178. }
  179. // Adds a name to name lookup. Prints a diagnostic for name conflicts.
  180. auto AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id) -> void;
  181. // Performs name lookup in a specified scope for a name appearing in a
  182. // declaration, returning the referenced instruction. If scope_id is invalid,
  183. // uses the current contextual scope.
  184. auto LookupNameInDecl(SemIR::LocId loc_id, SemIR::NameId name_id,
  185. SemIR::NameScopeId scope_id) -> SemIR::InstId;
  186. // Performs an unqualified name lookup, returning the referenced instruction.
  187. auto LookupUnqualifiedName(Parse::NodeId node_id, SemIR::NameId name_id,
  188. bool required = true) -> LookupResult;
  189. // Performs a name lookup in a specified scope, returning the referenced
  190. // instruction. Does not look into extended scopes. Returns an invalid
  191. // instruction if the name is not found.
  192. auto LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
  193. SemIR::NameScopeId scope_id,
  194. const SemIR::NameScope& scope)
  195. -> std::pair<SemIR::InstId, SemIR::AccessKind>;
  196. // Appends the lookup scopes corresponding to `base_const_id` to `*scopes`.
  197. // Returns `false` if not a scope. On invalid scopes, prints a diagnostic, but
  198. // still updates `*scopes` and returns `true`.
  199. auto AppendLookupScopesForConstant(SemIR::LocId loc_id,
  200. SemIR::ConstantId base_const_id,
  201. llvm::SmallVector<LookupScope>* scopes)
  202. -> bool;
  203. // Performs a qualified name lookup in a specified scopes and in scopes that
  204. // they extend, returning the referenced instruction.
  205. auto LookupQualifiedName(SemIR::LocId loc_id, SemIR::NameId name_id,
  206. llvm::ArrayRef<LookupScope> lookup_scopes,
  207. bool required = true,
  208. std::optional<AccessInfo> access_info = std::nullopt)
  209. -> LookupResult;
  210. // Returns the instruction corresponding to a name in the core package, or
  211. // BuiltinErrorInst if not found.
  212. auto LookupNameInCore(SemIRLoc loc, llvm::StringRef name) -> SemIR::InstId;
  213. // Prints a diagnostic for a duplicate name.
  214. auto DiagnoseDuplicateName(SemIRLoc dup_def, SemIRLoc prev_def) -> void;
  215. // Prints a diagnostic for a poisoned name.
  216. auto DiagnosePoisonedName(SemIRLoc loc) -> void;
  217. // Prints a diagnostic for a missing name.
  218. auto DiagnoseNameNotFound(SemIRLoc loc, SemIR::NameId name_id) -> void;
  219. // Prints a diagnostic for a missing qualified name.
  220. auto DiagnoseMemberNameNotFound(SemIRLoc loc, SemIR::NameId name_id,
  221. llvm::ArrayRef<LookupScope> lookup_scopes)
  222. -> void;
  223. // Adds a note to a diagnostic explaining that a class is incomplete.
  224. auto NoteIncompleteClass(SemIR::ClassId class_id, DiagnosticBuilder& builder)
  225. -> void;
  226. // Adds a note to a diagnostic explaining that a class is abstract.
  227. auto NoteAbstractClass(SemIR::ClassId class_id, DiagnosticBuilder& builder)
  228. -> void;
  229. // Adds a note to a diagnostic explaining that an interface is not defined.
  230. auto NoteUndefinedInterface(SemIR::InterfaceId interface_id,
  231. DiagnosticBuilder& builder) -> void;
  232. // Returns the current scope, if it is of the specified kind. Otherwise,
  233. // returns nullopt.
  234. template <typename InstT>
  235. auto GetCurrentScopeAs() -> std::optional<InstT> {
  236. return scope_stack().GetCurrentScopeAs<InstT>(sem_ir());
  237. }
  238. // Mark the start of a new single-entry region with the given entry block.
  239. auto PushRegion(SemIR::InstBlockId entry_block_id) -> void {
  240. region_stack_.PushArray();
  241. region_stack_.AppendToTop(entry_block_id);
  242. }
  243. // Add `block_id` to the most recently pushed single-entry region. To preserve
  244. // the single-entry property, `block_id` must not be directly reachable from
  245. // any block outside the region. To ensure the region's blocks are in lexical
  246. // order, this should be called when the first parse node associated with this
  247. // block is handled, or as close as possible.
  248. auto AddToRegion(SemIR::InstBlockId block_id, SemIR::LocId loc_id) -> void;
  249. // Complete creation of the most recently pushed single-entry region, and
  250. // return a list of its blocks.
  251. auto PopRegion() -> llvm::SmallVector<SemIR::InstBlockId> {
  252. llvm::SmallVector<SemIR::InstBlockId> result(region_stack_.PeekArray());
  253. region_stack_.PopArray();
  254. return result;
  255. }
  256. // Adds a `Branch` instruction branching to a new instruction block, and
  257. // returns the ID of the new block. All paths to the branch target must go
  258. // through the current block, though not necessarily through this branch.
  259. auto AddDominatedBlockAndBranch(Parse::NodeId node_id) -> SemIR::InstBlockId;
  260. // Adds a `Branch` instruction branching to a new instruction block with a
  261. // value, and returns the ID of the new block. All paths to the branch target
  262. // must go through the current block.
  263. auto AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  264. SemIR::InstId arg_id)
  265. -> SemIR::InstBlockId;
  266. // Adds a `BranchIf` instruction branching to a new instruction block, and
  267. // returns the ID of the new block. All paths to the branch target must go
  268. // through the current block.
  269. auto AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  270. SemIR::InstId cond_id)
  271. -> SemIR::InstBlockId;
  272. // Handles recovergence of control flow. Adds branches from the top
  273. // `num_blocks` on the instruction block stack to a new block, pops the
  274. // existing blocks, pushes the new block onto the instruction block stack,
  275. // and adds it to the most recently pushed region.
  276. auto AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  277. -> void;
  278. // Handles recovergence of control flow with a result value. Adds branches
  279. // from the top few blocks on the instruction block stack to a new block, pops
  280. // the existing blocks, pushes the new block onto the instruction block
  281. // stack, and adds it to the most recently pushed region. The number of blocks
  282. // popped is the size of `block_args`, and the corresponding result values are
  283. // the elements of `block_args`. Returns an instruction referring to the
  284. // result value.
  285. auto AddConvergenceBlockWithArgAndPush(
  286. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  287. -> SemIR::InstId;
  288. // Sets the constant value of a block argument created as the result of a
  289. // branch. `select_id` should be a `BlockArg` that selects between two
  290. // values. `cond_id` is the condition, `if_false` is the value to use if the
  291. // condition is false, and `if_true` is the value to use if the condition is
  292. // true. We don't track enough information in the `BlockArg` inst for
  293. // `TryEvalInst` to do this itself.
  294. auto SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  295. SemIR::InstId cond_id,
  296. SemIR::InstId if_true,
  297. SemIR::InstId if_false) -> void;
  298. // Returns whether the current position in the current block is reachable.
  299. auto is_current_position_reachable() -> bool;
  300. // Returns the type ID for a constant of type `type`.
  301. auto GetTypeIdForTypeConstant(SemIR::ConstantId constant_id) -> SemIR::TypeId;
  302. // Returns the type ID for an instruction whose constant value is of type
  303. // `type`.
  304. auto GetTypeIdForTypeInst(SemIR::InstId inst_id) -> SemIR::TypeId {
  305. return GetTypeIdForTypeConstant(constant_values().Get(inst_id));
  306. }
  307. // Attempts to complete the type `type_id`. Returns `true` if the type is
  308. // complete, or `false` if it could not be completed. A complete type has
  309. // known object and value representations. Returns `true` if the type is
  310. // symbolic.
  311. //
  312. // Avoid calling this where possible, as it can lead to coherence issues.
  313. // However, it's important that we use it during monomorphization, where we
  314. // don't want to trigger a request for more monomorphization.
  315. // TODO: Remove the other call to this function.
  316. auto TryToCompleteType(SemIR::TypeId type_id, SemIRLoc loc,
  317. BuildDiagnosticFn diagnoser = nullptr) -> bool;
  318. // Completes the type `type_id`. CHECK-fails if it can't be completed.
  319. auto CompleteTypeOrCheckFail(SemIR::TypeId type_id) -> void;
  320. // Like `TryToCompleteType`, but for cases where it is an error for the type
  321. // to be incomplete.
  322. //
  323. // If the type is not complete, `diagnoser` is invoked to diagnose the issue,
  324. // if a `diagnoser` is provided. The builder it returns will be annotated to
  325. // describe the reason why the type is not complete.
  326. //
  327. // `diagnoser` should build an error diagnostic. If `type_id` is dependent,
  328. // the completeness of the type will be enforced during monomorphization, and
  329. // `loc_id` is used as the location for a diagnostic produced at that time.
  330. auto RequireCompleteType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  331. BuildDiagnosticFn diagnoser) -> bool;
  332. // Like `RequireCompleteType`, but also require the type to not be an abstract
  333. // class type. If it is, `abstract_diagnoser` is used to diagnose the problem,
  334. // and this function returns false.
  335. auto RequireConcreteType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  336. BuildDiagnosticFn diagnoser,
  337. BuildDiagnosticFn abstract_diagnoser) -> bool;
  338. // Like `RequireCompleteType`, but also require the type to be defined. A
  339. // defined type has known members. If the type is not defined, `diagnoser` is
  340. // used to diagnose the problem, and this function returns false.
  341. //
  342. // This is the same as `RequireCompleteType` except for facet types, which are
  343. // complete before they are fully defined.
  344. auto RequireDefinedType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  345. BuildDiagnosticFn diagnoser) -> bool;
  346. // Returns the type `type_id` if it is a complete type, or produces an
  347. // incomplete type error and returns an error type. This is a convenience
  348. // wrapper around `RequireCompleteType`.
  349. auto AsCompleteType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  350. BuildDiagnosticFn diagnoser) -> SemIR::TypeId {
  351. return RequireCompleteType(type_id, loc_id, diagnoser)
  352. ? type_id
  353. : SemIR::ErrorInst::SingletonTypeId;
  354. }
  355. // Returns the type `type_id` if it is a concrete type, or produces an
  356. // incomplete or abstract type error and returns an error type. This is a
  357. // convenience wrapper around `RequireConcreteType`.
  358. auto AsConcreteType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  359. BuildDiagnosticFn diagnoser,
  360. BuildDiagnosticFn abstract_diagnoser) -> SemIR::TypeId {
  361. return RequireConcreteType(type_id, loc_id, diagnoser, abstract_diagnoser)
  362. ? type_id
  363. : SemIR::ErrorInst::SingletonTypeId;
  364. }
  365. // Returns whether `type_id` represents a facet type.
  366. auto IsFacetType(SemIR::TypeId type_id) -> bool {
  367. return type_id == SemIR::TypeType::SingletonTypeId ||
  368. types().Is<SemIR::FacetType>(type_id);
  369. }
  370. // Create a FacetType typed instruction object consisting of a single
  371. // interface.
  372. auto FacetTypeFromInterface(SemIR::InterfaceId interface_id,
  373. SemIR::SpecificId specific_id)
  374. -> SemIR::FacetType;
  375. // TODO: Consider moving these `Get*Type` functions to a separate class.
  376. // Gets the type for the name of an associated entity.
  377. auto GetAssociatedEntityType(SemIR::TypeId interface_type_id,
  378. SemIR::TypeId entity_type_id) -> SemIR::TypeId;
  379. // Gets a singleton type. The returned type will be complete. Requires that
  380. // `singleton_id` is already validated to be a singleton.
  381. auto GetSingletonType(SemIR::InstId singleton_id) -> SemIR::TypeId;
  382. // Gets a class type.
  383. auto GetClassType(SemIR::ClassId class_id, SemIR::SpecificId specific_id)
  384. -> SemIR::TypeId;
  385. // Gets a function type. The returned type will be complete.
  386. auto GetFunctionType(SemIR::FunctionId fn_id, SemIR::SpecificId specific_id)
  387. -> SemIR::TypeId;
  388. // Gets a generic class type, which is the type of a name of a generic class,
  389. // such as the type of `Vector` given `class Vector(T:! type)`. The returned
  390. // type will be complete.
  391. auto GetGenericClassType(SemIR::ClassId class_id,
  392. SemIR::SpecificId enclosing_specific_id)
  393. -> SemIR::TypeId;
  394. // Gets a generic interface type, which is the type of a name of a generic
  395. // interface, such as the type of `AddWith` given
  396. // `interface AddWith(T:! type)`. The returned type will be complete.
  397. auto GetGenericInterfaceType(SemIR::InterfaceId interface_id,
  398. SemIR::SpecificId enclosing_specific_id)
  399. -> SemIR::TypeId;
  400. // Gets the facet type corresponding to a particular interface.
  401. auto GetInterfaceType(SemIR::InterfaceId interface_id,
  402. SemIR::SpecificId specific_id) -> SemIR::TypeId;
  403. // Returns a pointer type whose pointee type is `pointee_type_id`.
  404. auto GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId;
  405. // Returns a struct type with the given fields.
  406. auto GetStructType(SemIR::StructTypeFieldsId fields_id) -> SemIR::TypeId;
  407. // Returns a tuple type with the given element types.
  408. auto GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids) -> SemIR::TypeId;
  409. // Returns an unbound element type.
  410. auto GetUnboundElementType(SemIR::TypeId class_type_id,
  411. SemIR::TypeId element_type_id) -> SemIR::TypeId;
  412. // Adds an exported name.
  413. auto AddExport(SemIR::InstId inst_id) -> void { exports_.push_back(inst_id); }
  414. auto Finalize() -> void;
  415. // Returns the imported IR ID for an IR, or invalid if not imported.
  416. auto GetImportIRId(const SemIR::File& sem_ir) -> SemIR::ImportIRId& {
  417. return check_ir_map_[sem_ir.check_ir_id().index];
  418. }
  419. // True if the current file is an impl file.
  420. auto IsImplFile() -> bool {
  421. return sem_ir_->import_irs().Get(SemIR::ImportIRId::ApiForImpl).sem_ir !=
  422. nullptr;
  423. }
  424. // Prints information for a stack dump.
  425. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  426. // Prints the the formatted sem_ir to stderr.
  427. LLVM_DUMP_METHOD auto DumpFormattedFile() const -> void;
  428. // Get the Lex::TokenKind of a node for diagnostics.
  429. auto token_kind(Parse::NodeId node_id) -> Lex::TokenKind {
  430. return tokens().GetKind(parse_tree().node_token(node_id));
  431. }
  432. auto emitter() -> DiagnosticEmitter& { return *emitter_; }
  433. auto parse_tree_and_subtrees() -> const Parse::TreeAndSubtrees& {
  434. return get_parse_tree_and_subtrees_();
  435. }
  436. auto sem_ir() -> SemIR::File& { return *sem_ir_; }
  437. auto sem_ir() const -> const SemIR::File& { return *sem_ir_; }
  438. auto parse_tree() const -> const Parse::Tree& {
  439. return sem_ir_->parse_tree();
  440. }
  441. auto tokens() const -> const Lex::TokenizedBuffer& {
  442. return parse_tree().tokens();
  443. }
  444. auto node_stack() -> NodeStack& { return node_stack_; }
  445. auto inst_block_stack() -> InstBlockStack& { return inst_block_stack_; }
  446. auto pattern_block_stack() -> InstBlockStack& { return pattern_block_stack_; }
  447. auto param_and_arg_refs_stack() -> ParamAndArgRefsStack& {
  448. return param_and_arg_refs_stack_;
  449. }
  450. auto args_type_info_stack() -> InstBlockStack& {
  451. return args_type_info_stack_;
  452. }
  453. auto struct_type_fields_stack() -> ArrayStack<SemIR::StructTypeField>& {
  454. return struct_type_fields_stack_;
  455. }
  456. auto field_decls_stack() -> ArrayStack<SemIR::InstId>& {
  457. return field_decls_stack_;
  458. }
  459. auto decl_name_stack() -> DeclNameStack& { return decl_name_stack_; }
  460. auto decl_introducer_state_stack() -> DeclIntroducerStateStack& {
  461. return decl_introducer_state_stack_;
  462. }
  463. auto scope_stack() -> ScopeStack& { return scope_stack_; }
  464. auto return_scope_stack() -> llvm::SmallVector<ScopeStack::ReturnScope>& {
  465. return scope_stack().return_scope_stack();
  466. }
  467. auto break_continue_stack()
  468. -> llvm::SmallVector<ScopeStack::BreakContinueScope>& {
  469. return scope_stack().break_continue_stack();
  470. }
  471. auto generic_region_stack() -> GenericRegionStack& {
  472. return generic_region_stack_;
  473. }
  474. auto import_ir_constant_values()
  475. -> llvm::SmallVector<SemIR::ConstantValueStore, 0>& {
  476. return import_ir_constant_values_;
  477. }
  478. // Directly expose SemIR::File data accessors for brevity in calls.
  479. auto identifiers() -> SharedValueStores::IdentifierStore& {
  480. return sem_ir().identifiers();
  481. }
  482. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  483. auto reals() -> SharedValueStores::RealStore& { return sem_ir().reals(); }
  484. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  485. auto string_literal_values() -> SharedValueStores::StringLiteralStore& {
  486. return sem_ir().string_literal_values();
  487. }
  488. auto entity_names() -> SemIR::EntityNameStore& {
  489. return sem_ir().entity_names();
  490. }
  491. auto functions() -> ValueStore<SemIR::FunctionId>& {
  492. return sem_ir().functions();
  493. }
  494. auto classes() -> ValueStore<SemIR::ClassId>& { return sem_ir().classes(); }
  495. auto interfaces() -> ValueStore<SemIR::InterfaceId>& {
  496. return sem_ir().interfaces();
  497. }
  498. auto facet_types() -> CanonicalValueStore<SemIR::FacetTypeId>& {
  499. return sem_ir().facet_types();
  500. }
  501. auto impls() -> SemIR::ImplStore& { return sem_ir().impls(); }
  502. auto generics() -> SemIR::GenericStore& { return sem_ir().generics(); }
  503. auto specifics() -> SemIR::SpecificStore& { return sem_ir().specifics(); }
  504. auto import_irs() -> ValueStore<SemIR::ImportIRId>& {
  505. return sem_ir().import_irs();
  506. }
  507. auto import_ir_insts() -> ValueStore<SemIR::ImportIRInstId>& {
  508. return sem_ir().import_ir_insts();
  509. }
  510. auto names() -> SemIR::NameStoreWrapper { return sem_ir().names(); }
  511. auto name_scopes() -> SemIR::NameScopeStore& {
  512. return sem_ir().name_scopes();
  513. }
  514. auto struct_type_fields() -> SemIR::StructTypeFieldsStore& {
  515. return sem_ir().struct_type_fields();
  516. }
  517. auto types() -> SemIR::TypeStore& { return sem_ir().types(); }
  518. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  519. return sem_ir().type_blocks();
  520. }
  521. // Instructions should be added with `AddInst` or `AddInstInNoBlock`. This is
  522. // `const` to prevent accidental misuse.
  523. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  524. auto constant_values() -> SemIR::ConstantValueStore& {
  525. return sem_ir().constant_values();
  526. }
  527. auto inst_blocks() -> SemIR::InstBlockStore& {
  528. return sem_ir().inst_blocks();
  529. }
  530. auto constants() -> SemIR::ConstantStore& { return sem_ir().constants(); }
  531. auto definitions_required() -> llvm::SmallVector<SemIR::InstId>& {
  532. return definitions_required_;
  533. }
  534. auto global_init() -> GlobalInit& { return global_init_; }
  535. // Marks the start of a region of insts in a pattern context that might
  536. // represent an expression or a pattern.
  537. auto BeginSubpattern() -> void;
  538. // Ends a region started by BeginSubpattern (in stack order), treating it as
  539. // an expression with the given result, and returns the ID of the region. The
  540. // region will not yet have any control-flow edges into or out of it.
  541. auto EndSubpatternAsExpr(SemIR::InstId result_id) -> SemIR::ExprRegionId;
  542. // Ends a region started by BeginSubpattern (in stack order), asserting that
  543. // it was empty.
  544. auto EndSubpatternAsEmpty() -> void;
  545. // TODO: Add EndSubpatternAsPattern, when needed.
  546. // Inserts the given region into the current code block. If the region
  547. // consists of a single block, this will be implemented as a `splice_block`
  548. // inst. Otherwise, this will end the current block with a branch to the entry
  549. // block of the region, and add future insts to a new block which is the
  550. // immediate successor of the region's exit block. As a result, this cannot be
  551. // called more than once for the same region.
  552. auto InsertHere(SemIR::ExprRegionId region_id) -> SemIR::InstId;
  553. auto import_ref_ids() -> llvm::SmallVector<SemIR::InstId>& {
  554. return import_ref_ids_;
  555. }
  556. // Map from an AnyBindingPattern inst to precomputed parts of the
  557. // pattern-match SemIR for it.
  558. //
  559. // TODO: Consider putting this behind a narrower API to guard against emitting
  560. // multiple times.
  561. struct BindingPatternInfo {
  562. // The corresponding AnyBindName inst.
  563. SemIR::InstId bind_name_id;
  564. // The region of insts that computes the type of the binding.
  565. SemIR::ExprRegionId type_expr_id;
  566. };
  567. auto bind_name_map() -> Map<SemIR::InstId, BindingPatternInfo>& {
  568. return bind_name_map_;
  569. }
  570. private:
  571. // A FoldingSet node for a type.
  572. class TypeNode : public llvm::FastFoldingSetNode {
  573. public:
  574. explicit TypeNode(const llvm::FoldingSetNodeID& node_id,
  575. SemIR::TypeId type_id)
  576. : llvm::FastFoldingSetNode(node_id), type_id_(type_id) {}
  577. auto type_id() -> SemIR::TypeId { return type_id_; }
  578. private:
  579. SemIR::TypeId type_id_;
  580. };
  581. // Checks that the provided imported location has a node kind that is
  582. // compatible with that of the given instruction.
  583. auto CheckCompatibleImportedNodeKind(SemIR::ImportIRInstId imported_loc_id,
  584. SemIR::InstKind kind) -> void;
  585. // Finish producing an instruction. Set its constant value, and register it in
  586. // any applicable instruction lists.
  587. auto FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void;
  588. // Handles diagnostics.
  589. DiagnosticEmitter* emitter_;
  590. // Returns a lazily constructed TreeAndSubtrees.
  591. llvm::function_ref<const Parse::TreeAndSubtrees&()>
  592. get_parse_tree_and_subtrees_;
  593. // The SemIR::File being added to.
  594. SemIR::File* sem_ir_;
  595. // Whether to print verbose output.
  596. llvm::raw_ostream* vlog_stream_;
  597. // The stack during Build. Will contain file-level parse nodes on return.
  598. NodeStack node_stack_;
  599. // The stack of instruction blocks being used for general IR generation.
  600. InstBlockStack inst_block_stack_;
  601. // The stack of instruction blocks that contain pattern instructions.
  602. InstBlockStack pattern_block_stack_;
  603. // The stack of instruction blocks being used for param and arg ref blocks.
  604. ParamAndArgRefsStack param_and_arg_refs_stack_;
  605. // The stack of instruction blocks being used for type information while
  606. // processing arguments. This is used in parallel with
  607. // param_and_arg_refs_stack_. It's currently only used for struct literals,
  608. // where we need to track names for a type separate from the literal
  609. // arguments.
  610. InstBlockStack args_type_info_stack_;
  611. // The stack of StructTypeFields for in-progress StructTypeLiterals.
  612. ArrayStack<SemIR::StructTypeField> struct_type_fields_stack_;
  613. // The stack of FieldDecls for in-progress Class definitions.
  614. ArrayStack<SemIR::InstId> field_decls_stack_;
  615. // The stack used for qualified declaration name construction.
  616. DeclNameStack decl_name_stack_;
  617. // The stack of declarations that could have modifiers.
  618. DeclIntroducerStateStack decl_introducer_state_stack_;
  619. // The stack of scopes we are currently within.
  620. ScopeStack scope_stack_;
  621. // The stack of generic regions we are currently within.
  622. GenericRegionStack generic_region_stack_;
  623. // Cache of reverse mapping from type constants to types.
  624. //
  625. // TODO: Instead of mapping to a dense `TypeId` space, we could make `TypeId`
  626. // be a thin wrapper around `ConstantId` and only perform the lookup only when
  627. // we want to access the completeness and value representation of a type. It's
  628. // not clear whether that would result in more or fewer lookups.
  629. //
  630. // TODO: Should this be part of the `TypeStore`?
  631. Map<SemIR::ConstantId, SemIR::TypeId> type_ids_for_type_constants_;
  632. // The list which will form NodeBlockId::Exports.
  633. llvm::SmallVector<SemIR::InstId> exports_;
  634. // Maps CheckIRId to ImportIRId.
  635. llvm::SmallVector<SemIR::ImportIRId> check_ir_map_;
  636. // Per-import constant values. These refer to the main IR and mainly serve as
  637. // a lookup table for quick access.
  638. //
  639. // Inline 0 elements because it's expected to require heap allocation.
  640. llvm::SmallVector<SemIR::ConstantValueStore, 0> import_ir_constant_values_;
  641. // Declaration instructions of entities that should have definitions by the
  642. // end of the current source file.
  643. llvm::SmallVector<SemIR::InstId> definitions_required_;
  644. // State for global initialization.
  645. GlobalInit global_init_;
  646. // A list of import refs which can't be inserted into their current context.
  647. // They're typically added during name lookup or import ref resolution, where
  648. // the current block on inst_block_stack_ is unrelated.
  649. //
  650. // These are instead added here because they're referenced by other
  651. // instructions and needs to be visible in textual IR.
  652. // FinalizeImportRefBlock() will produce an inst block for them.
  653. llvm::SmallVector<SemIR::InstId> import_ref_ids_;
  654. Map<SemIR::InstId, BindingPatternInfo> bind_name_map_;
  655. // Stack of single-entry regions being built.
  656. ArrayStack<SemIR::InstBlockId> region_stack_;
  657. };
  658. } // namespace Carbon::Check
  659. #endif // CARBON_TOOLCHAIN_CHECK_CONTEXT_H_