pattern_match.cpp 28 KB

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