pattern_match.cpp 28 KB

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