handle_where.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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/context.h"
  5. #include "toolchain/check/convert.h"
  6. #include "toolchain/check/facet_type.h"
  7. #include "toolchain/check/generic.h"
  8. #include "toolchain/check/handle.h"
  9. #include "toolchain/check/inst.h"
  10. #include "toolchain/check/type.h"
  11. #include "toolchain/sem_ir/facet_type_info.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/inst.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Check {
  16. auto HandleParseNode(Context& context, Parse::WhereOperandId node_id) -> bool {
  17. // The expression at the top of the stack represents a constraint type that
  18. // is being modified by the `where` operator. It would be `MyInterface` in
  19. // `MyInterface where .Member = i32`.
  20. auto [self_node, self_id] = context.node_stack().PopExprWithNodeId();
  21. auto self_with_constraints_type_id =
  22. ExprAsType(context, self_node, self_id).type_id;
  23. // Only facet types may have `where` restrictions.
  24. if (self_with_constraints_type_id != SemIR::ErrorInst::TypeId &&
  25. !context.types().IsFacetType(self_with_constraints_type_id)) {
  26. CARBON_DIAGNOSTIC(WhereOnNonFacetType, Error,
  27. "left argument of `where` operator must be a facet type");
  28. context.emitter().Emit(self_node, WhereOnNonFacetType);
  29. self_with_constraints_type_id = SemIR::ErrorInst::TypeId;
  30. }
  31. // Strip off any constraints provided by a `WhereExpr` from the `Self` facet
  32. // type. For a facet type like `I & J where .X = .Y`, this will reduce it down
  33. // to just `I & J`.
  34. //
  35. // Any references to `.Self` in constraints for the current `WhereExpr` will
  36. // not see constraints in the `Self` facet type, but they will resolve to
  37. // values through the constraints explicitly when they are combined together.
  38. auto self_without_constraints_type_id = self_with_constraints_type_id;
  39. if (auto facet_type = context.types().TryGetAs<SemIR::FacetType>(
  40. self_without_constraints_type_id)) {
  41. const auto& info = context.facet_types().Get(facet_type->facet_type_id);
  42. auto stripped_info =
  43. SemIR::FacetTypeInfo{.extend_constraints = info.extend_constraints};
  44. stripped_info.Canonicalize();
  45. self_without_constraints_type_id = GetFacetType(context, stripped_info);
  46. }
  47. // Introduce a name scope so that we can remove the `.Self` entry we are
  48. // adding to name lookup at the end of the `where` expression.
  49. context.scope_stack().PushForSameRegion();
  50. // Introduce `.Self` as a symbolic binding. Its type is the value of the
  51. // expression to the left of `where`, so `MyInterface` in the example above.
  52. //
  53. // It uses the `Self` type _without_ any constraints so that the `Self` is the
  54. // same at all levels of a nested facet type such as:
  55. // `(Z where .X = {}) where .X = {}`.
  56. auto entity_name_id = context.entity_names().AddCanonical(
  57. {.name_id = SemIR::NameId::PeriodSelf,
  58. .parent_scope_id = context.scope_stack().PeekNameScopeId()});
  59. auto period_self_inst_id = AddInst(
  60. context, SemIR::LocIdAndInst::NoLoc<SemIR::BindSymbolicName>({
  61. .type_id = self_without_constraints_type_id,
  62. .entity_name_id = entity_name_id,
  63. // `None` because there is no equivalent non-symbolic value.
  64. .value_id = SemIR::InstId::None,
  65. }));
  66. auto existing = context.scope_stack().LookupOrAddName(
  67. SemIR::NameId::PeriodSelf, period_self_inst_id);
  68. // Shouldn't have any names in newly created scope.
  69. CARBON_CHECK(!existing.has_value());
  70. // Save the `.Self` symbolic binding on the node stack. It will become the
  71. // first argument to the `WhereExpr` instruction.
  72. context.node_stack().Push(node_id, period_self_inst_id);
  73. // Going to put each requirement on `args_type_info_stack`, so we can have an
  74. // inst block with the varying number of requirements but keeping other
  75. // instructions on the current inst block from the `inst_block_stack()`.
  76. context.args_type_info_stack().Push();
  77. // Pass along all the constraints from the base facet type to be added to the
  78. // resulting facet type.
  79. context.args_type_info_stack().AddInstId(
  80. AddInstInNoBlock<SemIR::RequirementBaseFacetType>(
  81. context, SemIR::LocId(node_id),
  82. {.base_type_inst_id =
  83. context.types().GetInstId(self_with_constraints_type_id)}));
  84. // Add a context stack for tracking rewrite constraints, that will be used to
  85. // allow later constraints to read from them eagerly.
  86. context.rewrites_stack().emplace_back();
  87. // Make rewrite constraints from the self facet type available immediately to
  88. // expressions in rewrite constraints for this `where` expression.
  89. if (auto self_facet_type = context.types().TryGetAs<SemIR::FacetType>(
  90. self_with_constraints_type_id)) {
  91. const auto& base_facet_type_info =
  92. context.facet_types().Get(self_facet_type->facet_type_id);
  93. for (const auto& rewrite : base_facet_type_info.rewrite_constraints) {
  94. if (rewrite.lhs_id != SemIR::ErrorInst::InstId) {
  95. context.rewrites_stack().back().Insert(
  96. context.constant_values().Get(
  97. GetImplWitnessAccessWithoutSubstitution(context,
  98. rewrite.lhs_id)),
  99. rewrite.rhs_id);
  100. }
  101. }
  102. }
  103. return true;
  104. }
  105. auto HandleParseNode(Context& context, Parse::RequirementEqualId node_id)
  106. -> bool {
  107. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  108. auto lhs_id = context.node_stack().PopExpr();
  109. // Convert rhs to type of lhs.
  110. auto lhs_type_id = context.insts().Get(lhs_id).type_id();
  111. if (lhs_type_id.is_symbolic()) {
  112. // If the type of the associated constant is symbolic, we defer conversion
  113. // until the constraint is resolved, in case it depends on `Self` (which
  114. // will now be a reference to `.Self`).
  115. // For now we convert to a value expression eagerly because otherwise we'll
  116. // often be unable to constant-evaluate the enclosing `where` expression.
  117. // TODO: Perform the conversion symbolically and add an implicit constraint
  118. // that this conversion is valid and produces a constant.
  119. rhs_id = ConvertToValueExpr(context, rhs_id);
  120. } else {
  121. rhs_id = ConvertToValueOfType(context, rhs_node, rhs_id,
  122. context.insts().Get(lhs_id).type_id());
  123. }
  124. // Build up the list of arguments for the `WhereExpr` inst.
  125. context.args_type_info_stack().AddInstId(
  126. AddInstInNoBlock<SemIR::RequirementRewrite>(
  127. context, node_id, {.lhs_id = lhs_id, .rhs_id = rhs_id}));
  128. if (lhs_id != SemIR::ErrorInst::InstId) {
  129. // Track the value of the rewrite so further constraints can use it
  130. // immediately, before they are evaluated. This happens directly where the
  131. // `ImplWitnessAccess` that refers to the rewrite constraint would have been
  132. // created, and the value of the constraint will be used instead.
  133. context.rewrites_stack().back().Insert(
  134. context.constant_values().Get(
  135. GetImplWitnessAccessWithoutSubstitution(context, lhs_id)),
  136. rhs_id);
  137. }
  138. return true;
  139. }
  140. auto HandleParseNode(Context& context, Parse::RequirementEqualEqualId node_id)
  141. -> bool {
  142. auto rhs = context.node_stack().PopExpr();
  143. auto lhs = context.node_stack().PopExpr();
  144. // TODO: Type check lhs and rhs are comparable.
  145. // TODO: Require that at least one side uses a designator.
  146. // Build up the list of arguments for the `WhereExpr` inst.
  147. context.args_type_info_stack().AddInstId(
  148. AddInstInNoBlock<SemIR::RequirementEquivalent>(
  149. context, node_id, {.lhs_id = lhs, .rhs_id = rhs}));
  150. return true;
  151. }
  152. auto HandleParseNode(Context& context, Parse::RequirementImplsId node_id)
  153. -> bool {
  154. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  155. auto [lhs_node, lhs_id] = context.node_stack().PopExprWithNodeId();
  156. // Check lhs is a facet and rhs is a facet type.
  157. auto lhs_as_type = ExprAsType(context, lhs_node, lhs_id);
  158. auto rhs_as_type = ExprAsType(context, rhs_node, rhs_id);
  159. if (rhs_as_type.type_id != SemIR::ErrorInst::TypeId &&
  160. !context.types().IsFacetType(rhs_as_type.type_id)) {
  161. CARBON_DIAGNOSTIC(
  162. ImplsOnNonFacetType, Error,
  163. "right argument of `impls` requirement must be a facet type");
  164. context.emitter().Emit(rhs_node, ImplsOnNonFacetType);
  165. rhs_as_type.inst_id = SemIR::ErrorInst::TypeInstId;
  166. }
  167. // TODO: Require that at least one side uses a designator.
  168. // TODO: For things like `HashSet(.T) as type`, add an implied constraint
  169. // that `.T impls Hash`.
  170. // Build up the list of arguments for the `WhereExpr` inst.
  171. context.args_type_info_stack().AddInstId(
  172. AddInstInNoBlock<SemIR::RequirementImpls>(
  173. context, node_id,
  174. {.lhs_id = lhs_as_type.inst_id, .rhs_id = rhs_as_type.inst_id}));
  175. return true;
  176. }
  177. auto HandleParseNode(Context& /*context*/, Parse::RequirementAndId /*node_id*/)
  178. -> bool {
  179. // Nothing to do.
  180. return true;
  181. }
  182. auto HandleParseNode(Context& context, Parse::WhereExprId node_id) -> bool {
  183. context.rewrites_stack().pop_back();
  184. // Remove `PeriodSelf` from name lookup, undoing the `Push` done for the
  185. // `WhereOperand`.
  186. context.scope_stack().Pop();
  187. SemIR::InstId period_self_id =
  188. context.node_stack().Pop<Parse::NodeKind::WhereOperand>();
  189. SemIR::InstBlockId requirements_id = context.args_type_info_stack().Pop();
  190. AddInstAndPush<SemIR::WhereExpr>(context, node_id,
  191. {.type_id = SemIR::TypeType::TypeId,
  192. .period_self_id = period_self_id,
  193. .requirements_id = requirements_id});
  194. return true;
  195. }
  196. } // namespace Carbon::Check