pattern_match.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. namespace Carbon::Check {
  13. // Returns a best-effort name for the given ParamPattern, suitable for use in
  14. // IR pretty-printing.
  15. // TODO: Resolve overlap with SemIR::Function::ParamPatternInfo::GetNameId
  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::Invalid;
  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. // TODO: Add enumerator for non-function-call pattern match.
  41. };
  42. // The collected state of a pattern-matching operation.
  43. class MatchContext {
  44. public:
  45. struct WorkItem {
  46. SemIR::InstId pattern_id;
  47. // Invalid when processing the callee side.
  48. SemIR::InstId scrutinee_id;
  49. };
  50. // Constructs a MatchContext. If `callee_specific_id` is valid, this pattern
  51. // 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::Invalid)
  55. : next_index_(0), 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. When performing caller pattern
  59. // matching, returns an inst block with one inst reference for each
  60. // calling-convention argument. When performing callee pattern matching,
  61. // returns an inst block with references to all the emitted BindName insts.
  62. auto DoWork(Context& context) -> SemIR::InstBlockId;
  63. private:
  64. // Allocates the next unallocated RuntimeParamIndex, starting from 0.
  65. auto NextRuntimeIndex() -> SemIR::RuntimeParamIndex {
  66. auto result = next_index_;
  67. ++next_index_.index;
  68. return result;
  69. }
  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. // The stack of work to be processed.
  82. llvm::SmallVector<WorkItem> stack_;
  83. // The next index to be allocated by `NextRuntimeIndex`.
  84. SemIR::RuntimeParamIndex next_index_;
  85. // The pending results that will be returned by the current `DoWork` call.
  86. llvm::SmallVector<SemIR::InstId> results_;
  87. // The kind of pattern match being performed.
  88. MatchKind kind_;
  89. // The SpecificId of the function being called (if any).
  90. SemIR::SpecificId callee_specific_id_;
  91. };
  92. } // namespace
  93. auto MatchContext::DoWork(Context& context) -> SemIR::InstBlockId {
  94. results_.reserve(stack_.size());
  95. while (!stack_.empty()) {
  96. EmitPatternMatch(context, stack_.pop_back_val());
  97. }
  98. auto block_id = context.inst_blocks().Add(results_);
  99. results_.clear();
  100. return block_id;
  101. }
  102. auto MatchContext::EmitPatternMatch(Context& context,
  103. MatchContext::WorkItem entry) -> void {
  104. if (entry.pattern_id == SemIR::ErrorInst::SingletonInstId) {
  105. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  106. return;
  107. }
  108. DiagnosticAnnotationScope annotate_diagnostics(
  109. &context.emitter(), [&](auto& builder) {
  110. if (kind_ == MatchKind::Caller) {
  111. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  112. "initializing function parameter");
  113. builder.Note(entry.pattern_id, InCallToFunctionParam);
  114. }
  115. });
  116. auto pattern = context.insts().GetWithLocId(entry.pattern_id);
  117. CARBON_KIND_SWITCH(pattern.inst) {
  118. case SemIR::BindingPattern::Kind:
  119. case SemIR::SymbolicBindingPattern::Kind: {
  120. CARBON_CHECK(kind_ == MatchKind::Callee);
  121. // We're logically consuming this map entry, so we invalidate it in order
  122. // to avoid accidentally consuming it twice.
  123. auto [bind_name_id, type_expr_region_id] = std::exchange(
  124. context.bind_name_map().Lookup(entry.pattern_id).value(),
  125. {.bind_name_id = SemIR::InstId::Invalid,
  126. .type_expr_region_id = SemIR::ExprRegionId::Invalid});
  127. context.InsertHere(type_expr_region_id);
  128. auto bind_name = context.insts().GetAs<SemIR::AnyBindName>(bind_name_id);
  129. CARBON_CHECK(!bind_name.value_id.is_valid());
  130. bind_name.value_id = entry.scrutinee_id;
  131. context.ReplaceInstBeforeConstantUse(bind_name_id, bind_name);
  132. context.inst_block_stack().AddInstId(bind_name_id);
  133. if (context.insts()
  134. .GetAs<SemIR::AnyParam>(entry.scrutinee_id)
  135. .runtime_index.is_valid()) {
  136. results_.push_back(entry.scrutinee_id);
  137. }
  138. break;
  139. }
  140. case CARBON_KIND(SemIR::AddrPattern addr_pattern): {
  141. if (kind_ == MatchKind::Callee) {
  142. // We're emitting pattern-match IR for the callee, but we're still on
  143. // the caller side of the pattern, so we traverse without emitting any
  144. // insts.
  145. AddWork({.pattern_id = addr_pattern.inner_id,
  146. .scrutinee_id = SemIR::InstId::Invalid});
  147. break;
  148. }
  149. CARBON_CHECK(entry.scrutinee_id.is_valid());
  150. auto scrutinee_ref_id =
  151. ConvertToValueOrRefExpr(context, entry.scrutinee_id);
  152. switch (SemIR::GetExprCategory(context.sem_ir(), scrutinee_ref_id)) {
  153. case SemIR::ExprCategory::Error:
  154. case SemIR::ExprCategory::DurableRef:
  155. case SemIR::ExprCategory::EphemeralRef:
  156. break;
  157. default:
  158. CARBON_DIAGNOSTIC(AddrSelfIsNonRef, Error,
  159. "`addr self` method cannot be invoked on a value");
  160. context.emitter().Emit(
  161. TokenOnly(context.insts().GetLocId(entry.scrutinee_id)),
  162. AddrSelfIsNonRef);
  163. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  164. return;
  165. }
  166. auto scrutinee_ref = context.insts().Get(scrutinee_ref_id);
  167. auto new_scrutinee = context.AddInst<SemIR::AddrOf>(
  168. context.insts().GetLocId(scrutinee_ref_id),
  169. {.type_id = context.GetPointerType(scrutinee_ref.type_id()),
  170. .lvalue_id = scrutinee_ref_id});
  171. AddWork(
  172. {.pattern_id = addr_pattern.inner_id, .scrutinee_id = new_scrutinee});
  173. break;
  174. }
  175. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  176. CARBON_CHECK(param_pattern.runtime_index.index < 0 ||
  177. static_cast<size_t>(param_pattern.runtime_index.index) ==
  178. results_.size(),
  179. "Parameters out of order; expecting {0} but got {1}",
  180. results_.size(), param_pattern.runtime_index.index);
  181. switch (kind_) {
  182. case MatchKind::Caller: {
  183. CARBON_CHECK(entry.scrutinee_id.is_valid());
  184. if (entry.scrutinee_id == SemIR::ErrorInst::SingletonInstId) {
  185. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  186. } else {
  187. results_.push_back(ConvertToValueOfType(
  188. context, context.insts().GetLocId(entry.scrutinee_id),
  189. entry.scrutinee_id,
  190. SemIR::GetTypeInSpecific(context.sem_ir(), callee_specific_id_,
  191. param_pattern.type_id)));
  192. }
  193. // Do not traverse farther, because the caller side of the pattern
  194. // ends here.
  195. break;
  196. }
  197. case MatchKind::Callee: {
  198. if (param_pattern.runtime_index ==
  199. SemIR::RuntimeParamIndex::Unknown) {
  200. param_pattern.runtime_index = NextRuntimeIndex();
  201. context.ReplaceInstBeforeConstantUse(entry.pattern_id,
  202. param_pattern);
  203. }
  204. AddWork(
  205. {.pattern_id = param_pattern.subpattern_id,
  206. .scrutinee_id = context.AddInst<SemIR::ValueParam>(
  207. pattern.loc_id,
  208. {.type_id = param_pattern.type_id,
  209. .runtime_index = param_pattern.runtime_index,
  210. .pretty_name_id = GetPrettyName(context, param_pattern)})});
  211. break;
  212. }
  213. }
  214. break;
  215. }
  216. case CARBON_KIND(SemIR::OutParamPattern param_pattern): {
  217. switch (kind_) {
  218. case MatchKind::Caller: {
  219. CARBON_CHECK(entry.scrutinee_id.is_valid());
  220. CARBON_CHECK(context.insts().Get(entry.scrutinee_id).type_id() ==
  221. SemIR::GetTypeInSpecific(context.sem_ir(),
  222. callee_specific_id_,
  223. param_pattern.type_id));
  224. results_.push_back(entry.scrutinee_id);
  225. // Do not traverse farther, because the caller side of the pattern
  226. // ends here.
  227. break;
  228. }
  229. case MatchKind::Callee: {
  230. // TODO: Consider ways to address near-duplication with the
  231. // ValueParamPattern case.
  232. if (param_pattern.runtime_index ==
  233. SemIR::RuntimeParamIndex::Unknown) {
  234. param_pattern.runtime_index = NextRuntimeIndex();
  235. context.ReplaceInstBeforeConstantUse(entry.pattern_id,
  236. param_pattern);
  237. }
  238. AddWork(
  239. {.pattern_id = param_pattern.subpattern_id,
  240. .scrutinee_id = context.AddInst<SemIR::OutParam>(
  241. pattern.loc_id,
  242. {.type_id = param_pattern.type_id,
  243. .runtime_index = param_pattern.runtime_index,
  244. .pretty_name_id = GetPrettyName(context, param_pattern)})});
  245. break;
  246. }
  247. }
  248. break;
  249. }
  250. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  251. CARBON_CHECK(kind_ == MatchKind::Callee);
  252. auto return_slot_id = context.AddInst<SemIR::ReturnSlot>(
  253. pattern.loc_id, {.type_id = return_slot_pattern.type_id,
  254. .type_inst_id = return_slot_pattern.type_inst_id,
  255. .storage_id = entry.scrutinee_id});
  256. bool already_in_lookup =
  257. context.scope_stack()
  258. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  259. .is_valid();
  260. CARBON_CHECK(!already_in_lookup);
  261. results_.push_back(entry.scrutinee_id);
  262. break;
  263. }
  264. default: {
  265. CARBON_FATAL("Inst kind not handled: {0}", pattern.inst.kind());
  266. }
  267. }
  268. }
  269. auto CalleePatternMatch(Context& context,
  270. SemIR::InstBlockId implicit_param_patterns_id,
  271. SemIR::InstBlockId param_patterns_id,
  272. SemIR::InstId return_slot_pattern_id)
  273. -> SemIR::InstBlockId {
  274. if (!return_slot_pattern_id.is_valid() && !param_patterns_id.is_valid() &&
  275. !implicit_param_patterns_id.is_valid()) {
  276. return SemIR::InstBlockId::Invalid;
  277. }
  278. MatchContext match(MatchKind::Callee);
  279. // We add work to the stack in reverse so that the results will be produced
  280. // in the original order.
  281. if (return_slot_pattern_id.is_valid()) {
  282. match.AddWork({.pattern_id = return_slot_pattern_id,
  283. .scrutinee_id = SemIR::InstId::Invalid});
  284. }
  285. if (param_patterns_id.is_valid()) {
  286. for (SemIR::InstId inst_id :
  287. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  288. match.AddWork(
  289. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::Invalid});
  290. }
  291. }
  292. if (implicit_param_patterns_id.is_valid()) {
  293. for (SemIR::InstId inst_id :
  294. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  295. match.AddWork(
  296. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::Invalid});
  297. }
  298. }
  299. return match.DoWork(context);
  300. }
  301. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  302. SemIR::InstId self_pattern_id,
  303. SemIR::InstBlockId param_patterns_id,
  304. SemIR::InstId return_slot_pattern_id,
  305. SemIR::InstId self_arg_id,
  306. llvm::ArrayRef<SemIR::InstId> arg_refs,
  307. SemIR::InstId return_slot_arg_id)
  308. -> SemIR::InstBlockId {
  309. MatchContext match(MatchKind::Caller, specific_id);
  310. // Track the return storage, if present.
  311. if (return_slot_arg_id.is_valid()) {
  312. CARBON_CHECK(return_slot_pattern_id.is_valid());
  313. match.AddWork({.pattern_id = return_slot_pattern_id,
  314. .scrutinee_id = return_slot_arg_id});
  315. }
  316. // Check type conversions per-element.
  317. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  318. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  319. auto runtime_index = SemIR::Function::GetParamPatternInfoFromPatternId(
  320. context.sem_ir(), param_pattern_id)
  321. .inst.runtime_index;
  322. if (!runtime_index.is_valid()) {
  323. // Not a runtime parameter: we don't pass an argument.
  324. continue;
  325. }
  326. match.AddWork({.pattern_id = param_pattern_id, .scrutinee_id = arg_id});
  327. }
  328. if (self_pattern_id.is_valid()) {
  329. match.AddWork({.pattern_id = self_pattern_id, .scrutinee_id = self_arg_id});
  330. }
  331. return match.DoWork(context);
  332. }
  333. } // namespace Carbon::Check