pattern_match.cpp 27 KB

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