pattern_match.cpp 30 KB

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