pattern_match.cpp 30 KB

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