pattern_match.cpp 27 KB

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