pattern_match.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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. case SemIR::ErrorInst::Kind:
  282. return ConversionTarget::Value;
  283. default:
  284. CARBON_FATAL("Unexpected form {0}", form_inst);
  285. }
  286. }
  287. case CARBON_KIND(SemIR::FormParamPattern form_param_pattern): {
  288. auto form_inst_id =
  289. context.constant_values().GetInstId(form_param_pattern.form_id);
  290. auto form_inst = context.insts().Get(form_inst_id);
  291. switch (form_inst.kind()) {
  292. case SemIR::InitForm::Kind:
  293. return ConversionTarget::NoOp;
  294. case SemIR::RefForm::Kind:
  295. // TODO: Figure out rules for when the argument must have a `ref` tag.
  296. return entry.allow_unmarked_ref ? ConversionTarget::UnmarkedRefParam
  297. : ConversionTarget::RefParam;
  298. case SemIR::SymbolicBinding::Kind:
  299. context.TODO(entry.pattern_id, "Support symbolic form params");
  300. [[fallthrough]];
  301. case SemIR::ErrorInst::Kind:
  302. case SemIR::ValueForm::Kind:
  303. return ConversionTarget::Value;
  304. default:
  305. CARBON_FATAL("Unexpected form {0}", form_inst);
  306. }
  307. }
  308. default:
  309. CARBON_FATAL("Unexpected pattern kind in {0}", pattern);
  310. }
  311. }
  312. auto MatchContext::DoPreWork(Context& context,
  313. SemIR::AnyBindingPattern binding_pattern,
  314. SemIR::InstId scrutinee_id,
  315. MatchContext::WorkItem entry) -> void {
  316. if (kind_ == MatchKind::Caller) {
  317. CARBON_CHECK(
  318. binding_pattern.kind == SemIR::SymbolicBindingPattern::Kind,
  319. "Found named runtime binding pattern during caller pattern match");
  320. return;
  321. }
  322. // We're logically consuming this map entry, so we invalidate it in order
  323. // to avoid accidentally consuming it twice.
  324. auto [bind_name_id, type_expr_region_id] =
  325. std::exchange(context.bind_name_map().Lookup(entry.pattern_id).value(),
  326. {.bind_name_id = SemIR::InstId::None,
  327. .type_expr_region_id = SemIR::ExprRegionId::None});
  328. if (type_expr_region_id.has_value()) {
  329. InsertHere(context, type_expr_region_id);
  330. }
  331. auto value_id = SemIR::InstId::None;
  332. if (kind_ == MatchKind::Local) {
  333. auto conversion_kind = ConversionKindFor(context, binding_pattern, entry);
  334. if (!bind_name_id.has_value()) {
  335. // TODO: Is this appropriate, or should we perform a conversion based on
  336. // whether the `_` binding is a value or ref binding first, and then
  337. // separately discard the initializer for a `_` binding?
  338. conversion_kind = ConversionTarget::Discarded;
  339. }
  340. value_id =
  341. Convert(context, SemIR::LocId(scrutinee_id), scrutinee_id,
  342. {.kind = conversion_kind,
  343. .type_id = context.insts().Get(bind_name_id).type_id()});
  344. } else {
  345. // In a function call, conversion is handled while matching the enclosing
  346. // `*ParamPattern`.
  347. value_id = scrutinee_id;
  348. }
  349. if (bind_name_id.has_value()) {
  350. auto bind_name = context.insts().GetAs<SemIR::AnyBinding>(bind_name_id);
  351. CARBON_CHECK(!bind_name.value_id.has_value());
  352. bind_name.value_id = value_id;
  353. ReplaceInstBeforeConstantUse(context, bind_name_id, bind_name);
  354. context.inst_block_stack().AddInstId(bind_name_id);
  355. }
  356. if (need_subpattern_results()) {
  357. results_stack_.AppendToTop(value_id);
  358. }
  359. }
  360. // Returns the inst kind to use for the parameter corresponding to the given
  361. // parameter pattern.
  362. static auto ParamKindFor(Context& context, SemIR::Inst param_pattern,
  363. MatchContext::WorkItem entry) -> SemIR::InstKind {
  364. CARBON_KIND_SWITCH(param_pattern) {
  365. case SemIR::OutParamPattern::Kind:
  366. return SemIR::OutParam::Kind;
  367. case SemIR::RefParamPattern::Kind:
  368. case SemIR::VarParamPattern::Kind:
  369. return SemIR::RefParam::Kind;
  370. case SemIR::ValueParamPattern::Kind:
  371. return SemIR::ValueParam::Kind;
  372. case CARBON_KIND(SemIR::FormParamPattern form_param_pattern): {
  373. auto form_inst_id =
  374. context.constant_values().GetInstId(form_param_pattern.form_id);
  375. auto form_inst = context.insts().Get(form_inst_id);
  376. switch (form_inst.kind()) {
  377. case SemIR::InitForm::Kind:
  378. case SemIR::RefForm::Kind:
  379. return SemIR::RefParam::Kind;
  380. case SemIR::SymbolicBinding::Kind:
  381. context.TODO(entry.pattern_id, "Support symbolic form params");
  382. [[fallthrough]];
  383. case SemIR::ErrorInst::Kind:
  384. case SemIR::ValueForm::Kind:
  385. return SemIR::ValueParam::Kind;
  386. default:
  387. CARBON_FATAL("Unexpected form {0}", form_inst);
  388. }
  389. }
  390. default:
  391. CARBON_FATAL("Unexpected param pattern kind: {0}", param_pattern);
  392. }
  393. }
  394. auto MatchContext::DoPreWork(Context& context,
  395. SemIR::AnyParamPattern param_pattern,
  396. SemIR::InstId scrutinee_id, WorkItem entry)
  397. -> void {
  398. // If the form is initializing, match this as a `VarPattern` before matching
  399. // it as a parameter pattern.
  400. if (param_pattern.kind == SemIR::FormParamPattern::Kind) {
  401. auto form_inst_id =
  402. context.constant_values().GetInstId(param_pattern.form_id);
  403. if (context.insts().Get(form_inst_id).kind() == SemIR::InitForm::Kind) {
  404. auto new_scrutinee_id =
  405. DoVarPreWorkImpl(context, param_pattern.type_id, scrutinee_id, entry);
  406. scrutinee_id = new_scrutinee_id;
  407. }
  408. }
  409. switch (kind_) {
  410. case MatchKind::Caller: {
  411. CARBON_CHECK(scrutinee_id.has_value());
  412. if (scrutinee_id == SemIR::ErrorInst::InstId) {
  413. call_args_.push_back(SemIR::ErrorInst::InstId);
  414. } else {
  415. auto scrutinee_type_id = ExtractScrutineeType(
  416. context.sem_ir(),
  417. SemIR::GetTypeOfInstInSpecific(
  418. context.sem_ir(), callee_specific_id_, entry.pattern_id));
  419. call_args_.push_back(
  420. Convert(context, SemIR::LocId(scrutinee_id), scrutinee_id,
  421. {.kind = ConversionKindFor(context, param_pattern, entry),
  422. .type_id = scrutinee_type_id}));
  423. }
  424. // Do not traverse farther, because the caller side of the pattern
  425. // ends here.
  426. break;
  427. }
  428. case MatchKind::Callee: {
  429. if (need_subpattern_results()) {
  430. AddAsPostWork(entry);
  431. }
  432. SemIR::AnyParam param = {
  433. .kind = ParamKindFor(context, param_pattern, entry),
  434. .type_id =
  435. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  436. .index = SemIR::CallParamIndex(call_params_.size()),
  437. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  438. context.sem_ir(), entry.pattern_id)};
  439. auto param_id =
  440. AddInst(context, SemIR::LocIdAndInst::UncheckedLoc(
  441. SemIR::LocId(entry.pattern_id), param));
  442. AddWork({.pattern_id = param_pattern.subpattern_id,
  443. .work = PreWork{.scrutinee_id = param_id}});
  444. call_params_.push_back(param_id);
  445. call_param_patterns_.push_back(entry.pattern_id);
  446. break;
  447. }
  448. case MatchKind::Local: {
  449. CARBON_FATAL("Found ValueParamPattern during local pattern match");
  450. }
  451. }
  452. }
  453. auto MatchContext::DoPostWork(Context& /*context*/,
  454. SemIR::AnyParamPattern /*param_pattern*/,
  455. WorkItem /*entry*/) -> void {
  456. // No-op: the subpattern's result is this pattern's result.
  457. }
  458. auto MatchContext::DoPreWork(Context& context,
  459. SemIR::ReturnSlotPattern return_slot_pattern,
  460. SemIR::InstId scrutinee_id, WorkItem entry)
  461. -> void {
  462. CARBON_CHECK(kind_ == MatchKind::Callee);
  463. auto type_id =
  464. ExtractScrutineeType(context.sem_ir(), return_slot_pattern.type_id);
  465. auto return_slot_id = AddInst<SemIR::ReturnSlot>(
  466. context, SemIR::LocId(entry.pattern_id),
  467. {.type_id = type_id,
  468. .type_inst_id = context.types().GetTypeInstId(type_id),
  469. .storage_id = scrutinee_id});
  470. bool already_in_lookup =
  471. context.scope_stack()
  472. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  473. .has_value();
  474. CARBON_CHECK(!already_in_lookup);
  475. if (need_subpattern_results()) {
  476. results_stack_.AppendToTop(return_slot_id);
  477. }
  478. }
  479. auto MatchContext::DoPreWork(Context& context, SemIR::VarPattern var_pattern,
  480. SemIR::InstId scrutinee_id, WorkItem entry)
  481. -> void {
  482. auto new_scrutinee_id =
  483. DoVarPreWorkImpl(context, var_pattern.type_id, scrutinee_id, entry);
  484. if (need_subpattern_results()) {
  485. AddAsPostWork(entry);
  486. }
  487. AddWork({.pattern_id = var_pattern.subpattern_id,
  488. .work = PreWork{.scrutinee_id = new_scrutinee_id}});
  489. }
  490. auto MatchContext::DoVarPreWorkImpl(Context& context,
  491. SemIR::TypeId pattern_type_id,
  492. SemIR::InstId scrutinee_id,
  493. WorkItem entry) const -> SemIR::InstId {
  494. auto storage_id = SemIR::InstId::None;
  495. switch (kind_) {
  496. case MatchKind::Callee: {
  497. // We're emitting pattern-match IR for the callee, but we're still on
  498. // the caller side of the pattern, so we traverse without emitting any
  499. // insts.
  500. return SemIR::InstId::None;
  501. }
  502. case MatchKind::Local: {
  503. // In a `var`/`let` declaration, the `VarStorage` inst is created before
  504. // we start pattern matching.
  505. auto lookup_result = context.var_storage_map().Lookup(entry.pattern_id);
  506. CARBON_CHECK(lookup_result);
  507. storage_id = lookup_result.value();
  508. break;
  509. }
  510. case MatchKind::Caller: {
  511. storage_id = AddInst<SemIR::TemporaryStorage>(
  512. context, SemIR::LocId(entry.pattern_id),
  513. {.type_id = ExtractScrutineeType(context.sem_ir(), pattern_type_id)});
  514. CARBON_CHECK(scrutinee_id.has_value());
  515. break;
  516. }
  517. }
  518. // TODO: Find a more efficient way to put these insts in the global_init
  519. // block (or drop the distinction between the global_init block and the
  520. // file scope?)
  521. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  522. context.global_init().Resume();
  523. }
  524. if (scrutinee_id.has_value()) {
  525. auto init_id = Initialize(context, SemIR::LocId(entry.pattern_id),
  526. storage_id, scrutinee_id);
  527. // If we created a `TemporaryStorage` to hold the var, create a
  528. // corresponding `Temporary` to model that its initialization is complete.
  529. // TODO: If the subpattern is a binding, we may want to destroy the
  530. // parameter variable in the callee instead of the caller so that we can
  531. // support destructive move from it.
  532. if (kind_ == MatchKind::Caller) {
  533. storage_id = AddInstWithCleanup<SemIR::Temporary>(
  534. context, SemIR::LocId(entry.pattern_id),
  535. {.type_id = context.insts().Get(storage_id).type_id(),
  536. .storage_id = storage_id,
  537. .init_id = init_id});
  538. } else {
  539. // TODO: Consider using different instruction kinds for assignment
  540. // versus initialization.
  541. AddInst<SemIR::Assign>(context, SemIR::LocId(entry.pattern_id),
  542. {.lhs_id = storage_id, .rhs_id = init_id});
  543. }
  544. }
  545. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  546. context.global_init().Suspend();
  547. }
  548. return storage_id;
  549. }
  550. auto MatchContext::DoPostWork(Context& /*context*/,
  551. SemIR::VarPattern /*var_pattern*/,
  552. WorkItem /*entry*/) -> void {
  553. // No-op: the subpattern's result is this pattern's result.
  554. }
  555. auto MatchContext::DoPreWork(Context& context,
  556. SemIR::TuplePattern tuple_pattern,
  557. SemIR::InstId scrutinee_id, WorkItem entry)
  558. -> void {
  559. if (tuple_pattern.type_id == SemIR::ErrorInst::TypeId) {
  560. return;
  561. }
  562. auto subpattern_ids = context.inst_blocks().Get(tuple_pattern.elements_id);
  563. if (need_subpattern_results()) {
  564. results_stack_.PushArray();
  565. AddAsPostWork(entry);
  566. }
  567. auto add_all_subscrutinees =
  568. [&](llvm::ArrayRef<SemIR::InstId> subscrutinee_ids) {
  569. for (auto [subpattern_id, subscrutinee_id] :
  570. llvm::reverse(llvm::zip_equal(subpattern_ids, subscrutinee_ids))) {
  571. AddWork({.pattern_id = subpattern_id,
  572. .work = PreWork{.scrutinee_id = subscrutinee_id}});
  573. }
  574. };
  575. if (!scrutinee_id.has_value()) {
  576. CARBON_CHECK(kind_ == MatchKind::Callee);
  577. // If we don't have a scrutinee yet, we're still on the caller side of the
  578. // pattern, so the subpatterns don't have a scrutinee either.
  579. for (auto subpattern_id : llvm::reverse(subpattern_ids)) {
  580. AddWork({.pattern_id = subpattern_id,
  581. .work = PreWork{.scrutinee_id = SemIR::InstId::None}});
  582. }
  583. return;
  584. }
  585. auto scrutinee = context.insts().GetWithLocId(scrutinee_id);
  586. if (auto scrutinee_literal = scrutinee.inst.TryAs<SemIR::TupleLiteral>()) {
  587. auto subscrutinee_ids =
  588. context.inst_blocks().Get(scrutinee_literal->elements_id);
  589. if (subscrutinee_ids.size() != subpattern_ids.size()) {
  590. CARBON_DIAGNOSTIC(TuplePatternSizeDoesntMatchLiteral, Error,
  591. "tuple pattern expects {0} element{0:s}, but tuple "
  592. "literal has {1}",
  593. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  594. context.emitter().Emit(entry.pattern_id,
  595. TuplePatternSizeDoesntMatchLiteral,
  596. subpattern_ids.size(), subscrutinee_ids.size());
  597. return;
  598. }
  599. add_all_subscrutinees(subscrutinee_ids);
  600. return;
  601. }
  602. auto tuple_type_id =
  603. ExtractScrutineeType(context.sem_ir(), tuple_pattern.type_id);
  604. auto converted_scrutinee_id = ConvertToValueOrRefOfType(
  605. context, SemIR::LocId(entry.pattern_id), scrutinee_id, tuple_type_id);
  606. if (auto scrutinee_value =
  607. context.insts().TryGetAs<SemIR::TupleValue>(converted_scrutinee_id)) {
  608. add_all_subscrutinees(
  609. context.inst_blocks().Get(scrutinee_value->elements_id));
  610. return;
  611. }
  612. auto tuple_type = context.types().GetAs<SemIR::TupleType>(tuple_type_id);
  613. auto element_type_inst_ids =
  614. context.inst_blocks().Get(tuple_type.type_elements_id);
  615. llvm::SmallVector<SemIR::InstId> subscrutinee_ids;
  616. subscrutinee_ids.reserve(element_type_inst_ids.size());
  617. for (auto [i, element_type_id] : llvm::enumerate(
  618. context.types().GetBlockAsTypeIds(element_type_inst_ids))) {
  619. subscrutinee_ids.push_back(
  620. AddInst<SemIR::TupleAccess>(context, scrutinee.loc_id,
  621. {.type_id = element_type_id,
  622. .tuple_id = converted_scrutinee_id,
  623. .index = SemIR::ElementIndex(i)}));
  624. }
  625. add_all_subscrutinees(subscrutinee_ids);
  626. }
  627. auto MatchContext::DoPostWork(Context& context,
  628. SemIR::TuplePattern tuple_pattern, WorkItem entry)
  629. -> void {
  630. auto elements_id = context.inst_blocks().Add(results_stack_.PeekArray());
  631. results_stack_.PopArray();
  632. auto tuple_value_id =
  633. AddInst<SemIR::TupleValue>(context, SemIR::LocId(entry.pattern_id),
  634. {.type_id = SemIR::ExtractScrutineeType(
  635. context.sem_ir(), tuple_pattern.type_id),
  636. .elements_id = elements_id});
  637. results_stack_.AppendToTop(tuple_value_id);
  638. }
  639. auto MatchContext::Dispatch(Context& context, WorkItem entry) -> void {
  640. if (entry.pattern_id == SemIR::ErrorInst::InstId) {
  641. return;
  642. }
  643. Diagnostics::AnnotationScope annotate_diagnostics(
  644. &context.emitter(), [&](auto& builder) {
  645. if (kind_ == MatchKind::Caller) {
  646. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  647. "initializing function parameter");
  648. builder.Note(entry.pattern_id, InCallToFunctionParam);
  649. }
  650. });
  651. auto pattern = context.insts().Get(entry.pattern_id);
  652. CARBON_KIND_SWITCH(entry.work) {
  653. case CARBON_KIND(PreWork work): {
  654. // TODO: Require that `work.scrutinee_id` is valid if and only if insts
  655. // should be emitted, once we start emitting `Param` insts in the
  656. // `ParamPattern` case.
  657. CARBON_KIND_SWITCH(pattern) {
  658. case CARBON_KIND_ANY(SemIR::AnyBindingPattern, any_binding_pattern): {
  659. DoPreWork(context, any_binding_pattern, work.scrutinee_id, entry);
  660. break;
  661. }
  662. case CARBON_KIND_ANY(SemIR::AnyParamPattern, any_param_pattern): {
  663. DoPreWork(context, any_param_pattern, work.scrutinee_id, entry);
  664. break;
  665. }
  666. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  667. DoPreWork(context, return_slot_pattern, work.scrutinee_id, entry);
  668. break;
  669. }
  670. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  671. DoPreWork(context, var_pattern, work.scrutinee_id, entry);
  672. break;
  673. }
  674. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  675. DoPreWork(context, tuple_pattern, work.scrutinee_id, entry);
  676. break;
  677. }
  678. default: {
  679. CARBON_FATAL("Inst kind not handled: {0}", pattern.kind());
  680. }
  681. }
  682. break;
  683. }
  684. case CARBON_KIND(PostWork _): {
  685. CARBON_KIND_SWITCH(pattern) {
  686. case CARBON_KIND_ANY(SemIR::AnyParamPattern, any_param_pattern): {
  687. DoPostWork(context, any_param_pattern, entry);
  688. break;
  689. }
  690. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  691. DoPostWork(context, var_pattern, entry);
  692. break;
  693. }
  694. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  695. DoPostWork(context, tuple_pattern, entry);
  696. break;
  697. }
  698. default: {
  699. CARBON_FATAL("Inst kind not handled: {0}", pattern.kind());
  700. }
  701. }
  702. break;
  703. }
  704. }
  705. }
  706. auto CalleePatternMatch(Context& context,
  707. SemIR::InstBlockId implicit_param_patterns_id,
  708. SemIR::InstBlockId param_patterns_id,
  709. SemIR::InstBlockId return_patterns_id)
  710. -> CalleePatternMatchResults {
  711. if (!return_patterns_id.has_value() && !param_patterns_id.has_value() &&
  712. !implicit_param_patterns_id.has_value()) {
  713. return {.call_param_patterns_id = SemIR::InstBlockId::None,
  714. .call_params_id = SemIR::InstBlockId::None,
  715. .param_ranges = SemIR::Function::CallParamIndexRanges::Empty};
  716. }
  717. MatchContext match(MatchKind::Callee);
  718. // We add work to the stack in reverse so that the results will be produced
  719. // in the original order.
  720. if (implicit_param_patterns_id.has_value()) {
  721. for (SemIR::InstId inst_id :
  722. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  723. match.AddWork(
  724. {.pattern_id = inst_id,
  725. .work = MatchContext::PreWork{.scrutinee_id = SemIR::InstId::None}});
  726. }
  727. }
  728. match.DoWork(context);
  729. auto implicit_end = SemIR::CallParamIndex(match.param_count());
  730. if (param_patterns_id.has_value()) {
  731. for (SemIR::InstId inst_id :
  732. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  733. match.AddWork(
  734. {.pattern_id = inst_id,
  735. .work = MatchContext::PreWork{.scrutinee_id = SemIR::InstId::None}});
  736. }
  737. }
  738. match.DoWork(context);
  739. auto explicit_end = SemIR::CallParamIndex(match.param_count());
  740. for (auto return_pattern_id :
  741. context.inst_blocks().GetOrEmpty(return_patterns_id)) {
  742. match.AddWork(
  743. {.pattern_id = return_pattern_id,
  744. .work = MatchContext::PreWork{.scrutinee_id = SemIR::InstId::None}});
  745. }
  746. match.DoWork(context);
  747. auto return_end = SemIR::CallParamIndex(match.param_count());
  748. match.DoWork(context);
  749. auto blocks = std::move(match).GetCallParams(context);
  750. return {.call_param_patterns_id = blocks.call_param_patterns_id,
  751. .call_params_id = blocks.call_params_id,
  752. .param_ranges = {implicit_end, explicit_end, return_end}};
  753. }
  754. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  755. SemIR::InstId self_pattern_id,
  756. SemIR::InstBlockId param_patterns_id,
  757. SemIR::InstBlockId return_patterns_id,
  758. SemIR::InstId self_arg_id,
  759. llvm::ArrayRef<SemIR::InstId> arg_refs,
  760. llvm::ArrayRef<SemIR::InstId> return_arg_ids,
  761. bool is_operator_syntax) -> SemIR::InstBlockId {
  762. MatchContext match(MatchKind::Caller, specific_id);
  763. auto return_patterns = context.inst_blocks().GetOrEmpty(return_patterns_id);
  764. // Track the return storage, if present.
  765. for (auto [return_pattern_id, return_arg_id] :
  766. llvm::zip_equal(return_patterns, return_arg_ids)) {
  767. if (return_arg_id.has_value()) {
  768. match.AddWork(
  769. {.pattern_id = return_pattern_id,
  770. .work = MatchContext::PreWork{.scrutinee_id = return_arg_id}});
  771. } else {
  772. CARBON_CHECK(return_arg_ids.size() == 1,
  773. "TODO: do the match even if return_arg_id is None, so that "
  774. "subsequent args are at the right index in the arg block");
  775. }
  776. }
  777. // Check type conversions per-element.
  778. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  779. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  780. match.AddWork({.pattern_id = param_pattern_id,
  781. .work = MatchContext::PreWork{.scrutinee_id = arg_id},
  782. .allow_unmarked_ref = is_operator_syntax});
  783. }
  784. if (self_pattern_id.has_value()) {
  785. match.AddWork({.pattern_id = self_pattern_id,
  786. .work = MatchContext::PreWork{.scrutinee_id = self_arg_id},
  787. .allow_unmarked_ref = true});
  788. }
  789. match.DoWork(context);
  790. return std::move(match).GetCallArgs(context);
  791. }
  792. auto LocalPatternMatch(Context& context, SemIR::InstId pattern_id,
  793. SemIR::InstId scrutinee_id) -> void {
  794. MatchContext match(MatchKind::Local);
  795. match.AddWork({.pattern_id = pattern_id,
  796. .work = MatchContext::PreWork{.scrutinee_id = scrutinee_id}});
  797. match.DoWork(context);
  798. }
  799. } // namespace Carbon::Check