handle_where.cpp 13 KB

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