pattern_match.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. auto [bind_name_id, type_expr_id] =
  122. context.bind_name_map().Lookup(entry.pattern_id).value();
  123. context.InsertHere(type_expr_id);
  124. auto bind_name = context.insts().GetAs<SemIR::AnyBindName>(bind_name_id);
  125. CARBON_CHECK(!bind_name.value_id.is_valid());
  126. bind_name.value_id = entry.scrutinee_id;
  127. context.ReplaceInstBeforeConstantUse(bind_name_id, bind_name);
  128. context.inst_block_stack().AddInstId(bind_name_id);
  129. if (context.insts()
  130. .GetAs<SemIR::AnyParam>(entry.scrutinee_id)
  131. .runtime_index.is_valid()) {
  132. results_.push_back(entry.scrutinee_id);
  133. }
  134. break;
  135. }
  136. case CARBON_KIND(SemIR::AddrPattern addr_pattern): {
  137. if (kind_ == MatchKind::Callee) {
  138. // We're emitting pattern-match IR for the callee, but we're still on
  139. // the caller side of the pattern, so we traverse without emitting any
  140. // insts.
  141. AddWork({.pattern_id = addr_pattern.inner_id,
  142. .scrutinee_id = SemIR::InstId::Invalid});
  143. break;
  144. }
  145. CARBON_CHECK(entry.scrutinee_id.is_valid());
  146. auto scrutinee_ref_id =
  147. ConvertToValueOrRefExpr(context, entry.scrutinee_id);
  148. switch (SemIR::GetExprCategory(context.sem_ir(), scrutinee_ref_id)) {
  149. case SemIR::ExprCategory::Error:
  150. case SemIR::ExprCategory::DurableRef:
  151. case SemIR::ExprCategory::EphemeralRef:
  152. break;
  153. default:
  154. CARBON_DIAGNOSTIC(AddrSelfIsNonRef, Error,
  155. "`addr self` method cannot be invoked on a value");
  156. context.emitter().Emit(
  157. TokenOnly(context.insts().GetLocId(entry.scrutinee_id)),
  158. AddrSelfIsNonRef);
  159. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  160. return;
  161. }
  162. auto scrutinee_ref = context.insts().Get(scrutinee_ref_id);
  163. auto new_scrutinee = context.AddInst<SemIR::AddrOf>(
  164. context.insts().GetLocId(scrutinee_ref_id),
  165. {.type_id = context.GetPointerType(scrutinee_ref.type_id()),
  166. .lvalue_id = scrutinee_ref_id});
  167. AddWork(
  168. {.pattern_id = addr_pattern.inner_id, .scrutinee_id = new_scrutinee});
  169. break;
  170. }
  171. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  172. CARBON_CHECK(param_pattern.runtime_index.index < 0 ||
  173. static_cast<size_t>(param_pattern.runtime_index.index) ==
  174. results_.size(),
  175. "Parameters out of order; expecting {0} but got {1}",
  176. results_.size(), param_pattern.runtime_index.index);
  177. switch (kind_) {
  178. case MatchKind::Caller: {
  179. CARBON_CHECK(entry.scrutinee_id.is_valid());
  180. if (entry.scrutinee_id == SemIR::ErrorInst::SingletonInstId) {
  181. results_.push_back(SemIR::ErrorInst::SingletonInstId);
  182. } else {
  183. results_.push_back(ConvertToValueOfType(
  184. context, context.insts().GetLocId(entry.scrutinee_id),
  185. entry.scrutinee_id,
  186. SemIR::GetTypeInSpecific(context.sem_ir(), callee_specific_id_,
  187. param_pattern.type_id)));
  188. }
  189. // Do not traverse farther, because the caller side of the pattern
  190. // ends here.
  191. break;
  192. }
  193. case MatchKind::Callee: {
  194. if (param_pattern.runtime_index ==
  195. SemIR::RuntimeParamIndex::Unknown) {
  196. param_pattern.runtime_index = NextRuntimeIndex();
  197. context.ReplaceInstBeforeConstantUse(entry.pattern_id,
  198. param_pattern);
  199. }
  200. AddWork(
  201. {.pattern_id = param_pattern.subpattern_id,
  202. .scrutinee_id = context.AddInst<SemIR::ValueParam>(
  203. pattern.loc_id,
  204. {.type_id = param_pattern.type_id,
  205. .runtime_index = param_pattern.runtime_index,
  206. .pretty_name_id = GetPrettyName(context, param_pattern)})});
  207. break;
  208. }
  209. }
  210. break;
  211. }
  212. case CARBON_KIND(SemIR::OutParamPattern param_pattern): {
  213. switch (kind_) {
  214. case MatchKind::Caller: {
  215. CARBON_CHECK(entry.scrutinee_id.is_valid());
  216. CARBON_CHECK(context.insts().Get(entry.scrutinee_id).type_id() ==
  217. SemIR::GetTypeInSpecific(context.sem_ir(),
  218. callee_specific_id_,
  219. param_pattern.type_id));
  220. results_.push_back(entry.scrutinee_id);
  221. // Do not traverse farther, because the caller side of the pattern
  222. // ends here.
  223. break;
  224. }
  225. case MatchKind::Callee: {
  226. // TODO: Consider ways to address near-duplication with the
  227. // ValueParamPattern case.
  228. if (param_pattern.runtime_index ==
  229. SemIR::RuntimeParamIndex::Unknown) {
  230. param_pattern.runtime_index = NextRuntimeIndex();
  231. context.ReplaceInstBeforeConstantUse(entry.pattern_id,
  232. param_pattern);
  233. }
  234. AddWork(
  235. {.pattern_id = param_pattern.subpattern_id,
  236. .scrutinee_id = context.AddInst<SemIR::OutParam>(
  237. pattern.loc_id,
  238. {.type_id = param_pattern.type_id,
  239. .runtime_index = param_pattern.runtime_index,
  240. .pretty_name_id = GetPrettyName(context, param_pattern)})});
  241. break;
  242. }
  243. }
  244. break;
  245. }
  246. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  247. CARBON_CHECK(kind_ == MatchKind::Callee);
  248. auto return_slot_id = context.AddInst<SemIR::ReturnSlot>(
  249. pattern.loc_id, {.type_id = return_slot_pattern.type_id,
  250. .type_inst_id = return_slot_pattern.type_inst_id,
  251. .storage_id = entry.scrutinee_id});
  252. bool already_in_lookup =
  253. context.scope_stack()
  254. .LookupOrAddName(SemIR::NameId::ReturnSlot, return_slot_id)
  255. .is_valid();
  256. CARBON_CHECK(!already_in_lookup);
  257. results_.push_back(entry.scrutinee_id);
  258. break;
  259. }
  260. default: {
  261. CARBON_FATAL("Inst kind not handled: {0}", pattern.inst.kind());
  262. }
  263. }
  264. }
  265. auto CalleePatternMatch(Context& context,
  266. SemIR::InstBlockId implicit_param_patterns_id,
  267. SemIR::InstBlockId param_patterns_id,
  268. SemIR::InstId return_slot_pattern_id)
  269. -> SemIR::InstBlockId {
  270. if (!return_slot_pattern_id.is_valid() && !param_patterns_id.is_valid() &&
  271. !implicit_param_patterns_id.is_valid()) {
  272. return SemIR::InstBlockId::Invalid;
  273. }
  274. MatchContext match(MatchKind::Callee);
  275. // We add work to the stack in reverse so that the results will be produced
  276. // in the original order.
  277. if (return_slot_pattern_id.is_valid()) {
  278. match.AddWork({.pattern_id = return_slot_pattern_id,
  279. .scrutinee_id = SemIR::InstId::Invalid});
  280. }
  281. if (param_patterns_id.is_valid()) {
  282. for (SemIR::InstId inst_id :
  283. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  284. match.AddWork(
  285. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::Invalid});
  286. }
  287. }
  288. if (implicit_param_patterns_id.is_valid()) {
  289. for (SemIR::InstId inst_id :
  290. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  291. match.AddWork(
  292. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::Invalid});
  293. }
  294. }
  295. return match.DoWork(context);
  296. }
  297. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  298. SemIR::InstId self_pattern_id,
  299. SemIR::InstBlockId param_patterns_id,
  300. SemIR::InstId return_slot_pattern_id,
  301. SemIR::InstId self_arg_id,
  302. llvm::ArrayRef<SemIR::InstId> arg_refs,
  303. SemIR::InstId return_slot_arg_id)
  304. -> SemIR::InstBlockId {
  305. MatchContext match(MatchKind::Caller, specific_id);
  306. // Track the return storage, if present.
  307. if (return_slot_arg_id.is_valid()) {
  308. CARBON_CHECK(return_slot_pattern_id.is_valid());
  309. match.AddWork({.pattern_id = return_slot_pattern_id,
  310. .scrutinee_id = return_slot_arg_id});
  311. }
  312. // Check type conversions per-element.
  313. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  314. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  315. auto runtime_index = SemIR::Function::GetParamPatternInfoFromPatternId(
  316. context.sem_ir(), param_pattern_id)
  317. .inst.runtime_index;
  318. if (!runtime_index.is_valid()) {
  319. // Not a runtime parameter: we don't pass an argument.
  320. continue;
  321. }
  322. match.AddWork({.pattern_id = param_pattern_id, .scrutinee_id = arg_id});
  323. }
  324. if (self_pattern_id.is_valid()) {
  325. match.AddWork({.pattern_id = self_pattern_id, .scrutinee_id = self_arg_id});
  326. }
  327. return match.DoWork(context);
  328. }
  329. } // namespace Carbon::Check