pattern_match.cpp 28 KB

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