pattern_match.cpp 31 KB

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