deduce.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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/deduce.h"
  5. #include "llvm/ADT/SmallBitVector.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/context.h"
  8. #include "toolchain/check/convert.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/check/subst.h"
  11. #include "toolchain/diagnostics/diagnostic.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/impl.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Check {
  16. namespace {
  17. // A list of pairs of (instruction from generic, corresponding instruction from
  18. // call to of generic) for which we still need to perform deduction, along with
  19. // methods to add and pop pending deductions from the list. Deductions are
  20. // popped in order from most- to least-recently pushed, with the intent that
  21. // they are visited in depth-first order, although the order is not expected to
  22. // matter except when it influences which error is diagnosed.
  23. class DeductionWorklist {
  24. public:
  25. explicit DeductionWorklist(Context& context) : context_(context) {}
  26. struct PendingDeduction {
  27. SemIR::InstId param;
  28. SemIR::InstId arg;
  29. bool needs_substitution;
  30. };
  31. // Adds a single (param, arg) deduction.
  32. auto Add(SemIR::InstId param, SemIR::InstId arg, bool needs_substitution)
  33. -> void {
  34. deductions_.push_back(
  35. {.param = param, .arg = arg, .needs_substitution = needs_substitution});
  36. }
  37. // Adds a single (param, arg) type deduction.
  38. auto Add(SemIR::TypeId param, SemIR::TypeId arg, bool needs_substitution)
  39. -> void {
  40. Add(context_.types().GetInstId(param), context_.types().GetInstId(arg),
  41. needs_substitution);
  42. }
  43. // Adds a single (param, arg) deduction of a specific.
  44. auto Add(SemIR::SpecificId param, SemIR::SpecificId arg,
  45. bool needs_substitution) -> void {
  46. if (!param.has_value() || !arg.has_value()) {
  47. return;
  48. }
  49. auto& param_specific = context_.specifics().Get(param);
  50. auto& arg_specific = context_.specifics().Get(arg);
  51. if (param_specific.generic_id != arg_specific.generic_id) {
  52. // TODO: Decide whether to error on this or just treat the specific as
  53. // non-deduced. For now we treat it as non-deduced.
  54. return;
  55. }
  56. AddAll(param_specific.args_id, arg_specific.args_id, needs_substitution);
  57. }
  58. // Adds a list of (param, arg) deductions. These are added in reverse order so
  59. // they are popped in forward order.
  60. template <typename ElementId>
  61. auto AddAll(llvm::ArrayRef<ElementId> params, llvm::ArrayRef<ElementId> args,
  62. bool needs_substitution) -> void {
  63. if (params.size() != args.size()) {
  64. // TODO: Decide whether to error on this or just treat the parameter list
  65. // as non-deduced. For now we treat it as non-deduced.
  66. return;
  67. }
  68. for (auto [param, arg] : llvm::reverse(llvm::zip_equal(params, args))) {
  69. Add(param, arg, needs_substitution);
  70. }
  71. }
  72. auto AddAll(SemIR::InstBlockId params, llvm::ArrayRef<SemIR::InstId> args,
  73. bool needs_substitution) -> void {
  74. AddAll(context_.inst_blocks().Get(params), args, needs_substitution);
  75. }
  76. auto AddAll(SemIR::StructTypeFieldsId params, SemIR::StructTypeFieldsId args,
  77. bool needs_substitution) -> void {
  78. const auto& param_fields = context_.struct_type_fields().Get(params);
  79. const auto& arg_fields = context_.struct_type_fields().Get(args);
  80. if (param_fields.size() != arg_fields.size()) {
  81. // TODO: Decide whether to error on this or just treat the parameter list
  82. // as non-deduced. For now we treat it as non-deduced.
  83. return;
  84. }
  85. // Don't do deduction unless the names match in order.
  86. // TODO: Support reordering of names.
  87. for (auto [param, arg] : llvm::zip_equal(param_fields, arg_fields)) {
  88. if (param.name_id != arg.name_id) {
  89. return;
  90. }
  91. }
  92. for (auto [param, arg] :
  93. llvm::reverse(llvm::zip_equal(param_fields, arg_fields))) {
  94. Add(param.type_id, arg.type_id, needs_substitution);
  95. }
  96. }
  97. auto AddAll(SemIR::InstBlockId params, SemIR::InstBlockId args,
  98. bool needs_substitution) -> void {
  99. AddAll(context_.inst_blocks().Get(params), context_.inst_blocks().Get(args),
  100. needs_substitution);
  101. }
  102. auto AddAll(SemIR::TypeBlockId params, SemIR::TypeBlockId args,
  103. bool needs_substitution) -> void {
  104. AddAll(context_.type_blocks().Get(params), context_.type_blocks().Get(args),
  105. needs_substitution);
  106. }
  107. auto AddAll(SemIR::FacetTypeId params, SemIR::FacetTypeId args,
  108. bool needs_substitution) -> void {
  109. const auto& param_impls =
  110. context_.facet_types().Get(params).impls_constraints;
  111. const auto& arg_impls = context_.facet_types().Get(args).impls_constraints;
  112. // TODO: Decide whether to error on these or just treat the parameter list
  113. // as non-deduced. For now we treat it as non-deduced.
  114. if (param_impls.size() != 1 || arg_impls.size() != 1) {
  115. return;
  116. }
  117. auto param = param_impls.front();
  118. auto arg = arg_impls.front();
  119. if (param.interface_id != arg.interface_id) {
  120. return;
  121. }
  122. Add(param.specific_id, arg.specific_id, needs_substitution);
  123. }
  124. // Adds a (param, arg) pair for an instruction argument, given its kind.
  125. auto AddInstArg(SemIR::IdKind kind, int32_t param, int32_t arg,
  126. bool needs_substitution) -> void {
  127. switch (kind) {
  128. case SemIR::IdKind::None:
  129. case SemIR::IdKind::For<SemIR::ClassId>:
  130. case SemIR::IdKind::For<SemIR::IntKind>:
  131. break;
  132. case SemIR::IdKind::For<SemIR::InstId>:
  133. Add(SemIR::InstId(param), SemIR::InstId(arg), needs_substitution);
  134. break;
  135. case SemIR::IdKind::For<SemIR::TypeId>:
  136. Add(SemIR::TypeId(param), SemIR::TypeId(arg), needs_substitution);
  137. break;
  138. case SemIR::IdKind::For<SemIR::StructTypeFieldsId>:
  139. AddAll(SemIR::StructTypeFieldsId(param), SemIR::StructTypeFieldsId(arg),
  140. needs_substitution);
  141. break;
  142. case SemIR::IdKind::For<SemIR::InstBlockId>:
  143. AddAll(SemIR::InstBlockId(param), SemIR::InstBlockId(arg),
  144. needs_substitution);
  145. break;
  146. case SemIR::IdKind::For<SemIR::TypeBlockId>:
  147. AddAll(SemIR::TypeBlockId(param), SemIR::TypeBlockId(arg),
  148. needs_substitution);
  149. break;
  150. case SemIR::IdKind::For<SemIR::SpecificId>:
  151. Add(SemIR::SpecificId(param), SemIR::SpecificId(arg),
  152. needs_substitution);
  153. break;
  154. case SemIR::IdKind::For<SemIR::FacetTypeId>:
  155. AddAll(SemIR::FacetTypeId(param), SemIR::FacetTypeId(arg),
  156. needs_substitution);
  157. break;
  158. default:
  159. CARBON_FATAL("unexpected argument kind");
  160. }
  161. }
  162. // Returns whether we have completed all deductions.
  163. auto Done() -> bool { return deductions_.empty(); }
  164. // Pops the next deduction. Requires `!Done()`.
  165. auto PopNext() -> PendingDeduction { return deductions_.pop_back_val(); }
  166. private:
  167. Context& context_;
  168. llvm::SmallVector<PendingDeduction> deductions_;
  169. };
  170. // State that is tracked throughout the deduction process.
  171. class DeductionContext {
  172. public:
  173. // Preparse to perform deduction. If an enclosing specific or self type
  174. // are provided, adds the corresponding arguments as known arguments that will
  175. // not be deduced.
  176. DeductionContext(Context& context, SemIR::LocId loc_id,
  177. SemIR::GenericId generic_id,
  178. SemIR::SpecificId enclosing_specific_id,
  179. SemIR::InstId self_type_id, bool diagnose);
  180. auto context() const -> Context& { return *context_; }
  181. // Adds a pending deduction of `param` from `arg`. `needs_substitution`
  182. // indicates whether we need to substitute known generic parameters into
  183. // `param`.
  184. template <typename ParamT, typename ArgT>
  185. auto Add(ParamT param, ArgT arg, bool needs_substitution) -> void {
  186. worklist_.Add(param, arg, needs_substitution);
  187. }
  188. // Same as `Add` but for an array or block of operands.
  189. template <typename ParamT, typename ArgT>
  190. auto AddAll(ParamT param, ArgT arg, bool needs_substitution) -> void {
  191. worklist_.AddAll(param, arg, needs_substitution);
  192. }
  193. // Performs all deductions in the deduction worklist. Returns whether
  194. // deduction succeeded.
  195. auto Deduce() -> bool;
  196. // Returns whether every generic parameter has a corresponding deduced generic
  197. // argument. If not, issues a suitable diagnostic.
  198. auto CheckDeductionIsComplete() -> bool;
  199. // Forms a specific corresponding to the deduced generic with the deduced
  200. // argument list. Must not be called before deduction is complete.
  201. auto MakeSpecific() -> SemIR::SpecificId;
  202. private:
  203. auto NoteInitializingParam(SemIR::InstId param_id, auto& builder) -> void {
  204. if (auto param = context().insts().TryGetAs<SemIR::SymbolicBindingPattern>(
  205. param_id)) {
  206. CARBON_DIAGNOSTIC(InitializingGenericParam, Note,
  207. "initializing generic parameter `{0}` declared here",
  208. SemIR::NameId);
  209. builder.Note(param_id, InitializingGenericParam,
  210. context().entity_names().Get(param->entity_name_id).name_id);
  211. } else {
  212. NoteGenericHere(context(), generic_id_, builder);
  213. }
  214. }
  215. Context* context_;
  216. SemIR::LocId loc_id_;
  217. SemIR::GenericId generic_id_;
  218. bool diagnose_;
  219. DeductionWorklist worklist_;
  220. llvm::SmallVector<SemIR::InstId> result_arg_ids_;
  221. llvm::SmallVector<Substitution> substitutions_;
  222. SemIR::CompileTimeBindIndex first_deduced_index_;
  223. // Non-deduced indexes, indexed by parameter index - first_deduced_index_.
  224. llvm::SmallBitVector non_deduced_indexes_;
  225. };
  226. } // namespace
  227. static auto NoteGenericHere(Context& context, SemIR::GenericId generic_id,
  228. Context::DiagnosticBuilder& diag) -> void {
  229. CARBON_DIAGNOSTIC(DeductionGenericHere, Note,
  230. "while deducing parameters of generic declared here");
  231. diag.Note(context.generics().Get(generic_id).decl_id, DeductionGenericHere);
  232. }
  233. DeductionContext::DeductionContext(Context& context, SemIR::LocId loc_id,
  234. SemIR::GenericId generic_id,
  235. SemIR::SpecificId enclosing_specific_id,
  236. SemIR::InstId self_type_id, bool diagnose)
  237. : context_(&context),
  238. loc_id_(loc_id),
  239. generic_id_(generic_id),
  240. diagnose_(diagnose),
  241. worklist_(context),
  242. first_deduced_index_(0) {
  243. CARBON_CHECK(generic_id.has_value(),
  244. "Performing deduction for non-generic entity");
  245. // Initialize the deduced arguments to `None`.
  246. result_arg_ids_.resize(
  247. context.inst_blocks()
  248. .Get(context.generics().Get(generic_id_).bindings_id)
  249. .size(),
  250. SemIR::InstId::None);
  251. if (enclosing_specific_id.has_value()) {
  252. // Copy any outer generic arguments from the specified instance and prepare
  253. // to substitute them into the function declaration.
  254. auto args = context.inst_blocks().Get(
  255. context.specifics().Get(enclosing_specific_id).args_id);
  256. llvm::copy(args, result_arg_ids_.begin());
  257. // TODO: Subst is linear in the length of the substitutions list. Change
  258. // it so we can pass in an array mapping indexes to substitutions instead.
  259. substitutions_.reserve(args.size() + result_arg_ids_.size());
  260. for (auto [i, subst_inst_id] : llvm::enumerate(args)) {
  261. substitutions_.push_back(
  262. {.bind_id = SemIR::CompileTimeBindIndex(i),
  263. .replacement_id = context.constant_values().Get(subst_inst_id)});
  264. }
  265. first_deduced_index_ = SemIR::CompileTimeBindIndex(args.size());
  266. }
  267. if (self_type_id.has_value()) {
  268. // Copy the provided `Self` type as the value of the next binding.
  269. auto self_index = first_deduced_index_;
  270. result_arg_ids_[self_index.index] = self_type_id;
  271. substitutions_.push_back(
  272. {.bind_id = SemIR::CompileTimeBindIndex(self_index),
  273. .replacement_id = context.constant_values().Get(self_type_id)});
  274. first_deduced_index_ = SemIR::CompileTimeBindIndex(self_index.index + 1);
  275. }
  276. non_deduced_indexes_.resize(result_arg_ids_.size() -
  277. first_deduced_index_.index);
  278. }
  279. auto DeductionContext::Deduce() -> bool {
  280. while (!worklist_.Done()) {
  281. auto [param_id, arg_id, needs_substitution] = worklist_.PopNext();
  282. // TODO: Bail out if there's nothing to deduce: if we're not in a pattern
  283. // and the parameter doesn't have a symbolic constant value.
  284. auto param_type_id = context().insts().Get(param_id).type_id();
  285. // If the parameter has a symbolic type, deduce against that.
  286. if (param_type_id.AsConstantId().is_symbolic()) {
  287. Add(context().types().GetInstId(param_type_id),
  288. context().types().GetInstId(context().insts().Get(arg_id).type_id()),
  289. needs_substitution);
  290. } else {
  291. // The argument (e.g. a TupleLiteral of types) may be convertible to a
  292. // compile-time value (e.g. TupleType) that we can decompose further.
  293. // So we do this conversion here, even though we will later try convert
  294. // again when we have deduced all of the bindings.
  295. DiagnosticAnnotationScope annotate_diagnostics(
  296. &context().emitter(),
  297. [&](auto& builder) { NoteInitializingParam(param_id, builder); });
  298. // TODO: The call logic should reuse the conversion here (if any) instead
  299. // of doing the same conversion again. At the moment we throw away the
  300. // converted arg_id.
  301. arg_id = ConvertToValueOfType(context(), loc_id_, arg_id, param_type_id);
  302. if (arg_id == SemIR::ErrorInst::SingletonInstId) {
  303. return false;
  304. }
  305. }
  306. // Attempt to match `param_inst` against `arg_id`. If the match succeeds,
  307. // this should `continue` the outer loop. On `break`, we will try to desugar
  308. // the parameter to continue looking for a match.
  309. auto param_inst = context().insts().Get(param_id);
  310. CARBON_KIND_SWITCH(param_inst) {
  311. // Deducing a symbolic binding pattern from an argument deduces the
  312. // binding as having that constant value. For example, deducing
  313. // `(T:! type)` against `(i32)` deduces `T` to be `i32`. This only arises
  314. // when initializing a generic parameter from an explicitly specified
  315. // argument, and in this case, the argument is required to be a
  316. // compile-time constant.
  317. case CARBON_KIND(SemIR::SymbolicBindingPattern bind): {
  318. auto& entity_name = context().entity_names().Get(bind.entity_name_id);
  319. auto index = entity_name.bind_index;
  320. if (!index.has_value()) {
  321. break;
  322. }
  323. CARBON_CHECK(
  324. index >= first_deduced_index_ &&
  325. static_cast<size_t>(index.index) < result_arg_ids_.size(),
  326. "Unexpected index {0} for symbolic binding pattern; "
  327. "expected to be in range [{1}, {2})",
  328. index.index, first_deduced_index_.index, result_arg_ids_.size());
  329. CARBON_CHECK(!result_arg_ids_[index.index].has_value(),
  330. "Deduced a value for parameter prior to its declaration");
  331. auto arg_const_inst_id =
  332. context().constant_values().GetConstantInstId(arg_id);
  333. if (!arg_const_inst_id.has_value()) {
  334. if (diagnose_) {
  335. CARBON_DIAGNOSTIC(CompTimeArgumentNotConstant, Error,
  336. "argument for generic parameter is not a "
  337. "compile-time constant");
  338. auto diag =
  339. context().emitter().Build(loc_id_, CompTimeArgumentNotConstant);
  340. NoteInitializingParam(param_id, diag);
  341. diag.Emit();
  342. }
  343. return false;
  344. }
  345. result_arg_ids_[index.index] = arg_const_inst_id;
  346. // This parameter index should not be deduced if it appears later.
  347. non_deduced_indexes_[index.index - first_deduced_index_.index] = true;
  348. continue;
  349. }
  350. // Deducing a symbolic binding appearing within an expression against a
  351. // constant value deduces the binding as having that value. For example,
  352. // deducing `[T:! type](x: T)` against `("foo")` deduces `T` as `String`.
  353. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  354. auto& entity_name = context().entity_names().Get(bind.entity_name_id);
  355. auto index = entity_name.bind_index;
  356. if (!index.has_value() || index < first_deduced_index_ ||
  357. non_deduced_indexes_[index.index - first_deduced_index_.index]) {
  358. break;
  359. }
  360. CARBON_CHECK(static_cast<size_t>(index.index) < result_arg_ids_.size(),
  361. "Deduced value for unexpected index {0}; expected to "
  362. "deduce {1} arguments.",
  363. index, result_arg_ids_.size());
  364. auto arg_const_inst_id =
  365. context().constant_values().GetConstantInstId(arg_id);
  366. if (arg_const_inst_id.has_value()) {
  367. if (result_arg_ids_[index.index].has_value() &&
  368. result_arg_ids_[index.index] != arg_const_inst_id) {
  369. if (diagnose_) {
  370. // TODO: Include the two different deduced values.
  371. CARBON_DIAGNOSTIC(DeductionInconsistent, Error,
  372. "inconsistent deductions for value of generic "
  373. "parameter `{0}`",
  374. SemIR::NameId);
  375. auto diag = context().emitter().Build(
  376. loc_id_, DeductionInconsistent, entity_name.name_id);
  377. NoteGenericHere(context(), generic_id_, diag);
  378. diag.Emit();
  379. }
  380. return false;
  381. }
  382. result_arg_ids_[index.index] = arg_const_inst_id;
  383. }
  384. continue;
  385. }
  386. case CARBON_KIND(SemIR::ValueParamPattern pattern): {
  387. Add(pattern.subpattern_id, arg_id, needs_substitution);
  388. continue;
  389. }
  390. case SemIR::StructValue::Kind:
  391. // TODO: Match field name order between param and arg.
  392. break;
  393. case SemIR::FacetAccessType::Kind:
  394. // Given `fn F[G:! Interface](g: G)`, the type of `g` is `G as type`.
  395. // `G` is a symbolic binding, whose type is a facet type, but `G as
  396. // type` converts into a `FacetAccessType`.
  397. //
  398. // When we see a `FacetAccessType` parameter here, we want to deduce the
  399. // facet type of `G`, not `G as type`, for the argument (so that the
  400. // argument would be a facet value, whose type is the same facet type of
  401. // `G`. So here we "undo" the `as type` operation that's built into the
  402. // `g` parameter's type.
  403. Add(param_inst.As<SemIR::FacetAccessType>().facet_value_inst_id, arg_id,
  404. needs_substitution);
  405. continue;
  406. // TODO: Handle more cases.
  407. default:
  408. if (param_inst.kind().deduce_through()) {
  409. // Various kinds of parameter should match an argument of the same
  410. // form, if the operands all match.
  411. auto arg_inst = context().insts().Get(arg_id);
  412. if (arg_inst.kind() != param_inst.kind()) {
  413. break;
  414. }
  415. auto [kind0, kind1] = param_inst.ArgKinds();
  416. worklist_.AddInstArg(kind0, param_inst.arg0(), arg_inst.arg0(),
  417. needs_substitution);
  418. worklist_.AddInstArg(kind1, param_inst.arg1(), arg_inst.arg1(),
  419. needs_substitution);
  420. continue;
  421. }
  422. break;
  423. }
  424. // We didn't manage to deduce against the syntactic form of the parameter.
  425. // Convert it to a canonical constant value and try deducing against that.
  426. auto param_const_id = context().constant_values().Get(param_id);
  427. if (!param_const_id.has_value() || !param_const_id.is_symbolic()) {
  428. // It's not a symbolic constant. There's nothing here to deduce.
  429. continue;
  430. }
  431. auto param_const_inst_id =
  432. context().constant_values().GetInstId(param_const_id);
  433. if (param_const_inst_id != param_id) {
  434. Add(param_const_inst_id, arg_id, needs_substitution);
  435. continue;
  436. }
  437. // If we've not yet substituted into the parameter, do so now and try again.
  438. if (needs_substitution) {
  439. param_const_id = SubstConstant(context(), param_const_id, substitutions_);
  440. if (!param_const_id.has_value() || !param_const_id.is_symbolic()) {
  441. continue;
  442. }
  443. Add(context().constant_values().GetInstId(param_const_id), arg_id,
  444. /*needs_substitution=*/false);
  445. }
  446. }
  447. return true;
  448. }
  449. auto DeductionContext::CheckDeductionIsComplete() -> bool {
  450. // Check we deduced an argument value for every parameter, and convert each
  451. // argument to match the final parameter type after substituting any deduced
  452. // types it depends on.
  453. for (auto&& [i, deduced_arg_id] :
  454. llvm::enumerate(llvm::MutableArrayRef(result_arg_ids_)
  455. .drop_front(first_deduced_index_.index))) {
  456. auto binding_index = first_deduced_index_.index + i;
  457. auto binding_id = context().inst_blocks().Get(
  458. context().generics().Get(generic_id_).bindings_id)[binding_index];
  459. if (!deduced_arg_id.has_value()) {
  460. if (diagnose_) {
  461. auto entity_name_id = context()
  462. .insts()
  463. .GetAs<SemIR::AnyBindName>(binding_id)
  464. .entity_name_id;
  465. CARBON_DIAGNOSTIC(DeductionIncomplete, Error,
  466. "cannot deduce value for generic parameter `{0}`",
  467. SemIR::NameId);
  468. auto diag = context().emitter().Build(
  469. loc_id_, DeductionIncomplete,
  470. context().entity_names().Get(entity_name_id).name_id);
  471. NoteGenericHere(context(), generic_id_, diag);
  472. diag.Emit();
  473. }
  474. return false;
  475. }
  476. // If the binding is symbolic it can refer to other earlier bindings in the
  477. // same generic, or from an enclosing specific. Substitute to replace those
  478. // and get a non-symbolic type in order for us to know the final type that
  479. // the argument needs to be converted to.
  480. //
  481. // Note that when typechecking a checked generic, the arguments can
  482. // still be symbolic, so the substitution would also be symbolic. We are
  483. // unable to get the final type for symbolic bindings until deducing with
  484. // non-symbolic arguments.
  485. //
  486. // TODO: If arguments of different values, but that _convert to_ the same
  487. // value, are deduced for the same symbolic binding, then we will fail
  488. // typechecking in Deduce() with conflicting types via the
  489. // `DeductionInconsistent` diagnostic. If we defer that check until after
  490. // all conversions are done (after the code below) then we won't diagnose
  491. // that incorrectly.
  492. auto arg_type_id = context().insts().Get(deduced_arg_id).type_id();
  493. auto binding_type_id = context().insts().Get(binding_id).type_id();
  494. if (!arg_type_id.AsConstantId().is_symbolic() &&
  495. binding_type_id.AsConstantId().is_symbolic()) {
  496. auto param_type_const_id = SubstConstant(
  497. context(), binding_type_id.AsConstantId(), substitutions_);
  498. CARBON_CHECK(param_type_const_id.has_value());
  499. binding_type_id = context().GetTypeIdForTypeConstant(param_type_const_id);
  500. // TODO: Suppress diagnostics here if `diagnose_` is false.
  501. DiagnosticAnnotationScope annotate_diagnostics(
  502. &context().emitter(),
  503. [&](auto& builder) { NoteInitializingParam(binding_id, builder); });
  504. auto converted_arg_id = ConvertToValueOfType(
  505. context(), loc_id_, deduced_arg_id, binding_type_id);
  506. // Replace the deduced arg with its value converted to the parameter
  507. // type. The conversion of the argument type must produce a constant value
  508. // to be used in deduction.
  509. if (context().constant_values().Get(converted_arg_id).is_constant()) {
  510. deduced_arg_id = converted_arg_id;
  511. } else {
  512. CARBON_DIAGNOSTIC(RuntimeConversionDuringCompTimeDeduction, Error,
  513. "compile-time value requires runtime conversion, "
  514. "constructing value of type {0}",
  515. SemIR::TypeId);
  516. auto diag = context().emitter().Build(
  517. loc_id_, RuntimeConversionDuringCompTimeDeduction, binding_type_id);
  518. NoteGenericHere(context(), generic_id_, diag);
  519. diag.Emit();
  520. deduced_arg_id = SemIR::ErrorInst::SingletonInstId;
  521. }
  522. }
  523. substitutions_.push_back(
  524. {.bind_id = SemIR::CompileTimeBindIndex(binding_index),
  525. .replacement_id = context().constant_values().Get(deduced_arg_id)});
  526. }
  527. return true;
  528. }
  529. auto DeductionContext::MakeSpecific() -> SemIR::SpecificId {
  530. // TODO: Convert the deduced values to the types of the bindings.
  531. return Check::MakeSpecific(context(), loc_id_, generic_id_, result_arg_ids_);
  532. }
  533. auto DeduceGenericCallArguments(
  534. Context& context, SemIR::LocId loc_id, SemIR::GenericId generic_id,
  535. SemIR::SpecificId enclosing_specific_id, SemIR::InstId self_type_id,
  536. [[maybe_unused]] SemIR::InstBlockId implicit_params_id,
  537. SemIR::InstBlockId params_id, [[maybe_unused]] SemIR::InstId self_id,
  538. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::SpecificId {
  539. DeductionContext deduction(context, loc_id, generic_id, enclosing_specific_id,
  540. self_type_id, /*diagnose=*/true);
  541. // Prepare to perform deduction of the explicit parameters against their
  542. // arguments.
  543. // TODO: Also perform deduction for type of self.
  544. deduction.AddAll(params_id, arg_ids, /*needs_substitution=*/true);
  545. if (!deduction.Deduce() || !deduction.CheckDeductionIsComplete()) {
  546. return SemIR::SpecificId::None;
  547. }
  548. return deduction.MakeSpecific();
  549. }
  550. // Deduces the impl arguments to use in a use of a parameterized impl. Returns
  551. // `None` if deduction fails.
  552. auto DeduceImplArguments(Context& context, SemIR::LocId loc_id,
  553. const SemIR::Impl& impl, SemIR::ConstantId self_id,
  554. SemIR::ConstantId constraint_id) -> SemIR::SpecificId {
  555. DeductionContext deduction(context, loc_id, impl.generic_id,
  556. /*enclosing_specific_id=*/SemIR::SpecificId::None,
  557. /*self_type_id=*/SemIR::InstId::None,
  558. /*diagnose=*/false);
  559. // Prepare to perform deduction of the type and interface.
  560. deduction.Add(impl.self_id, context.constant_values().GetInstId(self_id),
  561. /*needs_substitution=*/false);
  562. deduction.Add(impl.constraint_id,
  563. context.constant_values().GetInstId(constraint_id),
  564. /*needs_substitution=*/false);
  565. if (!deduction.Deduce() || !deduction.CheckDeductionIsComplete()) {
  566. return SemIR::SpecificId::None;
  567. }
  568. return deduction.MakeSpecific();
  569. }
  570. } // namespace Carbon::Check