pattern_match.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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(binding_pattern.kind == SemIR::SymbolicBindingPattern::Kind,
  218. "Found runtime binding pattern during caller pattern match");
  219. return;
  220. }
  221. // We're logically consuming this map entry, so we invalidate it in order
  222. // to avoid accidentally consuming it twice.
  223. auto [bind_name_id, type_expr_region_id] =
  224. std::exchange(context.bind_name_map().Lookup(entry.pattern_id).value(),
  225. {.bind_name_id = SemIR::InstId::None,
  226. .type_expr_region_id = SemIR::ExprRegionId::None});
  227. // bind_name_id doesn't have a value in the case of an unused binding pattern,
  228. // but type_expr_region_id should always be populated.
  229. CARBON_CHECK(type_expr_region_id.has_value());
  230. InsertHere(context, type_expr_region_id);
  231. auto value_id = SemIR::InstId::None;
  232. if (kind_ == MatchKind::Local) {
  233. auto conversion_kind = [&binding_pattern]() -> ConversionTarget::Kind {
  234. switch (binding_pattern.kind) {
  235. case SemIR::SymbolicBindingPattern::Kind:
  236. case SemIR::ValueBindingPattern::Kind:
  237. return ConversionTarget::Value;
  238. case SemIR::RefBindingPattern::Kind:
  239. return ConversionTarget::DurableRef;
  240. default:
  241. CARBON_FATAL("Unexpected inst kind {0}", binding_pattern.kind);
  242. }
  243. }();
  244. if (!bind_name_id.has_value()) {
  245. // TODO: Is this appropriate, or should we perform a conversion based on
  246. // whether the `_` binding is a value or ref binding first, and then
  247. // separately discard the initializer for a `_` binding?
  248. conversion_kind = ConversionTarget::Discarded;
  249. }
  250. value_id =
  251. Convert(context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  252. {.kind = conversion_kind,
  253. .type_id = context.insts().Get(bind_name_id).type_id()});
  254. } else {
  255. // In a function call, conversion is handled while matching the enclosing
  256. // `*ParamPattern`.
  257. value_id = entry.scrutinee_id;
  258. }
  259. if (bind_name_id.has_value()) {
  260. auto bind_name = context.insts().GetAs<SemIR::AnyBinding>(bind_name_id);
  261. CARBON_CHECK(!bind_name.value_id.has_value());
  262. bind_name.value_id = value_id;
  263. ReplaceInstBeforeConstantUse(context, bind_name_id, bind_name);
  264. context.inst_block_stack().AddInstId(bind_name_id);
  265. }
  266. }
  267. auto MatchContext::DoEmitPatternMatch(Context& context,
  268. SemIR::ValueParamPattern param_pattern,
  269. WorkItem entry) -> void {
  270. switch (kind_) {
  271. case MatchKind::Caller: {
  272. CARBON_CHECK(
  273. static_cast<size_t>(param_pattern.index.index) == call_args_.size(),
  274. "Parameters out of order; expecting {0} but got {1}",
  275. call_args_.size(), param_pattern.index.index);
  276. CARBON_CHECK(entry.scrutinee_id.has_value());
  277. if (entry.scrutinee_id == SemIR::ErrorInst::InstId) {
  278. call_args_.push_back(SemIR::ErrorInst::InstId);
  279. } else {
  280. call_args_.push_back(ConvertToValueOfType(
  281. context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  282. ExtractScrutineeType(
  283. context.sem_ir(),
  284. SemIR::GetTypeOfInstInSpecific(
  285. context.sem_ir(), callee_specific_id_, entry.pattern_id))));
  286. }
  287. // Do not traverse farther, because the caller side of the pattern
  288. // ends here.
  289. break;
  290. }
  291. case MatchKind::Callee: {
  292. auto param_id = AddInst<SemIR::ValueParam>(
  293. context, SemIR::LocId(entry.pattern_id),
  294. {.type_id =
  295. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  296. .index = param_pattern.index,
  297. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  298. context.sem_ir(), entry.pattern_id)});
  299. AddWork({.pattern_id = param_pattern.subpattern_id,
  300. .scrutinee_id = param_id});
  301. call_params_.push_back(param_id);
  302. call_param_patterns_.push_back(entry.pattern_id);
  303. break;
  304. }
  305. case MatchKind::Local: {
  306. CARBON_FATAL("Found ValueParamPattern during local pattern match");
  307. }
  308. }
  309. }
  310. template <typename RefParamPatternT>
  311. requires std::is_same_v<RefParamPatternT, SemIR::RefParamPattern> ||
  312. std::is_same_v<RefParamPatternT, SemIR::VarParamPattern>
  313. auto MatchContext::DoEmitPatternMatch(Context& context,
  314. RefParamPatternT param_pattern,
  315. WorkItem entry) -> void {
  316. switch (kind_) {
  317. case MatchKind::Caller: {
  318. CARBON_CHECK(
  319. static_cast<size_t>(param_pattern.index.index) == call_args_.size(),
  320. "Parameters out of order; expecting {0} but got {1}",
  321. call_args_.size(), param_pattern.index.index);
  322. CARBON_CHECK(entry.scrutinee_id.has_value());
  323. if (std::is_same_v<RefParamPatternT, SemIR::VarParamPattern>) {
  324. call_args_.push_back(entry.scrutinee_id);
  325. break;
  326. }
  327. auto scrutinee_type_id = ExtractScrutineeType(
  328. context.sem_ir(),
  329. SemIR::GetTypeOfInstInSpecific(context.sem_ir(), callee_specific_id_,
  330. entry.pattern_id));
  331. call_args_.push_back(Convert(
  332. context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  333. {.kind = entry.allow_unmarked_ref ? ConversionTarget::UnmarkedRefParam
  334. : ConversionTarget::RefParam,
  335. .type_id = scrutinee_type_id}));
  336. // Do not traverse farther, because the caller side of the pattern
  337. // ends here.
  338. break;
  339. }
  340. case MatchKind::Callee: {
  341. auto param_id = AddInst<SemIR::RefParam>(
  342. context, SemIR::LocId(entry.pattern_id),
  343. {.type_id =
  344. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  345. .index = param_pattern.index,
  346. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  347. context.sem_ir(), entry.pattern_id)});
  348. AddWork({.pattern_id = param_pattern.subpattern_id,
  349. .scrutinee_id = param_id});
  350. call_params_.push_back(param_id);
  351. call_param_patterns_.push_back(entry.pattern_id);
  352. break;
  353. }
  354. case MatchKind::Local: {
  355. CARBON_FATAL("Found RefParamPattern during local pattern match");
  356. }
  357. }
  358. }
  359. auto MatchContext::DoEmitPatternMatch(Context& context,
  360. SemIR::OutParamPattern param_pattern,
  361. WorkItem entry) -> void {
  362. switch (kind_) {
  363. case MatchKind::Caller: {
  364. CARBON_CHECK(
  365. static_cast<size_t>(param_pattern.index.index) == call_args_.size(),
  366. "Parameters out of order; expecting {0} but got {1}",
  367. call_args_.size(), param_pattern.index.index);
  368. CARBON_CHECK(entry.scrutinee_id.has_value());
  369. CARBON_CHECK(
  370. context.insts().Get(entry.scrutinee_id).type_id() ==
  371. ExtractScrutineeType(
  372. context.sem_ir(),
  373. SemIR::GetTypeOfInstInSpecific(
  374. context.sem_ir(), callee_specific_id_, entry.pattern_id)));
  375. call_args_.push_back(entry.scrutinee_id);
  376. // Do not traverse farther, because the caller side of the pattern
  377. // ends here.
  378. break;
  379. }
  380. case MatchKind::Callee: {
  381. // TODO: Consider ways to address near-duplication with the
  382. // other ParamPattern cases.
  383. auto param_id = AddInst<SemIR::OutParam>(
  384. context, SemIR::LocId(entry.pattern_id),
  385. {.type_id =
  386. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  387. .index = param_pattern.index,
  388. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  389. context.sem_ir(), entry.pattern_id)});
  390. AddWork({.pattern_id = param_pattern.subpattern_id,
  391. .scrutinee_id = param_id});
  392. call_param_patterns_.push_back(entry.pattern_id);
  393. call_params_.push_back(param_id);
  394. break;
  395. }
  396. case MatchKind::Local: {
  397. CARBON_FATAL("Found OutParamPattern during local pattern match");
  398. }
  399. }
  400. }
  401. auto MatchContext::DoEmitPatternMatch(
  402. Context& context, SemIR::ReturnSlotPattern return_slot_pattern,
  403. WorkItem entry) -> void {
  404. CARBON_CHECK(kind_ == MatchKind::Callee);
  405. auto type_id =
  406. ExtractScrutineeType(context.sem_ir(), return_slot_pattern.type_id);
  407. auto return_slot_id = AddInst<SemIR::ReturnSlot>(
  408. context, SemIR::LocId(entry.pattern_id),
  409. {.type_id = type_id,
  410. .type_inst_id = context.types().GetInstId(type_id),
  411. .storage_id = entry.scrutinee_id});
  412. bool already_in_lookup =
  413. context.scope_stack()
  414. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  415. .has_value();
  416. CARBON_CHECK(!already_in_lookup);
  417. }
  418. auto MatchContext::DoEmitPatternMatch(Context& context,
  419. SemIR::VarPattern var_pattern,
  420. WorkItem entry) -> void {
  421. auto storage_id = SemIR::InstId::None;
  422. switch (kind_) {
  423. case MatchKind::Callee: {
  424. // We're emitting pattern-match IR for the callee, but we're still on
  425. // the caller side of the pattern, so we traverse without emitting any
  426. // insts.
  427. AddWork({.pattern_id = var_pattern.subpattern_id,
  428. .scrutinee_id = SemIR::InstId::None});
  429. return;
  430. }
  431. case MatchKind::Local: {
  432. // In a `var`/`let` declaration, the `VarStorage` inst is created before
  433. // we start pattern matching.
  434. auto lookup_result = context.var_storage_map().Lookup(entry.pattern_id);
  435. CARBON_CHECK(lookup_result);
  436. storage_id = lookup_result.value();
  437. break;
  438. }
  439. case MatchKind::Caller: {
  440. storage_id = AddInst<SemIR::TemporaryStorage>(
  441. context, SemIR::LocId(entry.pattern_id),
  442. {.type_id =
  443. ExtractScrutineeType(context.sem_ir(), var_pattern.type_id)});
  444. CARBON_CHECK(entry.scrutinee_id.has_value());
  445. break;
  446. }
  447. }
  448. // TODO: Find a more efficient way to put these insts in the global_init
  449. // block (or drop the distinction between the global_init block and the
  450. // file scope?)
  451. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  452. context.global_init().Resume();
  453. }
  454. if (entry.scrutinee_id.has_value()) {
  455. auto init_id = Initialize(context, SemIR::LocId(entry.pattern_id),
  456. storage_id, entry.scrutinee_id);
  457. // If we created a `TemporaryStorage` to hold the var, create a
  458. // corresponding `Temporary` to model that its initialization is complete.
  459. // TODO: If the subpattern is a binding, we may want to destroy the
  460. // parameter variable in the callee instead of the caller so that we can
  461. // support destructive move from it.
  462. if (kind_ == MatchKind::Caller) {
  463. storage_id = AddInstWithCleanup<SemIR::Temporary>(
  464. context, SemIR::LocId(entry.pattern_id),
  465. {.type_id = context.insts().Get(storage_id).type_id(),
  466. .storage_id = storage_id,
  467. .init_id = init_id});
  468. } else {
  469. // TODO: Consider using different instruction kinds for assignment
  470. // versus initialization.
  471. AddInst<SemIR::Assign>(context, SemIR::LocId(entry.pattern_id),
  472. {.lhs_id = storage_id, .rhs_id = init_id});
  473. }
  474. }
  475. AddWork(
  476. {.pattern_id = var_pattern.subpattern_id, .scrutinee_id = storage_id});
  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. WorkItem entry) -> void {
  484. if (tuple_pattern.type_id == SemIR::ErrorInst::TypeId) {
  485. return;
  486. }
  487. auto subpattern_ids = context.inst_blocks().Get(tuple_pattern.elements_id);
  488. auto add_all_subscrutinees =
  489. [&](llvm::ArrayRef<SemIR::InstId> subscrutinee_ids) {
  490. for (auto [subpattern_id, subscrutinee_id] :
  491. llvm::reverse(llvm::zip_equal(subpattern_ids, subscrutinee_ids))) {
  492. AddWork(
  493. {.pattern_id = subpattern_id, .scrutinee_id = subscrutinee_id});
  494. }
  495. };
  496. if (!entry.scrutinee_id.has_value()) {
  497. CARBON_CHECK(kind_ == MatchKind::Callee);
  498. context.TODO(entry.pattern_id,
  499. "Support patterns besides bindings in parameter list");
  500. return;
  501. }
  502. auto scrutinee = context.insts().GetWithLocId(entry.scrutinee_id);
  503. if (auto scrutinee_literal = scrutinee.inst.TryAs<SemIR::TupleLiteral>()) {
  504. auto subscrutinee_ids =
  505. context.inst_blocks().Get(scrutinee_literal->elements_id);
  506. if (subscrutinee_ids.size() != subpattern_ids.size()) {
  507. CARBON_DIAGNOSTIC(TuplePatternSizeDoesntMatchLiteral, Error,
  508. "tuple pattern expects {0} element{0:s}, but tuple "
  509. "literal has {1}",
  510. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  511. context.emitter().Emit(entry.pattern_id,
  512. TuplePatternSizeDoesntMatchLiteral,
  513. subpattern_ids.size(), subscrutinee_ids.size());
  514. return;
  515. }
  516. add_all_subscrutinees(subscrutinee_ids);
  517. return;
  518. }
  519. auto tuple_type_id =
  520. ExtractScrutineeType(context.sem_ir(), tuple_pattern.type_id);
  521. auto converted_scrutinee_id =
  522. ConvertToValueOrRefOfType(context, SemIR::LocId(entry.pattern_id),
  523. entry.scrutinee_id, tuple_type_id);
  524. if (auto scrutinee_value =
  525. context.insts().TryGetAs<SemIR::TupleValue>(converted_scrutinee_id)) {
  526. add_all_subscrutinees(
  527. context.inst_blocks().Get(scrutinee_value->elements_id));
  528. return;
  529. }
  530. auto tuple_type = context.types().GetAs<SemIR::TupleType>(tuple_type_id);
  531. auto element_type_inst_ids =
  532. context.inst_blocks().Get(tuple_type.type_elements_id);
  533. llvm::SmallVector<SemIR::InstId> subscrutinee_ids;
  534. subscrutinee_ids.reserve(element_type_inst_ids.size());
  535. for (auto [i, element_type_id] : llvm::enumerate(
  536. context.types().GetBlockAsTypeIds(element_type_inst_ids))) {
  537. subscrutinee_ids.push_back(
  538. AddInst<SemIR::TupleAccess>(context, scrutinee.loc_id,
  539. {.type_id = element_type_id,
  540. .tuple_id = converted_scrutinee_id,
  541. .index = SemIR::ElementIndex(i)}));
  542. }
  543. add_all_subscrutinees(subscrutinee_ids);
  544. }
  545. auto MatchContext::EmitPatternMatch(Context& context,
  546. MatchContext::WorkItem entry) -> void {
  547. if (entry.pattern_id == SemIR::ErrorInst::InstId) {
  548. return;
  549. }
  550. Diagnostics::AnnotationScope annotate_diagnostics(
  551. &context.emitter(), [&](auto& builder) {
  552. if (kind_ == MatchKind::Caller) {
  553. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  554. "initializing function parameter");
  555. builder.Note(entry.pattern_id, InCallToFunctionParam);
  556. }
  557. });
  558. auto pattern = context.insts().Get(entry.pattern_id);
  559. CARBON_KIND_SWITCH(pattern) {
  560. case SemIR::RefBindingPattern::Kind:
  561. case SemIR::SymbolicBindingPattern::Kind:
  562. case SemIR::ValueBindingPattern::Kind: {
  563. DoEmitPatternMatch(context, pattern.As<SemIR::AnyBindingPattern>(),
  564. entry);
  565. break;
  566. }
  567. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  568. DoEmitPatternMatch(context, param_pattern, entry);
  569. break;
  570. }
  571. case CARBON_KIND(SemIR::RefParamPattern param_pattern): {
  572. DoEmitPatternMatch(context, param_pattern, entry);
  573. break;
  574. }
  575. case CARBON_KIND(SemIR::VarParamPattern param_pattern): {
  576. DoEmitPatternMatch(context, param_pattern, entry);
  577. break;
  578. }
  579. case CARBON_KIND(SemIR::OutParamPattern param_pattern): {
  580. DoEmitPatternMatch(context, param_pattern, entry);
  581. break;
  582. }
  583. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  584. DoEmitPatternMatch(context, return_slot_pattern, entry);
  585. break;
  586. }
  587. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  588. DoEmitPatternMatch(context, var_pattern, entry);
  589. break;
  590. }
  591. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  592. DoEmitPatternMatch(context, tuple_pattern, entry);
  593. break;
  594. }
  595. default: {
  596. CARBON_FATAL("Inst kind not handled: {0}", pattern.kind());
  597. }
  598. }
  599. }
  600. auto CalleePatternMatch(Context& context,
  601. SemIR::InstBlockId implicit_param_patterns_id,
  602. SemIR::InstBlockId param_patterns_id,
  603. SemIR::InstBlockId return_patterns_id)
  604. -> CalleePatternMatchResults {
  605. if (!return_patterns_id.has_value() && !param_patterns_id.has_value() &&
  606. !implicit_param_patterns_id.has_value()) {
  607. return {.call_param_patterns_id = SemIR::InstBlockId::None,
  608. .call_params_id = 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. for (auto return_pattern_id :
  614. context.inst_blocks().GetOrEmpty(return_patterns_id)) {
  615. match.AddWork(
  616. {.pattern_id = return_pattern_id, .scrutinee_id = SemIR::InstId::None});
  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(
  622. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  623. }
  624. }
  625. if (implicit_param_patterns_id.has_value()) {
  626. for (SemIR::InstId inst_id :
  627. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  628. match.AddWork(
  629. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  630. }
  631. }
  632. match.DoWork(context);
  633. return std::move(match).CalleeResults(context);
  634. }
  635. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  636. SemIR::InstId self_pattern_id,
  637. SemIR::InstBlockId param_patterns_id,
  638. SemIR::InstBlockId return_patterns_id,
  639. SemIR::InstId self_arg_id,
  640. llvm::ArrayRef<SemIR::InstId> arg_refs,
  641. llvm::ArrayRef<SemIR::InstId> return_arg_ids,
  642. bool is_operator_syntax) -> SemIR::InstBlockId {
  643. MatchContext match(MatchKind::Caller, specific_id);
  644. auto return_patterns = context.inst_blocks().GetOrEmpty(return_patterns_id);
  645. // Track the return storage, if present.
  646. for (auto [return_pattern_id, return_arg_id] :
  647. llvm::zip_equal(return_patterns, return_arg_ids)) {
  648. if (return_arg_id.has_value()) {
  649. match.AddWork(
  650. {.pattern_id = return_pattern_id, .scrutinee_id = return_arg_id});
  651. } else {
  652. CARBON_CHECK(return_arg_ids.size() == 1,
  653. "TODO: do the match even if return_arg_id is None, so that "
  654. "subsequent args are at the right index in the arg block");
  655. }
  656. }
  657. // Check type conversions per-element.
  658. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  659. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  660. match.AddWork({.pattern_id = param_pattern_id,
  661. .scrutinee_id = arg_id,
  662. .allow_unmarked_ref = is_operator_syntax});
  663. }
  664. if (self_pattern_id.has_value()) {
  665. match.AddWork({.pattern_id = self_pattern_id,
  666. .scrutinee_id = self_arg_id,
  667. .allow_unmarked_ref = true});
  668. }
  669. match.DoWork(context);
  670. return std::move(match).CallerResults(context);
  671. }
  672. auto LocalPatternMatch(Context& context, SemIR::InstId pattern_id,
  673. SemIR::InstId scrutinee_id) -> void {
  674. MatchContext match(MatchKind::Local);
  675. match.AddWork({.pattern_id = pattern_id, .scrutinee_id = scrutinee_id});
  676. match.DoWork(context);
  677. }
  678. } // namespace Carbon::Check