deduce.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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/sem_ir/ids.h"
  12. #include "toolchain/sem_ir/impl.h"
  13. #include "toolchain/sem_ir/typed_insts.h"
  14. namespace Carbon::Check {
  15. namespace {
  16. // A list of pairs of (instruction from generic, corresponding instruction from
  17. // call to of generic) for which we still need to perform deduction, along with
  18. // methods to add and pop pending deductions from the list. Deductions are
  19. // popped in order from most- to least-recently pushed, with the intent that
  20. // they are visited in depth-first order, although the order is not expected to
  21. // matter except when it influences which error is diagnosed.
  22. class DeductionWorklist {
  23. public:
  24. explicit DeductionWorklist(Context& context) : context_(context) {}
  25. struct PendingDeduction {
  26. SemIR::InstId param;
  27. SemIR::InstId arg;
  28. bool needs_substitution;
  29. };
  30. // Adds a single (param, arg) deduction.
  31. auto Add(SemIR::InstId param, SemIR::InstId arg, bool needs_substitution)
  32. -> void {
  33. deductions_.push_back(
  34. {.param = param, .arg = arg, .needs_substitution = needs_substitution});
  35. }
  36. // Adds a single (param, arg) type deduction.
  37. auto Add(SemIR::TypeId param, SemIR::TypeId arg, bool needs_substitution)
  38. -> void {
  39. Add(context_.types().GetInstId(param), context_.types().GetInstId(arg),
  40. needs_substitution);
  41. }
  42. // Adds a single (param, arg) deduction of a specific.
  43. auto Add(SemIR::SpecificId param, SemIR::SpecificId arg,
  44. bool needs_substitution) -> void {
  45. auto& param_specific = context_.specifics().Get(param);
  46. auto& arg_specific = context_.specifics().Get(arg);
  47. if (param_specific.generic_id != arg_specific.generic_id) {
  48. // TODO: Decide whether to error on this or just treat the specific as
  49. // non-deduced. For now we treat it as non-deduced.
  50. return;
  51. }
  52. AddAll(param_specific.args_id, arg_specific.args_id, needs_substitution);
  53. }
  54. // Adds a list of (param, arg) deductions. These are added in reverse order so
  55. // they are popped in forward order.
  56. template <typename ElementId>
  57. auto AddAll(llvm::ArrayRef<ElementId> params, llvm::ArrayRef<ElementId> args,
  58. bool needs_substitution) -> void {
  59. if (params.size() != args.size()) {
  60. // TODO: Decide whether to error on this or just treat the parameter list
  61. // as non-deduced. For now we treat it as non-deduced.
  62. return;
  63. }
  64. for (auto [param, arg] : llvm::reverse(llvm::zip_equal(params, args))) {
  65. Add(param, arg, needs_substitution);
  66. }
  67. }
  68. auto AddAll(SemIR::InstBlockId params, llvm::ArrayRef<SemIR::InstId> args,
  69. bool needs_substitution) -> void {
  70. AddAll(context_.inst_blocks().Get(params), args, needs_substitution);
  71. }
  72. auto AddAll(SemIR::InstBlockId params, SemIR::InstBlockId args,
  73. bool needs_substitution) -> void {
  74. AddAll(context_.inst_blocks().Get(params), context_.inst_blocks().Get(args),
  75. needs_substitution);
  76. }
  77. auto AddAll(SemIR::TypeBlockId params, SemIR::TypeBlockId args,
  78. bool needs_substitution) -> void {
  79. AddAll(context_.type_blocks().Get(params), context_.type_blocks().Get(args),
  80. needs_substitution);
  81. }
  82. // Adds a (param, arg) pair for an instruction argument, given its kind.
  83. auto AddInstArg(SemIR::IdKind kind, int32_t param, int32_t arg,
  84. bool needs_substitution) -> void {
  85. switch (kind) {
  86. case SemIR::IdKind::None:
  87. case SemIR::IdKind::For<SemIR::ClassId>:
  88. case SemIR::IdKind::For<SemIR::InterfaceId>:
  89. case SemIR::IdKind::For<SemIR::IntKind>:
  90. break;
  91. case SemIR::IdKind::For<SemIR::InstId>:
  92. Add(SemIR::InstId(param), SemIR::InstId(arg), needs_substitution);
  93. break;
  94. case SemIR::IdKind::For<SemIR::TypeId>:
  95. Add(SemIR::TypeId(param), SemIR::TypeId(arg), needs_substitution);
  96. break;
  97. case SemIR::IdKind::For<SemIR::InstBlockId>:
  98. AddAll(SemIR::InstBlockId(param), SemIR::InstBlockId(arg),
  99. needs_substitution);
  100. break;
  101. case SemIR::IdKind::For<SemIR::TypeBlockId>:
  102. AddAll(SemIR::TypeBlockId(param), SemIR::TypeBlockId(arg),
  103. needs_substitution);
  104. break;
  105. case SemIR::IdKind::For<SemIR::SpecificId>:
  106. Add(SemIR::SpecificId(param), SemIR::SpecificId(arg),
  107. needs_substitution);
  108. break;
  109. default:
  110. CARBON_FATAL("unexpected argument kind");
  111. }
  112. }
  113. // Returns whether we have completed all deductions.
  114. auto Done() -> bool { return deductions_.empty(); }
  115. // Pops the next deduction. Requires `!Done()`.
  116. auto PopNext() -> PendingDeduction { return deductions_.pop_back_val(); }
  117. private:
  118. Context& context_;
  119. llvm::SmallVector<PendingDeduction> deductions_;
  120. };
  121. // State that is tracked throughout the deduction process.
  122. class DeductionContext {
  123. public:
  124. // Preparse to perform deduction. If an enclosing specific is provided, adds
  125. // the arguments from the given specific as known arguments that will not be
  126. // deduced.
  127. DeductionContext(Context& context, SemIR::LocId loc_id,
  128. SemIR::GenericId generic_id,
  129. SemIR::SpecificId enclosing_specific_id, bool diagnose);
  130. auto context() const -> Context& { return *context_; }
  131. // Adds a pending deduction of `param` from `arg`. `needs_substitution`
  132. // indicates whether we need to substitute known generic parameters into
  133. // `param`.
  134. template <typename ParamT, typename ArgT>
  135. auto Add(ParamT param, ArgT arg, bool needs_substitution) -> void {
  136. worklist_.Add(param, arg, needs_substitution);
  137. }
  138. // Same as `Add` but for an array or block of operands.
  139. template <typename ParamT, typename ArgT>
  140. auto AddAll(ParamT param, ArgT arg, bool needs_substitution) -> void {
  141. worklist_.AddAll(param, arg, needs_substitution);
  142. }
  143. // Performs all deductions in the deduction worklist. Returns whether
  144. // deduction succeeded.
  145. auto Deduce() -> bool;
  146. // Returns whether every generic parameter has a corresponding deduced generic
  147. // argument. If not, issues a suitable diagnostic.
  148. auto CheckDeductionIsComplete() -> bool;
  149. // Forms a specific corresponding to the deduced generic with the deduced
  150. // argument list. Must not be called before deduction is complete.
  151. auto MakeSpecific() -> SemIR::SpecificId;
  152. private:
  153. Context* context_;
  154. SemIR::LocId loc_id_;
  155. SemIR::GenericId generic_id_;
  156. bool diagnose_;
  157. DeductionWorklist worklist_;
  158. llvm::SmallVector<SemIR::InstId> result_arg_ids_;
  159. llvm::SmallVector<Substitution> substitutions_;
  160. SemIR::CompileTimeBindIndex first_deduced_index_;
  161. // Non-deduced indexes, indexed by parameter index - first_deduced_index_.
  162. llvm::SmallBitVector non_deduced_indexes_;
  163. };
  164. } // namespace
  165. static auto NoteGenericHere(Context& context, SemIR::GenericId generic_id,
  166. Context::DiagnosticBuilder& diag) -> void {
  167. CARBON_DIAGNOSTIC(DeductionGenericHere, Note,
  168. "while deducing parameters of generic declared here");
  169. diag.Note(context.generics().Get(generic_id).decl_id, DeductionGenericHere);
  170. }
  171. DeductionContext::DeductionContext(Context& context, SemIR::LocId loc_id,
  172. SemIR::GenericId generic_id,
  173. SemIR::SpecificId enclosing_specific_id,
  174. bool diagnose)
  175. : context_(&context),
  176. loc_id_(loc_id),
  177. generic_id_(generic_id),
  178. diagnose_(diagnose),
  179. worklist_(context),
  180. first_deduced_index_(0) {
  181. CARBON_CHECK(generic_id.is_valid(),
  182. "Performing deduction for non-generic entity");
  183. // Initialize the deduced arguments to Invalid.
  184. result_arg_ids_.resize(
  185. context.inst_blocks()
  186. .Get(context.generics().Get(generic_id_).bindings_id)
  187. .size(),
  188. SemIR::InstId::Invalid);
  189. if (enclosing_specific_id.is_valid()) {
  190. // Copy any outer generic arguments from the specified instance and prepare
  191. // to substitute them into the function declaration.
  192. auto args = context.inst_blocks().Get(
  193. context.specifics().Get(enclosing_specific_id).args_id);
  194. std::copy(args.begin(), args.end(), result_arg_ids_.begin());
  195. // TODO: Subst is linear in the length of the substitutions list. Change
  196. // it so we can pass in an array mapping indexes to substitutions instead.
  197. substitutions_.reserve(args.size());
  198. for (auto [i, subst_inst_id] : llvm::enumerate(args)) {
  199. substitutions_.push_back(
  200. {.bind_id = SemIR::CompileTimeBindIndex(i),
  201. .replacement_id = context.constant_values().Get(subst_inst_id)});
  202. }
  203. first_deduced_index_ = SemIR::CompileTimeBindIndex(args.size());
  204. }
  205. non_deduced_indexes_.resize(result_arg_ids_.size() -
  206. first_deduced_index_.index);
  207. }
  208. auto DeductionContext::Deduce() -> bool {
  209. while (!worklist_.Done()) {
  210. auto [param_id, arg_id, needs_substitution] = worklist_.PopNext();
  211. auto note_initializing_param = [&](auto& builder) {
  212. if (auto param =
  213. context().insts().TryGetAs<SemIR::SymbolicBindingPattern>(
  214. param_id)) {
  215. CARBON_DIAGNOSTIC(InitializingGenericParam, Note,
  216. "initializing generic parameter `{0}` declared here",
  217. SemIR::NameId);
  218. builder.Note(
  219. param_id, InitializingGenericParam,
  220. context().entity_names().Get(param->entity_name_id).name_id);
  221. } else {
  222. NoteGenericHere(context(), generic_id_, builder);
  223. }
  224. };
  225. // TODO: Bail out if there's nothing to deduce: if we're not in a pattern
  226. // and the parameter doesn't have a symbolic constant value.
  227. // If the parameter has a symbolic type, deduce against that.
  228. auto param_type_id = context().insts().Get(param_id).type_id();
  229. if (param_type_id.AsConstantId().is_symbolic()) {
  230. Add(context().types().GetInstId(param_type_id),
  231. context().types().GetInstId(context().insts().Get(arg_id).type_id()),
  232. needs_substitution);
  233. } else {
  234. // The argument needs to have the same type as the parameter.
  235. // TODO: Suppress diagnostics here if diagnose_ is false.
  236. // TODO: Only do this when deducing against a symbolic pattern.
  237. DiagnosticAnnotationScope annotate_diagnostics(&context().emitter(),
  238. note_initializing_param);
  239. arg_id = ConvertToValueOfType(context(), loc_id_, arg_id, param_type_id);
  240. if (arg_id == SemIR::InstId::BuiltinError) {
  241. return false;
  242. }
  243. }
  244. // Attempt to match `param_inst` against `arg_id`. If the match succeeds,
  245. // this should `continue` the outer loop. On `break`, we will try to desugar
  246. // the parameter to continue looking for a match.
  247. auto param_inst = context().insts().Get(param_id);
  248. CARBON_KIND_SWITCH(param_inst) {
  249. // Deducing a symbolic binding pattern from an argument deduces the
  250. // binding as having that constant value. For example, deducing
  251. // `(T:! type)` against `(i32)` deduces `T` to be `i32`. This only arises
  252. // when initializing a generic parameter from an explicitly specified
  253. // argument, and in this case, the argument is required to be a
  254. // compile-time constant.
  255. case CARBON_KIND(SemIR::SymbolicBindingPattern bind): {
  256. auto& entity_name = context().entity_names().Get(bind.entity_name_id);
  257. auto index = entity_name.bind_index;
  258. if (!index.is_valid()) {
  259. break;
  260. }
  261. CARBON_CHECK(
  262. index >= first_deduced_index_ &&
  263. static_cast<size_t>(index.index) < result_arg_ids_.size(),
  264. "Unexpected index {0} for symbolic binding pattern; "
  265. "expected to be in range [{1}, {2})",
  266. index.index, first_deduced_index_.index, result_arg_ids_.size());
  267. CARBON_CHECK(!result_arg_ids_[index.index].is_valid(),
  268. "Deduced a value for parameter prior to its declaration");
  269. auto arg_const_inst_id =
  270. context().constant_values().GetConstantInstId(arg_id);
  271. if (!arg_const_inst_id.is_valid()) {
  272. if (diagnose_) {
  273. CARBON_DIAGNOSTIC(CompTimeArgumentNotConstant, Error,
  274. "argument for generic parameter is not a "
  275. "compile-time constant");
  276. auto diag =
  277. context().emitter().Build(loc_id_, CompTimeArgumentNotConstant);
  278. note_initializing_param(diag);
  279. diag.Emit();
  280. }
  281. return false;
  282. }
  283. result_arg_ids_[index.index] = arg_const_inst_id;
  284. // This parameter index should not be deduced if it appears later.
  285. non_deduced_indexes_[index.index - first_deduced_index_.index] = true;
  286. continue;
  287. }
  288. // Deducing a symbolic binding appearing within an expression against a
  289. // constant value deduces the binding as having that value. For example,
  290. // deducing `[T:! type](x: T)` against `("foo")` deduces `T` as `String`.
  291. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  292. auto& entity_name = context().entity_names().Get(bind.entity_name_id);
  293. auto index = entity_name.bind_index;
  294. if (!index.is_valid() || index < first_deduced_index_ ||
  295. non_deduced_indexes_[index.index - first_deduced_index_.index]) {
  296. break;
  297. }
  298. CARBON_CHECK(static_cast<size_t>(index.index) < result_arg_ids_.size(),
  299. "Deduced value for unexpected index {0}; expected to "
  300. "deduce {1} arguments.",
  301. index, result_arg_ids_.size());
  302. auto arg_const_inst_id =
  303. context().constant_values().GetConstantInstId(arg_id);
  304. if (arg_const_inst_id.is_valid()) {
  305. if (result_arg_ids_[index.index].is_valid() &&
  306. result_arg_ids_[index.index] != arg_const_inst_id) {
  307. if (diagnose_) {
  308. // TODO: Include the two different deduced values.
  309. CARBON_DIAGNOSTIC(DeductionInconsistent, Error,
  310. "inconsistent deductions for value of generic "
  311. "parameter `{0}`",
  312. SemIR::NameId);
  313. auto diag = context().emitter().Build(
  314. loc_id_, DeductionInconsistent, entity_name.name_id);
  315. NoteGenericHere(context(), generic_id_, diag);
  316. diag.Emit();
  317. }
  318. return false;
  319. }
  320. result_arg_ids_[index.index] = arg_const_inst_id;
  321. }
  322. continue;
  323. }
  324. case CARBON_KIND(SemIR::ValueParamPattern pattern): {
  325. Add(pattern.subpattern_id, arg_id, needs_substitution);
  326. continue;
  327. }
  328. // Various kinds of parameter should match an argument of the same form,
  329. // if the operands all match.
  330. case SemIR::ArrayType::Kind:
  331. case SemIR::ClassType::Kind:
  332. case SemIR::ConstType::Kind:
  333. case SemIR::FloatType::Kind:
  334. case SemIR::InterfaceType::Kind:
  335. case SemIR::IntType::Kind:
  336. case SemIR::PointerType::Kind:
  337. case SemIR::TupleType::Kind:
  338. case SemIR::TupleValue::Kind: {
  339. auto arg_inst = context().insts().Get(arg_id);
  340. if (arg_inst.kind() != param_inst.kind()) {
  341. break;
  342. }
  343. auto [kind0, kind1] = param_inst.ArgKinds();
  344. worklist_.AddInstArg(kind0, param_inst.arg0(), arg_inst.arg0(),
  345. needs_substitution);
  346. worklist_.AddInstArg(kind1, param_inst.arg1(), arg_inst.arg1(),
  347. needs_substitution);
  348. continue;
  349. }
  350. case SemIR::StructType::Kind:
  351. case SemIR::StructValue::Kind:
  352. // TODO: Match field name order between param and arg.
  353. break;
  354. // TODO: Handle more cases.
  355. default:
  356. break;
  357. }
  358. // We didn't manage to deduce against the syntactic form of the parameter.
  359. // Convert it to a canonical constant value and try deducing against that.
  360. auto param_const_id = context().constant_values().Get(param_id);
  361. if (!param_const_id.is_valid() || !param_const_id.is_symbolic()) {
  362. // It's not a symbolic constant. There's nothing here to deduce.
  363. continue;
  364. }
  365. auto param_const_inst_id =
  366. context().constant_values().GetInstId(param_const_id);
  367. if (param_const_inst_id != param_id) {
  368. Add(param_const_inst_id, arg_id, needs_substitution);
  369. continue;
  370. }
  371. // If we've not yet substituted into the parameter, do so now and try again.
  372. if (needs_substitution) {
  373. param_const_id = SubstConstant(context(), param_const_id, substitutions_);
  374. if (!param_const_id.is_valid() || !param_const_id.is_symbolic()) {
  375. continue;
  376. }
  377. Add(context().constant_values().GetInstId(param_const_id), arg_id,
  378. /*needs_substitution=*/false);
  379. }
  380. }
  381. return true;
  382. }
  383. auto DeductionContext::CheckDeductionIsComplete() -> bool {
  384. // Check we deduced an argument value for every parameter.
  385. for (auto [i, deduced_arg_id] :
  386. llvm::enumerate(llvm::ArrayRef(result_arg_ids_)
  387. .drop_front(first_deduced_index_.index))) {
  388. if (!deduced_arg_id.is_valid()) {
  389. if (diagnose_) {
  390. auto binding_index = first_deduced_index_.index + i;
  391. auto binding_id = context().inst_blocks().Get(
  392. context().generics().Get(generic_id_).bindings_id)[binding_index];
  393. auto entity_name_id = context()
  394. .insts()
  395. .GetAs<SemIR::AnyBindName>(binding_id)
  396. .entity_name_id;
  397. CARBON_DIAGNOSTIC(DeductionIncomplete, Error,
  398. "cannot deduce value for generic parameter `{0}`",
  399. SemIR::NameId);
  400. auto diag = context().emitter().Build(
  401. loc_id_, DeductionIncomplete,
  402. context().entity_names().Get(entity_name_id).name_id);
  403. NoteGenericHere(context(), generic_id_, diag);
  404. diag.Emit();
  405. }
  406. return false;
  407. }
  408. }
  409. return true;
  410. }
  411. auto DeductionContext::MakeSpecific() -> SemIR::SpecificId {
  412. // TODO: Convert the deduced values to the types of the bindings.
  413. return Check::MakeSpecific(
  414. context(), generic_id_,
  415. context().inst_blocks().AddCanonical(result_arg_ids_));
  416. }
  417. auto DeduceGenericCallArguments(
  418. Context& context, SemIR::LocId loc_id, SemIR::GenericId generic_id,
  419. SemIR::SpecificId enclosing_specific_id,
  420. [[maybe_unused]] SemIR::InstBlockId implicit_params_id,
  421. SemIR::InstBlockId params_id, [[maybe_unused]] SemIR::InstId self_id,
  422. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::SpecificId {
  423. DeductionContext deduction(context, loc_id, generic_id, enclosing_specific_id,
  424. /*diagnose=*/true);
  425. // Prepare to perform deduction of the explicit parameters against their
  426. // arguments.
  427. // TODO: Also perform deduction for type of self.
  428. deduction.AddAll(params_id, arg_ids, /*needs_substitution=*/true);
  429. if (!deduction.Deduce() || !deduction.CheckDeductionIsComplete()) {
  430. return SemIR::SpecificId::Invalid;
  431. }
  432. return deduction.MakeSpecific();
  433. }
  434. // Deduces the impl arguments to use in a use of a parameterized impl. Returns
  435. // `Invalid` if deduction fails.
  436. auto DeduceImplArguments(Context& context, SemIR::LocId loc_id,
  437. const SemIR::Impl& impl, SemIR::ConstantId self_id,
  438. SemIR::ConstantId constraint_id) -> SemIR::SpecificId {
  439. DeductionContext deduction(
  440. context, loc_id, impl.generic_id,
  441. /*enclosing_specific_id=*/SemIR::SpecificId::Invalid,
  442. /*diagnose=*/false);
  443. // Prepare to perform deduction of the type and interface.
  444. deduction.Add(impl.self_id, context.constant_values().GetInstId(self_id),
  445. /*needs_substitution=*/false);
  446. deduction.Add(impl.constraint_id,
  447. context.constant_values().GetInstId(constraint_id),
  448. /*needs_substitution=*/false);
  449. if (!deduction.Deduce() || !deduction.CheckDeductionIsComplete()) {
  450. return SemIR::SpecificId::Invalid;
  451. }
  452. return deduction.MakeSpecific();
  453. }
  454. } // namespace Carbon::Check