pattern_match.cpp 35 KB

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