pattern_match.cpp 27 KB

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