pattern_match.cpp 30 KB

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