pattern_match.cpp 28 KB

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