pattern_match.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/pattern_match.h"
  5. #include <functional>
  6. #include <utility>
  7. #include <vector>
  8. #include "llvm/ADT/STLExtras.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/check/context.h"
  12. #include "toolchain/check/control_flow.h"
  13. #include "toolchain/check/convert.h"
  14. #include "toolchain/check/pattern.h"
  15. #include "toolchain/check/type.h"
  16. #include "toolchain/diagnostics/format_providers.h"
  17. #include "toolchain/sem_ir/expr_info.h"
  18. #include "toolchain/sem_ir/pattern.h"
  19. namespace Carbon::Check {
  20. namespace {
  21. // Selects between the different kinds of pattern matching.
  22. enum class MatchKind : uint8_t {
  23. // Caller pattern matching occurs on the caller side of a function call, and
  24. // is responsible for matching the argument expression against the portion
  25. // of the pattern above the ParamPattern insts.
  26. Caller,
  27. // Callee pattern matching occurs in the function decl block, and is
  28. // responsible for matching the function's calling-convention parameters
  29. // against the portion of the pattern below the ParamPattern insts.
  30. Callee,
  31. // Local pattern matching is pattern matching outside of a function call,
  32. // such as in a let/var declaration.
  33. Local,
  34. };
  35. // The collected state of a pattern-matching operation.
  36. class MatchContext {
  37. public:
  38. struct WorkItem : Printable<WorkItem> {
  39. SemIR::InstId pattern_id;
  40. // `None` when processing the callee side.
  41. SemIR::InstId scrutinee_id;
  42. // If true, disables diagnostics that would otherwise require scrutinee_id
  43. // to be tagged with `ref`. Only affects caller pattern matching.
  44. bool allow_unmarked_ref = false;
  45. auto Print(llvm::raw_ostream& out) const -> void {
  46. out << "{pattern_id: " << pattern_id << ", scrutinee_id: " << scrutinee_id
  47. << ", allow_unmarked_ref = " << allow_unmarked_ref << "}";
  48. }
  49. };
  50. // Constructs a MatchContext. If `callee_specific_id` is not `None`, this
  51. // pattern match operation is part of implementing the signature of the given
  52. // specific.
  53. explicit MatchContext(MatchKind kind, SemIR::SpecificId callee_specific_id =
  54. SemIR::SpecificId::None)
  55. : kind_(kind), callee_specific_id_(callee_specific_id) {}
  56. // Adds a work item to the stack.
  57. auto AddWork(WorkItem work_item) -> void { stack_.push_back(work_item); }
  58. // Processes all work items on the stack.
  59. auto DoWork(Context& context) -> void;
  60. // Returns an inst block of references to all the emitted `Call` arguments.
  61. // Can only be called once, at the end of Caller pattern matching.
  62. auto CallerResults(Context& context) && -> SemIR::InstBlockId;
  63. // Returns an inst block of references to all the emitted `Call` params,
  64. // and an inst block of references to the `Call` param patterns they were
  65. // emitted to match. Can only be called once, at the end of Callee pattern
  66. // matching.
  67. auto CalleeResults(Context& context) && -> CalleePatternMatchResults;
  68. ~MatchContext();
  69. private:
  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. 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 in-progress contents of the `Call` arguments block. This is populated
  108. // only when kind_ is Caller.
  109. llvm::SmallVector<SemIR::InstId> call_args_;
  110. // The in-progress contents of the `Call` parameters block. This is populated
  111. // only when kind_ is Callee.
  112. llvm::SmallVector<SemIR::InstId> call_params_;
  113. // The in-progress contents of the `Call` parameter patterns block. This is
  114. // populated only when kind_ is Callee.
  115. llvm::SmallVector<SemIR::InstId> call_param_patterns_;
  116. // The kind of pattern match being performed.
  117. MatchKind kind_;
  118. // The SpecificId of the function being called (if any).
  119. SemIR::SpecificId callee_specific_id_;
  120. };
  121. } // namespace
  122. auto MatchContext::DoWork(Context& context) -> void {
  123. CARBON_CHECK(call_args_.empty() && call_params_.empty() &&
  124. call_param_patterns_.empty());
  125. switch (kind_) {
  126. case MatchKind::Caller: {
  127. call_args_.reserve(stack_.size());
  128. break;
  129. }
  130. case MatchKind::Callee: {
  131. call_param_patterns_.reserve(stack_.size());
  132. call_params_.reserve(stack_.size());
  133. break;
  134. }
  135. case MatchKind::Local:
  136. break;
  137. }
  138. while (!stack_.empty()) {
  139. EmitPatternMatch(context, stack_.pop_back_val());
  140. }
  141. }
  142. auto MatchContext::CallerResults(Context& context) && -> SemIR::InstBlockId {
  143. CARBON_CHECK(kind_ == MatchKind::Caller);
  144. auto block_id = context.inst_blocks().Add(call_args_);
  145. call_args_.clear();
  146. return block_id;
  147. }
  148. auto MatchContext::CalleeResults(
  149. Context& context) && -> CalleePatternMatchResults {
  150. CARBON_CHECK(kind_ == MatchKind::Callee);
  151. CARBON_CHECK(call_params_.size() == call_param_patterns_.size());
  152. auto call_param_patterns_id = context.inst_blocks().Add(call_param_patterns_);
  153. call_param_patterns_.clear();
  154. auto call_params_id = context.inst_blocks().Add(call_params_);
  155. call_params_.clear();
  156. return {.call_param_patterns_id = call_param_patterns_id,
  157. .call_params_id = call_params_id};
  158. }
  159. MatchContext::~MatchContext() {
  160. CARBON_CHECK(call_args_.empty() && call_params_.empty() &&
  161. call_param_patterns_.empty(),
  162. "Unhandled pattern matching outputs. call_args_.size(): {0}, "
  163. "call_params_.size(): {1}, call_param_patterns_.size(): {2}",
  164. call_args_.size(), call_params_.size(),
  165. call_param_patterns_.size());
  166. }
  167. // Inserts the given region into the current code block. If the region
  168. // consists of a single block, this will be implemented as a `splice_block`
  169. // inst. Otherwise, this will end the current block with a branch to the entry
  170. // block of the region, and add future insts to a new block which is the
  171. // immediate successor of the region's exit block. As a result, this cannot be
  172. // called more than once for the same region.
  173. static auto InsertHere(Context& context, SemIR::ExprRegionId region_id)
  174. -> SemIR::InstId {
  175. auto region = context.sem_ir().expr_regions().Get(region_id);
  176. auto exit_block = context.inst_blocks().Get(region.block_ids.back());
  177. if (region.block_ids.size() == 1) {
  178. // TODO: Is it possible to avoid leaving an "orphan" block in the IR in the
  179. // first two cases?
  180. if (exit_block.empty()) {
  181. return region.result_id;
  182. }
  183. if (exit_block.size() == 1) {
  184. context.inst_block_stack().AddInstId(exit_block.front());
  185. return region.result_id;
  186. }
  187. return AddInst<SemIR::SpliceBlock>(
  188. context, SemIR::LocId(region.result_id),
  189. {.type_id = context.insts().Get(region.result_id).type_id(),
  190. .block_id = region.block_ids.front(),
  191. .result_id = region.result_id});
  192. }
  193. if (context.region_stack().empty()) {
  194. context.TODO(region.result_id,
  195. "Control flow expressions are currently only supported inside "
  196. "functions.");
  197. return SemIR::ErrorInst::InstId;
  198. }
  199. AddInst(context, SemIR::LocIdAndInst::NoLoc<SemIR::Branch>(
  200. {.target_id = region.block_ids.front()}));
  201. context.inst_block_stack().Pop();
  202. // TODO: this will cumulatively cost O(MN) running time for M blocks
  203. // at the Nth level of the stack. Figure out how to do better.
  204. context.region_stack().AddToRegion(region.block_ids);
  205. auto resume_with_block_id =
  206. context.insts().GetAs<SemIR::Branch>(exit_block.back()).target_id;
  207. CARBON_CHECK(context.inst_blocks().GetOrEmpty(resume_with_block_id).empty());
  208. context.inst_block_stack().Push(resume_with_block_id);
  209. context.region_stack().AddToRegion(resume_with_block_id,
  210. SemIR::LocId(region.result_id));
  211. return region.result_id;
  212. }
  213. auto MatchContext::DoEmitPatternMatch(Context& context,
  214. SemIR::AnyBindingPattern binding_pattern,
  215. MatchContext::WorkItem entry) -> void {
  216. if (kind_ == MatchKind::Caller) {
  217. CARBON_CHECK(
  218. binding_pattern.kind == SemIR::SymbolicBindingPattern::Kind,
  219. "Found named runtime binding pattern during caller pattern match");
  220. return;
  221. }
  222. // We're logically consuming this map entry, so we invalidate it in order
  223. // to avoid accidentally consuming it twice.
  224. auto [bind_name_id, type_expr_region_id] =
  225. std::exchange(context.bind_name_map().Lookup(entry.pattern_id).value(),
  226. {.bind_name_id = SemIR::InstId::None,
  227. .type_expr_region_id = SemIR::ExprRegionId::None});
  228. // bind_name_id doesn't have a value in the case of an unused binding pattern,
  229. // but type_expr_region_id should always be populated.
  230. CARBON_CHECK(type_expr_region_id.has_value());
  231. InsertHere(context, type_expr_region_id);
  232. auto value_id = SemIR::InstId::None;
  233. if (kind_ == MatchKind::Local) {
  234. auto conversion_kind = [&binding_pattern]() -> ConversionTarget::Kind {
  235. switch (binding_pattern.kind) {
  236. case SemIR::SymbolicBindingPattern::Kind:
  237. case SemIR::ValueBindingPattern::Kind:
  238. return ConversionTarget::Value;
  239. case SemIR::RefBindingPattern::Kind:
  240. return ConversionTarget::DurableRef;
  241. default:
  242. CARBON_FATAL("Unexpected inst kind {0}", binding_pattern.kind);
  243. }
  244. }();
  245. if (!bind_name_id.has_value()) {
  246. // TODO: Is this appropriate, or should we perform a conversion based on
  247. // whether the `_` binding is a value or ref binding first, and then
  248. // separately discard the initializer for a `_` binding?
  249. conversion_kind = ConversionTarget::Discarded;
  250. }
  251. value_id =
  252. Convert(context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  253. {.kind = conversion_kind,
  254. .type_id = context.insts().Get(bind_name_id).type_id()});
  255. } else {
  256. // In a function call, conversion is handled while matching the enclosing
  257. // `*ParamPattern`.
  258. value_id = entry.scrutinee_id;
  259. }
  260. if (bind_name_id.has_value()) {
  261. auto bind_name = context.insts().GetAs<SemIR::AnyBinding>(bind_name_id);
  262. CARBON_CHECK(!bind_name.value_id.has_value());
  263. bind_name.value_id = value_id;
  264. ReplaceInstBeforeConstantUse(context, bind_name_id, bind_name);
  265. context.inst_block_stack().AddInstId(bind_name_id);
  266. }
  267. }
  268. auto MatchContext::DoEmitPatternMatch(Context& context,
  269. SemIR::ValueParamPattern param_pattern,
  270. WorkItem entry) -> void {
  271. switch (kind_) {
  272. case MatchKind::Caller: {
  273. CARBON_CHECK(
  274. static_cast<size_t>(param_pattern.index.index) == call_args_.size(),
  275. "Parameters out of order; expecting {0} but got {1}",
  276. call_args_.size(), param_pattern.index.index);
  277. CARBON_CHECK(entry.scrutinee_id.has_value());
  278. if (entry.scrutinee_id == SemIR::ErrorInst::InstId) {
  279. call_args_.push_back(SemIR::ErrorInst::InstId);
  280. } else {
  281. call_args_.push_back(ConvertToValueOfType(
  282. context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  283. ExtractScrutineeType(
  284. context.sem_ir(),
  285. SemIR::GetTypeOfInstInSpecific(
  286. context.sem_ir(), callee_specific_id_, entry.pattern_id))));
  287. }
  288. // Do not traverse farther, because the caller side of the pattern
  289. // ends here.
  290. break;
  291. }
  292. case MatchKind::Callee: {
  293. auto param_id = AddInst<SemIR::ValueParam>(
  294. context, SemIR::LocId(entry.pattern_id),
  295. {.type_id =
  296. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  297. .index = param_pattern.index,
  298. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  299. context.sem_ir(), entry.pattern_id)});
  300. AddWork({.pattern_id = param_pattern.subpattern_id,
  301. .scrutinee_id = param_id});
  302. call_params_.push_back(param_id);
  303. call_param_patterns_.push_back(entry.pattern_id);
  304. break;
  305. }
  306. case MatchKind::Local: {
  307. CARBON_FATAL("Found ValueParamPattern during local pattern match");
  308. }
  309. }
  310. }
  311. template <typename RefParamPatternT>
  312. requires std::is_same_v<RefParamPatternT, SemIR::RefParamPattern> ||
  313. std::is_same_v<RefParamPatternT, SemIR::VarParamPattern>
  314. auto MatchContext::DoEmitPatternMatch(Context& context,
  315. RefParamPatternT param_pattern,
  316. WorkItem entry) -> void {
  317. switch (kind_) {
  318. case MatchKind::Caller: {
  319. CARBON_CHECK(
  320. static_cast<size_t>(param_pattern.index.index) == call_args_.size(),
  321. "Parameters out of order; expecting {0} but got {1}",
  322. call_args_.size(), param_pattern.index.index);
  323. CARBON_CHECK(entry.scrutinee_id.has_value());
  324. if (std::is_same_v<RefParamPatternT, SemIR::VarParamPattern>) {
  325. call_args_.push_back(entry.scrutinee_id);
  326. break;
  327. }
  328. auto scrutinee_type_id = ExtractScrutineeType(
  329. context.sem_ir(),
  330. SemIR::GetTypeOfInstInSpecific(context.sem_ir(), callee_specific_id_,
  331. entry.pattern_id));
  332. call_args_.push_back(Convert(
  333. context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  334. {.kind = entry.allow_unmarked_ref ? ConversionTarget::UnmarkedRefParam
  335. : ConversionTarget::RefParam,
  336. .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. auto param_id = AddInst<SemIR::RefParam>(
  343. context, SemIR::LocId(entry.pattern_id),
  344. {.type_id =
  345. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  346. .index = param_pattern.index,
  347. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  348. context.sem_ir(), entry.pattern_id)});
  349. AddWork({.pattern_id = param_pattern.subpattern_id,
  350. .scrutinee_id = param_id});
  351. call_params_.push_back(param_id);
  352. call_param_patterns_.push_back(entry.pattern_id);
  353. break;
  354. }
  355. case MatchKind::Local: {
  356. CARBON_FATAL("Found RefParamPattern during local pattern match");
  357. }
  358. }
  359. }
  360. auto MatchContext::DoEmitPatternMatch(Context& context,
  361. SemIR::OutParamPattern param_pattern,
  362. WorkItem entry) -> void {
  363. switch (kind_) {
  364. case MatchKind::Caller: {
  365. CARBON_CHECK(
  366. static_cast<size_t>(param_pattern.index.index) == call_args_.size(),
  367. "Parameters out of order; expecting {0} but got {1}",
  368. call_args_.size(), param_pattern.index.index);
  369. CARBON_CHECK(entry.scrutinee_id.has_value());
  370. CARBON_CHECK(
  371. context.insts().Get(entry.scrutinee_id).type_id() ==
  372. ExtractScrutineeType(
  373. context.sem_ir(),
  374. SemIR::GetTypeOfInstInSpecific(
  375. context.sem_ir(), callee_specific_id_, entry.pattern_id)));
  376. call_args_.push_back(entry.scrutinee_id);
  377. // Do not traverse farther, because the caller side of the pattern
  378. // ends here.
  379. break;
  380. }
  381. case MatchKind::Callee: {
  382. // TODO: Consider ways to address near-duplication with the
  383. // other ParamPattern cases.
  384. auto param_id = AddInst<SemIR::OutParam>(
  385. context, SemIR::LocId(entry.pattern_id),
  386. {.type_id =
  387. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  388. .index = param_pattern.index,
  389. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  390. context.sem_ir(), entry.pattern_id)});
  391. AddWork({.pattern_id = param_pattern.subpattern_id,
  392. .scrutinee_id = param_id});
  393. call_param_patterns_.push_back(entry.pattern_id);
  394. call_params_.push_back(param_id);
  395. break;
  396. }
  397. case MatchKind::Local: {
  398. CARBON_FATAL("Found OutParamPattern during local pattern match");
  399. }
  400. }
  401. }
  402. auto MatchContext::DoEmitPatternMatch(
  403. Context& context, SemIR::ReturnSlotPattern return_slot_pattern,
  404. WorkItem entry) -> void {
  405. CARBON_CHECK(kind_ == MatchKind::Callee);
  406. auto type_id =
  407. ExtractScrutineeType(context.sem_ir(), return_slot_pattern.type_id);
  408. auto return_slot_id = AddInst<SemIR::ReturnSlot>(
  409. context, SemIR::LocId(entry.pattern_id),
  410. {.type_id = type_id,
  411. .type_inst_id = context.types().GetInstId(type_id),
  412. .storage_id = entry.scrutinee_id});
  413. bool already_in_lookup =
  414. context.scope_stack()
  415. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  416. .has_value();
  417. CARBON_CHECK(!already_in_lookup);
  418. }
  419. auto MatchContext::DoEmitPatternMatch(Context& context,
  420. SemIR::VarPattern var_pattern,
  421. WorkItem entry) -> void {
  422. auto storage_id = SemIR::InstId::None;
  423. switch (kind_) {
  424. case MatchKind::Callee: {
  425. // We're emitting pattern-match IR for the callee, but we're still on
  426. // the caller side of the pattern, so we traverse without emitting any
  427. // insts.
  428. AddWork({.pattern_id = var_pattern.subpattern_id,
  429. .scrutinee_id = SemIR::InstId::None});
  430. return;
  431. }
  432. case MatchKind::Local: {
  433. // In a `var`/`let` declaration, the `VarStorage` inst is created before
  434. // we start pattern matching.
  435. auto lookup_result = context.var_storage_map().Lookup(entry.pattern_id);
  436. CARBON_CHECK(lookup_result);
  437. storage_id = lookup_result.value();
  438. break;
  439. }
  440. case MatchKind::Caller: {
  441. storage_id = AddInst<SemIR::TemporaryStorage>(
  442. context, SemIR::LocId(entry.pattern_id),
  443. {.type_id =
  444. ExtractScrutineeType(context.sem_ir(), var_pattern.type_id)});
  445. CARBON_CHECK(entry.scrutinee_id.has_value());
  446. break;
  447. }
  448. }
  449. // TODO: Find a more efficient way to put these insts in the global_init
  450. // block (or drop the distinction between the global_init block and the
  451. // file scope?)
  452. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  453. context.global_init().Resume();
  454. }
  455. if (entry.scrutinee_id.has_value()) {
  456. auto init_id = Initialize(context, SemIR::LocId(entry.pattern_id),
  457. storage_id, entry.scrutinee_id);
  458. // If we created a `TemporaryStorage` to hold the var, create a
  459. // corresponding `Temporary` to model that its initialization is complete.
  460. // TODO: If the subpattern is a binding, we may want to destroy the
  461. // parameter variable in the callee instead of the caller so that we can
  462. // support destructive move from it.
  463. if (kind_ == MatchKind::Caller) {
  464. storage_id = AddInstWithCleanup<SemIR::Temporary>(
  465. context, SemIR::LocId(entry.pattern_id),
  466. {.type_id = context.insts().Get(storage_id).type_id(),
  467. .storage_id = storage_id,
  468. .init_id = init_id});
  469. } else {
  470. // TODO: Consider using different instruction kinds for assignment
  471. // versus initialization.
  472. AddInst<SemIR::Assign>(context, SemIR::LocId(entry.pattern_id),
  473. {.lhs_id = storage_id, .rhs_id = init_id});
  474. }
  475. }
  476. AddWork(
  477. {.pattern_id = var_pattern.subpattern_id, .scrutinee_id = storage_id});
  478. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  479. context.global_init().Suspend();
  480. }
  481. }
  482. auto MatchContext::DoEmitPatternMatch(Context& context,
  483. SemIR::TuplePattern tuple_pattern,
  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_equal(subpattern_ids, subscrutinee_ids))) {
  493. AddWork(
  494. {.pattern_id = subpattern_id, .scrutinee_id = subscrutinee_id});
  495. }
  496. };
  497. if (!entry.scrutinee_id.has_value()) {
  498. CARBON_CHECK(kind_ == MatchKind::Callee);
  499. // If we don't have a scrutinee yet, we're still on the caller side of the
  500. // pattern, so the subpatterns don't have a scrutinee either.
  501. for (auto subpattern_id : llvm::reverse(subpattern_ids)) {
  502. AddWork(
  503. {.pattern_id = subpattern_id, .scrutinee_id = SemIR::InstId::None});
  504. }
  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::ValueParamPattern param_pattern): {
  573. DoEmitPatternMatch(context, param_pattern, entry);
  574. break;
  575. }
  576. case CARBON_KIND(SemIR::RefParamPattern param_pattern): {
  577. DoEmitPatternMatch(context, param_pattern, entry);
  578. break;
  579. }
  580. case CARBON_KIND(SemIR::VarParamPattern param_pattern): {
  581. DoEmitPatternMatch(context, param_pattern, entry);
  582. break;
  583. }
  584. case CARBON_KIND(SemIR::OutParamPattern param_pattern): {
  585. DoEmitPatternMatch(context, param_pattern, entry);
  586. break;
  587. }
  588. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  589. DoEmitPatternMatch(context, return_slot_pattern, entry);
  590. break;
  591. }
  592. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  593. DoEmitPatternMatch(context, var_pattern, entry);
  594. break;
  595. }
  596. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  597. DoEmitPatternMatch(context, tuple_pattern, entry);
  598. break;
  599. }
  600. default: {
  601. CARBON_FATAL("Inst kind not handled: {0}", pattern.kind());
  602. }
  603. }
  604. }
  605. auto CalleePatternMatch(Context& context,
  606. SemIR::InstBlockId implicit_param_patterns_id,
  607. SemIR::InstBlockId param_patterns_id,
  608. SemIR::InstBlockId return_patterns_id)
  609. -> CalleePatternMatchResults {
  610. if (!return_patterns_id.has_value() && !param_patterns_id.has_value() &&
  611. !implicit_param_patterns_id.has_value()) {
  612. return {.call_param_patterns_id = SemIR::InstBlockId::None,
  613. .call_params_id = SemIR::InstBlockId::None};
  614. }
  615. MatchContext match(MatchKind::Callee);
  616. // We add work to the stack in reverse so that the results will be produced
  617. // in the original order.
  618. for (auto return_pattern_id :
  619. context.inst_blocks().GetOrEmpty(return_patterns_id)) {
  620. match.AddWork(
  621. {.pattern_id = return_pattern_id, .scrutinee_id = SemIR::InstId::None});
  622. }
  623. if (param_patterns_id.has_value()) {
  624. for (SemIR::InstId inst_id :
  625. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  626. match.AddWork(
  627. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  628. }
  629. }
  630. if (implicit_param_patterns_id.has_value()) {
  631. for (SemIR::InstId inst_id :
  632. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  633. match.AddWork(
  634. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  635. }
  636. }
  637. match.DoWork(context);
  638. return std::move(match).CalleeResults(context);
  639. }
  640. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  641. SemIR::InstId self_pattern_id,
  642. SemIR::InstBlockId param_patterns_id,
  643. SemIR::InstBlockId return_patterns_id,
  644. SemIR::InstId self_arg_id,
  645. llvm::ArrayRef<SemIR::InstId> arg_refs,
  646. llvm::ArrayRef<SemIR::InstId> return_arg_ids,
  647. bool is_operator_syntax) -> SemIR::InstBlockId {
  648. MatchContext match(MatchKind::Caller, specific_id);
  649. auto return_patterns = context.inst_blocks().GetOrEmpty(return_patterns_id);
  650. // Track the return storage, if present.
  651. for (auto [return_pattern_id, return_arg_id] :
  652. llvm::zip_equal(return_patterns, return_arg_ids)) {
  653. if (return_arg_id.has_value()) {
  654. match.AddWork(
  655. {.pattern_id = return_pattern_id, .scrutinee_id = return_arg_id});
  656. } else {
  657. CARBON_CHECK(return_arg_ids.size() == 1,
  658. "TODO: do the match even if return_arg_id is None, so that "
  659. "subsequent args are at the right index in the arg block");
  660. }
  661. }
  662. // Check type conversions per-element.
  663. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  664. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  665. match.AddWork({.pattern_id = param_pattern_id,
  666. .scrutinee_id = arg_id,
  667. .allow_unmarked_ref = is_operator_syntax});
  668. }
  669. if (self_pattern_id.has_value()) {
  670. match.AddWork({.pattern_id = self_pattern_id,
  671. .scrutinee_id = self_arg_id,
  672. .allow_unmarked_ref = true});
  673. }
  674. match.DoWork(context);
  675. return std::move(match).CallerResults(context);
  676. }
  677. auto LocalPatternMatch(Context& context, SemIR::InstId pattern_id,
  678. SemIR::InstId scrutinee_id) -> void {
  679. MatchContext match(MatchKind::Local);
  680. match.AddWork({.pattern_id = pattern_id, .scrutinee_id = scrutinee_id});
  681. match.DoWork(context);
  682. }
  683. } // namespace Carbon::Check