pattern_match.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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/control_flow.h"
  12. #include "toolchain/check/convert.h"
  13. #include "toolchain/check/subpattern.h"
  14. #include "toolchain/check/type.h"
  15. #include "toolchain/diagnostics/format_providers.h"
  16. #include "toolchain/sem_ir/expr_info.h"
  17. #include "toolchain/sem_ir/pattern.h"
  18. namespace Carbon::Check {
  19. namespace {
  20. // Selects between the different kinds of pattern matching.
  21. enum class MatchKind : uint8_t {
  22. // Caller pattern matching occurs on the caller side of a function call, and
  23. // is responsible for matching the argument expression against the portion
  24. // of the pattern above the ParamPattern insts.
  25. Caller,
  26. // Callee pattern matching occurs in the function decl block, and is
  27. // responsible for matching the function's calling-convention parameters
  28. // against the portion of the pattern below the ParamPattern insts.
  29. Callee,
  30. // Local pattern matching is pattern matching outside of a function call,
  31. // such as in a let/var declaration.
  32. Local,
  33. };
  34. // The collected state of a pattern-matching operation.
  35. class MatchContext {
  36. public:
  37. struct WorkItem {
  38. SemIR::InstId pattern_id;
  39. // `None` when processing the callee side.
  40. SemIR::InstId scrutinee_id;
  41. };
  42. // Constructs a MatchContext. If `callee_specific_id` is not `None`, this
  43. // pattern match operation is part of implementing the signature of the given
  44. // specific.
  45. explicit MatchContext(MatchKind kind, SemIR::SpecificId callee_specific_id =
  46. SemIR::SpecificId::None)
  47. : next_index_(0), kind_(kind), callee_specific_id_(callee_specific_id) {}
  48. // Adds a work item to the stack.
  49. auto AddWork(WorkItem work_item) -> void { stack_.push_back(work_item); }
  50. // Processes all work items on the stack. When performing caller pattern
  51. // matching, returns an inst block with one inst reference for each
  52. // calling-convention argument. When performing callee pattern matching,
  53. // returns an inst block with references to all the emitted BindName insts.
  54. auto DoWork(Context& context) -> SemIR::InstBlockId;
  55. private:
  56. // Allocates the next unallocated RuntimeParamIndex, starting from 0.
  57. auto NextRuntimeIndex() -> SemIR::CallParamIndex {
  58. auto result = next_index_;
  59. ++next_index_.index;
  60. return result;
  61. }
  62. // Emits the pattern-match insts necessary to match the pattern inst
  63. // `entry.pattern_id` against the scrutinee value `entry.scrutinee_id`, and
  64. // adds to `stack_` any work necessary to traverse into its subpatterns. This
  65. // behavior is contingent on the kind of match being performed, as indicated
  66. // by kind_`. For example, when performing a callee pattern match, this does
  67. // not emit insts for patterns on the caller side. However, it still traverses
  68. // into subpatterns if any of their descendants might emit insts.
  69. // TODO: Require that `entry.scrutinee_id` is valid if and only if insts
  70. // should be emitted, once we start emitting `Param` insts in the
  71. // `ParamPattern` case.
  72. auto EmitPatternMatch(Context& context, MatchContext::WorkItem entry) -> void;
  73. // Implementations of `EmitPatternMatch` for particular pattern inst kinds.
  74. // The pattern argument is always equal to
  75. // `context.insts().Get(entry.pattern_id)`, and `pattern_loc_id` is always
  76. // equal to `context.insts().GetLocId(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 loc_id = context.insts().GetLocId(region.result_id);
  141. auto exit_block = context.inst_blocks().Get(region.block_ids.back());
  142. if (region.block_ids.size() == 1) {
  143. // TODO: Is it possible to avoid leaving an "orphan" block in the IR in the
  144. // first two cases?
  145. if (exit_block.empty()) {
  146. return region.result_id;
  147. }
  148. if (exit_block.size() == 1) {
  149. context.inst_block_stack().AddInstId(exit_block.front());
  150. return region.result_id;
  151. }
  152. return AddInst<SemIR::SpliceBlock>(
  153. context, loc_id,
  154. {.type_id = context.insts().Get(region.result_id).type_id(),
  155. .block_id = region.block_ids.front(),
  156. .result_id = region.result_id});
  157. }
  158. if (context.region_stack().empty()) {
  159. context.TODO(loc_id,
  160. "Control flow expressions are currently only supported inside "
  161. "functions.");
  162. return SemIR::ErrorInst::SingletonInstId;
  163. }
  164. AddInst(context, SemIR::LocIdAndInst::NoLoc<SemIR::Branch>(
  165. {.target_id = region.block_ids.front()}));
  166. context.inst_block_stack().Pop();
  167. // TODO: this will cumulatively cost O(MN) running time for M blocks
  168. // at the Nth level of the stack. Figure out how to do better.
  169. context.region_stack().AddToRegion(region.block_ids);
  170. auto resume_with_block_id =
  171. context.insts().GetAs<SemIR::Branch>(exit_block.back()).target_id;
  172. CARBON_CHECK(context.inst_blocks().GetOrEmpty(resume_with_block_id).empty());
  173. context.inst_block_stack().Push(resume_with_block_id);
  174. context.region_stack().AddToRegion(resume_with_block_id, loc_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, context.insts().GetLocId(entry.scrutinee_id),
  200. entry.scrutinee_id,
  201. {.kind = bind_name_id.has_value() ? ConversionTarget::ValueOrRef
  202. : ConversionTarget::Discarded,
  203. .type_id = binding_pattern.type_id});
  204. } else {
  205. // In a function call, conversion is handled while matching the enclosing
  206. // `*ParamPattern`.
  207. value_id = entry.scrutinee_id;
  208. }
  209. if (bind_name_id.has_value()) {
  210. auto bind_name = context.insts().GetAs<SemIR::AnyBindName>(bind_name_id);
  211. CARBON_CHECK(!bind_name.value_id.has_value());
  212. bind_name.value_id = value_id;
  213. ReplaceInstBeforeConstantUse(context, bind_name_id, bind_name);
  214. context.inst_block_stack().AddInstId(bind_name_id);
  215. }
  216. }
  217. auto MatchContext::DoEmitPatternMatch(Context& context,
  218. SemIR::AddrPattern addr_pattern,
  219. SemIR::InstId /*pattern_inst_id*/,
  220. WorkItem entry) -> void {
  221. CARBON_CHECK(kind_ != MatchKind::Local);
  222. if (kind_ == MatchKind::Callee) {
  223. // We're emitting pattern-match IR for the callee, but we're still on
  224. // the caller side of the pattern, so we traverse without emitting any
  225. // insts.
  226. AddWork({.pattern_id = addr_pattern.inner_id,
  227. .scrutinee_id = SemIR::InstId::None});
  228. return;
  229. }
  230. CARBON_CHECK(entry.scrutinee_id.has_value());
  231. auto scrutinee_ref_id = ConvertToValueOrRefExpr(context, entry.scrutinee_id);
  232. switch (SemIR::GetExprCategory(context.sem_ir(), scrutinee_ref_id)) {
  233. case SemIR::ExprCategory::Error:
  234. case SemIR::ExprCategory::DurableRef:
  235. case SemIR::ExprCategory::EphemeralRef:
  236. break;
  237. default:
  238. CARBON_DIAGNOSTIC(AddrSelfIsNonRef, Error,
  239. "`addr self` method cannot be invoked on a value");
  240. context.emitter().Emit(
  241. TokenOnly(context.insts().GetLocId(entry.scrutinee_id)),
  242. AddrSelfIsNonRef);
  243. // Add fake reference expression to preserve invariants.
  244. auto scrutinee = context.insts().GetWithLocId(entry.scrutinee_id);
  245. scrutinee_ref_id = AddInstWithCleanup<SemIR::TemporaryStorage>(
  246. context, scrutinee.loc_id, {.type_id = scrutinee.inst.type_id()});
  247. }
  248. auto scrutinee_ref = context.insts().Get(scrutinee_ref_id);
  249. auto scrutinee_ref_type_inst_id =
  250. context.types().GetInstId(scrutinee_ref.type_id());
  251. auto new_scrutinee = AddInst<SemIR::AddrOf>(
  252. context, context.insts().GetLocId(scrutinee_ref_id),
  253. {.type_id = GetPointerType(context, scrutinee_ref_type_inst_id),
  254. .lvalue_id = scrutinee_ref_id});
  255. AddWork({.pattern_id = addr_pattern.inner_id, .scrutinee_id = new_scrutinee});
  256. }
  257. auto MatchContext::DoEmitPatternMatch(Context& context,
  258. SemIR::ValueParamPattern param_pattern,
  259. SemIR::InstId pattern_inst_id,
  260. WorkItem entry) -> void {
  261. switch (kind_) {
  262. case MatchKind::Caller: {
  263. CARBON_CHECK(
  264. static_cast<size_t>(param_pattern.index.index) == results_.size(),
  265. "Parameters out of order; expecting {0} but got {1}", results_.size(),
  266. param_pattern.index.index);
  267. CARBON_CHECK(entry.scrutinee_id.has_value());
  268. if (entry.scrutinee_id == SemIR::ErrorInst::SingletonInstId) {
  269. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  270. } else {
  271. results_.push_back(ConvertToValueOfType(
  272. context, context.insts().GetLocId(entry.scrutinee_id),
  273. entry.scrutinee_id,
  274. SemIR::GetTypeOfInstInSpecific(
  275. context.sem_ir(), callee_specific_id_, pattern_inst_id)));
  276. }
  277. // Do not traverse farther, because the caller side of the pattern
  278. // ends here.
  279. break;
  280. }
  281. case MatchKind::Callee: {
  282. CARBON_CHECK(!param_pattern.index.has_value());
  283. param_pattern.index = NextRuntimeIndex();
  284. ReplaceInstBeforeConstantUse(context, entry.pattern_id, param_pattern);
  285. auto param_id = AddInst<SemIR::ValueParam>(
  286. context, context.insts().GetLocId(pattern_inst_id),
  287. {.type_id = param_pattern.type_id,
  288. .index = param_pattern.index,
  289. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  290. context.sem_ir(), entry.pattern_id)});
  291. AddWork({.pattern_id = param_pattern.subpattern_id,
  292. .scrutinee_id = param_id});
  293. results_.push_back(param_id);
  294. break;
  295. }
  296. case MatchKind::Local: {
  297. CARBON_FATAL("Found ValueParamPattern during local pattern match");
  298. }
  299. }
  300. }
  301. auto MatchContext::DoEmitPatternMatch(Context& context,
  302. SemIR::RefParamPattern param_pattern,
  303. SemIR::InstId pattern_inst_id,
  304. WorkItem entry) -> void {
  305. switch (kind_) {
  306. case MatchKind::Caller: {
  307. CARBON_CHECK(
  308. static_cast<size_t>(param_pattern.index.index) == results_.size(),
  309. "Parameters out of order; expecting {0} but got {1}", results_.size(),
  310. param_pattern.index.index);
  311. CARBON_CHECK(entry.scrutinee_id.has_value());
  312. auto expr_category =
  313. SemIR::GetExprCategory(context.sem_ir(), entry.scrutinee_id);
  314. CARBON_CHECK(expr_category == SemIR::ExprCategory::EphemeralRef ||
  315. expr_category == SemIR::ExprCategory::DurableRef);
  316. results_.push_back(entry.scrutinee_id);
  317. // Do not traverse farther, because the caller side of the pattern
  318. // ends here.
  319. break;
  320. }
  321. case MatchKind::Callee: {
  322. CARBON_CHECK(!param_pattern.index.has_value());
  323. param_pattern.index = NextRuntimeIndex();
  324. ReplaceInstBeforeConstantUse(context, entry.pattern_id, param_pattern);
  325. auto param_id = AddInst<SemIR::RefParam>(
  326. context, context.insts().GetLocId(pattern_inst_id),
  327. {.type_id = 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(context.insts().Get(entry.scrutinee_id).type_id() ==
  353. SemIR::GetTypeOfInstInSpecific(
  354. context.sem_ir(), callee_specific_id_, pattern_inst_id));
  355. results_.push_back(entry.scrutinee_id);
  356. // Do not traverse farther, because the caller side of the pattern
  357. // ends here.
  358. break;
  359. }
  360. case MatchKind::Callee: {
  361. // TODO: Consider ways to address near-duplication with the
  362. // other ParamPattern cases.
  363. CARBON_CHECK(!param_pattern.index.has_value());
  364. param_pattern.index = NextRuntimeIndex();
  365. ReplaceInstBeforeConstantUse(context, entry.pattern_id, param_pattern);
  366. auto param_id = AddInst<SemIR::OutParam>(
  367. context, context.insts().GetLocId(pattern_inst_id),
  368. {.type_id = param_pattern.type_id,
  369. .index = param_pattern.index,
  370. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  371. context.sem_ir(), entry.pattern_id)});
  372. AddWork({.pattern_id = param_pattern.subpattern_id,
  373. .scrutinee_id = param_id});
  374. results_.push_back(param_id);
  375. break;
  376. }
  377. case MatchKind::Local: {
  378. CARBON_FATAL("Found OutParamPattern during local pattern match");
  379. }
  380. }
  381. }
  382. auto MatchContext::DoEmitPatternMatch(
  383. Context& context, SemIR::ReturnSlotPattern return_slot_pattern,
  384. SemIR::InstId pattern_inst_id, WorkItem entry) -> void {
  385. CARBON_CHECK(kind_ == MatchKind::Callee);
  386. auto return_slot_id = AddInst<SemIR::ReturnSlot>(
  387. context, context.insts().GetLocId(pattern_inst_id),
  388. {.type_id = return_slot_pattern.type_id,
  389. .type_inst_id = return_slot_pattern.type_inst_id,
  390. .storage_id = entry.scrutinee_id});
  391. bool already_in_lookup =
  392. context.scope_stack()
  393. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  394. .has_value();
  395. CARBON_CHECK(!already_in_lookup);
  396. }
  397. auto MatchContext::DoEmitPatternMatch(Context& context,
  398. SemIR::VarPattern var_pattern,
  399. SemIR::InstId pattern_inst_id,
  400. WorkItem entry) -> void {
  401. auto storage_id = SemIR::InstId::None;
  402. switch (kind_) {
  403. case MatchKind::Callee: {
  404. // We're emitting pattern-match IR for the callee, but we're still on
  405. // the caller side of the pattern, so we traverse without emitting any
  406. // insts.
  407. AddWork({.pattern_id = var_pattern.subpattern_id,
  408. .scrutinee_id = SemIR::InstId::None});
  409. return;
  410. }
  411. case MatchKind::Local: {
  412. // In a `var`/`let` declaration, the `VarStorage` inst is created before
  413. // we start pattern matching.
  414. auto lookup_result = context.var_storage_map().Lookup(entry.pattern_id);
  415. CARBON_CHECK(lookup_result);
  416. storage_id = lookup_result.value();
  417. break;
  418. }
  419. case MatchKind::Caller: {
  420. storage_id = AddInstWithCleanup<SemIR::TemporaryStorage>(
  421. context, context.insts().GetLocId(pattern_inst_id),
  422. {.type_id = var_pattern.type_id});
  423. CARBON_CHECK(entry.scrutinee_id.has_value());
  424. break;
  425. }
  426. }
  427. // TODO: Find a more efficient way to put these insts in the global_init
  428. // block (or drop the distinction between the global_init block and the
  429. // file scope?)
  430. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  431. context.global_init().Resume();
  432. }
  433. if (entry.scrutinee_id.has_value()) {
  434. auto loc_id = context.insts().GetLocId(pattern_inst_id);
  435. auto init_id = Initialize(context, loc_id, storage_id, entry.scrutinee_id);
  436. // TODO: Consider using different instruction kinds for assignment
  437. // versus initialization.
  438. AddInst<SemIR::Assign>(context, loc_id,
  439. {.lhs_id = storage_id, .rhs_id = init_id});
  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. SemIR::InstId pattern_inst_id,
  450. WorkItem entry) -> void {
  451. if (tuple_pattern.type_id == SemIR::ErrorInst::SingletonTypeId) {
  452. return;
  453. }
  454. auto subpattern_ids = context.inst_blocks().Get(tuple_pattern.elements_id);
  455. auto add_all_subscrutinees =
  456. [&](llvm::ArrayRef<SemIR::InstId> subscrutinee_ids) {
  457. for (auto [subpattern_id, subscrutinee_id] :
  458. llvm::reverse(llvm::zip(subpattern_ids, subscrutinee_ids))) {
  459. AddWork(
  460. {.pattern_id = subpattern_id, .scrutinee_id = subscrutinee_id});
  461. }
  462. };
  463. if (!entry.scrutinee_id.has_value()) {
  464. CARBON_CHECK(kind_ == MatchKind::Callee);
  465. context.TODO(pattern_inst_id,
  466. "Support patterns besides bindings in parameter list");
  467. return;
  468. }
  469. auto scrutinee = context.insts().GetWithLocId(entry.scrutinee_id);
  470. if (auto scrutinee_literal = scrutinee.inst.TryAs<SemIR::TupleLiteral>()) {
  471. auto subscrutinee_ids =
  472. context.inst_blocks().Get(scrutinee_literal->elements_id);
  473. if (subscrutinee_ids.size() != subpattern_ids.size()) {
  474. CARBON_DIAGNOSTIC(TuplePatternSizeDoesntMatchLiteral, Error,
  475. "tuple pattern expects {0} element{0:s}, but tuple "
  476. "literal has {1}",
  477. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  478. context.emitter().Emit(pattern_inst_id,
  479. TuplePatternSizeDoesntMatchLiteral,
  480. subpattern_ids.size(), subscrutinee_ids.size());
  481. return;
  482. }
  483. add_all_subscrutinees(subscrutinee_ids);
  484. return;
  485. }
  486. auto converted_scrutinee = ConvertToValueOrRefOfType(
  487. context, context.insts().GetLocId(pattern_inst_id), entry.scrutinee_id,
  488. tuple_pattern.type_id);
  489. if (auto scrutinee_value =
  490. context.insts().TryGetAs<SemIR::TupleValue>(converted_scrutinee)) {
  491. add_all_subscrutinees(
  492. context.inst_blocks().Get(scrutinee_value->elements_id));
  493. return;
  494. }
  495. auto tuple_type =
  496. context.types().GetAs<SemIR::TupleType>(tuple_pattern.type_id);
  497. auto element_type_ids = context.type_blocks().Get(tuple_type.elements_id);
  498. llvm::SmallVector<SemIR::InstId> subscrutinee_ids;
  499. subscrutinee_ids.reserve(element_type_ids.size());
  500. for (auto [i, element_type_id] : llvm::enumerate(element_type_ids)) {
  501. subscrutinee_ids.push_back(
  502. AddInst<SemIR::TupleAccess>(context, scrutinee.loc_id,
  503. {.type_id = element_type_id,
  504. .tuple_id = entry.scrutinee_id,
  505. .index = SemIR::ElementIndex(i)}));
  506. }
  507. add_all_subscrutinees(subscrutinee_ids);
  508. }
  509. auto MatchContext::EmitPatternMatch(Context& context,
  510. MatchContext::WorkItem entry) -> void {
  511. if (entry.pattern_id == SemIR::ErrorInst::SingletonInstId) {
  512. return;
  513. }
  514. Diagnostics::AnnotationScope annotate_diagnostics(
  515. &context.emitter(), [&](auto& builder) {
  516. if (kind_ == MatchKind::Caller) {
  517. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  518. "initializing function parameter");
  519. builder.Note(entry.pattern_id, InCallToFunctionParam);
  520. }
  521. });
  522. auto pattern = context.insts().Get(entry.pattern_id);
  523. CARBON_KIND_SWITCH(pattern) {
  524. case SemIR::BindingPattern::Kind:
  525. case SemIR::SymbolicBindingPattern::Kind: {
  526. DoEmitPatternMatch(context, pattern.As<SemIR::AnyBindingPattern>(),
  527. entry.pattern_id, entry);
  528. break;
  529. }
  530. case CARBON_KIND(SemIR::AddrPattern addr_pattern): {
  531. DoEmitPatternMatch(context, addr_pattern, entry.pattern_id, entry);
  532. break;
  533. }
  534. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  535. DoEmitPatternMatch(context, param_pattern, entry.pattern_id, entry);
  536. break;
  537. }
  538. case CARBON_KIND(SemIR::RefParamPattern param_pattern): {
  539. DoEmitPatternMatch(context, param_pattern, entry.pattern_id, entry);
  540. break;
  541. }
  542. case CARBON_KIND(SemIR::OutParamPattern param_pattern): {
  543. DoEmitPatternMatch(context, param_pattern, entry.pattern_id, entry);
  544. break;
  545. }
  546. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  547. DoEmitPatternMatch(context, return_slot_pattern, entry.pattern_id, entry);
  548. break;
  549. }
  550. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  551. DoEmitPatternMatch(context, var_pattern, entry.pattern_id, entry);
  552. break;
  553. }
  554. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  555. DoEmitPatternMatch(context, tuple_pattern, entry.pattern_id, entry);
  556. break;
  557. }
  558. default: {
  559. CARBON_FATAL("Inst kind not handled: {0}", pattern.kind());
  560. }
  561. }
  562. }
  563. auto CalleePatternMatch(Context& context,
  564. SemIR::InstBlockId implicit_param_patterns_id,
  565. SemIR::InstBlockId param_patterns_id,
  566. SemIR::InstId return_slot_pattern_id)
  567. -> SemIR::InstBlockId {
  568. if (!return_slot_pattern_id.has_value() && !param_patterns_id.has_value() &&
  569. !implicit_param_patterns_id.has_value()) {
  570. return SemIR::InstBlockId::None;
  571. }
  572. MatchContext match(MatchKind::Callee);
  573. // We add work to the stack in reverse so that the results will be produced
  574. // in the original order.
  575. if (return_slot_pattern_id.has_value()) {
  576. match.AddWork({.pattern_id = return_slot_pattern_id,
  577. .scrutinee_id = SemIR::InstId::None});
  578. }
  579. if (param_patterns_id.has_value()) {
  580. for (SemIR::InstId inst_id :
  581. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  582. match.AddWork(
  583. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  584. }
  585. }
  586. if (implicit_param_patterns_id.has_value()) {
  587. for (SemIR::InstId inst_id :
  588. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  589. match.AddWork(
  590. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  591. }
  592. }
  593. return match.DoWork(context);
  594. }
  595. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  596. SemIR::InstId self_pattern_id,
  597. SemIR::InstBlockId param_patterns_id,
  598. SemIR::InstId return_slot_pattern_id,
  599. SemIR::InstId self_arg_id,
  600. llvm::ArrayRef<SemIR::InstId> arg_refs,
  601. SemIR::InstId return_slot_arg_id)
  602. -> SemIR::InstBlockId {
  603. MatchContext match(MatchKind::Caller, specific_id);
  604. // Track the return storage, if present.
  605. if (return_slot_arg_id.has_value()) {
  606. CARBON_CHECK(return_slot_pattern_id.has_value());
  607. match.AddWork({.pattern_id = return_slot_pattern_id,
  608. .scrutinee_id = return_slot_arg_id});
  609. }
  610. // Check type conversions per-element.
  611. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  612. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  613. match.AddWork({.pattern_id = param_pattern_id, .scrutinee_id = arg_id});
  614. }
  615. if (self_pattern_id.has_value()) {
  616. match.AddWork({.pattern_id = self_pattern_id, .scrutinee_id = self_arg_id});
  617. }
  618. return match.DoWork(context);
  619. }
  620. auto LocalPatternMatch(Context& context, SemIR::InstId pattern_id,
  621. SemIR::InstId scrutinee_id) -> void {
  622. MatchContext match(MatchKind::Local);
  623. match.AddWork({.pattern_id = pattern_id, .scrutinee_id = scrutinee_id});
  624. match.DoWork(context);
  625. }
  626. } // namespace Carbon::Check