pattern_match.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 <vector>
  7. #include "llvm/ADT/STLExtras.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "toolchain/base/kind_switch.h"
  10. #include "toolchain/check/context.h"
  11. #include "toolchain/check/convert.h"
  12. #include "toolchain/check/subpattern.h"
  13. namespace Carbon::Check {
  14. // Returns a best-effort name for the given ParamPattern, suitable for use in
  15. // IR pretty-printing.
  16. template <typename ParamPattern>
  17. static auto GetPrettyName(Context& context, ParamPattern param_pattern)
  18. -> SemIR::NameId {
  19. if (context.insts().Is<SemIR::ReturnSlotPattern>(
  20. param_pattern.subpattern_id)) {
  21. return SemIR::NameId::ReturnSlot;
  22. }
  23. if (auto binding_pattern = context.insts().TryGetAs<SemIR::AnyBindingPattern>(
  24. param_pattern.subpattern_id)) {
  25. return context.entity_names().Get(binding_pattern->entity_name_id).name_id;
  26. }
  27. return SemIR::NameId::None;
  28. }
  29. namespace {
  30. // Selects between the different kinds of pattern matching.
  31. enum class MatchKind : uint8_t {
  32. // Caller pattern matching occurs on the caller side of a function call, and
  33. // is responsible for matching the argument expression against the portion
  34. // of the pattern above the ParamPattern insts.
  35. Caller,
  36. // Callee pattern matching occurs in the function decl block, and is
  37. // responsible for matching the function's calling-convention parameters
  38. // against the portion of the pattern below the ParamPattern insts.
  39. Callee,
  40. // Local pattern matching is pattern matching outside of a function call,
  41. // such as in a let/var declaration.
  42. Local,
  43. };
  44. // The collected state of a pattern-matching operation.
  45. class MatchContext {
  46. public:
  47. struct WorkItem {
  48. SemIR::InstId pattern_id;
  49. // `None` when processing the callee side.
  50. SemIR::InstId scrutinee_id;
  51. };
  52. // Constructs a MatchContext. If `callee_specific_id` is not `None`, this
  53. // pattern match operation is part of implementing the signature of the given
  54. // specific.
  55. explicit MatchContext(MatchKind kind, SemIR::SpecificId callee_specific_id =
  56. SemIR::SpecificId::None)
  57. : next_index_(0), kind_(kind), callee_specific_id_(callee_specific_id) {}
  58. // Adds a work item to the stack.
  59. auto AddWork(WorkItem work_item) -> void { stack_.push_back(work_item); }
  60. // Processes all work items on the stack. When performing caller pattern
  61. // matching, returns an inst block with one inst reference for each
  62. // calling-convention argument. When performing callee pattern matching,
  63. // returns an inst block with references to all the emitted BindName insts.
  64. auto DoWork(Context& context) -> SemIR::InstBlockId;
  65. private:
  66. // Allocates the next unallocated RuntimeParamIndex, starting from 0.
  67. auto NextRuntimeIndex() -> SemIR::RuntimeParamIndex {
  68. auto result = next_index_;
  69. ++next_index_.index;
  70. return result;
  71. }
  72. // Emits the pattern-match insts necessary to match the pattern inst
  73. // `entry.pattern_id` against the scrutinee value `entry.scrutinee_id`, and
  74. // adds to `stack_` any work necessary to traverse into its subpatterns. This
  75. // behavior is contingent on the kind of match being performed, as indicated
  76. // by kind_`. For example, when performing a callee pattern match, this does
  77. // not emit insts for patterns on the caller side. However, it still traverses
  78. // into subpatterns if any of their descendants might emit insts.
  79. // TODO: Require that `entry.scrutinee_id` is valid if and only if insts
  80. // should be emitted, once we start emitting `Param` insts in the
  81. // `ParamPattern` case.
  82. auto EmitPatternMatch(Context& context, MatchContext::WorkItem entry) -> void;
  83. // The stack of work to be processed.
  84. llvm::SmallVector<WorkItem> stack_;
  85. // The next index to be allocated by `NextRuntimeIndex`.
  86. SemIR::RuntimeParamIndex next_index_;
  87. // The pending results that will be returned by the current `DoWork` call.
  88. llvm::SmallVector<SemIR::InstId> results_;
  89. // The kind of pattern match being performed.
  90. MatchKind kind_;
  91. // The SpecificId of the function being called (if any).
  92. SemIR::SpecificId callee_specific_id_;
  93. };
  94. } // namespace
  95. auto MatchContext::DoWork(Context& context) -> SemIR::InstBlockId {
  96. results_.reserve(stack_.size());
  97. while (!stack_.empty()) {
  98. EmitPatternMatch(context, stack_.pop_back_val());
  99. }
  100. auto block_id = context.inst_blocks().Add(results_);
  101. results_.clear();
  102. return block_id;
  103. }
  104. // Inserts the given region into the current code block. If the region
  105. // consists of a single block, this will be implemented as a `splice_block`
  106. // inst. Otherwise, this will end the current block with a branch to the entry
  107. // block of the region, and add future insts to a new block which is the
  108. // immediate successor of the region's exit block. As a result, this cannot be
  109. // called more than once for the same region.
  110. static auto InsertHere(Context& context, SemIR::ExprRegionId region_id)
  111. -> SemIR::InstId {
  112. auto region = context.sem_ir().expr_regions().Get(region_id);
  113. auto loc_id = context.insts().GetLocId(region.result_id);
  114. auto exit_block = context.inst_blocks().Get(region.block_ids.back());
  115. if (region.block_ids.size() == 1) {
  116. // TODO: Is it possible to avoid leaving an "orphan" block in the IR in the
  117. // first two cases?
  118. if (exit_block.empty()) {
  119. return region.result_id;
  120. }
  121. if (exit_block.size() == 1) {
  122. context.inst_block_stack().AddInstId(exit_block.front());
  123. return region.result_id;
  124. }
  125. return context.AddInst<SemIR::SpliceBlock>(
  126. loc_id, {.type_id = context.insts().Get(region.result_id).type_id(),
  127. .block_id = region.block_ids.front(),
  128. .result_id = region.result_id});
  129. }
  130. if (context.region_stack().empty()) {
  131. context.TODO(loc_id,
  132. "Control flow expressions are currently only supported inside "
  133. "functions.");
  134. return SemIR::ErrorInst::SingletonInstId;
  135. }
  136. context.AddInst(SemIR::LocIdAndInst::NoLoc<SemIR::Branch>(
  137. {.target_id = region.block_ids.front()}));
  138. context.inst_block_stack().Pop();
  139. // TODO: this will cumulatively cost O(MN) running time for M blocks
  140. // at the Nth level of the stack. Figure out how to do better.
  141. context.region_stack().AddToRegion(region.block_ids);
  142. auto resume_with_block_id =
  143. context.insts().GetAs<SemIR::Branch>(exit_block.back()).target_id;
  144. CARBON_CHECK(context.inst_blocks().GetOrEmpty(resume_with_block_id).empty());
  145. context.inst_block_stack().Push(resume_with_block_id);
  146. context.region_stack().AddToRegion(resume_with_block_id, loc_id);
  147. return region.result_id;
  148. }
  149. auto MatchContext::EmitPatternMatch(Context& context,
  150. MatchContext::WorkItem entry) -> void {
  151. if (entry.pattern_id == SemIR::ErrorInst::SingletonInstId) {
  152. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  153. return;
  154. }
  155. DiagnosticAnnotationScope annotate_diagnostics(
  156. &context.emitter(), [&](auto& builder) {
  157. if (kind_ == MatchKind::Caller) {
  158. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  159. "initializing function parameter");
  160. builder.Note(entry.pattern_id, InCallToFunctionParam);
  161. }
  162. });
  163. auto pattern = context.insts().GetWithLocId(entry.pattern_id);
  164. CARBON_KIND_SWITCH(pattern.inst) {
  165. case SemIR::BindingPattern::Kind:
  166. case SemIR::SymbolicBindingPattern::Kind: {
  167. auto binding_pattern = pattern.inst.As<SemIR::AnyBindingPattern>();
  168. // We're logically consuming this map entry, so we invalidate it in order
  169. // to avoid accidentally consuming it twice.
  170. auto [bind_name_id, type_expr_region_id] = std::exchange(
  171. context.bind_name_map().Lookup(entry.pattern_id).value(),
  172. {.bind_name_id = SemIR::InstId::None,
  173. .type_expr_region_id = SemIR::ExprRegionId::None});
  174. InsertHere(context, type_expr_region_id);
  175. auto value_id = entry.scrutinee_id;
  176. switch (kind_) {
  177. case MatchKind::Local: {
  178. value_id = ConvertToValueOrRefOfType(
  179. context, context.insts().GetLocId(entry.scrutinee_id),
  180. entry.scrutinee_id, binding_pattern.type_id);
  181. break;
  182. }
  183. case MatchKind::Callee: {
  184. if (context.insts()
  185. .GetAs<SemIR::AnyParam>(value_id)
  186. .runtime_index.has_value()) {
  187. results_.push_back(value_id);
  188. }
  189. break;
  190. }
  191. case MatchKind::Caller:
  192. CARBON_FATAL("Found binding pattern during caller pattern match");
  193. }
  194. auto bind_name = context.insts().GetAs<SemIR::AnyBindName>(bind_name_id);
  195. CARBON_CHECK(!bind_name.value_id.has_value());
  196. bind_name.value_id = value_id;
  197. context.ReplaceInstBeforeConstantUse(bind_name_id, bind_name);
  198. context.inst_block_stack().AddInstId(bind_name_id);
  199. break;
  200. }
  201. case CARBON_KIND(SemIR::AddrPattern addr_pattern): {
  202. CARBON_CHECK(kind_ != MatchKind::Local);
  203. if (kind_ == MatchKind::Callee) {
  204. // We're emitting pattern-match IR for the callee, but we're still on
  205. // the caller side of the pattern, so we traverse without emitting any
  206. // insts.
  207. AddWork({.pattern_id = addr_pattern.inner_id,
  208. .scrutinee_id = SemIR::InstId::None});
  209. break;
  210. }
  211. CARBON_CHECK(entry.scrutinee_id.has_value());
  212. auto scrutinee_ref_id =
  213. ConvertToValueOrRefExpr(context, entry.scrutinee_id);
  214. switch (SemIR::GetExprCategory(context.sem_ir(), scrutinee_ref_id)) {
  215. case SemIR::ExprCategory::Error:
  216. case SemIR::ExprCategory::DurableRef:
  217. case SemIR::ExprCategory::EphemeralRef:
  218. break;
  219. default:
  220. CARBON_DIAGNOSTIC(AddrSelfIsNonRef, Error,
  221. "`addr self` method cannot be invoked on a value");
  222. context.emitter().Emit(
  223. TokenOnly(context.insts().GetLocId(entry.scrutinee_id)),
  224. AddrSelfIsNonRef);
  225. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  226. return;
  227. }
  228. auto scrutinee_ref = context.insts().Get(scrutinee_ref_id);
  229. auto new_scrutinee = context.AddInst<SemIR::AddrOf>(
  230. context.insts().GetLocId(scrutinee_ref_id),
  231. {.type_id = context.GetPointerType(scrutinee_ref.type_id()),
  232. .lvalue_id = scrutinee_ref_id});
  233. AddWork(
  234. {.pattern_id = addr_pattern.inner_id, .scrutinee_id = new_scrutinee});
  235. break;
  236. }
  237. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  238. CARBON_CHECK(param_pattern.runtime_index.index < 0 ||
  239. static_cast<size_t>(param_pattern.runtime_index.index) ==
  240. results_.size(),
  241. "Parameters out of order; expecting {0} but got {1}",
  242. results_.size(), param_pattern.runtime_index.index);
  243. switch (kind_) {
  244. case MatchKind::Caller: {
  245. CARBON_CHECK(entry.scrutinee_id.has_value());
  246. if (entry.scrutinee_id == SemIR::ErrorInst::SingletonInstId) {
  247. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  248. } else {
  249. results_.push_back(ConvertToValueOfType(
  250. context, context.insts().GetLocId(entry.scrutinee_id),
  251. entry.scrutinee_id,
  252. SemIR::GetTypeInSpecific(context.sem_ir(), callee_specific_id_,
  253. param_pattern.type_id)));
  254. }
  255. // Do not traverse farther, because the caller side of the pattern
  256. // ends here.
  257. break;
  258. }
  259. case MatchKind::Callee: {
  260. if (param_pattern.runtime_index ==
  261. SemIR::RuntimeParamIndex::Unknown) {
  262. param_pattern.runtime_index = NextRuntimeIndex();
  263. context.ReplaceInstBeforeConstantUse(entry.pattern_id,
  264. param_pattern);
  265. }
  266. AddWork(
  267. {.pattern_id = param_pattern.subpattern_id,
  268. .scrutinee_id = context.AddInst<SemIR::ValueParam>(
  269. pattern.loc_id,
  270. {.type_id = param_pattern.type_id,
  271. .runtime_index = param_pattern.runtime_index,
  272. .pretty_name_id = GetPrettyName(context, param_pattern)})});
  273. break;
  274. }
  275. case MatchKind::Local: {
  276. CARBON_FATAL("Found ValueParamPattern during local pattern match");
  277. }
  278. }
  279. break;
  280. }
  281. case CARBON_KIND(SemIR::OutParamPattern param_pattern): {
  282. switch (kind_) {
  283. case MatchKind::Caller: {
  284. CARBON_CHECK(entry.scrutinee_id.has_value());
  285. CARBON_CHECK(context.insts().Get(entry.scrutinee_id).type_id() ==
  286. SemIR::GetTypeInSpecific(context.sem_ir(),
  287. callee_specific_id_,
  288. param_pattern.type_id));
  289. results_.push_back(entry.scrutinee_id);
  290. // Do not traverse farther, because the caller side of the pattern
  291. // ends here.
  292. break;
  293. }
  294. case MatchKind::Callee: {
  295. // TODO: Consider ways to address near-duplication with the
  296. // ValueParamPattern case.
  297. if (param_pattern.runtime_index ==
  298. SemIR::RuntimeParamIndex::Unknown) {
  299. param_pattern.runtime_index = NextRuntimeIndex();
  300. context.ReplaceInstBeforeConstantUse(entry.pattern_id,
  301. param_pattern);
  302. }
  303. AddWork(
  304. {.pattern_id = param_pattern.subpattern_id,
  305. .scrutinee_id = context.AddInst<SemIR::OutParam>(
  306. pattern.loc_id,
  307. {.type_id = param_pattern.type_id,
  308. .runtime_index = param_pattern.runtime_index,
  309. .pretty_name_id = GetPrettyName(context, param_pattern)})});
  310. break;
  311. }
  312. case MatchKind::Local: {
  313. CARBON_FATAL("Found OutParamPattern during local pattern match");
  314. }
  315. }
  316. break;
  317. }
  318. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  319. CARBON_CHECK(kind_ == MatchKind::Callee);
  320. auto return_slot_id = context.AddInst<SemIR::ReturnSlot>(
  321. pattern.loc_id, {.type_id = return_slot_pattern.type_id,
  322. .type_inst_id = return_slot_pattern.type_inst_id,
  323. .storage_id = entry.scrutinee_id});
  324. bool already_in_lookup =
  325. context.scope_stack()
  326. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  327. .has_value();
  328. CARBON_CHECK(!already_in_lookup);
  329. results_.push_back(entry.scrutinee_id);
  330. break;
  331. }
  332. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  333. auto var_id = context.var_storage_map().Lookup(entry.pattern_id).value();
  334. // TODO: Find a more efficient way to put these insts in the global_init
  335. // block (or drop the distinction between the global_init block and the
  336. // file scope?)
  337. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  338. context.global_init().Resume();
  339. }
  340. if (entry.scrutinee_id.has_value()) {
  341. auto init_id =
  342. Initialize(context, pattern.loc_id, var_id, entry.scrutinee_id);
  343. // TODO: Consider using different instruction kinds for assignment
  344. // versus initialization.
  345. context.AddInst<SemIR::Assign>(pattern.loc_id,
  346. {.lhs_id = var_id, .rhs_id = init_id});
  347. }
  348. AddWork(
  349. {.pattern_id = var_pattern.subpattern_id, .scrutinee_id = var_id});
  350. if (context.scope_stack().PeekIndex() == ScopeIndex::Package) {
  351. context.global_init().Suspend();
  352. }
  353. break;
  354. }
  355. default: {
  356. CARBON_FATAL("Inst kind not handled: {0}", pattern.inst.kind());
  357. }
  358. }
  359. }
  360. auto CalleePatternMatch(Context& context,
  361. SemIR::InstBlockId implicit_param_patterns_id,
  362. SemIR::InstBlockId param_patterns_id,
  363. SemIR::InstId return_slot_pattern_id)
  364. -> SemIR::InstBlockId {
  365. if (!return_slot_pattern_id.has_value() && !param_patterns_id.has_value() &&
  366. !implicit_param_patterns_id.has_value()) {
  367. return SemIR::InstBlockId::None;
  368. }
  369. MatchContext match(MatchKind::Callee);
  370. // We add work to the stack in reverse so that the results will be produced
  371. // in the original order.
  372. if (return_slot_pattern_id.has_value()) {
  373. match.AddWork({.pattern_id = return_slot_pattern_id,
  374. .scrutinee_id = SemIR::InstId::None});
  375. }
  376. if (param_patterns_id.has_value()) {
  377. for (SemIR::InstId inst_id :
  378. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  379. match.AddWork(
  380. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  381. }
  382. }
  383. if (implicit_param_patterns_id.has_value()) {
  384. for (SemIR::InstId inst_id :
  385. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  386. match.AddWork(
  387. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::None});
  388. }
  389. }
  390. return match.DoWork(context);
  391. }
  392. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  393. SemIR::InstId self_pattern_id,
  394. SemIR::InstBlockId param_patterns_id,
  395. SemIR::InstId return_slot_pattern_id,
  396. SemIR::InstId self_arg_id,
  397. llvm::ArrayRef<SemIR::InstId> arg_refs,
  398. SemIR::InstId return_slot_arg_id)
  399. -> SemIR::InstBlockId {
  400. MatchContext match(MatchKind::Caller, specific_id);
  401. // Track the return storage, if present.
  402. if (return_slot_arg_id.has_value()) {
  403. CARBON_CHECK(return_slot_pattern_id.has_value());
  404. match.AddWork({.pattern_id = return_slot_pattern_id,
  405. .scrutinee_id = return_slot_arg_id});
  406. }
  407. // Check type conversions per-element.
  408. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  409. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  410. auto runtime_index = SemIR::Function::GetParamPatternInfoFromPatternId(
  411. context.sem_ir(), param_pattern_id)
  412. .inst.runtime_index;
  413. if (!runtime_index.has_value()) {
  414. // Not a runtime parameter: we don't pass an argument.
  415. continue;
  416. }
  417. match.AddWork({.pattern_id = param_pattern_id, .scrutinee_id = arg_id});
  418. }
  419. if (self_pattern_id.has_value()) {
  420. match.AddWork({.pattern_id = self_pattern_id, .scrutinee_id = self_arg_id});
  421. }
  422. return match.DoWork(context);
  423. }
  424. auto LocalPatternMatch(Context& context, SemIR::InstId pattern_id,
  425. SemIR::InstId scrutinee_id) -> void {
  426. MatchContext match(MatchKind::Local);
  427. match.AddWork({.pattern_id = pattern_id, .scrutinee_id = scrutinee_id});
  428. match.DoWork(context);
  429. }
  430. } // namespace Carbon::Check