pattern_match.cpp 31 KB

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