generic.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. #include "toolchain/check/generic.h"
  5. #include "common/map.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/diagnostic_helpers.h"
  8. #include "toolchain/check/eval.h"
  9. #include "toolchain/check/generic_region_stack.h"
  10. #include "toolchain/check/inst.h"
  11. #include "toolchain/check/subst.h"
  12. #include "toolchain/check/type.h"
  13. #include "toolchain/check/type_completion.h"
  14. #include "toolchain/diagnostics/diagnostic.h"
  15. #include "toolchain/sem_ir/constant.h"
  16. #include "toolchain/sem_ir/generic.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/inst.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::Check {
  21. static auto MakeSelfSpecificId(Context& context, SemIR::GenericId generic_id)
  22. -> SemIR::SpecificId;
  23. auto StartGenericDecl(Context& context) -> void {
  24. context.generic_region_stack().Push();
  25. }
  26. auto StartGenericDefinition(Context& context) -> void {
  27. // Push a generic region even if we don't have a generic_id. We might still
  28. // have locally-introduced generic parameters to track:
  29. //
  30. // fn F() {
  31. // let T:! type = i32;
  32. // var x: T;
  33. // }
  34. context.generic_region_stack().Push();
  35. }
  36. // Adds an instruction `generic_inst_id` to the eval block for a generic region,
  37. // which is the current instruction block. The instruction `generic_inst_id` is
  38. // expected to compute the value of the constant described by `const_inst_id` in
  39. // each specific. Forms and returns a corresponding symbolic constant ID that
  40. // refers to the substituted value of that instruction in each specific.
  41. static auto AddGenericConstantInstToEvalBlock(
  42. Context& context, SemIR::GenericId generic_id,
  43. SemIR::GenericInstIndex::Region region, SemIR::InstId const_inst_id,
  44. SemIR::InstId generic_inst_id, SemIR::ConstantDependence dependence)
  45. -> SemIR::ConstantId {
  46. auto index = SemIR::GenericInstIndex(
  47. region, context.inst_block_stack().PeekCurrentBlockContents().size());
  48. context.inst_block_stack().AddInstId(generic_inst_id);
  49. return context.constant_values().AddSymbolicConstant(
  50. {.inst_id = const_inst_id,
  51. .generic_id = generic_id,
  52. .index = index,
  53. .dependence = dependence});
  54. }
  55. namespace {
  56. // A map from an instruction ID representing a canonical symbolic constant to an
  57. // instruction within an eval block of the generic that computes the specific
  58. // value for that constant.
  59. //
  60. // We arbitrarily use a small size of 256 bytes for the map.
  61. // TODO: Determine a better number based on measurements.
  62. using ConstantsInGenericMap = Map<SemIR::InstId, SemIR::InstId, 256>;
  63. // Substitution callbacks to rebuild a generic constant in the eval block for a
  64. // generic region.
  65. class RebuildGenericConstantInEvalBlockCallbacks : public SubstInstCallbacks {
  66. public:
  67. // `context` must not be null.
  68. RebuildGenericConstantInEvalBlockCallbacks(
  69. Context* context, SemIR::GenericId generic_id,
  70. SemIR::GenericInstIndex::Region region, SemIR::LocId loc_id,
  71. ConstantsInGenericMap& constants_in_generic, bool inside_redeclaration)
  72. : context_(context),
  73. generic_id_(generic_id),
  74. region_(region),
  75. loc_id_(loc_id),
  76. constants_in_generic_(constants_in_generic),
  77. inside_redeclaration_(inside_redeclaration) {}
  78. auto context() const -> Context& { return *context_; }
  79. // Check for instructions for which we already have a mapping into the eval
  80. // block, and substitute them for the instructions in the eval block.
  81. auto Subst(SemIR::InstId& inst_id) const -> bool override {
  82. auto const_id = context_->constant_values().Get(inst_id);
  83. if (!const_id.has_value()) {
  84. // An unloaded import ref should never contain anything we need to
  85. // substitute into. Don't trigger loading it here.
  86. CARBON_CHECK(
  87. context_->insts().Is<SemIR::ImportRefUnloaded>(inst_id),
  88. "Substituting into instruction with invalid constant ID: {0}",
  89. context_->insts().Get(inst_id));
  90. return true;
  91. }
  92. if (!context_->constant_values().DependsOnGenericParameter(const_id)) {
  93. // This instruction doesn't have a symbolic constant value, so can't
  94. // contain any bindings that need to be substituted.
  95. return true;
  96. }
  97. // If this instruction is in the map, return the known result.
  98. if (auto result = constants_in_generic_.Lookup(
  99. context_->constant_values().GetInstId(const_id))) {
  100. // In order to reuse instructions from the generic as often as possible,
  101. // keep this instruction as-is if it already has the desired symbolic
  102. // constant value.
  103. if (const_id != context_->constant_values().Get(result.value())) {
  104. inst_id = result.value();
  105. }
  106. CARBON_CHECK(inst_id.has_value());
  107. return true;
  108. }
  109. return false;
  110. }
  111. // Build a new instruction in the eval block corresponding to the given
  112. // constant.
  113. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst) const
  114. -> SemIR::InstId override {
  115. auto& orig_symbolic_const = context_->constant_values().GetSymbolicConstant(
  116. context_->constant_values().Get(orig_inst_id));
  117. auto const_inst_id = orig_symbolic_const.inst_id;
  118. auto dependence = orig_symbolic_const.dependence;
  119. // We might already have an instruction in the eval block if a transitive
  120. // operand of this instruction has the same constant value.
  121. auto result = constants_in_generic_.Insert(const_inst_id, [&] {
  122. if (inside_redeclaration_) {
  123. // Adding instructions to a redeclaration causes crashes later since it
  124. // causes us to produce invalid indices into the original declaration's
  125. // set of instructions. So we terminate now and avoid adding a new
  126. // instruction and new index. It should not be possible to create this
  127. // situation where a generic redeclaration introduces new instructions
  128. // to the eval block.
  129. CARBON_FATAL("generic redeclaration differs from previous declaration");
  130. }
  131. // TODO: Add a function on `Context` to add the instruction without
  132. // inserting it into the dependent instructions list or computing a
  133. // constant value for it.
  134. // TODO: Is the location we pick here always appropriate for the new
  135. // instruction?
  136. auto inst_id = context_->sem_ir().insts().AddInNoBlock(
  137. SemIR::LocIdAndInst::UncheckedLoc(loc_id_, new_inst));
  138. auto const_id = AddGenericConstantInstToEvalBlock(
  139. *context_, generic_id_, region_, const_inst_id, inst_id, dependence);
  140. context_->constant_values().Set(inst_id, const_id);
  141. return inst_id;
  142. });
  143. return result.value();
  144. }
  145. auto ReuseUnchanged(SemIR::InstId orig_inst_id) const
  146. -> SemIR::InstId override {
  147. auto inst = context_->insts().Get(orig_inst_id);
  148. CARBON_CHECK(
  149. inst.Is<SemIR::BindSymbolicName>() ||
  150. inst.Is<SemIR::SymbolicBindingPattern>(),
  151. "Instruction {0} has symbolic constant value but no symbolic operands",
  152. inst);
  153. // Rebuild the instruction anyway so that it's included in the eval block.
  154. // TODO: Can we just reuse the instruction in this case?
  155. return Rebuild(orig_inst_id, inst);
  156. }
  157. private:
  158. Context* context_;
  159. SemIR::GenericId generic_id_;
  160. SemIR::GenericInstIndex::Region region_;
  161. SemIR::LocId loc_id_;
  162. ConstantsInGenericMap& constants_in_generic_;
  163. bool inside_redeclaration_;
  164. };
  165. // Substitution callbacks to rebuild a template action. This rebuilds the action
  166. // instruction in-place if it needs to be modified.
  167. class RebuildTemplateActionInEvalBlockCallbacks final
  168. : public RebuildGenericConstantInEvalBlockCallbacks {
  169. public:
  170. // `context` must not be null.
  171. RebuildTemplateActionInEvalBlockCallbacks(
  172. Context* context, SemIR::GenericId generic_id,
  173. SemIR::GenericInstIndex::Region region, SemIR::LocId loc_id,
  174. ConstantsInGenericMap& constants_in_generic, bool inside_redeclaration,
  175. SemIR::InstId action_inst_id)
  176. : RebuildGenericConstantInEvalBlockCallbacks(context, generic_id, region,
  177. loc_id, constants_in_generic,
  178. inside_redeclaration),
  179. action_inst_id_(action_inst_id) {}
  180. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst) const
  181. -> SemIR::InstId override {
  182. if (orig_inst_id == action_inst_id_) {
  183. // TODO: We want to ReplaceInstPreservingConstantValue here, but don't
  184. // want to evaluate the action to check the value hasn't changed.
  185. context().sem_ir().insts().Set(orig_inst_id, new_inst);
  186. return orig_inst_id;
  187. }
  188. return RebuildGenericConstantInEvalBlockCallbacks::Rebuild(orig_inst_id,
  189. new_inst);
  190. }
  191. auto ReuseUnchanged(SemIR::InstId orig_inst_id) const
  192. -> SemIR::InstId override {
  193. if (orig_inst_id == action_inst_id_) {
  194. return orig_inst_id;
  195. }
  196. return RebuildGenericConstantInEvalBlockCallbacks::ReuseUnchanged(
  197. orig_inst_id);
  198. }
  199. private:
  200. SemIR::InstId action_inst_id_;
  201. };
  202. } // namespace
  203. // Adds instructions to compute the substituted version of `type_id` in each
  204. // specific into the eval block for the generic, which is the current
  205. // instruction block. Returns a symbolic type ID that refers to the substituted
  206. // type in each specific.
  207. static auto AddGenericTypeToEvalBlock(
  208. Context& context, SemIR::GenericId generic_id,
  209. SemIR::GenericInstIndex::Region region, SemIR::LocId loc_id,
  210. ConstantsInGenericMap& constants_in_generic, bool inside_redeclaration,
  211. SemIR::TypeId type_id) -> SemIR::TypeId {
  212. // Substitute into the type's constant instruction and rebuild it in the eval
  213. // block.
  214. auto type_inst_id =
  215. SubstInst(context, context.types().GetInstId(type_id),
  216. RebuildGenericConstantInEvalBlockCallbacks(
  217. &context, generic_id, region, loc_id, constants_in_generic,
  218. inside_redeclaration));
  219. return context.types().GetTypeIdForTypeInstId(type_inst_id);
  220. }
  221. // Adds instructions to compute the substituted value of `inst_id` in each
  222. // specific into the eval block for the generic, which is the current
  223. // instruction block. Returns a symbolic constant instruction ID that refers to
  224. // the substituted constant value in each specific.
  225. static auto AddGenericConstantToEvalBlock(
  226. Context& context, SemIR::GenericId generic_id,
  227. SemIR::GenericInstIndex::Region region,
  228. ConstantsInGenericMap& constants_in_generic, bool inside_redeclaration,
  229. SemIR::InstId inst_id) -> SemIR::ConstantId {
  230. // Substitute into the constant value and rebuild it in the eval block if
  231. // we've not encountered it before.
  232. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  233. auto callbacks = RebuildGenericConstantInEvalBlockCallbacks(
  234. &context, generic_id, region, SemIR::LocId(inst_id), constants_in_generic,
  235. inside_redeclaration);
  236. auto new_inst_id = SubstInst(context, const_inst_id, callbacks);
  237. CARBON_CHECK(new_inst_id != const_inst_id,
  238. "No substitutions performed for generic constant {0}",
  239. context.insts().Get(inst_id));
  240. return context.constant_values().Get(new_inst_id);
  241. }
  242. // Adds an instruction that performs a template action to the eval block for the
  243. // generic. The instruction should not yet have been added to any block. The
  244. // instruction might refer to types and constants that need to be rewritten, so
  245. // substitute into it first.
  246. static auto AddTemplateActionToEvalBlock(
  247. Context& context, SemIR::GenericId generic_id,
  248. SemIR::GenericInstIndex::Region region,
  249. ConstantsInGenericMap& constants_in_generic, bool inside_redeclaration,
  250. SemIR::InstId inst_id) -> void {
  251. // Substitute into the constant value and rebuild it in the eval block.
  252. auto new_inst_id =
  253. SubstInst(context, inst_id,
  254. RebuildTemplateActionInEvalBlockCallbacks(
  255. &context, generic_id, region, SemIR::LocId(inst_id),
  256. constants_in_generic, inside_redeclaration, inst_id));
  257. CARBON_CHECK(new_inst_id == inst_id,
  258. "Substitution changed InstId of template action");
  259. constants_in_generic.Insert(inst_id, inst_id);
  260. // Add the action to the eval block and point its constant value back to its
  261. // index within the block.
  262. auto& symbolic_constant = context.constant_values().GetSymbolicConstant(
  263. context.constant_values().Get(inst_id));
  264. symbolic_constant.generic_id = generic_id;
  265. symbolic_constant.index = SemIR::GenericInstIndex(
  266. region, context.inst_block_stack().PeekCurrentBlockContents().size());
  267. context.inst_block_stack().AddInstId(inst_id);
  268. }
  269. // Populates a map of constants in a generic from the constants in the
  270. // declaration region, in preparation for building the definition region.
  271. static auto PopulateConstantsFromDeclaration(
  272. Context& context, SemIR::GenericId generic_id,
  273. ConstantsInGenericMap& constants_in_generic) {
  274. // For the definition region, populate constants from the declaration.
  275. auto decl_eval_block = context.inst_blocks().Get(
  276. context.generics().Get(generic_id).decl_block_id);
  277. constants_in_generic.GrowForInsertCount(decl_eval_block.size());
  278. for (auto inst_id : decl_eval_block) {
  279. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  280. auto result = constants_in_generic.Insert(const_inst_id, inst_id);
  281. CARBON_CHECK(result.is_inserted(),
  282. "Duplicate constant in generic decl eval block: {0}",
  283. context.insts().Get(const_inst_id));
  284. }
  285. }
  286. // Builds and returns a block of instructions whose constant values need to be
  287. // evaluated in order to resolve a generic to a specific.
  288. static auto MakeGenericEvalBlock(Context& context, SemIR::GenericId generic_id,
  289. SemIR::GenericInstIndex::Region region,
  290. bool inside_redeclaration)
  291. -> SemIR::InstBlockId {
  292. context.inst_block_stack().Push();
  293. ConstantsInGenericMap constants_in_generic;
  294. if (region == SemIR::GenericInstIndex::Region::Definition ||
  295. inside_redeclaration) {
  296. PopulateConstantsFromDeclaration(context, generic_id, constants_in_generic);
  297. }
  298. // The work done in this loop might invalidate iterators into the generic
  299. // region stack, but shouldn't add new dependent instructions to the current
  300. // region.
  301. auto num_dependent_insts =
  302. context.generic_region_stack().PeekDependentInsts().size();
  303. for (auto i : llvm::seq(num_dependent_insts)) {
  304. auto [inst_id, dep_kind] =
  305. context.generic_region_stack().PeekDependentInsts()[i];
  306. // If the type is symbolic, replace it with a type specific to this generic.
  307. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicType) !=
  308. GenericRegionStack::DependencyKind::None) {
  309. auto inst = context.insts().Get(inst_id);
  310. auto type_id = AddGenericTypeToEvalBlock(
  311. context, generic_id, region, SemIR::LocId(inst_id),
  312. constants_in_generic, inside_redeclaration, inst.type_id());
  313. // If the generic declaration is invalid, it can result in an error.
  314. if (type_id == SemIR::ErrorInst::TypeId) {
  315. break;
  316. }
  317. // TODO: Eventually, completeness requirements should be modeled as
  318. // constraints on the generic rather than properties of the type. For now,
  319. // require the transformed type to be complete if the original was.
  320. if (context.types().IsComplete(inst.type_id())) {
  321. CompleteTypeOrCheckFail(context, type_id);
  322. }
  323. inst.SetType(type_id);
  324. context.sem_ir().insts().Set(inst_id, inst);
  325. }
  326. // If the instruction has a symbolic constant value, then make a note that
  327. // we'll need to evaluate this instruction when forming the specific. Update
  328. // the constant value of the instruction to refer to the result of that
  329. // eventual evaluation.
  330. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicConstant) !=
  331. GenericRegionStack::DependencyKind::None) {
  332. // Update the constant value to refer to this generic.
  333. context.constant_values().Set(
  334. inst_id, AddGenericConstantToEvalBlock(
  335. context, generic_id, region, constants_in_generic,
  336. inside_redeclaration, inst_id));
  337. }
  338. // If the instruction is a template action, add it directly to this position
  339. // in the eval block.
  340. if ((dep_kind & GenericRegionStack::DependencyKind::Template) !=
  341. GenericRegionStack::DependencyKind::None) {
  342. AddTemplateActionToEvalBlock(context, generic_id, region,
  343. constants_in_generic, inside_redeclaration,
  344. inst_id);
  345. }
  346. }
  347. CARBON_CHECK(
  348. num_dependent_insts ==
  349. context.generic_region_stack().PeekDependentInsts().size(),
  350. "Building eval block added new dependent insts, for example {0}",
  351. context.insts().Get(context.generic_region_stack()
  352. .PeekDependentInsts()[num_dependent_insts]
  353. .inst_id));
  354. return context.inst_block_stack().Pop();
  355. }
  356. // Builds and returns an eval block, given the list of canonical symbolic
  357. // constants that the instructions in the eval block should produce. This is
  358. // used when importing a generic.
  359. auto RebuildGenericEvalBlock(Context& context, SemIR::GenericId generic_id,
  360. SemIR::GenericInstIndex::Region region,
  361. llvm::ArrayRef<SemIR::InstId> const_ids)
  362. -> SemIR::InstBlockId {
  363. context.inst_block_stack().Push();
  364. // We say we are not inside a redeclaration since this function is used for
  365. // import and there's no redeclaration there.
  366. bool inside_redeclaration = false;
  367. ConstantsInGenericMap constants_in_generic;
  368. // For the definition region, populate constants from the declaration.
  369. if (inside_redeclaration ||
  370. region == SemIR::GenericInstIndex::Region::Definition) {
  371. PopulateConstantsFromDeclaration(context, generic_id, constants_in_generic);
  372. }
  373. constants_in_generic.GrowForInsertCount(const_ids.size());
  374. for (auto [i, inst_id] : llvm::enumerate(const_ids)) {
  375. // Build a constant in the inst block.
  376. AddGenericConstantToEvalBlock(context, generic_id, region,
  377. constants_in_generic, inside_redeclaration,
  378. inst_id);
  379. CARBON_CHECK(
  380. context.inst_block_stack().PeekCurrentBlockContents().size() == i + 1,
  381. "Produced {0} instructions when importing {1}",
  382. (context.inst_block_stack().PeekCurrentBlockContents().size() - i),
  383. context.insts().Get(inst_id));
  384. }
  385. return context.inst_block_stack().Pop();
  386. }
  387. auto DiscardGenericDecl(Context& context) -> void {
  388. context.generic_region_stack().Pop();
  389. }
  390. auto BuildGeneric(Context& context, SemIR::InstId decl_id) -> SemIR::GenericId {
  391. auto all_bindings =
  392. context.scope_stack().compile_time_bindings_stack().PeekAllValues();
  393. if (all_bindings.empty()) {
  394. CARBON_CHECK(context.generic_region_stack().PeekDependentInsts().empty(),
  395. "Have dependent instruction {0} in declaration {1} but no "
  396. "compile time bindings are in scope.",
  397. context.insts().Get(context.generic_region_stack()
  398. .PeekDependentInsts()
  399. .front()
  400. .inst_id),
  401. context.insts().Get(decl_id));
  402. context.generic_region_stack().Pop();
  403. return SemIR::GenericId::None;
  404. }
  405. // Build the new Generic object. Note that we intentionally do not hold a
  406. // persistent reference to it throughout this function, because the `generics`
  407. // collection can have items added to it by import resolution while we are
  408. // building this generic.
  409. auto bindings_id = context.inst_blocks().Add(all_bindings);
  410. SemIR::GenericId generic_id = context.generics().Add(
  411. SemIR::Generic{.decl_id = decl_id,
  412. .bindings_id = bindings_id,
  413. .self_specific_id = SemIR::SpecificId::None});
  414. // MakeSelfSpecificId could cause something to be imported, which would
  415. // invalidate the return value of `context.generics().Get(generic_id)`.
  416. auto self_specific_id = MakeSelfSpecificId(context, generic_id);
  417. context.generics().Get(generic_id).self_specific_id = self_specific_id;
  418. return generic_id;
  419. }
  420. auto FinishGenericDecl(Context& context, SemIR::LocId loc_id,
  421. SemIR::GenericId generic_id) -> void {
  422. if (!generic_id.has_value()) {
  423. return;
  424. }
  425. auto decl_block_id = MakeGenericEvalBlock(
  426. context, generic_id, SemIR::GenericInstIndex::Region::Declaration,
  427. /*inside_redeclaration=*/false);
  428. context.generic_region_stack().Pop();
  429. context.generics().Get(generic_id).decl_block_id = decl_block_id;
  430. ResolveSpecificDeclaration(context, loc_id,
  431. context.generics().GetSelfSpecific(generic_id));
  432. }
  433. auto BuildGenericDecl(Context& context, SemIR::InstId decl_id)
  434. -> SemIR::GenericId {
  435. SemIR::GenericId generic_id = BuildGeneric(context, decl_id);
  436. if (generic_id.has_value()) {
  437. FinishGenericDecl(context, SemIR::LocId(decl_id), generic_id);
  438. }
  439. return generic_id;
  440. }
  441. auto FinishGenericRedecl(Context& context, SemIR::GenericId generic_id)
  442. -> void {
  443. if (!generic_id.has_value()) {
  444. context.generic_region_stack().Pop();
  445. return;
  446. }
  447. auto definition_block_id = MakeGenericEvalBlock(
  448. context, generic_id, SemIR::GenericInstIndex::Region::Declaration,
  449. /*inside_redeclaration=*/true);
  450. CARBON_CHECK(definition_block_id == SemIR::InstBlockId::Empty);
  451. context.generic_region_stack().Pop();
  452. }
  453. auto FinishGenericDefinition(Context& context, SemIR::GenericId generic_id)
  454. -> void {
  455. if (!generic_id.has_value()) {
  456. // TODO: We can have symbolic constants in a context that had a non-generic
  457. // declaration, for example if there's a local generic let binding in a
  458. // function definition. Handle this case somehow -- perhaps by forming
  459. // substituted constant values now.
  460. context.generic_region_stack().Pop();
  461. return;
  462. }
  463. auto definition_block_id = MakeGenericEvalBlock(
  464. context, generic_id, SemIR::GenericInstIndex::Region::Definition,
  465. /*inside_redeclaration=*/false);
  466. context.generics().Get(generic_id).definition_block_id = definition_block_id;
  467. context.generic_region_stack().Pop();
  468. }
  469. auto ResolveSpecificDeclaration(Context& context, SemIR::LocId loc_id,
  470. SemIR::SpecificId specific_id) -> void {
  471. // If this is the first time we've formed this specific, evaluate its decl
  472. // block to form information about the specific.
  473. if (!context.specifics().Get(specific_id).decl_block_id.has_value()) {
  474. // Set a placeholder value as the decl block ID so we won't attempt to
  475. // recursively resolve the same specific.
  476. context.specifics().Get(specific_id).decl_block_id =
  477. SemIR::InstBlockId::Empty;
  478. auto decl_block_id =
  479. TryEvalBlockForSpecific(context, loc_id, specific_id,
  480. SemIR::GenericInstIndex::Region::Declaration);
  481. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  482. // so re-lookup the specific here.
  483. context.specifics().Get(specific_id).decl_block_id = decl_block_id;
  484. }
  485. }
  486. auto MakeSpecific(Context& context, SemIR::LocId loc_id,
  487. SemIR::GenericId generic_id, SemIR::InstBlockId args_id)
  488. -> SemIR::SpecificId {
  489. auto specific_id = context.specifics().GetOrAdd(generic_id, args_id);
  490. ResolveSpecificDeclaration(context, loc_id, specific_id);
  491. return specific_id;
  492. }
  493. auto MakeSpecific(Context& context, SemIR::LocId loc_id,
  494. SemIR::GenericId generic_id,
  495. llvm::ArrayRef<SemIR::InstId> args) -> SemIR::SpecificId {
  496. auto args_id = context.inst_blocks().AddCanonical(args);
  497. return MakeSpecific(context, loc_id, generic_id, args_id);
  498. }
  499. static auto MakeSelfSpecificId(Context& context, SemIR::GenericId generic_id)
  500. -> SemIR::SpecificId {
  501. if (!generic_id.has_value()) {
  502. return SemIR::SpecificId::None;
  503. }
  504. auto& generic = context.generics().Get(generic_id);
  505. auto args = context.inst_blocks().Get(generic.bindings_id);
  506. // Form a canonical argument list for the generic.
  507. llvm::SmallVector<SemIR::InstId> arg_ids;
  508. arg_ids.reserve(args.size());
  509. for (auto arg_id : args) {
  510. arg_ids.push_back(context.constant_values().GetConstantInstId(arg_id));
  511. }
  512. auto args_id = context.inst_blocks().AddCanonical(arg_ids);
  513. return context.specifics().GetOrAdd(generic_id, args_id);
  514. }
  515. auto MakeSelfSpecific(Context& context, SemIR::LocId loc_id,
  516. SemIR::GenericId generic_id) -> SemIR::SpecificId {
  517. // Build a corresponding specific.
  518. SemIR::SpecificId specific_id = MakeSelfSpecificId(context, generic_id);
  519. // TODO: This could be made more efficient. We don't need to perform
  520. // substitution here; we know we want identity mappings for all constants and
  521. // types. We could also consider not storing the mapping at all in this case.
  522. ResolveSpecificDeclaration(context, loc_id, specific_id);
  523. return specific_id;
  524. }
  525. auto ResolveSpecificDefinition(Context& context, SemIR::LocId loc_id,
  526. SemIR::SpecificId specific_id) -> bool {
  527. // TODO: Handle recursive resolution of the same generic definition.
  528. auto& specific = context.specifics().Get(specific_id);
  529. auto generic_id = specific.generic_id;
  530. CARBON_CHECK(generic_id.has_value(), "Specific with no generic ID");
  531. if (!specific.definition_block_id.has_value()) {
  532. // Evaluate the eval block for the definition of the generic.
  533. auto& generic = context.generics().Get(generic_id);
  534. if (!generic.definition_block_id.has_value()) {
  535. // The generic is not defined yet.
  536. return false;
  537. }
  538. auto definition_block_id =
  539. TryEvalBlockForSpecific(context, loc_id, specific_id,
  540. SemIR::GenericInstIndex::Region::Definition);
  541. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  542. // so re-lookup the specific here.
  543. context.specifics().Get(specific_id).definition_block_id =
  544. definition_block_id;
  545. }
  546. return true;
  547. }
  548. auto DiagnoseIfGenericMissingExplicitParameters(
  549. Context& context, SemIR::EntityWithParamsBase& entity_base) -> void {
  550. if (!entity_base.implicit_param_patterns_id.has_value() ||
  551. entity_base.param_patterns_id.has_value()) {
  552. return;
  553. }
  554. CARBON_DIAGNOSTIC(GenericMissingExplicitParameters, Error,
  555. "expected explicit parameters after implicit parameters");
  556. context.emitter().Emit(entity_base.last_param_node_id,
  557. GenericMissingExplicitParameters);
  558. }
  559. } // namespace Carbon::Check