pattern_match.cpp 39 KB

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