pattern_match.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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 new_scrutinee = AddInst<SemIR::AddrOf>(
  250. context, context.insts().GetLocId(scrutinee_ref_id),
  251. {.type_id = GetPointerType(context, scrutinee_ref.type_id()),
  252. .lvalue_id = scrutinee_ref_id});
  253. AddWork({.pattern_id = addr_pattern.inner_id, .scrutinee_id = new_scrutinee});
  254. }
  255. auto MatchContext::DoEmitPatternMatch(Context& context,
  256. SemIR::ValueParamPattern param_pattern,
  257. SemIR::InstId pattern_inst_id,
  258. WorkItem entry) -> void {
  259. switch (kind_) {
  260. case MatchKind::Caller: {
  261. CARBON_CHECK(
  262. static_cast<size_t>(param_pattern.index.index) == results_.size(),
  263. "Parameters out of order; expecting {0} but got {1}", results_.size(),
  264. param_pattern.index.index);
  265. CARBON_CHECK(entry.scrutinee_id.has_value());
  266. if (entry.scrutinee_id == SemIR::ErrorInst::SingletonInstId) {
  267. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  268. } else {
  269. results_.push_back(ConvertToValueOfType(
  270. context, context.insts().GetLocId(entry.scrutinee_id),
  271. entry.scrutinee_id,
  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, context.insts().GetLocId(pattern_inst_id),
  285. {.type_id = param_pattern.type_id,
  286. .index = param_pattern.index,
  287. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  288. context.sem_ir(), entry.pattern_id)});
  289. AddWork({.pattern_id = param_pattern.subpattern_id,
  290. .scrutinee_id = param_id});
  291. results_.push_back(param_id);
  292. break;
  293. }
  294. case MatchKind::Local: {
  295. CARBON_FATAL("Found ValueParamPattern during local pattern match");
  296. }
  297. }
  298. }
  299. auto MatchContext::DoEmitPatternMatch(Context& context,
  300. SemIR::RefParamPattern param_pattern,
  301. SemIR::InstId pattern_inst_id,
  302. WorkItem entry) -> void {
  303. switch (kind_) {
  304. case MatchKind::Caller: {
  305. CARBON_CHECK(
  306. static_cast<size_t>(param_pattern.index.index) == results_.size(),
  307. "Parameters out of order; expecting {0} but got {1}", results_.size(),
  308. param_pattern.index.index);
  309. CARBON_CHECK(entry.scrutinee_id.has_value());
  310. auto expr_category =
  311. SemIR::GetExprCategory(context.sem_ir(), entry.scrutinee_id);
  312. CARBON_CHECK(expr_category == SemIR::ExprCategory::EphemeralRef ||
  313. expr_category == SemIR::ExprCategory::DurableRef);
  314. results_.push_back(entry.scrutinee_id);
  315. // Do not traverse farther, because the caller side of the pattern
  316. // ends here.
  317. break;
  318. }
  319. case MatchKind::Callee: {
  320. CARBON_CHECK(!param_pattern.index.has_value());
  321. param_pattern.index = NextRuntimeIndex();
  322. ReplaceInstBeforeConstantUse(context, entry.pattern_id, param_pattern);
  323. auto param_id = AddInst<SemIR::RefParam>(
  324. context, context.insts().GetLocId(pattern_inst_id),
  325. {.type_id = param_pattern.type_id,
  326. .index = param_pattern.index,
  327. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  328. context.sem_ir(), entry.pattern_id)});
  329. AddWork({.pattern_id = param_pattern.subpattern_id,
  330. .scrutinee_id = param_id});
  331. results_.push_back(param_id);
  332. break;
  333. }
  334. case MatchKind::Local: {
  335. CARBON_FATAL("Found RefParamPattern during local pattern match");
  336. }
  337. }
  338. }
  339. auto MatchContext::DoEmitPatternMatch(Context& context,
  340. SemIR::OutParamPattern param_pattern,
  341. SemIR::InstId pattern_inst_id,
  342. WorkItem entry) -> void {
  343. switch (kind_) {
  344. case MatchKind::Caller: {
  345. CARBON_CHECK(
  346. static_cast<size_t>(param_pattern.index.index) == results_.size(),
  347. "Parameters out of order; expecting {0} but got {1}", results_.size(),
  348. param_pattern.index.index);
  349. CARBON_CHECK(entry.scrutinee_id.has_value());
  350. CARBON_CHECK(context.insts().Get(entry.scrutinee_id).type_id() ==
  351. SemIR::GetTypeOfInstInSpecific(
  352. context.sem_ir(), callee_specific_id_, pattern_inst_id));
  353. results_.push_back(entry.scrutinee_id);
  354. // Do not traverse farther, because the caller side of the pattern
  355. // ends here.
  356. break;
  357. }
  358. case MatchKind::Callee: {
  359. // TODO: Consider ways to address near-duplication with the
  360. // other ParamPattern cases.
  361. CARBON_CHECK(!param_pattern.index.has_value());
  362. param_pattern.index = NextRuntimeIndex();
  363. ReplaceInstBeforeConstantUse(context, entry.pattern_id, param_pattern);
  364. auto param_id = AddInst<SemIR::OutParam>(
  365. context, context.insts().GetLocId(pattern_inst_id),
  366. {.type_id = param_pattern.type_id,
  367. .index = param_pattern.index,
  368. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  369. context.sem_ir(), entry.pattern_id)});
  370. AddWork({.pattern_id = param_pattern.subpattern_id,
  371. .scrutinee_id = param_id});
  372. results_.push_back(param_id);
  373. break;
  374. }
  375. case MatchKind::Local: {
  376. CARBON_FATAL("Found OutParamPattern during local pattern match");
  377. }
  378. }
  379. }
  380. auto MatchContext::DoEmitPatternMatch(
  381. Context& context, SemIR::ReturnSlotPattern return_slot_pattern,
  382. SemIR::InstId pattern_inst_id, WorkItem entry) -> void {
  383. CARBON_CHECK(kind_ == MatchKind::Callee);
  384. auto return_slot_id = AddInst<SemIR::ReturnSlot>(
  385. context, context.insts().GetLocId(pattern_inst_id),
  386. {.type_id = return_slot_pattern.type_id,
  387. .type_inst_id = return_slot_pattern.type_inst_id,
  388. .storage_id = entry.scrutinee_id});
  389. bool already_in_lookup =
  390. context.scope_stack()
  391. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  392. .has_value();
  393. CARBON_CHECK(!already_in_lookup);
  394. }
  395. auto MatchContext::DoEmitPatternMatch(Context& context,
  396. SemIR::VarPattern var_pattern,
  397. SemIR::InstId pattern_inst_id,
  398. WorkItem entry) -> void {
  399. auto storage_id = SemIR::InstId::None;
  400. switch (kind_) {
  401. case MatchKind::Callee: {
  402. // We're emitting pattern-match IR for the callee, but we're still on
  403. // the caller side of the pattern, so we traverse without emitting any
  404. // insts.
  405. AddWork({.pattern_id = var_pattern.subpattern_id,
  406. .scrutinee_id = SemIR::InstId::None});
  407. return;
  408. }
  409. case MatchKind::Local: {
  410. // In a `var`/`let` declaration, the `VarStorage` inst is created before
  411. // we start pattern matching.
  412. auto lookup_result = context.var_storage_map().Lookup(entry.pattern_id);
  413. CARBON_CHECK(lookup_result);
  414. storage_id = lookup_result.value();
  415. break;
  416. }
  417. case MatchKind::Caller: {
  418. storage_id = AddInstWithCleanup<SemIR::TemporaryStorage>(
  419. context, context.insts().GetLocId(pattern_inst_id),
  420. {.type_id = var_pattern.type_id});
  421. CARBON_CHECK(entry.scrutinee_id.has_value());
  422. break;
  423. }
  424. }
  425. // TODO: Find a more efficient way to put these insts in the global_init
  426. // block (or drop the distinction between the global_init block and the
  427. // file scope?)
  428. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  429. context.global_init().Resume();
  430. }
  431. if (entry.scrutinee_id.has_value()) {
  432. auto loc_id = context.insts().GetLocId(pattern_inst_id);
  433. auto init_id = Initialize(context, loc_id, storage_id, entry.scrutinee_id);
  434. // TODO: Consider using different instruction kinds for assignment
  435. // versus initialization.
  436. AddInst<SemIR::Assign>(context, loc_id,
  437. {.lhs_id = storage_id, .rhs_id = init_id});
  438. }
  439. AddWork(
  440. {.pattern_id = var_pattern.subpattern_id, .scrutinee_id = storage_id});
  441. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  442. context.global_init().Suspend();
  443. }
  444. }
  445. auto MatchContext::DoEmitPatternMatch(Context& context,
  446. SemIR::TuplePattern tuple_pattern,
  447. SemIR::InstId pattern_inst_id,
  448. WorkItem entry) -> void {
  449. if (tuple_pattern.type_id == SemIR::ErrorInst::SingletonTypeId) {
  450. return;
  451. }
  452. auto subpattern_ids = context.inst_blocks().Get(tuple_pattern.elements_id);
  453. auto add_all_subscrutinees =
  454. [&](llvm::ArrayRef<SemIR::InstId> subscrutinee_ids) {
  455. for (auto [subpattern_id, subscrutinee_id] :
  456. llvm::reverse(llvm::zip(subpattern_ids, subscrutinee_ids))) {
  457. AddWork(
  458. {.pattern_id = subpattern_id, .scrutinee_id = subscrutinee_id});
  459. }
  460. };
  461. if (!entry.scrutinee_id.has_value()) {
  462. CARBON_CHECK(kind_ == MatchKind::Callee);
  463. context.TODO(pattern_inst_id,
  464. "Support patterns besides bindings in parameter list");
  465. return;
  466. }
  467. auto scrutinee = context.insts().GetWithLocId(entry.scrutinee_id);
  468. if (auto scrutinee_literal = scrutinee.inst.TryAs<SemIR::TupleLiteral>()) {
  469. auto subscrutinee_ids =
  470. context.inst_blocks().Get(scrutinee_literal->elements_id);
  471. if (subscrutinee_ids.size() != subpattern_ids.size()) {
  472. CARBON_DIAGNOSTIC(TuplePatternSizeDoesntMatchLiteral, Error,
  473. "tuple pattern expects {0} element{0:s}, but tuple "
  474. "literal has {1}",
  475. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  476. context.emitter().Emit(pattern_inst_id,
  477. TuplePatternSizeDoesntMatchLiteral,
  478. subpattern_ids.size(), subscrutinee_ids.size());
  479. return;
  480. }
  481. add_all_subscrutinees(subscrutinee_ids);
  482. return;
  483. }
  484. auto converted_scrutinee = ConvertToValueOrRefOfType(
  485. context, context.insts().GetLocId(pattern_inst_id), entry.scrutinee_id,
  486. tuple_pattern.type_id);
  487. if (auto scrutinee_value =
  488. context.insts().TryGetAs<SemIR::TupleValue>(converted_scrutinee)) {
  489. add_all_subscrutinees(
  490. context.inst_blocks().Get(scrutinee_value->elements_id));
  491. return;
  492. }
  493. auto tuple_type =
  494. context.types().GetAs<SemIR::TupleType>(tuple_pattern.type_id);
  495. auto element_type_ids = context.type_blocks().Get(tuple_type.elements_id);
  496. llvm::SmallVector<SemIR::InstId> subscrutinee_ids;
  497. subscrutinee_ids.reserve(element_type_ids.size());
  498. for (auto [i, element_type_id] : llvm::enumerate(element_type_ids)) {
  499. subscrutinee_ids.push_back(
  500. AddInst<SemIR::TupleAccess>(context, scrutinee.loc_id,
  501. {.type_id = element_type_id,
  502. .tuple_id = entry.scrutinee_id,
  503. .index = SemIR::ElementIndex(i)}));
  504. }
  505. add_all_subscrutinees(subscrutinee_ids);
  506. }
  507. auto MatchContext::EmitPatternMatch(Context& context,
  508. MatchContext::WorkItem entry) -> void {
  509. if (entry.pattern_id == SemIR::ErrorInst::SingletonInstId) {
  510. return;
  511. }
  512. Diagnostics::AnnotationScope annotate_diagnostics(
  513. &context.emitter(), [&](auto& builder) {
  514. if (kind_ == MatchKind::Caller) {
  515. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  516. "initializing function parameter");
  517. builder.Note(entry.pattern_id, InCallToFunctionParam);
  518. }
  519. });
  520. auto pattern = context.insts().Get(entry.pattern_id);
  521. CARBON_KIND_SWITCH(pattern) {
  522. case SemIR::BindingPattern::Kind:
  523. case SemIR::SymbolicBindingPattern::Kind: {
  524. DoEmitPatternMatch(context, pattern.As<SemIR::AnyBindingPattern>(),
  525. entry.pattern_id, entry);
  526. break;
  527. }
  528. case CARBON_KIND(SemIR::AddrPattern addr_pattern): {
  529. DoEmitPatternMatch(context, addr_pattern, entry.pattern_id, entry);
  530. break;
  531. }
  532. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  533. DoEmitPatternMatch(context, param_pattern, entry.pattern_id, entry);
  534. break;
  535. }
  536. case CARBON_KIND(SemIR::RefParamPattern param_pattern): {
  537. DoEmitPatternMatch(context, param_pattern, entry.pattern_id, entry);
  538. break;
  539. }
  540. case CARBON_KIND(SemIR::OutParamPattern param_pattern): {
  541. DoEmitPatternMatch(context, param_pattern, entry.pattern_id, entry);
  542. break;
  543. }
  544. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  545. DoEmitPatternMatch(context, return_slot_pattern, entry.pattern_id, entry);
  546. break;
  547. }
  548. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  549. DoEmitPatternMatch(context, var_pattern, entry.pattern_id, entry);
  550. break;
  551. }
  552. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  553. DoEmitPatternMatch(context, tuple_pattern, entry.pattern_id, entry);
  554. break;
  555. }
  556. default: {
  557. CARBON_FATAL("Inst kind not handled: {0}", pattern.kind());
  558. }
  559. }
  560. }
  561. auto CalleePatternMatch(Context& context,
  562. SemIR::InstBlockId implicit_param_patterns_id,
  563. SemIR::InstBlockId param_patterns_id,
  564. SemIR::InstId return_slot_pattern_id)
  565. -> SemIR::InstBlockId {
  566. if (!return_slot_pattern_id.has_value() && !param_patterns_id.has_value() &&
  567. !implicit_param_patterns_id.has_value()) {
  568. return SemIR::InstBlockId::None;
  569. }
  570. MatchContext match(MatchKind::Callee);
  571. // We add work to the stack in reverse so that the results will be produced
  572. // in the original order.
  573. if (return_slot_pattern_id.has_value()) {
  574. match.AddWork({.pattern_id = return_slot_pattern_id,
  575. .scrutinee_id = SemIR::InstId::None});
  576. }
  577. if (param_patterns_id.has_value()) {
  578. for (SemIR::InstId inst_id :
  579. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  580. match.AddWork(
  581. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  582. }
  583. }
  584. if (implicit_param_patterns_id.has_value()) {
  585. for (SemIR::InstId inst_id :
  586. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  587. match.AddWork(
  588. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  589. }
  590. }
  591. return match.DoWork(context);
  592. }
  593. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  594. SemIR::InstId self_pattern_id,
  595. SemIR::InstBlockId param_patterns_id,
  596. SemIR::InstId return_slot_pattern_id,
  597. SemIR::InstId self_arg_id,
  598. llvm::ArrayRef<SemIR::InstId> arg_refs,
  599. SemIR::InstId return_slot_arg_id)
  600. -> SemIR::InstBlockId {
  601. MatchContext match(MatchKind::Caller, specific_id);
  602. // Track the return storage, if present.
  603. if (return_slot_arg_id.has_value()) {
  604. CARBON_CHECK(return_slot_pattern_id.has_value());
  605. match.AddWork({.pattern_id = return_slot_pattern_id,
  606. .scrutinee_id = return_slot_arg_id});
  607. }
  608. // Check type conversions per-element.
  609. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  610. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  611. match.AddWork({.pattern_id = param_pattern_id, .scrutinee_id = arg_id});
  612. }
  613. if (self_pattern_id.has_value()) {
  614. match.AddWork({.pattern_id = self_pattern_id, .scrutinee_id = self_arg_id});
  615. }
  616. return match.DoWork(context);
  617. }
  618. auto LocalPatternMatch(Context& context, SemIR::InstId pattern_id,
  619. SemIR::InstId scrutinee_id) -> void {
  620. MatchContext match(MatchKind::Local);
  621. match.AddWork({.pattern_id = pattern_id, .scrutinee_id = scrutinee_id});
  622. match.DoWork(context);
  623. }
  624. } // namespace Carbon::Check