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