pattern_match.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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(
  384. static_cast<size_t>(param_pattern.index.index) == call_args_.size(),
  385. "Parameters out of order; expecting {0} but got {1}",
  386. call_args_.size(), param_pattern.index.index);
  387. CARBON_CHECK(entry.scrutinee_id.has_value());
  388. if (entry.scrutinee_id == SemIR::ErrorInst::InstId) {
  389. call_args_.push_back(SemIR::ErrorInst::InstId);
  390. } else {
  391. auto scrutinee_type_id = ExtractScrutineeType(
  392. context.sem_ir(),
  393. SemIR::GetTypeOfInstInSpecific(
  394. context.sem_ir(), callee_specific_id_, entry.pattern_id));
  395. call_args_.push_back(Convert(
  396. context, SemIR::LocId(entry.scrutinee_id), entry.scrutinee_id,
  397. {.kind =
  398. ConversionKindFor(context, param_pattern, entry, form_kind),
  399. .type_id = scrutinee_type_id}));
  400. }
  401. // Do not traverse farther, because the caller side of the pattern
  402. // ends here.
  403. break;
  404. }
  405. case MatchKind::Callee: {
  406. SemIR::AnyParam param = {
  407. .kind = ParamKindFor(context, param_pattern, entry, form_kind),
  408. .type_id =
  409. ExtractScrutineeType(context.sem_ir(), param_pattern.type_id),
  410. .index = param_pattern.index,
  411. .pretty_name_id = SemIR::GetPrettyNameFromPatternId(
  412. context.sem_ir(), entry.pattern_id)};
  413. auto param_id =
  414. AddInst(context, SemIR::LocIdAndInst::UncheckedLoc(
  415. SemIR::LocId(entry.pattern_id), param));
  416. AddWork({.pattern_id = param_pattern.subpattern_id,
  417. .scrutinee_id = param_id});
  418. call_params_.push_back(param_id);
  419. call_param_patterns_.push_back(entry.pattern_id);
  420. break;
  421. }
  422. case MatchKind::Local: {
  423. CARBON_FATAL("Found ValueParamPattern during local pattern match");
  424. }
  425. }
  426. }
  427. auto MatchContext::DoEmitPatternMatch(
  428. Context& context, SemIR::ReturnSlotPattern return_slot_pattern,
  429. WorkItem entry) -> void {
  430. CARBON_CHECK(kind_ == MatchKind::Callee);
  431. auto type_id =
  432. ExtractScrutineeType(context.sem_ir(), return_slot_pattern.type_id);
  433. auto return_slot_id = AddInst<SemIR::ReturnSlot>(
  434. context, SemIR::LocId(entry.pattern_id),
  435. {.type_id = type_id,
  436. .type_inst_id = context.types().GetTypeInstId(type_id),
  437. .storage_id = entry.scrutinee_id});
  438. bool already_in_lookup =
  439. context.scope_stack()
  440. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  441. .has_value();
  442. CARBON_CHECK(!already_in_lookup);
  443. }
  444. auto MatchContext::DoEmitPatternMatch(Context& context,
  445. SemIR::VarPattern var_pattern,
  446. WorkItem entry) -> void {
  447. auto new_scrutinee_id =
  448. DoEmitVarPatternMatchImpl(context, var_pattern.type_id, entry);
  449. AddWork({.pattern_id = var_pattern.subpattern_id,
  450. .scrutinee_id = new_scrutinee_id});
  451. }
  452. auto MatchContext::DoEmitVarPatternMatchImpl(Context& context,
  453. SemIR::TypeId pattern_type_id,
  454. WorkItem entry) const
  455. -> SemIR::InstId {
  456. auto storage_id = SemIR::InstId::None;
  457. switch (kind_) {
  458. case MatchKind::Callee: {
  459. // We're emitting pattern-match IR for the callee, but we're still on
  460. // the caller side of the pattern, so we traverse without emitting any
  461. // insts.
  462. return SemIR::InstId::None;
  463. }
  464. case MatchKind::Local: {
  465. // In a `var`/`let` declaration, the `VarStorage` inst is created before
  466. // we start pattern matching.
  467. auto lookup_result = context.var_storage_map().Lookup(entry.pattern_id);
  468. CARBON_CHECK(lookup_result);
  469. storage_id = lookup_result.value();
  470. break;
  471. }
  472. case MatchKind::Caller: {
  473. storage_id = AddInst<SemIR::TemporaryStorage>(
  474. context, SemIR::LocId(entry.pattern_id),
  475. {.type_id = ExtractScrutineeType(context.sem_ir(), pattern_type_id)});
  476. CARBON_CHECK(entry.scrutinee_id.has_value());
  477. break;
  478. }
  479. }
  480. // TODO: Find a more efficient way to put these insts in the global_init
  481. // block (or drop the distinction between the global_init block and the
  482. // file scope?)
  483. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  484. context.global_init().Resume();
  485. }
  486. if (entry.scrutinee_id.has_value()) {
  487. auto init_id = Initialize(context, SemIR::LocId(entry.pattern_id),
  488. storage_id, entry.scrutinee_id);
  489. // If we created a `TemporaryStorage` to hold the var, create a
  490. // corresponding `Temporary` to model that its initialization is complete.
  491. // TODO: If the subpattern is a binding, we may want to destroy the
  492. // parameter variable in the callee instead of the caller so that we can
  493. // support destructive move from it.
  494. if (kind_ == MatchKind::Caller) {
  495. storage_id = AddInstWithCleanup<SemIR::Temporary>(
  496. context, SemIR::LocId(entry.pattern_id),
  497. {.type_id = context.insts().Get(storage_id).type_id(),
  498. .storage_id = storage_id,
  499. .init_id = init_id});
  500. } else {
  501. // TODO: Consider using different instruction kinds for assignment
  502. // versus initialization.
  503. AddInst<SemIR::Assign>(context, SemIR::LocId(entry.pattern_id),
  504. {.lhs_id = storage_id, .rhs_id = init_id});
  505. }
  506. }
  507. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  508. context.global_init().Suspend();
  509. }
  510. return storage_id;
  511. }
  512. auto MatchContext::DoEmitPatternMatch(Context& context,
  513. SemIR::TuplePattern tuple_pattern,
  514. WorkItem entry) -> void {
  515. if (tuple_pattern.type_id == SemIR::ErrorInst::TypeId) {
  516. return;
  517. }
  518. auto subpattern_ids = context.inst_blocks().Get(tuple_pattern.elements_id);
  519. auto add_all_subscrutinees =
  520. [&](llvm::ArrayRef<SemIR::InstId> subscrutinee_ids) {
  521. for (auto [subpattern_id, subscrutinee_id] :
  522. llvm::reverse(llvm::zip_equal(subpattern_ids, subscrutinee_ids))) {
  523. AddWork(
  524. {.pattern_id = subpattern_id, .scrutinee_id = subscrutinee_id});
  525. }
  526. };
  527. if (!entry.scrutinee_id.has_value()) {
  528. CARBON_CHECK(kind_ == MatchKind::Callee);
  529. // If we don't have a scrutinee yet, we're still on the caller side of the
  530. // pattern, so the subpatterns don't have a scrutinee either.
  531. for (auto subpattern_id : llvm::reverse(subpattern_ids)) {
  532. AddWork(
  533. {.pattern_id = subpattern_id, .scrutinee_id = SemIR::InstId::None});
  534. }
  535. return;
  536. }
  537. auto scrutinee = context.insts().GetWithLocId(entry.scrutinee_id);
  538. if (auto scrutinee_literal = scrutinee.inst.TryAs<SemIR::TupleLiteral>()) {
  539. auto subscrutinee_ids =
  540. context.inst_blocks().Get(scrutinee_literal->elements_id);
  541. if (subscrutinee_ids.size() != subpattern_ids.size()) {
  542. CARBON_DIAGNOSTIC(TuplePatternSizeDoesntMatchLiteral, Error,
  543. "tuple pattern expects {0} element{0:s}, but tuple "
  544. "literal has {1}",
  545. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  546. context.emitter().Emit(entry.pattern_id,
  547. TuplePatternSizeDoesntMatchLiteral,
  548. subpattern_ids.size(), subscrutinee_ids.size());
  549. return;
  550. }
  551. add_all_subscrutinees(subscrutinee_ids);
  552. return;
  553. }
  554. auto tuple_type_id =
  555. ExtractScrutineeType(context.sem_ir(), tuple_pattern.type_id);
  556. auto converted_scrutinee_id =
  557. ConvertToValueOrRefOfType(context, SemIR::LocId(entry.pattern_id),
  558. entry.scrutinee_id, tuple_type_id);
  559. if (auto scrutinee_value =
  560. context.insts().TryGetAs<SemIR::TupleValue>(converted_scrutinee_id)) {
  561. add_all_subscrutinees(
  562. context.inst_blocks().Get(scrutinee_value->elements_id));
  563. return;
  564. }
  565. auto tuple_type = context.types().GetAs<SemIR::TupleType>(tuple_type_id);
  566. auto element_type_inst_ids =
  567. context.inst_blocks().Get(tuple_type.type_elements_id);
  568. llvm::SmallVector<SemIR::InstId> subscrutinee_ids;
  569. subscrutinee_ids.reserve(element_type_inst_ids.size());
  570. for (auto [i, element_type_id] : llvm::enumerate(
  571. context.types().GetBlockAsTypeIds(element_type_inst_ids))) {
  572. subscrutinee_ids.push_back(
  573. AddInst<SemIR::TupleAccess>(context, scrutinee.loc_id,
  574. {.type_id = element_type_id,
  575. .tuple_id = converted_scrutinee_id,
  576. .index = SemIR::ElementIndex(i)}));
  577. }
  578. add_all_subscrutinees(subscrutinee_ids);
  579. }
  580. auto MatchContext::EmitPatternMatch(Context& context,
  581. MatchContext::WorkItem entry) -> void {
  582. if (entry.pattern_id == SemIR::ErrorInst::InstId) {
  583. return;
  584. }
  585. Diagnostics::AnnotationScope annotate_diagnostics(
  586. &context.emitter(), [&](auto& builder) {
  587. if (kind_ == MatchKind::Caller) {
  588. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  589. "initializing function parameter");
  590. builder.Note(entry.pattern_id, InCallToFunctionParam);
  591. }
  592. });
  593. auto pattern = context.insts().Get(entry.pattern_id);
  594. CARBON_KIND_SWITCH(pattern) {
  595. case SemIR::RefBindingPattern::Kind:
  596. case SemIR::SymbolicBindingPattern::Kind:
  597. case SemIR::ValueBindingPattern::Kind:
  598. case SemIR::FormBindingPattern::Kind:
  599. DoEmitPatternMatch(context, pattern.As<SemIR::AnyBindingPattern>(),
  600. entry);
  601. break;
  602. case SemIR::FormParamPattern::Kind:
  603. case SemIR::RefParamPattern::Kind:
  604. case SemIR::ValueParamPattern::Kind:
  605. case SemIR::VarParamPattern::Kind:
  606. case SemIR::OutParamPattern::Kind:
  607. DoEmitPatternMatch(context, pattern.As<SemIR::AnyParamPattern>(), entry);
  608. break;
  609. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  610. DoEmitPatternMatch(context, return_slot_pattern, entry);
  611. break;
  612. }
  613. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  614. DoEmitPatternMatch(context, var_pattern, entry);
  615. break;
  616. }
  617. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  618. DoEmitPatternMatch(context, tuple_pattern, entry);
  619. break;
  620. }
  621. default: {
  622. CARBON_FATAL("Inst kind not handled: {0}", pattern.kind());
  623. }
  624. }
  625. }
  626. auto CalleePatternMatch(Context& context,
  627. SemIR::InstBlockId implicit_param_patterns_id,
  628. SemIR::InstBlockId param_patterns_id,
  629. SemIR::InstBlockId return_patterns_id)
  630. -> CalleePatternMatchResults {
  631. if (!return_patterns_id.has_value() && !param_patterns_id.has_value() &&
  632. !implicit_param_patterns_id.has_value()) {
  633. return {.call_param_patterns_id = SemIR::InstBlockId::None,
  634. .call_params_id = SemIR::InstBlockId::None};
  635. }
  636. MatchContext match(MatchKind::Callee);
  637. // We add work to the stack in reverse so that the results will be produced
  638. // in the original order.
  639. for (auto return_pattern_id :
  640. context.inst_blocks().GetOrEmpty(return_patterns_id)) {
  641. match.AddWork(
  642. {.pattern_id = return_pattern_id, .scrutinee_id = SemIR::InstId::None});
  643. }
  644. if (param_patterns_id.has_value()) {
  645. for (SemIR::InstId inst_id :
  646. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  647. match.AddWork(
  648. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  649. }
  650. }
  651. if (implicit_param_patterns_id.has_value()) {
  652. for (SemIR::InstId inst_id :
  653. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  654. match.AddWork(
  655. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  656. }
  657. }
  658. match.DoWork(context);
  659. return std::move(match).CalleeResults(context);
  660. }
  661. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  662. SemIR::InstId self_pattern_id,
  663. SemIR::InstBlockId param_patterns_id,
  664. SemIR::InstBlockId return_patterns_id,
  665. SemIR::InstId self_arg_id,
  666. llvm::ArrayRef<SemIR::InstId> arg_refs,
  667. llvm::ArrayRef<SemIR::InstId> return_arg_ids,
  668. bool is_operator_syntax) -> SemIR::InstBlockId {
  669. MatchContext match(MatchKind::Caller, specific_id);
  670. auto return_patterns = context.inst_blocks().GetOrEmpty(return_patterns_id);
  671. // Track the return storage, if present.
  672. for (auto [return_pattern_id, return_arg_id] :
  673. llvm::zip_equal(return_patterns, return_arg_ids)) {
  674. if (return_arg_id.has_value()) {
  675. match.AddWork(
  676. {.pattern_id = return_pattern_id, .scrutinee_id = return_arg_id});
  677. } else {
  678. CARBON_CHECK(return_arg_ids.size() == 1,
  679. "TODO: do the match even if return_arg_id is None, so that "
  680. "subsequent args are at the right index in the arg block");
  681. }
  682. }
  683. // Check type conversions per-element.
  684. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  685. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  686. match.AddWork({.pattern_id = param_pattern_id,
  687. .scrutinee_id = arg_id,
  688. .allow_unmarked_ref = is_operator_syntax});
  689. }
  690. if (self_pattern_id.has_value()) {
  691. match.AddWork({.pattern_id = self_pattern_id,
  692. .scrutinee_id = self_arg_id,
  693. .allow_unmarked_ref = true});
  694. }
  695. match.DoWork(context);
  696. return std::move(match).CallerResults(context);
  697. }
  698. auto LocalPatternMatch(Context& context, SemIR::InstId pattern_id,
  699. SemIR::InstId scrutinee_id) -> void {
  700. MatchContext match(MatchKind::Local);
  701. match.AddWork({.pattern_id = pattern_id, .scrutinee_id = scrutinee_id});
  702. match.DoWork(context);
  703. }
  704. } // namespace Carbon::Check