pattern_match.cpp 40 KB

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