handle_where.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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/base/kind_switch.h"
  5. #include "toolchain/check/context.h"
  6. #include "toolchain/check/convert.h"
  7. #include "toolchain/check/facet_type.h"
  8. #include "toolchain/check/generic.h"
  9. #include "toolchain/check/handle.h"
  10. #include "toolchain/check/inst.h"
  11. #include "toolchain/check/period_self.h"
  12. #include "toolchain/check/subst.h"
  13. #include "toolchain/check/type.h"
  14. #include "toolchain/check/unused.h"
  15. #include "toolchain/sem_ir/facet_type_info.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/inst.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. auto HandleParseNode(Context& context, Parse::WhereOperandId node_id) -> bool {
  21. // The expression at the top of the stack represents a constraint type that
  22. // is being modified by the `where` operator. It would be `MyInterface` in
  23. // `MyInterface where .Member = i32`.
  24. auto [self_node, self_id] = context.node_stack().PopExprWithNodeId();
  25. auto self_with_constraints_type_id =
  26. ExprAsType(context, self_node, self_id).type_id;
  27. // Only facet types may have `where` restrictions.
  28. if (!context.types().IsFacetTypeOrError(self_with_constraints_type_id)) {
  29. CARBON_DIAGNOSTIC(WhereOnNonFacetType, Error,
  30. "left argument of `where` operator must be a facet type");
  31. context.emitter().Emit(self_node, WhereOnNonFacetType);
  32. self_with_constraints_type_id = SemIR::ErrorInst::TypeId;
  33. }
  34. if (self_with_constraints_type_id == SemIR::ErrorInst::TypeId) {
  35. // Keep `self_id` in sync with `self_with_constraints_type_id`, if one is an
  36. // error they both are. Note that ExprAsType may have returned ErrorInst,
  37. // or we may have set it to ErrorInst in this function.
  38. self_id = SemIR::ErrorInst::InstId;
  39. }
  40. // Strip off any constraints provided by a `WhereExpr` from the `Self` facet
  41. // type. For a facet type like `I & J where .X = .Y`, this will reduce it down
  42. // to just `I & J`.
  43. //
  44. // Any references to `.Self` in constraints for the current `WhereExpr` will
  45. // not see constraints in the `Self` facet type, but they will resolve to
  46. // values through the constraints explicitly when they are combined together.
  47. auto period_self_type_id = self_with_constraints_type_id;
  48. if (auto facet_type =
  49. context.types().TryGetAs<SemIR::FacetType>(period_self_type_id)) {
  50. const auto& info = context.facet_types().Get(facet_type->facet_type_id);
  51. auto stripped_info = SemIR::FacetTypeInfo::ExtendedOnly(info);
  52. stripped_info.Canonicalize();
  53. period_self_type_id = GetFacetType(context, stripped_info);
  54. } else if (period_self_type_id == SemIR::TypeType::TypeId) {
  55. // The self may be `TypeType` in `type where X impls Y`, so we use an empty
  56. // facet type.
  57. period_self_type_id = GetEmptyFacetType(context);
  58. } else {
  59. CARBON_CHECK(period_self_type_id == SemIR::ErrorInst::TypeId,
  60. "unexpected .Self type {0}", period_self_type_id);
  61. }
  62. // Introduce a name scope so that we can remove the `.Self` entry we are
  63. // adding to name lookup at the end of the `where` expression.
  64. context.scope_stack().PushForSameRegion();
  65. // Introduce `.Self` as a symbolic binding. Its type is the value of the
  66. // expression to the left of `where`, so `MyInterface` in the example above.
  67. MakePeriodSelfFacetValue(context, period_self_type_id);
  68. // Going to put each requirement on `args_type_info_stack`, so we can have an
  69. // inst block with the varying number of requirements but keeping other
  70. // instructions on the current inst block from the `inst_block_stack()`.
  71. context.args_type_info_stack().Push();
  72. // Pass along all the constraints from the base facet type to be added to the
  73. // resulting facet type.
  74. context.args_type_info_stack().AddInstId(
  75. AddInstInNoBlock<SemIR::RequirementBaseFacetType>(
  76. context, SemIR::LocId(node_id),
  77. {.base_type_inst_id = context.types().GetAsTypeInstId(self_id)}));
  78. // Add a context stack for tracking rewrite constraints, that will be used to
  79. // allow later constraints to read from them eagerly.
  80. context.rewrites_stack().emplace_back();
  81. // Make rewrite constraints from the self facet type available immediately to
  82. // expressions in rewrite constraints for this `where` expression.
  83. if (auto self_facet_type = context.types().TryGetAs<SemIR::FacetType>(
  84. self_with_constraints_type_id)) {
  85. const auto& base_facet_type_info =
  86. context.facet_types().Get(self_facet_type->facet_type_id);
  87. for (const auto& rewrite : base_facet_type_info.rewrite_constraints) {
  88. if (rewrite.lhs_id != SemIR::ErrorInst::InstId) {
  89. context.rewrites_stack().back().Insert(
  90. context.constant_values().Get(
  91. GetImplWitnessAccessWithoutSubstitution(context,
  92. rewrite.lhs_id)),
  93. rewrite.rhs_id);
  94. }
  95. }
  96. }
  97. return true;
  98. }
  99. auto HandleParseNode(Context& context, Parse::RequirementEqualId node_id)
  100. -> bool {
  101. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  102. auto lhs_id = context.node_stack().PopExpr();
  103. // Convert rhs to type of lhs.
  104. auto lhs_type_id = context.insts().Get(lhs_id).type_id();
  105. if (lhs_type_id.is_symbolic()) {
  106. // If the type of the associated constant is symbolic, we defer conversion
  107. // until the constraint is resolved, in case it depends on `Self` (which
  108. // will now be a reference to `.Self`).
  109. // For now we convert to a value expression eagerly because otherwise we'll
  110. // often be unable to constant-evaluate the enclosing `where` expression.
  111. // TODO: Perform the conversion symbolically and add an implicit constraint
  112. // that this conversion is valid and produces a constant.
  113. rhs_id = ConvertToValueExpr(context, rhs_id);
  114. } else {
  115. rhs_id = ConvertToValueOfType(context, rhs_node, rhs_id,
  116. context.insts().Get(lhs_id).type_id());
  117. }
  118. // Build up the list of arguments for the `WhereExpr` inst.
  119. context.args_type_info_stack().AddInstId(
  120. AddInstInNoBlock<SemIR::RequirementRewrite>(
  121. context, node_id, {.lhs_id = lhs_id, .rhs_id = rhs_id}));
  122. if (lhs_id != SemIR::ErrorInst::InstId) {
  123. // Track the value of the rewrite so further constraints can use it
  124. // immediately, before they are evaluated. This happens directly where the
  125. // `ImplWitnessAccess` that refers to the rewrite constraint would have been
  126. // created, and the value of the constraint will be used instead.
  127. context.rewrites_stack().back().Insert(
  128. context.constant_values().Get(
  129. GetImplWitnessAccessWithoutSubstitution(context, lhs_id)),
  130. rhs_id);
  131. }
  132. return true;
  133. }
  134. auto HandleParseNode(Context& context, Parse::RequirementEqualEqualId node_id)
  135. -> bool {
  136. auto rhs = context.node_stack().PopExpr();
  137. auto lhs = context.node_stack().PopExpr();
  138. // TODO: Type check lhs and rhs are comparable.
  139. // TODO: Require that at least one side uses a designator.
  140. // Build up the list of arguments for the `WhereExpr` inst.
  141. context.args_type_info_stack().AddInstId(
  142. AddInstInNoBlock<SemIR::RequirementEquivalent>(
  143. context, node_id, {.lhs_id = lhs, .rhs_id = rhs}));
  144. return true;
  145. }
  146. auto HandleParseNode(Context& context, Parse::RequirementImplsId node_id)
  147. -> bool {
  148. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  149. auto [lhs_node, lhs_id] = context.node_stack().PopExprWithNodeId();
  150. // Check lhs is a facet and rhs is a facet type.
  151. auto lhs_as_type = ExprAsType(context, lhs_node, lhs_id);
  152. auto rhs_as_type = ExprAsType(context, rhs_node, rhs_id);
  153. if (rhs_as_type.type_id != SemIR::ErrorInst::TypeId &&
  154. !context.types().IsFacetType(rhs_as_type.type_id)) {
  155. CARBON_DIAGNOSTIC(
  156. ImplsOnNonFacetType, Error,
  157. "right argument of `impls` requirement must be a facet type");
  158. context.emitter().Emit(rhs_node, ImplsOnNonFacetType);
  159. rhs_as_type.inst_id = SemIR::ErrorInst::TypeInstId;
  160. }
  161. // TODO: Require that at least one side uses a designator.
  162. // TODO: For things like `HashSet(.T) as type`, add an implied constraint
  163. // that `.T impls Hash`.
  164. if (FindAndDiagnoseAmbiguousPeriodSelf(context, lhs_as_type.inst_id,
  165. rhs_id)) {
  166. rhs_as_type.inst_id = SemIR::ErrorInst::TypeInstId;
  167. }
  168. // Build up the list of arguments for the `WhereExpr` inst.
  169. context.args_type_info_stack().AddInstId(
  170. AddInstInNoBlock<SemIR::RequirementImpls>(
  171. context, node_id,
  172. {.lhs_id = lhs_as_type.inst_id, .rhs_id = rhs_as_type.inst_id}));
  173. return true;
  174. }
  175. auto HandleParseNode(Context& /*context*/, Parse::RequirementAndId /*node_id*/)
  176. -> bool {
  177. // Nothing to do.
  178. return true;
  179. }
  180. // Returns whether a designator (`.Self` or `.MemberName`) is present in the
  181. // where clause.
  182. static auto FindDesignator(Context& context,
  183. SemIR::InstBlockId requirements_block_id) -> bool {
  184. auto block = context.inst_blocks().GetOrEmpty(requirements_block_id);
  185. llvm::SmallVector<SemIR::InstId> requirements;
  186. requirements.reserve(block.size() * 2);
  187. for (auto inst_id : block) {
  188. auto inst = context.insts().Get(inst_id);
  189. CARBON_KIND_SWITCH(inst) {
  190. case CARBON_KIND(SemIR::RequirementBaseFacetType base): {
  191. requirements.push_back(base.base_type_inst_id);
  192. break;
  193. }
  194. case CARBON_KIND(SemIR::RequirementRewrite rewrite): {
  195. requirements.push_back(rewrite.lhs_id);
  196. requirements.push_back(rewrite.rhs_id);
  197. break;
  198. }
  199. case CARBON_KIND(SemIR::RequirementEquivalent equiv): {
  200. requirements.push_back(equiv.lhs_id);
  201. requirements.push_back(equiv.rhs_id);
  202. break;
  203. }
  204. case CARBON_KIND(SemIR::RequirementImpls impls): {
  205. requirements.push_back(impls.lhs_id);
  206. requirements.push_back(impls.rhs_id);
  207. break;
  208. }
  209. default:
  210. CARBON_CHECK(inst_id == SemIR::ErrorInst::InstId,
  211. "unexpected inst {0} in requirements", inst);
  212. }
  213. }
  214. class SubstFindDesignator : public SubstInstCallbacks {
  215. public:
  216. explicit SubstFindDesignator(Context* context, bool* found)
  217. : SubstInstCallbacks(context), found_(found) {}
  218. auto Subst(SemIR::InstId& inst_id) -> SubstResult override {
  219. if (*found_) {
  220. return FullySubstituted;
  221. }
  222. // An error was diagnosed for the where clause already.
  223. if (inst_id == SemIR::ErrorInst::InstId) {
  224. *found_ = true;
  225. return FullySubstituted;
  226. }
  227. // TypeType has type TypeType, avoid recursing on its type.
  228. if (context().insts().Is<SemIR::TypeType>(inst_id)) {
  229. return FullySubstituted;
  230. }
  231. // `.MemberName` is represented as an ImplWitnessAccess through `.Self` so
  232. // we only need to look for `.Self` here.
  233. if (auto bind =
  234. context().insts().TryGetAs<SemIR::SymbolicBinding>(inst_id)) {
  235. auto entity_name = context().entity_names().Get(bind->entity_name_id);
  236. if (entity_name.name_id == SemIR::NameId::PeriodSelf) {
  237. *found_ = true;
  238. return FullySubstituted;
  239. }
  240. }
  241. return SubstOperands;
  242. }
  243. auto Rebuild(SemIR::InstId /*orig_inst_id*/, SemIR::Inst /*new_inst*/)
  244. -> SemIR::InstId override {
  245. CARBON_FATAL("unexpected rebuild, no insts should change");
  246. }
  247. bool* found_;
  248. };
  249. for (auto inst_id : requirements) {
  250. bool found = false;
  251. SubstFindDesignator callbacks(&context, &found);
  252. SubstInst(context, inst_id, callbacks);
  253. if (found) {
  254. return true;
  255. }
  256. }
  257. return false;
  258. }
  259. auto HandleParseNode(Context& context, Parse::WhereExprId node_id) -> bool {
  260. context.rewrites_stack().pop_back();
  261. // Remove `PeriodSelf` from name lookup, undoing the `Push` done for the
  262. // `WhereOperand`.
  263. context.scope_stack().Pop(/*check_unused=*/true);
  264. SemIR::InstBlockId requirements_id = context.args_type_info_stack().Pop();
  265. auto type_id = SemIR::TypeType::TypeId;
  266. if (!FindDesignator(context, requirements_id)) {
  267. CARBON_DIAGNOSTIC(WhereWithoutDesignator, Error,
  268. "`where` clause without a designator; expected `.Self` "
  269. "to appear in a requirement, or a member of `.Self`");
  270. context.emitter().Emit(node_id, WhereWithoutDesignator);
  271. type_id = SemIR::ErrorInst::TypeId;
  272. }
  273. AddInstAndPush<SemIR::WhereExpr>(
  274. context, node_id,
  275. {.type_id = type_id, .requirements_id = requirements_id});
  276. return true;
  277. }
  278. } // namespace Carbon::Check