pattern_match.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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/pattern_match.h"
  5. #include <functional>
  6. #include <utility>
  7. #include <vector>
  8. #include "llvm/ADT/STLExtras.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/check/context.h"
  12. #include "toolchain/check/control_flow.h"
  13. #include "toolchain/check/convert.h"
  14. #include "toolchain/check/pattern.h"
  15. #include "toolchain/check/type.h"
  16. #include "toolchain/diagnostics/format_providers.h"
  17. #include "toolchain/sem_ir/expr_info.h"
  18. #include "toolchain/sem_ir/pattern.h"
  19. namespace Carbon::Check {
  20. namespace {
  21. // Selects between the different kinds of pattern matching.
  22. enum class MatchKind : uint8_t {
  23. // Caller pattern matching occurs on the caller side of a function call, and
  24. // is responsible for matching the argument expression against the portion
  25. // of the pattern above the ParamPattern insts.
  26. Caller,
  27. // Callee pattern matching occurs in the function decl block, and is
  28. // responsible for matching the function's calling-convention parameters
  29. // against the portion of the pattern below the ParamPattern insts.
  30. Callee,
  31. // Local pattern matching is pattern matching outside of a function call,
  32. // such as in a let/var declaration.
  33. Local,
  34. };
  35. // The collected state of a pattern-matching operation.
  36. class MatchContext {
  37. public:
  38. struct WorkItem : Printable<WorkItem> {
  39. SemIR::InstId pattern_id;
  40. // `None` when processing the callee side.
  41. SemIR::InstId scrutinee_id;
  42. bool is_self = false;
  43. auto Print(llvm::raw_ostream& out) const -> void {
  44. out << "{pattern_id: " << pattern_id << ", scrutinee_id: " << scrutinee_id
  45. << ", is_self = " << is_self << "}";
  46. }
  47. };
  48. // Constructs a MatchContext. If `callee_specific_id` is not `None`, this
  49. // pattern match operation is part of implementing the signature of the given
  50. // specific.
  51. explicit MatchContext(MatchKind kind, SemIR::SpecificId callee_specific_id =
  52. SemIR::SpecificId::None)
  53. : kind_(kind), callee_specific_id_(callee_specific_id) {}
  54. // Adds a work item to the stack.
  55. auto AddWork(WorkItem work_item) -> void { stack_.push_back(work_item); }
  56. // Processes all work items on the stack. When performing caller pattern
  57. // matching, returns an inst block with one inst reference for each
  58. // calling-convention argument. When performing callee pattern matching,
  59. // returns an inst block with references to all the emitted BindName insts.
  60. auto DoWork(Context& context) -> SemIR::InstBlockId;
  61. private:
  62. // Emits the pattern-match insts necessary to match the pattern inst
  63. // `entry.pattern_id` against the scrutinee value `entry.scrutinee_id`, and
  64. // adds to `stack_` any work necessary to traverse into its subpatterns. This
  65. // behavior is contingent on the kind of match being performed, as indicated
  66. // by kind_`. For example, when performing a callee pattern match, this does
  67. // not emit insts for patterns on the caller side. However, it still traverses
  68. // into subpatterns if any of their descendants might emit insts.
  69. // TODO: Require that `entry.scrutinee_id` is valid if and only if insts
  70. // should be emitted, once we start emitting `Param` insts in the
  71. // `ParamPattern` case.
  72. auto EmitPatternMatch(Context& context, MatchContext::WorkItem entry) -> void;
  73. // Implementations of `EmitPatternMatch` for particular pattern inst kinds.
  74. // The pattern argument is always equal to
  75. // `context.insts().Get(entry.pattern_id)`.
  76. auto DoEmitPatternMatch(Context& context,
  77. SemIR::AnyBindingPattern binding_pattern,
  78. WorkItem entry) -> void;
  79. auto DoEmitPatternMatch(Context& context,
  80. SemIR::ValueParamPattern param_pattern,
  81. WorkItem entry) -> void;
  82. template <typename RefParamPatternT>
  83. requires std::is_same_v<RefParamPatternT, SemIR::RefParamPattern> ||
  84. std::is_same_v<RefParamPatternT, SemIR::VarParamPattern>
  85. auto DoEmitPatternMatch(Context& context, RefParamPatternT param_pattern,
  86. WorkItem entry) -> void;
  87. auto DoEmitPatternMatch(Context& context,
  88. SemIR::OutParamPattern param_pattern, WorkItem entry)
  89. -> void;
  90. auto DoEmitPatternMatch(Context& context,
  91. SemIR::ReturnSlotPattern return_slot_pattern,
  92. WorkItem entry) -> void;
  93. auto DoEmitPatternMatch(Context& context, SemIR::VarPattern var_pattern,
  94. WorkItem entry) -> void;
  95. auto DoEmitPatternMatch(Context& context, SemIR::TuplePattern tuple_pattern,
  96. WorkItem entry) -> void;
  97. // The stack of work to be processed.
  98. llvm::SmallVector<WorkItem> stack_;
  99. // The pending results that will be returned by the current `DoWork` call.
  100. // It represents the contents of the `Call` arguments block when kind_
  101. // is Caller, or the `Call` parameters block when kind_ is Callee
  102. // (it is empty when kind_ is Local). Consequently, it is populated
  103. // only by DoEmitPatternMatch for *ParamPattern insts.
  104. llvm::SmallVector<SemIR::InstId> results_;
  105. // The kind of pattern match being performed.
  106. MatchKind kind_;
  107. // The SpecificId of the function being called (if any).
  108. SemIR::SpecificId callee_specific_id_;
  109. };
  110. } // namespace
  111. auto MatchContext::DoWork(Context& context) -> SemIR::InstBlockId {
  112. results_.reserve(stack_.size());
  113. while (!stack_.empty()) {
  114. EmitPatternMatch(context, stack_.pop_back_val());
  115. }
  116. auto block_id = context.inst_blocks().Add(results_);
  117. results_.clear();
  118. return block_id;
  119. }
  120. // Inserts the given region into the current code block. If the region
  121. // consists of a single block, this will be implemented as a `splice_block`
  122. // inst. Otherwise, this will end the current block with a branch to the entry
  123. // block of the region, and add future insts to a new block which is the
  124. // immediate successor of the region's exit block. As a result, this cannot be
  125. // called more than once for the same region.
  126. static auto InsertHere(Context& context, SemIR::ExprRegionId region_id)
  127. -> SemIR::InstId {
  128. auto region = context.sem_ir().expr_regions().Get(region_id);
  129. auto exit_block = context.inst_blocks().Get(region.block_ids.back());
  130. if (region.block_ids.size() == 1) {
  131. // TODO: Is it possible to avoid leaving an "orphan" block in the IR in the
  132. // first two cases?
  133. if (exit_block.empty()) {
  134. return region.result_id;
  135. }
  136. if (exit_block.size() == 1) {
  137. context.inst_block_stack().AddInstId(exit_block.front());
  138. return region.result_id;
  139. }
  140. return AddInst<SemIR::SpliceBlock>(
  141. context, SemIR::LocId(region.result_id),
  142. {.type_id = context.insts().Get(region.result_id).type_id(),
  143. .block_id = region.block_ids.front(),
  144. .result_id = region.result_id});
  145. }
  146. if (context.region_stack().empty()) {
  147. context.TODO(region.result_id,
  148. "Control flow expressions are currently only supported inside "
  149. "functions.");
  150. return SemIR::ErrorInst::InstId;
  151. }
  152. AddInst(context, SemIR::LocIdAndInst::NoLoc<SemIR::Branch>(
  153. {.target_id = region.block_ids.front()}));
  154. context.inst_block_stack().Pop();
  155. // TODO: this will cumulatively cost O(MN) running time for M blocks
  156. // at the Nth level of the stack. Figure out how to do better.
  157. context.region_stack().AddToRegion(region.block_ids);
  158. auto resume_with_block_id =
  159. context.insts().GetAs<SemIR::Branch>(exit_block.back()).target_id;
  160. CARBON_CHECK(context.inst_blocks().GetOrEmpty(resume_with_block_id).empty());
  161. context.inst_block_stack().Push(resume_with_block_id);
  162. context.region_stack().AddToRegion(resume_with_block_id,
  163. SemIR::LocId(region.result_id));
  164. return region.result_id;
  165. }
  166. auto MatchContext::DoEmitPatternMatch(Context& context,
  167. SemIR::AnyBindingPattern binding_pattern,
  168. MatchContext::WorkItem entry) -> void {
  169. if (kind_ == MatchKind::Caller) {
  170. CARBON_CHECK(binding_pattern.kind == SemIR::SymbolicBindingPattern::Kind,
  171. "Found runtime binding pattern during caller pattern match");
  172. return;
  173. }
  174. // We're logically consuming this map entry, so we invalidate it in order
  175. // to avoid accidentally consuming it twice.
  176. auto [bind_name_id, type_expr_region_id] =
  177. std::exchange(context.bind_name_map().Lookup(entry.pattern_id).value(),
  178. {.bind_name_id = SemIR::InstId::None,
  179. .type_expr_region_id = SemIR::ExprRegionId::None});
  180. // bind_name_id doesn't have a value in the case of an unused binding pattern,
  181. // but type_expr_region_id should always be populated.
  182. CARBON_CHECK(type_expr_region_id.has_value());
  183. InsertHere(context, type_expr_region_id);
  184. auto value_id = SemIR::InstId::None;
  185. if (kind_ == MatchKind::Local) {
  186. auto conversion_kind = [&binding_pattern]() -> ConversionTarget::Kind {
  187. switch (binding_pattern.kind) {
  188. case SemIR::SymbolicBindingPattern::Kind:
  189. case SemIR::ValueBindingPattern::Kind:
  190. return ConversionTarget::Value;
  191. case SemIR::RefBindingPattern::Kind:
  192. return ConversionTarget::DurableRef;
  193. default:
  194. CARBON_FATAL("Unexpected inst kind {0}", binding_pattern.kind);
  195. }
  196. }();
  197. if (!bind_name_id.has_value()) {
  198. // TODO: Is this appropriate, or should we perform a conversion based on
  199. // whether the `_` binding is a value or ref binding first, and then
  200. // separately discard the initializer for a `_` binding?
  201. conversion_kind = ConversionTarget::Discarded;
  202. }
  203. value_id =
  204. Convert(context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  205. {.kind = conversion_kind,
  206. .type_id = context.insts().Get(bind_name_id).type_id()});
  207. } else {
  208. // In a function call, conversion is handled while matching the enclosing
  209. // `*ParamPattern`.
  210. value_id = entry.scrutinee_id;
  211. }
  212. if (bind_name_id.has_value()) {
  213. auto bind_name = context.insts().GetAs<SemIR::AnyBinding>(bind_name_id);
  214. CARBON_CHECK(!bind_name.value_id.has_value());
  215. bind_name.value_id = value_id;
  216. ReplaceInstBeforeConstantUse(context, bind_name_id, bind_name);
  217. context.inst_block_stack().AddInstId(bind_name_id);
  218. }
  219. }
  220. auto MatchContext::DoEmitPatternMatch(Context& context,
  221. SemIR::ValueParamPattern param_pattern,
  222. WorkItem entry) -> void {
  223. switch (kind_) {
  224. case MatchKind::Caller: {
  225. CARBON_CHECK(
  226. static_cast<size_t>(param_pattern.index.index) == results_.size(),
  227. "Parameters out of order; expecting {0} but got {1}", results_.size(),
  228. param_pattern.index.index);
  229. CARBON_CHECK(entry.scrutinee_id.has_value());
  230. if (entry.scrutinee_id == SemIR::ErrorInst::InstId) {
  231. results_.push_back(SemIR::ErrorInst::InstId);
  232. } else {
  233. results_.push_back(ConvertToValueOfType(
  234. context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  235. ExtractScrutineeType(
  236. context.sem_ir(),
  237. SemIR::GetTypeOfInstInSpecific(
  238. context.sem_ir(), callee_specific_id_, entry.pattern_id))));
  239. }
  240. // Do not traverse farther, because the caller side of the pattern
  241. // ends here.
  242. break;
  243. }
  244. case MatchKind::Callee: {
  245. auto param_id = AddInst<SemIR::ValueParam>(
  246. context, SemIR::LocId(entry.pattern_id),
  247. {.type_id =
  248. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  249. .index = param_pattern.index,
  250. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  251. context.sem_ir(), entry.pattern_id)});
  252. AddWork({.pattern_id = param_pattern.subpattern_id,
  253. .scrutinee_id = param_id});
  254. results_.push_back(param_id);
  255. break;
  256. }
  257. case MatchKind::Local: {
  258. CARBON_FATAL("Found ValueParamPattern during local pattern match");
  259. }
  260. }
  261. }
  262. template <typename RefParamPatternT>
  263. requires std::is_same_v<RefParamPatternT, SemIR::RefParamPattern> ||
  264. std::is_same_v<RefParamPatternT, SemIR::VarParamPattern>
  265. auto MatchContext::DoEmitPatternMatch(Context& context,
  266. RefParamPatternT param_pattern,
  267. WorkItem entry) -> void {
  268. switch (kind_) {
  269. case MatchKind::Caller: {
  270. CARBON_CHECK(
  271. static_cast<size_t>(param_pattern.index.index) == results_.size(),
  272. "Parameters out of order; expecting {0} but got {1}", results_.size(),
  273. param_pattern.index.index);
  274. CARBON_CHECK(entry.scrutinee_id.has_value());
  275. if (std::is_same_v<RefParamPatternT, SemIR::VarParamPattern>) {
  276. results_.push_back(entry.scrutinee_id);
  277. break;
  278. }
  279. auto scrutinee_type_id = ExtractScrutineeType(
  280. context.sem_ir(),
  281. SemIR::GetTypeOfInstInSpecific(context.sem_ir(), callee_specific_id_,
  282. entry.pattern_id));
  283. results_.push_back(Convert(
  284. context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  285. {.kind = ConversionTarget::RefParam, .type_id = scrutinee_type_id}));
  286. // Do not traverse farther, because the caller side of the pattern
  287. // ends here.
  288. break;
  289. }
  290. case MatchKind::Callee: {
  291. auto param_id = AddInst<SemIR::RefParam>(
  292. context, SemIR::LocId(entry.pattern_id),
  293. {.type_id =
  294. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  295. .index = param_pattern.index,
  296. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  297. context.sem_ir(), entry.pattern_id)});
  298. AddWork({.pattern_id = param_pattern.subpattern_id,
  299. .scrutinee_id = param_id});
  300. results_.push_back(param_id);
  301. break;
  302. }
  303. case MatchKind::Local: {
  304. CARBON_FATAL("Found RefParamPattern during local pattern match");
  305. }
  306. }
  307. }
  308. auto MatchContext::DoEmitPatternMatch(Context& context,
  309. SemIR::OutParamPattern param_pattern,
  310. WorkItem entry) -> void {
  311. switch (kind_) {
  312. case MatchKind::Caller: {
  313. CARBON_CHECK(
  314. static_cast<size_t>(param_pattern.index.index) == results_.size(),
  315. "Parameters out of order; expecting {0} but got {1}", results_.size(),
  316. param_pattern.index.index);
  317. CARBON_CHECK(entry.scrutinee_id.has_value());
  318. CARBON_CHECK(
  319. context.insts().Get(entry.scrutinee_id).type_id() ==
  320. ExtractScrutineeType(
  321. context.sem_ir(),
  322. SemIR::GetTypeOfInstInSpecific(
  323. context.sem_ir(), callee_specific_id_, entry.pattern_id)));
  324. results_.push_back(entry.scrutinee_id);
  325. // Do not traverse farther, because the caller side of the pattern
  326. // ends here.
  327. break;
  328. }
  329. case MatchKind::Callee: {
  330. // TODO: Consider ways to address near-duplication with the
  331. // other ParamPattern cases.
  332. auto param_id = AddInst<SemIR::OutParam>(
  333. context, SemIR::LocId(entry.pattern_id),
  334. {.type_id =
  335. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  336. .index = param_pattern.index,
  337. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  338. context.sem_ir(), entry.pattern_id)});
  339. AddWork({.pattern_id = param_pattern.subpattern_id,
  340. .scrutinee_id = param_id});
  341. results_.push_back(param_id);
  342. break;
  343. }
  344. case MatchKind::Local: {
  345. CARBON_FATAL("Found OutParamPattern during local pattern match");
  346. }
  347. }
  348. }
  349. auto MatchContext::DoEmitPatternMatch(
  350. Context& context, SemIR::ReturnSlotPattern return_slot_pattern,
  351. WorkItem entry) -> void {
  352. CARBON_CHECK(kind_ == MatchKind::Callee);
  353. auto type_id =
  354. ExtractScrutineeType(context.sem_ir(), return_slot_pattern.type_id);
  355. auto return_slot_id = AddInst<SemIR::ReturnSlot>(
  356. context, SemIR::LocId(entry.pattern_id),
  357. {.type_id = type_id,
  358. .type_inst_id = context.types().GetInstId(type_id),
  359. .storage_id = entry.scrutinee_id});
  360. bool already_in_lookup =
  361. context.scope_stack()
  362. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  363. .has_value();
  364. CARBON_CHECK(!already_in_lookup);
  365. }
  366. auto MatchContext::DoEmitPatternMatch(Context& context,
  367. SemIR::VarPattern var_pattern,
  368. WorkItem entry) -> void {
  369. auto storage_id = SemIR::InstId::None;
  370. switch (kind_) {
  371. case MatchKind::Callee: {
  372. // We're emitting pattern-match IR for the callee, but we're still on
  373. // the caller side of the pattern, so we traverse without emitting any
  374. // insts.
  375. AddWork({.pattern_id = var_pattern.subpattern_id,
  376. .scrutinee_id = SemIR::InstId::None});
  377. return;
  378. }
  379. case MatchKind::Local: {
  380. // In a `var`/`let` declaration, the `VarStorage` inst is created before
  381. // we start pattern matching.
  382. auto lookup_result = context.var_storage_map().Lookup(entry.pattern_id);
  383. CARBON_CHECK(lookup_result);
  384. storage_id = lookup_result.value();
  385. break;
  386. }
  387. case MatchKind::Caller: {
  388. storage_id = AddInst<SemIR::TemporaryStorage>(
  389. context, SemIR::LocId(entry.pattern_id),
  390. {.type_id =
  391. ExtractScrutineeType(context.sem_ir(), var_pattern.type_id)});
  392. CARBON_CHECK(entry.scrutinee_id.has_value());
  393. break;
  394. }
  395. }
  396. // TODO: Find a more efficient way to put these insts in the global_init
  397. // block (or drop the distinction between the global_init block and the
  398. // file scope?)
  399. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  400. context.global_init().Resume();
  401. }
  402. if (entry.scrutinee_id.has_value()) {
  403. auto init_id = Initialize(context, SemIR::LocId(entry.pattern_id),
  404. storage_id, entry.scrutinee_id);
  405. // If we created a `TemporaryStorage` to hold the var, create a
  406. // corresponding `Temporary` to model that its initialization is complete.
  407. // TODO: If the subpattern is a binding, we may want to destroy the
  408. // parameter variable in the callee instead of the caller so that we can
  409. // support destructive move from it.
  410. if (kind_ == MatchKind::Caller) {
  411. storage_id = AddInstWithCleanup<SemIR::Temporary>(
  412. context, SemIR::LocId(entry.pattern_id),
  413. {.type_id = context.insts().Get(storage_id).type_id(),
  414. .storage_id = storage_id,
  415. .init_id = init_id});
  416. } else {
  417. // TODO: Consider using different instruction kinds for assignment
  418. // versus initialization.
  419. AddInst<SemIR::Assign>(context, SemIR::LocId(entry.pattern_id),
  420. {.lhs_id = storage_id, .rhs_id = init_id});
  421. }
  422. }
  423. AddWork(
  424. {.pattern_id = var_pattern.subpattern_id, .scrutinee_id = storage_id});
  425. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  426. context.global_init().Suspend();
  427. }
  428. }
  429. auto MatchContext::DoEmitPatternMatch(Context& context,
  430. SemIR::TuplePattern tuple_pattern,
  431. WorkItem entry) -> void {
  432. if (tuple_pattern.type_id == SemIR::ErrorInst::TypeId) {
  433. return;
  434. }
  435. auto subpattern_ids = context.inst_blocks().Get(tuple_pattern.elements_id);
  436. auto add_all_subscrutinees =
  437. [&](llvm::ArrayRef<SemIR::InstId> subscrutinee_ids) {
  438. for (auto [subpattern_id, subscrutinee_id] :
  439. llvm::reverse(llvm::zip_equal(subpattern_ids, subscrutinee_ids))) {
  440. AddWork(
  441. {.pattern_id = subpattern_id, .scrutinee_id = subscrutinee_id});
  442. }
  443. };
  444. if (!entry.scrutinee_id.has_value()) {
  445. CARBON_CHECK(kind_ == MatchKind::Callee);
  446. context.TODO(entry.pattern_id,
  447. "Support patterns besides bindings in parameter list");
  448. return;
  449. }
  450. auto scrutinee = context.insts().GetWithLocId(entry.scrutinee_id);
  451. if (auto scrutinee_literal = scrutinee.inst.TryAs<SemIR::TupleLiteral>()) {
  452. auto subscrutinee_ids =
  453. context.inst_blocks().Get(scrutinee_literal->elements_id);
  454. if (subscrutinee_ids.size() != subpattern_ids.size()) {
  455. CARBON_DIAGNOSTIC(TuplePatternSizeDoesntMatchLiteral, Error,
  456. "tuple pattern expects {0} element{0:s}, but tuple "
  457. "literal has {1}",
  458. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  459. context.emitter().Emit(entry.pattern_id,
  460. TuplePatternSizeDoesntMatchLiteral,
  461. subpattern_ids.size(), subscrutinee_ids.size());
  462. return;
  463. }
  464. add_all_subscrutinees(subscrutinee_ids);
  465. return;
  466. }
  467. auto tuple_type_id =
  468. ExtractScrutineeType(context.sem_ir(), tuple_pattern.type_id);
  469. auto converted_scrutinee_id =
  470. ConvertToValueOrRefOfType(context, SemIR::LocId(entry.pattern_id),
  471. entry.scrutinee_id, tuple_type_id);
  472. if (auto scrutinee_value =
  473. context.insts().TryGetAs<SemIR::TupleValue>(converted_scrutinee_id)) {
  474. add_all_subscrutinees(
  475. context.inst_blocks().Get(scrutinee_value->elements_id));
  476. return;
  477. }
  478. auto tuple_type = context.types().GetAs<SemIR::TupleType>(tuple_type_id);
  479. auto element_type_inst_ids =
  480. context.inst_blocks().Get(tuple_type.type_elements_id);
  481. llvm::SmallVector<SemIR::InstId> subscrutinee_ids;
  482. subscrutinee_ids.reserve(element_type_inst_ids.size());
  483. for (auto [i, element_type_id] : llvm::enumerate(
  484. context.types().GetBlockAsTypeIds(element_type_inst_ids))) {
  485. subscrutinee_ids.push_back(
  486. AddInst<SemIR::TupleAccess>(context, scrutinee.loc_id,
  487. {.type_id = element_type_id,
  488. .tuple_id = converted_scrutinee_id,
  489. .index = SemIR::ElementIndex(i)}));
  490. }
  491. add_all_subscrutinees(subscrutinee_ids);
  492. }
  493. auto MatchContext::EmitPatternMatch(Context& context,
  494. MatchContext::WorkItem entry) -> void {
  495. if (entry.pattern_id == SemIR::ErrorInst::InstId) {
  496. return;
  497. }
  498. Diagnostics::AnnotationScope annotate_diagnostics(
  499. &context.emitter(), [&](auto& builder) {
  500. if (kind_ == MatchKind::Caller) {
  501. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  502. "initializing function parameter");
  503. builder.Note(entry.pattern_id, InCallToFunctionParam);
  504. }
  505. });
  506. auto pattern = context.insts().Get(entry.pattern_id);
  507. CARBON_KIND_SWITCH(pattern) {
  508. case SemIR::RefBindingPattern::Kind:
  509. case SemIR::SymbolicBindingPattern::Kind:
  510. case SemIR::ValueBindingPattern::Kind: {
  511. DoEmitPatternMatch(context, pattern.As<SemIR::AnyBindingPattern>(),
  512. entry);
  513. break;
  514. }
  515. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  516. DoEmitPatternMatch(context, param_pattern, entry);
  517. break;
  518. }
  519. case CARBON_KIND(SemIR::RefParamPattern param_pattern): {
  520. DoEmitPatternMatch(context, param_pattern, entry);
  521. break;
  522. }
  523. case CARBON_KIND(SemIR::VarParamPattern param_pattern): {
  524. DoEmitPatternMatch(context, param_pattern, entry);
  525. break;
  526. }
  527. case CARBON_KIND(SemIR::OutParamPattern param_pattern): {
  528. DoEmitPatternMatch(context, param_pattern, entry);
  529. break;
  530. }
  531. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  532. DoEmitPatternMatch(context, return_slot_pattern, entry);
  533. break;
  534. }
  535. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  536. DoEmitPatternMatch(context, var_pattern, entry);
  537. break;
  538. }
  539. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  540. DoEmitPatternMatch(context, tuple_pattern, entry);
  541. break;
  542. }
  543. default: {
  544. CARBON_FATAL("Inst kind not handled: {0}", pattern.kind());
  545. }
  546. }
  547. }
  548. auto CalleePatternMatch(Context& context,
  549. SemIR::InstBlockId implicit_param_patterns_id,
  550. SemIR::InstBlockId param_patterns_id,
  551. SemIR::InstBlockId return_patterns_id)
  552. -> SemIR::InstBlockId {
  553. if (!return_patterns_id.has_value() && !param_patterns_id.has_value() &&
  554. !implicit_param_patterns_id.has_value()) {
  555. return SemIR::InstBlockId::None;
  556. }
  557. MatchContext match(MatchKind::Callee);
  558. // We add work to the stack in reverse so that the results will be produced
  559. // in the original order.
  560. for (auto return_pattern_id :
  561. context.inst_blocks().GetOrEmpty(return_patterns_id)) {
  562. match.AddWork(
  563. {.pattern_id = return_pattern_id, .scrutinee_id = SemIR::InstId::None});
  564. }
  565. if (param_patterns_id.has_value()) {
  566. for (SemIR::InstId inst_id :
  567. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  568. match.AddWork(
  569. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  570. }
  571. }
  572. if (implicit_param_patterns_id.has_value()) {
  573. for (SemIR::InstId inst_id :
  574. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  575. match.AddWork(
  576. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  577. }
  578. }
  579. return match.DoWork(context);
  580. }
  581. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  582. SemIR::InstId self_pattern_id,
  583. SemIR::InstBlockId param_patterns_id,
  584. SemIR::InstBlockId return_patterns_id,
  585. SemIR::InstId self_arg_id,
  586. llvm::ArrayRef<SemIR::InstId> arg_refs,
  587. SemIR::InstId return_slot_arg_id)
  588. -> SemIR::InstBlockId {
  589. MatchContext match(MatchKind::Caller, specific_id);
  590. auto return_patterns = context.inst_blocks().GetOrEmpty(return_patterns_id);
  591. // Track the return storage, if present.
  592. if (return_slot_arg_id.has_value()) {
  593. CARBON_CHECK(return_patterns.size() == 1,
  594. "TODO: implement support for multiple return patterns");
  595. match.AddWork(
  596. {.pattern_id = return_patterns[0], .scrutinee_id = return_slot_arg_id});
  597. }
  598. // Check type conversions per-element.
  599. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  600. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  601. match.AddWork({.pattern_id = param_pattern_id, .scrutinee_id = arg_id});
  602. }
  603. if (self_pattern_id.has_value()) {
  604. match.AddWork({.pattern_id = self_pattern_id,
  605. .scrutinee_id = self_arg_id,
  606. .is_self = true});
  607. }
  608. return match.DoWork(context);
  609. }
  610. auto LocalPatternMatch(Context& context, SemIR::InstId pattern_id,
  611. SemIR::InstId scrutinee_id) -> void {
  612. MatchContext match(MatchKind::Local);
  613. match.AddWork({.pattern_id = pattern_id, .scrutinee_id = scrutinee_id});
  614. match.DoWork(context);
  615. }
  616. } // namespace Carbon::Check