pattern_match.cpp 31 KB

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