pattern_match.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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. // If true, disables diagnostics that would otherwise require scrutinee_id
  43. // to be tagged with `ref`. Only affects caller pattern matching.
  44. bool allow_unmarked_ref = false;
  45. auto Print(llvm::raw_ostream& out) const -> void {
  46. out << "{pattern_id: " << pattern_id << ", scrutinee_id: " << scrutinee_id
  47. << ", allow_unmarked_ref = " << allow_unmarked_ref << "}";
  48. }
  49. };
  50. // Constructs a MatchContext. If `callee_specific_id` is not `None`, this
  51. // pattern match operation is part of implementing the signature of the given
  52. // specific.
  53. explicit MatchContext(MatchKind kind, SemIR::SpecificId callee_specific_id =
  54. SemIR::SpecificId::None)
  55. : kind_(kind), callee_specific_id_(callee_specific_id) {}
  56. // Adds a work item to the stack.
  57. auto AddWork(WorkItem work_item) -> void { stack_.push_back(work_item); }
  58. // Processes all work items on the stack. When performing caller pattern
  59. // matching, returns an inst block with one inst reference for each
  60. // calling-convention argument. When performing callee pattern matching,
  61. // returns an inst block with references to all the emitted BindName insts.
  62. auto DoWork(Context& context) -> SemIR::InstBlockId;
  63. private:
  64. // Emits the pattern-match insts necessary to match the pattern inst
  65. // `entry.pattern_id` against the scrutinee value `entry.scrutinee_id`, and
  66. // adds to `stack_` any work necessary to traverse into its subpatterns. This
  67. // behavior is contingent on the kind of match being performed, as indicated
  68. // by kind_`. For example, when performing a callee pattern match, this does
  69. // not emit insts for patterns on the caller side. However, it still traverses
  70. // into subpatterns if any of their descendants might emit insts.
  71. // TODO: Require that `entry.scrutinee_id` is valid if and only if insts
  72. // should be emitted, once we start emitting `Param` insts in the
  73. // `ParamPattern` case.
  74. auto EmitPatternMatch(Context& context, MatchContext::WorkItem entry) -> void;
  75. // Implementations of `EmitPatternMatch` for particular pattern inst kinds.
  76. // The pattern argument is always equal to
  77. // `context.insts().Get(entry.pattern_id)`.
  78. auto DoEmitPatternMatch(Context& context,
  79. SemIR::AnyBindingPattern binding_pattern,
  80. WorkItem entry) -> void;
  81. auto DoEmitPatternMatch(Context& context,
  82. SemIR::ValueParamPattern param_pattern,
  83. WorkItem entry) -> void;
  84. template <typename RefParamPatternT>
  85. requires std::is_same_v<RefParamPatternT, SemIR::RefParamPattern> ||
  86. std::is_same_v<RefParamPatternT, SemIR::VarParamPattern>
  87. auto DoEmitPatternMatch(Context& context, RefParamPatternT param_pattern,
  88. WorkItem entry) -> void;
  89. auto DoEmitPatternMatch(Context& context,
  90. SemIR::OutParamPattern param_pattern, WorkItem entry)
  91. -> void;
  92. auto DoEmitPatternMatch(Context& context,
  93. SemIR::ReturnSlotPattern return_slot_pattern,
  94. WorkItem entry) -> void;
  95. auto DoEmitPatternMatch(Context& context, SemIR::VarPattern var_pattern,
  96. WorkItem entry) -> void;
  97. auto DoEmitPatternMatch(Context& context, SemIR::TuplePattern tuple_pattern,
  98. WorkItem entry) -> void;
  99. // The stack of work to be processed.
  100. llvm::SmallVector<WorkItem> stack_;
  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 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, SemIR::LocId(region.result_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(region.result_id,
  150. "Control flow expressions are currently only supported inside "
  151. "functions.");
  152. return SemIR::ErrorInst::InstId;
  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,
  165. SemIR::LocId(region.result_id));
  166. return region.result_id;
  167. }
  168. auto MatchContext::DoEmitPatternMatch(Context& context,
  169. SemIR::AnyBindingPattern binding_pattern,
  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. // bind_name_id doesn't have a value in the case of an unused binding pattern,
  183. // but type_expr_region_id should always be populated.
  184. CARBON_CHECK(type_expr_region_id.has_value());
  185. InsertHere(context, type_expr_region_id);
  186. auto value_id = SemIR::InstId::None;
  187. if (kind_ == MatchKind::Local) {
  188. auto conversion_kind = [&binding_pattern]() -> ConversionTarget::Kind {
  189. switch (binding_pattern.kind) {
  190. case SemIR::SymbolicBindingPattern::Kind:
  191. case SemIR::ValueBindingPattern::Kind:
  192. return ConversionTarget::Value;
  193. case SemIR::RefBindingPattern::Kind:
  194. return ConversionTarget::DurableRef;
  195. default:
  196. CARBON_FATAL("Unexpected inst kind {0}", binding_pattern.kind);
  197. }
  198. }();
  199. if (!bind_name_id.has_value()) {
  200. // TODO: Is this appropriate, or should we perform a conversion based on
  201. // whether the `_` binding is a value or ref binding first, and then
  202. // separately discard the initializer for a `_` binding?
  203. conversion_kind = ConversionTarget::Discarded;
  204. }
  205. value_id =
  206. Convert(context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  207. {.kind = conversion_kind,
  208. .type_id = context.insts().Get(bind_name_id).type_id()});
  209. } else {
  210. // In a function call, conversion is handled while matching the enclosing
  211. // `*ParamPattern`.
  212. value_id = entry.scrutinee_id;
  213. }
  214. if (bind_name_id.has_value()) {
  215. auto bind_name = context.insts().GetAs<SemIR::AnyBinding>(bind_name_id);
  216. CARBON_CHECK(!bind_name.value_id.has_value());
  217. bind_name.value_id = value_id;
  218. ReplaceInstBeforeConstantUse(context, bind_name_id, bind_name);
  219. context.inst_block_stack().AddInstId(bind_name_id);
  220. }
  221. }
  222. auto MatchContext::DoEmitPatternMatch(Context& context,
  223. SemIR::ValueParamPattern param_pattern,
  224. WorkItem entry) -> void {
  225. switch (kind_) {
  226. case MatchKind::Caller: {
  227. CARBON_CHECK(
  228. static_cast<size_t>(param_pattern.index.index) == results_.size(),
  229. "Parameters out of order; expecting {0} but got {1}", results_.size(),
  230. param_pattern.index.index);
  231. CARBON_CHECK(entry.scrutinee_id.has_value());
  232. if (entry.scrutinee_id == SemIR::ErrorInst::InstId) {
  233. results_.push_back(SemIR::ErrorInst::InstId);
  234. } else {
  235. results_.push_back(ConvertToValueOfType(
  236. context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  237. ExtractScrutineeType(
  238. context.sem_ir(),
  239. SemIR::GetTypeOfInstInSpecific(
  240. context.sem_ir(), callee_specific_id_, entry.pattern_id))));
  241. }
  242. // Do not traverse farther, because the caller side of the pattern
  243. // ends here.
  244. break;
  245. }
  246. case MatchKind::Callee: {
  247. auto param_id = AddInst<SemIR::ValueParam>(
  248. context, SemIR::LocId(entry.pattern_id),
  249. {.type_id =
  250. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  251. .index = param_pattern.index,
  252. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  253. context.sem_ir(), entry.pattern_id)});
  254. AddWork({.pattern_id = param_pattern.subpattern_id,
  255. .scrutinee_id = param_id});
  256. results_.push_back(param_id);
  257. break;
  258. }
  259. case MatchKind::Local: {
  260. CARBON_FATAL("Found ValueParamPattern during local pattern match");
  261. }
  262. }
  263. }
  264. template <typename RefParamPatternT>
  265. requires std::is_same_v<RefParamPatternT, SemIR::RefParamPattern> ||
  266. std::is_same_v<RefParamPatternT, SemIR::VarParamPattern>
  267. auto MatchContext::DoEmitPatternMatch(Context& context,
  268. RefParamPatternT param_pattern,
  269. WorkItem entry) -> void {
  270. switch (kind_) {
  271. case MatchKind::Caller: {
  272. CARBON_CHECK(
  273. static_cast<size_t>(param_pattern.index.index) == results_.size(),
  274. "Parameters out of order; expecting {0} but got {1}", results_.size(),
  275. param_pattern.index.index);
  276. CARBON_CHECK(entry.scrutinee_id.has_value());
  277. if (std::is_same_v<RefParamPatternT, SemIR::VarParamPattern>) {
  278. results_.push_back(entry.scrutinee_id);
  279. break;
  280. }
  281. auto scrutinee_type_id = ExtractScrutineeType(
  282. context.sem_ir(),
  283. SemIR::GetTypeOfInstInSpecific(context.sem_ir(), callee_specific_id_,
  284. entry.pattern_id));
  285. results_.push_back(Convert(
  286. context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  287. {.kind = entry.allow_unmarked_ref ? ConversionTarget::UnmarkedRefParam
  288. : ConversionTarget::RefParam,
  289. .type_id = scrutinee_type_id}));
  290. // Do not traverse farther, because the caller side of the pattern
  291. // ends here.
  292. break;
  293. }
  294. case MatchKind::Callee: {
  295. auto param_id = AddInst<SemIR::RefParam>(
  296. context, SemIR::LocId(entry.pattern_id),
  297. {.type_id =
  298. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  299. .index = param_pattern.index,
  300. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  301. context.sem_ir(), entry.pattern_id)});
  302. AddWork({.pattern_id = param_pattern.subpattern_id,
  303. .scrutinee_id = param_id});
  304. results_.push_back(param_id);
  305. break;
  306. }
  307. case MatchKind::Local: {
  308. CARBON_FATAL("Found RefParamPattern during local pattern match");
  309. }
  310. }
  311. }
  312. auto MatchContext::DoEmitPatternMatch(Context& context,
  313. SemIR::OutParamPattern param_pattern,
  314. WorkItem entry) -> void {
  315. switch (kind_) {
  316. case MatchKind::Caller: {
  317. CARBON_CHECK(
  318. static_cast<size_t>(param_pattern.index.index) == results_.size(),
  319. "Parameters out of order; expecting {0} but got {1}", results_.size(),
  320. param_pattern.index.index);
  321. CARBON_CHECK(entry.scrutinee_id.has_value());
  322. CARBON_CHECK(
  323. context.insts().Get(entry.scrutinee_id).type_id() ==
  324. ExtractScrutineeType(
  325. context.sem_ir(),
  326. SemIR::GetTypeOfInstInSpecific(
  327. context.sem_ir(), callee_specific_id_, entry.pattern_id)));
  328. results_.push_back(entry.scrutinee_id);
  329. // Do not traverse farther, because the caller side of the pattern
  330. // ends here.
  331. break;
  332. }
  333. case MatchKind::Callee: {
  334. // TODO: Consider ways to address near-duplication with the
  335. // other ParamPattern cases.
  336. auto param_id = AddInst<SemIR::OutParam>(
  337. context, SemIR::LocId(entry.pattern_id),
  338. {.type_id =
  339. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  340. .index = param_pattern.index,
  341. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  342. context.sem_ir(), entry.pattern_id)});
  343. AddWork({.pattern_id = param_pattern.subpattern_id,
  344. .scrutinee_id = param_id});
  345. results_.push_back(param_id);
  346. break;
  347. }
  348. case MatchKind::Local: {
  349. CARBON_FATAL("Found OutParamPattern during local pattern match");
  350. }
  351. }
  352. }
  353. auto MatchContext::DoEmitPatternMatch(
  354. Context& context, SemIR::ReturnSlotPattern return_slot_pattern,
  355. WorkItem entry) -> void {
  356. CARBON_CHECK(kind_ == MatchKind::Callee);
  357. auto type_id =
  358. ExtractScrutineeType(context.sem_ir(), return_slot_pattern.type_id);
  359. auto return_slot_id = AddInst<SemIR::ReturnSlot>(
  360. context, SemIR::LocId(entry.pattern_id),
  361. {.type_id = type_id,
  362. .type_inst_id = context.types().GetInstId(type_id),
  363. .storage_id = entry.scrutinee_id});
  364. bool already_in_lookup =
  365. context.scope_stack()
  366. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  367. .has_value();
  368. CARBON_CHECK(!already_in_lookup);
  369. }
  370. auto MatchContext::DoEmitPatternMatch(Context& context,
  371. SemIR::VarPattern var_pattern,
  372. WorkItem entry) -> void {
  373. auto storage_id = SemIR::InstId::None;
  374. switch (kind_) {
  375. case MatchKind::Callee: {
  376. // We're emitting pattern-match IR for the callee, but we're still on
  377. // the caller side of the pattern, so we traverse without emitting any
  378. // insts.
  379. AddWork({.pattern_id = var_pattern.subpattern_id,
  380. .scrutinee_id = SemIR::InstId::None});
  381. return;
  382. }
  383. case MatchKind::Local: {
  384. // In a `var`/`let` declaration, the `VarStorage` inst is created before
  385. // we start pattern matching.
  386. auto lookup_result = context.var_storage_map().Lookup(entry.pattern_id);
  387. CARBON_CHECK(lookup_result);
  388. storage_id = lookup_result.value();
  389. break;
  390. }
  391. case MatchKind::Caller: {
  392. storage_id = AddInst<SemIR::TemporaryStorage>(
  393. context, SemIR::LocId(entry.pattern_id),
  394. {.type_id =
  395. ExtractScrutineeType(context.sem_ir(), var_pattern.type_id)});
  396. CARBON_CHECK(entry.scrutinee_id.has_value());
  397. break;
  398. }
  399. }
  400. // TODO: Find a more efficient way to put these insts in the global_init
  401. // block (or drop the distinction between the global_init block and the
  402. // file scope?)
  403. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  404. context.global_init().Resume();
  405. }
  406. if (entry.scrutinee_id.has_value()) {
  407. auto init_id = Initialize(context, SemIR::LocId(entry.pattern_id),
  408. storage_id, entry.scrutinee_id);
  409. // If we created a `TemporaryStorage` to hold the var, create a
  410. // corresponding `Temporary` to model that its initialization is complete.
  411. // TODO: If the subpattern is a binding, we may want to destroy the
  412. // parameter variable in the callee instead of the caller so that we can
  413. // support destructive move from it.
  414. if (kind_ == MatchKind::Caller) {
  415. storage_id = AddInstWithCleanup<SemIR::Temporary>(
  416. context, SemIR::LocId(entry.pattern_id),
  417. {.type_id = context.insts().Get(storage_id).type_id(),
  418. .storage_id = storage_id,
  419. .init_id = init_id});
  420. } else {
  421. // TODO: Consider using different instruction kinds for assignment
  422. // versus initialization.
  423. AddInst<SemIR::Assign>(context, SemIR::LocId(entry.pattern_id),
  424. {.lhs_id = storage_id, .rhs_id = init_id});
  425. }
  426. }
  427. AddWork(
  428. {.pattern_id = var_pattern.subpattern_id, .scrutinee_id = storage_id});
  429. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  430. context.global_init().Suspend();
  431. }
  432. }
  433. auto MatchContext::DoEmitPatternMatch(Context& context,
  434. SemIR::TuplePattern tuple_pattern,
  435. WorkItem entry) -> void {
  436. if (tuple_pattern.type_id == SemIR::ErrorInst::TypeId) {
  437. return;
  438. }
  439. auto subpattern_ids = context.inst_blocks().Get(tuple_pattern.elements_id);
  440. auto add_all_subscrutinees =
  441. [&](llvm::ArrayRef<SemIR::InstId> subscrutinee_ids) {
  442. for (auto [subpattern_id, subscrutinee_id] :
  443. llvm::reverse(llvm::zip_equal(subpattern_ids, subscrutinee_ids))) {
  444. AddWork(
  445. {.pattern_id = subpattern_id, .scrutinee_id = subscrutinee_id});
  446. }
  447. };
  448. if (!entry.scrutinee_id.has_value()) {
  449. CARBON_CHECK(kind_ == MatchKind::Callee);
  450. context.TODO(entry.pattern_id,
  451. "Support patterns besides bindings in parameter list");
  452. return;
  453. }
  454. auto scrutinee = context.insts().GetWithLocId(entry.scrutinee_id);
  455. if (auto scrutinee_literal = scrutinee.inst.TryAs<SemIR::TupleLiteral>()) {
  456. auto subscrutinee_ids =
  457. context.inst_blocks().Get(scrutinee_literal->elements_id);
  458. if (subscrutinee_ids.size() != subpattern_ids.size()) {
  459. CARBON_DIAGNOSTIC(TuplePatternSizeDoesntMatchLiteral, Error,
  460. "tuple pattern expects {0} element{0:s}, but tuple "
  461. "literal has {1}",
  462. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  463. context.emitter().Emit(entry.pattern_id,
  464. TuplePatternSizeDoesntMatchLiteral,
  465. subpattern_ids.size(), subscrutinee_ids.size());
  466. return;
  467. }
  468. add_all_subscrutinees(subscrutinee_ids);
  469. return;
  470. }
  471. auto tuple_type_id =
  472. ExtractScrutineeType(context.sem_ir(), tuple_pattern.type_id);
  473. auto converted_scrutinee_id =
  474. ConvertToValueOrRefOfType(context, SemIR::LocId(entry.pattern_id),
  475. entry.scrutinee_id, tuple_type_id);
  476. if (auto scrutinee_value =
  477. context.insts().TryGetAs<SemIR::TupleValue>(converted_scrutinee_id)) {
  478. add_all_subscrutinees(
  479. context.inst_blocks().Get(scrutinee_value->elements_id));
  480. return;
  481. }
  482. auto tuple_type = context.types().GetAs<SemIR::TupleType>(tuple_type_id);
  483. auto element_type_inst_ids =
  484. context.inst_blocks().Get(tuple_type.type_elements_id);
  485. llvm::SmallVector<SemIR::InstId> subscrutinee_ids;
  486. subscrutinee_ids.reserve(element_type_inst_ids.size());
  487. for (auto [i, element_type_id] : llvm::enumerate(
  488. context.types().GetBlockAsTypeIds(element_type_inst_ids))) {
  489. subscrutinee_ids.push_back(
  490. AddInst<SemIR::TupleAccess>(context, scrutinee.loc_id,
  491. {.type_id = element_type_id,
  492. .tuple_id = converted_scrutinee_id,
  493. .index = SemIR::ElementIndex(i)}));
  494. }
  495. add_all_subscrutinees(subscrutinee_ids);
  496. }
  497. auto MatchContext::EmitPatternMatch(Context& context,
  498. MatchContext::WorkItem entry) -> void {
  499. if (entry.pattern_id == SemIR::ErrorInst::InstId) {
  500. return;
  501. }
  502. Diagnostics::AnnotationScope annotate_diagnostics(
  503. &context.emitter(), [&](auto& builder) {
  504. if (kind_ == MatchKind::Caller) {
  505. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  506. "initializing function parameter");
  507. builder.Note(entry.pattern_id, InCallToFunctionParam);
  508. }
  509. });
  510. auto pattern = context.insts().Get(entry.pattern_id);
  511. CARBON_KIND_SWITCH(pattern) {
  512. case SemIR::RefBindingPattern::Kind:
  513. case SemIR::SymbolicBindingPattern::Kind:
  514. case SemIR::ValueBindingPattern::Kind: {
  515. DoEmitPatternMatch(context, pattern.As<SemIR::AnyBindingPattern>(),
  516. entry);
  517. break;
  518. }
  519. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  520. DoEmitPatternMatch(context, param_pattern, entry);
  521. break;
  522. }
  523. case CARBON_KIND(SemIR::RefParamPattern param_pattern): {
  524. DoEmitPatternMatch(context, param_pattern, entry);
  525. break;
  526. }
  527. case CARBON_KIND(SemIR::VarParamPattern param_pattern): {
  528. DoEmitPatternMatch(context, param_pattern, entry);
  529. break;
  530. }
  531. case CARBON_KIND(SemIR::OutParamPattern param_pattern): {
  532. DoEmitPatternMatch(context, param_pattern, entry);
  533. break;
  534. }
  535. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  536. DoEmitPatternMatch(context, return_slot_pattern, entry);
  537. break;
  538. }
  539. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  540. DoEmitPatternMatch(context, var_pattern, entry);
  541. break;
  542. }
  543. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  544. DoEmitPatternMatch(context, tuple_pattern, entry);
  545. break;
  546. }
  547. default: {
  548. CARBON_FATAL("Inst kind not handled: {0}", pattern.kind());
  549. }
  550. }
  551. }
  552. auto CalleePatternMatch(Context& context,
  553. SemIR::InstBlockId implicit_param_patterns_id,
  554. SemIR::InstBlockId param_patterns_id,
  555. SemIR::InstBlockId return_patterns_id)
  556. -> SemIR::InstBlockId {
  557. if (!return_patterns_id.has_value() && !param_patterns_id.has_value() &&
  558. !implicit_param_patterns_id.has_value()) {
  559. return SemIR::InstBlockId::None;
  560. }
  561. MatchContext match(MatchKind::Callee);
  562. // We add work to the stack in reverse so that the results will be produced
  563. // in the original order.
  564. for (auto return_pattern_id :
  565. context.inst_blocks().GetOrEmpty(return_patterns_id)) {
  566. match.AddWork(
  567. {.pattern_id = return_pattern_id, .scrutinee_id = SemIR::InstId::None});
  568. }
  569. if (param_patterns_id.has_value()) {
  570. for (SemIR::InstId inst_id :
  571. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  572. match.AddWork(
  573. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  574. }
  575. }
  576. if (implicit_param_patterns_id.has_value()) {
  577. for (SemIR::InstId inst_id :
  578. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  579. match.AddWork(
  580. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  581. }
  582. }
  583. return match.DoWork(context);
  584. }
  585. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  586. SemIR::InstId self_pattern_id,
  587. SemIR::InstBlockId param_patterns_id,
  588. SemIR::InstBlockId return_patterns_id,
  589. SemIR::InstId self_arg_id,
  590. llvm::ArrayRef<SemIR::InstId> arg_refs,
  591. llvm::ArrayRef<SemIR::InstId> return_arg_ids,
  592. bool is_operator_syntax) -> SemIR::InstBlockId {
  593. MatchContext match(MatchKind::Caller, specific_id);
  594. auto return_patterns = context.inst_blocks().GetOrEmpty(return_patterns_id);
  595. // Track the return storage, if present.
  596. for (auto [return_pattern_id, return_arg_id] :
  597. llvm::zip_equal(return_patterns, return_arg_ids)) {
  598. if (return_arg_id.has_value()) {
  599. match.AddWork(
  600. {.pattern_id = return_pattern_id, .scrutinee_id = return_arg_id});
  601. } else {
  602. CARBON_CHECK(return_arg_ids.size() == 1,
  603. "TODO: do the match even if return_arg_id is None, so that "
  604. "subsequent args are at the right index in the arg block");
  605. }
  606. }
  607. // Check type conversions per-element.
  608. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  609. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  610. match.AddWork({.pattern_id = param_pattern_id,
  611. .scrutinee_id = arg_id,
  612. .allow_unmarked_ref = is_operator_syntax});
  613. }
  614. if (self_pattern_id.has_value()) {
  615. match.AddWork({.pattern_id = self_pattern_id,
  616. .scrutinee_id = self_arg_id,
  617. .allow_unmarked_ref = true});
  618. }
  619. return match.DoWork(context);
  620. }
  621. auto LocalPatternMatch(Context& context, SemIR::InstId pattern_id,
  622. SemIR::InstId scrutinee_id) -> void {
  623. MatchContext match(MatchKind::Local);
  624. match.AddWork({.pattern_id = pattern_id, .scrutinee_id = scrutinee_id});
  625. match.DoWork(context);
  626. }
  627. } // namespace Carbon::Check