pattern_match.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 {
  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),
  56. kind_(kind),
  57. callee_specific_id_(callee_specific_id),
  58. return_slot_id_(SemIR::InstId::Invalid) {}
  59. // Adds a work item to the stack.
  60. auto AddWork(WorkItem work_item) -> void { stack_.push_back(work_item); }
  61. // Processes all work items on the stack. When performing caller pattern
  62. // matching, returns an inst block with one inst reference for each
  63. // calling-convention argument. When performing callee pattern matching,
  64. // returns an inst block with references to all the emitted BindName insts.
  65. auto DoWork(Context& context) -> SemIR::InstBlockId;
  66. auto return_slot_id() const -> SemIR::InstId { return return_slot_id_; }
  67. private:
  68. // Allocates the next unallocated RuntimeParamIndex, starting from 0.
  69. auto NextRuntimeIndex() -> SemIR::RuntimeParamIndex {
  70. auto result = next_index_;
  71. ++next_index_.index;
  72. return result;
  73. }
  74. // Emits the pattern-match insts necessary to match the pattern inst
  75. // `entry.pattern_id` against the scrutinee value `entry.scrutinee_id`, and
  76. // adds to `stack_` any work necessary to traverse into its subpatterns. This
  77. // behavior is contingent on the kind of match being performed, as indicated
  78. // by kind_`. For example, when performing a callee pattern match, this does
  79. // not emit insts for patterns on the caller side. However, it still traverses
  80. // into subpatterns if any of their descendants might emit insts.
  81. // TODO: Require that `entry.scrutinee_id` is valid if and only if insts
  82. // should be emitted, once we start emitting `Param` insts in the
  83. // `ParamPattern` case.
  84. auto EmitPatternMatch(Context& context, MatchContext::WorkItem entry) -> void;
  85. // The stack of work to be processed.
  86. llvm::SmallVector<WorkItem> stack_;
  87. // The next index to be allocated by `NextRuntimeIndex`.
  88. SemIR::RuntimeParamIndex next_index_;
  89. // The pending results that will be returned by the current `DoWork` call.
  90. llvm::SmallVector<SemIR::InstId> results_;
  91. // The kind of pattern match being performed.
  92. MatchKind kind_;
  93. // The SpecificId of the function being called (if any).
  94. SemIR::SpecificId callee_specific_id_;
  95. // The return slot inst emitted by `DoWork`, if any.
  96. // TODO: Can this be added to the block returned by `DoWork`, instead?
  97. SemIR::InstId return_slot_id_;
  98. };
  99. } // namespace
  100. auto MatchContext::DoWork(Context& context) -> SemIR::InstBlockId {
  101. results_.reserve(stack_.size());
  102. while (!stack_.empty()) {
  103. EmitPatternMatch(context, stack_.pop_back_val());
  104. }
  105. auto block_id = context.inst_blocks().Add(results_);
  106. results_.clear();
  107. return block_id;
  108. }
  109. auto MatchContext::EmitPatternMatch(Context& context,
  110. MatchContext::WorkItem entry) -> void {
  111. if (entry.pattern_id == SemIR::InstId::BuiltinErrorInst) {
  112. results_.push_back(SemIR::InstId::BuiltinErrorInst);
  113. return;
  114. }
  115. DiagnosticAnnotationScope annotate_diagnostics(
  116. &context.emitter(), [&](auto& builder) {
  117. if (kind_ == MatchKind::Caller) {
  118. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  119. "initializing function parameter");
  120. builder.Note(entry.pattern_id, InCallToFunctionParam);
  121. }
  122. });
  123. auto pattern = context.insts().GetWithLocId(entry.pattern_id);
  124. CARBON_KIND_SWITCH(pattern.inst) {
  125. case SemIR::BindingPattern::Kind:
  126. case SemIR::SymbolicBindingPattern::Kind: {
  127. CARBON_CHECK(kind_ == MatchKind::Callee);
  128. auto binding_pattern = pattern.inst.As<SemIR::AnyBindingPattern>();
  129. auto cache_entry =
  130. context.bind_name_cache().Lookup(binding_pattern.entity_name_id);
  131. // The cached bind_name should only be used once.
  132. auto bind_name_id =
  133. std::exchange(cache_entry.value(), SemIR::InstId::Invalid);
  134. auto bind_name = context.insts().GetAs<SemIR::AnyBindName>(bind_name_id);
  135. CARBON_CHECK(!bind_name.value_id.is_valid());
  136. bind_name.value_id = entry.scrutinee_id;
  137. context.ReplaceInstBeforeConstantUse(bind_name_id, bind_name);
  138. context.inst_block_stack().AddInstId(bind_name_id);
  139. results_.push_back(bind_name_id);
  140. break;
  141. }
  142. case CARBON_KIND(SemIR::AddrPattern addr_pattern): {
  143. if (kind_ == MatchKind::Callee) {
  144. // We're emitting pattern-match IR for the callee, but we're still on
  145. // the caller side of the pattern, so we traverse without emitting any
  146. // insts.
  147. AddWork({.pattern_id = addr_pattern.inner_id,
  148. .scrutinee_id = SemIR::InstId::Invalid});
  149. break;
  150. }
  151. CARBON_CHECK(entry.scrutinee_id.is_valid());
  152. auto scrutinee_ref_id =
  153. ConvertToValueOrRefExpr(context, entry.scrutinee_id);
  154. switch (SemIR::GetExprCategory(context.sem_ir(), scrutinee_ref_id)) {
  155. case SemIR::ExprCategory::Error:
  156. case SemIR::ExprCategory::DurableRef:
  157. case SemIR::ExprCategory::EphemeralRef:
  158. break;
  159. default:
  160. CARBON_DIAGNOSTIC(AddrSelfIsNonRef, Error,
  161. "`addr self` method cannot be invoked on a value");
  162. context.emitter().Emit(
  163. TokenOnly(context.insts().GetLocId(entry.scrutinee_id)),
  164. AddrSelfIsNonRef);
  165. results_.push_back(SemIR::InstId::BuiltinErrorInst);
  166. return;
  167. }
  168. auto scrutinee_ref = context.insts().Get(scrutinee_ref_id);
  169. auto new_scrutinee = context.AddInst<SemIR::AddrOf>(
  170. context.insts().GetLocId(scrutinee_ref_id),
  171. {.type_id = context.GetPointerType(scrutinee_ref.type_id()),
  172. .lvalue_id = scrutinee_ref_id});
  173. AddWork(
  174. {.pattern_id = addr_pattern.inner_id, .scrutinee_id = new_scrutinee});
  175. break;
  176. }
  177. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  178. CARBON_CHECK(param_pattern.runtime_index.index < 0 ||
  179. static_cast<size_t>(param_pattern.runtime_index.index) ==
  180. results_.size(),
  181. "Parameters out of order; expecting {0} but got {1}",
  182. results_.size(), param_pattern.runtime_index.index);
  183. switch (kind_) {
  184. case MatchKind::Caller: {
  185. CARBON_CHECK(entry.scrutinee_id.is_valid());
  186. if (entry.scrutinee_id == SemIR::InstId::BuiltinErrorInst) {
  187. results_.push_back(SemIR::InstId::BuiltinErrorInst);
  188. } else {
  189. results_.push_back(ConvertToValueOfType(
  190. context, context.insts().GetLocId(entry.scrutinee_id),
  191. entry.scrutinee_id,
  192. SemIR::GetTypeInSpecific(context.sem_ir(), callee_specific_id_,
  193. param_pattern.type_id)));
  194. }
  195. // Do not traverse farther, because the caller side of the pattern
  196. // ends here.
  197. break;
  198. }
  199. case MatchKind::Callee: {
  200. if (param_pattern.runtime_index ==
  201. SemIR::RuntimeParamIndex::Unknown) {
  202. param_pattern.runtime_index = NextRuntimeIndex();
  203. context.ReplaceInstBeforeConstantUse(entry.pattern_id,
  204. param_pattern);
  205. }
  206. AddWork(
  207. {.pattern_id = param_pattern.subpattern_id,
  208. .scrutinee_id = context.AddInst<SemIR::ValueParam>(
  209. pattern.loc_id,
  210. {.type_id = param_pattern.type_id,
  211. .runtime_index = param_pattern.runtime_index,
  212. .pretty_name_id = GetPrettyName(context, param_pattern)})});
  213. break;
  214. }
  215. }
  216. break;
  217. }
  218. case CARBON_KIND(SemIR::OutParamPattern param_pattern): {
  219. switch (kind_) {
  220. case MatchKind::Caller: {
  221. CARBON_CHECK(entry.scrutinee_id.is_valid());
  222. CARBON_CHECK(context.insts().Get(entry.scrutinee_id).type_id() ==
  223. SemIR::GetTypeInSpecific(context.sem_ir(),
  224. callee_specific_id_,
  225. param_pattern.type_id));
  226. results_.push_back(entry.scrutinee_id);
  227. // Do not traverse farther, because the caller side of the pattern
  228. // ends here.
  229. break;
  230. }
  231. case MatchKind::Callee: {
  232. // TODO: Consider ways to address near-duplication with the
  233. // ValueParamPattern case.
  234. if (param_pattern.runtime_index ==
  235. SemIR::RuntimeParamIndex::Unknown) {
  236. param_pattern.runtime_index = NextRuntimeIndex();
  237. context.ReplaceInstBeforeConstantUse(entry.pattern_id,
  238. param_pattern);
  239. }
  240. AddWork(
  241. {.pattern_id = param_pattern.subpattern_id,
  242. .scrutinee_id = context.AddInst<SemIR::OutParam>(
  243. pattern.loc_id,
  244. {.type_id = param_pattern.type_id,
  245. .runtime_index = param_pattern.runtime_index,
  246. .pretty_name_id = GetPrettyName(context, param_pattern)})});
  247. break;
  248. }
  249. }
  250. break;
  251. }
  252. case CARBON_KIND(SemIR::ReturnSlotPattern return_slot_pattern): {
  253. CARBON_CHECK(kind_ == MatchKind::Callee);
  254. return_slot_id_ = context.AddInst<SemIR::ReturnSlot>(
  255. pattern.loc_id, {.type_id = return_slot_pattern.type_id,
  256. .type_inst_id = return_slot_pattern.type_inst_id,
  257. .storage_id = 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. -> ParameterBlocks {
  270. auto params_id = SemIR::InstBlockId::Invalid;
  271. auto implicit_params_id = SemIR::InstBlockId::Invalid;
  272. MatchContext match(MatchKind::Callee);
  273. if (implicit_param_patterns_id.is_valid()) {
  274. // We add work to the stack in reverse so that the results will be produced
  275. // in the original order.
  276. for (SemIR::InstId inst_id :
  277. llvm::reverse(context.inst_blocks().Get(implicit_param_patterns_id))) {
  278. match.AddWork(
  279. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::Invalid});
  280. }
  281. implicit_params_id = match.DoWork(context);
  282. }
  283. if (param_patterns_id.is_valid()) {
  284. for (SemIR::InstId inst_id :
  285. llvm::reverse(context.inst_blocks().Get(param_patterns_id))) {
  286. match.AddWork(
  287. {.pattern_id = inst_id, .scrutinee_id = SemIR::InstId::Invalid});
  288. }
  289. params_id = match.DoWork(context);
  290. }
  291. if (return_slot_pattern_id.is_valid()) {
  292. match.AddWork({.pattern_id = return_slot_pattern_id,
  293. .scrutinee_id = SemIR::InstId::Invalid});
  294. CARBON_CHECK(match.DoWork(context) == SemIR::InstBlockId::Empty);
  295. }
  296. return {.implicit_params_id = implicit_params_id,
  297. .params_id = params_id,
  298. .return_slot_id = match.return_slot_id()};
  299. }
  300. auto CallerPatternMatch(Context& context, SemIR::SpecificId specific_id,
  301. SemIR::InstId self_pattern_id,
  302. SemIR::InstBlockId param_patterns_id,
  303. SemIR::InstId return_slot_pattern_id,
  304. SemIR::InstId self_arg_id,
  305. llvm::ArrayRef<SemIR::InstId> arg_refs,
  306. SemIR::InstId return_slot_arg_id)
  307. -> SemIR::InstBlockId {
  308. MatchContext match(MatchKind::Caller, specific_id);
  309. // Track the return storage, if present.
  310. if (return_slot_arg_id.is_valid()) {
  311. CARBON_CHECK(return_slot_pattern_id.is_valid());
  312. match.AddWork({.pattern_id = return_slot_pattern_id,
  313. .scrutinee_id = return_slot_arg_id});
  314. }
  315. // Check type conversions per-element.
  316. for (auto [arg_id, param_pattern_id] : llvm::reverse(llvm::zip_equal(
  317. arg_refs, context.inst_blocks().GetOrEmpty(param_patterns_id)))) {
  318. auto runtime_index = SemIR::Function::GetParamPatternInfoFromPatternId(
  319. context.sem_ir(), param_pattern_id)
  320. .inst.runtime_index;
  321. if (!runtime_index.is_valid()) {
  322. // Not a runtime parameter: we don't pass an argument.
  323. continue;
  324. }
  325. match.AddWork({.pattern_id = param_pattern_id, .scrutinee_id = arg_id});
  326. }
  327. if (self_pattern_id.is_valid()) {
  328. match.AddWork({.pattern_id = self_pattern_id, .scrutinee_id = self_arg_id});
  329. }
  330. return match.DoWork(context);
  331. }
  332. } // namespace Carbon::Check