handle_where.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. // TODO: Missing named constraints here.
  45. auto stripped_info =
  46. SemIR::FacetTypeInfo{.extend_constraints = info.extend_constraints};
  47. stripped_info.Canonicalize();
  48. period_self_type_id = GetFacetType(context, stripped_info);
  49. } else if (period_self_type_id == SemIR::TypeType::TypeId) {
  50. // The self may be `TypeType` in `type where X impls Y`, so we use an empty
  51. // facet type.
  52. period_self_type_id = GetEmptyFacetType(context);
  53. } else {
  54. CARBON_CHECK(period_self_type_id == SemIR::ErrorInst::TypeId,
  55. "unexpected .Self type {0}", period_self_type_id);
  56. }
  57. // Introduce a name scope so that we can remove the `.Self` entry we are
  58. // adding to name lookup at the end of the `where` expression.
  59. context.scope_stack().PushForSameRegion();
  60. // Introduce `.Self` as a symbolic binding. Its type is the value of the
  61. // expression to the left of `where`, so `MyInterface` in the example above.
  62. auto period_self_inst_id =
  63. MakePeriodSelfFacetValue(context, period_self_type_id);
  64. // Save the `.Self` symbolic binding on the node stack. It will become the
  65. // first argument to the `WhereExpr` instruction.
  66. context.node_stack().Push(node_id, period_self_inst_id);
  67. // Going to put each requirement on `args_type_info_stack`, so we can have an
  68. // inst block with the varying number of requirements but keeping other
  69. // instructions on the current inst block from the `inst_block_stack()`.
  70. context.args_type_info_stack().Push();
  71. // Pass along all the constraints from the base facet type to be added to the
  72. // resulting facet type.
  73. context.args_type_info_stack().AddInstId(
  74. AddInstInNoBlock<SemIR::RequirementBaseFacetType>(
  75. context, SemIR::LocId(node_id),
  76. {.base_type_inst_id =
  77. context.types().GetTypeInstId(self_with_constraints_type_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. // Build up the list of arguments for the `WhereExpr` inst.
  165. context.args_type_info_stack().AddInstId(
  166. AddInstInNoBlock<SemIR::RequirementImpls>(
  167. context, node_id,
  168. {.lhs_id = lhs_as_type.inst_id, .rhs_id = rhs_as_type.inst_id}));
  169. return true;
  170. }
  171. auto HandleParseNode(Context& /*context*/, Parse::RequirementAndId /*node_id*/)
  172. -> bool {
  173. // Nothing to do.
  174. return true;
  175. }
  176. // Returns whether a designator (`.Self` or `.MemberName`) is present in the
  177. // where clause.
  178. static auto FindDesignator(Context& context,
  179. SemIR::InstBlockId requirements_block_id) -> bool {
  180. auto block = context.inst_blocks().GetOrEmpty(requirements_block_id);
  181. llvm::SmallVector<SemIR::InstId> requirements;
  182. requirements.reserve(block.size() * 2);
  183. // These requirement instructions don't have a constant value, but they
  184. // contain only canonical instructions.
  185. for (auto inst_id : block) {
  186. auto inst = context.insts().Get(inst_id);
  187. CARBON_KIND_SWITCH(inst) {
  188. case CARBON_KIND(SemIR::RequirementBaseFacetType base): {
  189. requirements.push_back(base.base_type_inst_id);
  190. break;
  191. }
  192. case CARBON_KIND(SemIR::RequirementRewrite rewrite): {
  193. requirements.push_back(rewrite.lhs_id);
  194. requirements.push_back(rewrite.rhs_id);
  195. break;
  196. }
  197. case CARBON_KIND(SemIR::RequirementEquivalent equiv): {
  198. requirements.push_back(equiv.lhs_id);
  199. requirements.push_back(equiv.rhs_id);
  200. break;
  201. }
  202. case CARBON_KIND(SemIR::RequirementImpls impls): {
  203. requirements.push_back(impls.lhs_id);
  204. requirements.push_back(impls.rhs_id);
  205. break;
  206. }
  207. default:
  208. CARBON_CHECK(inst_id == SemIR::ErrorInst::InstId,
  209. "unexpected inst {0} in requirements", inst);
  210. }
  211. }
  212. class SubstFindDesignator : public SubstInstCallbacks {
  213. public:
  214. explicit SubstFindDesignator(Context* context, bool* found)
  215. : SubstInstCallbacks(context), found_(found) {}
  216. auto Subst(SemIR::InstId& inst_id) -> SubstResult override {
  217. if (*found_) {
  218. return FullySubstituted;
  219. }
  220. // An error was diagnosed for the where clause already.
  221. if (inst_id == SemIR::ErrorInst::InstId) {
  222. *found_ = true;
  223. return FullySubstituted;
  224. }
  225. // TypeType has type TypeType, avoid recursing on its type.
  226. if (context().insts().Is<SemIR::TypeType>(inst_id)) {
  227. return FullySubstituted;
  228. }
  229. // `.MemberName` is represented as an ImplWitnessAccess through `.Self` so
  230. // we only need to look for `.Self` here.
  231. if (auto bind =
  232. context().insts().TryGetAs<SemIR::SymbolicBinding>(inst_id)) {
  233. auto entity_name = context().entity_names().Get(bind->entity_name_id);
  234. if (entity_name.name_id == SemIR::NameId::PeriodSelf) {
  235. *found_ = true;
  236. return FullySubstituted;
  237. }
  238. }
  239. // FacetAccessType of `.Self` is evaluated to SymbolicBindingType, so we
  240. // need to look for this instruction too, since we won't find a `.Self`
  241. // directly in that case.
  242. if (auto bind =
  243. context().insts().TryGetAs<SemIR::SymbolicBindingType>(inst_id)) {
  244. auto entity_name = context().entity_names().Get(bind->entity_name_id);
  245. if (entity_name.name_id == SemIR::NameId::PeriodSelf) {
  246. *found_ = true;
  247. return FullySubstituted;
  248. }
  249. }
  250. return SubstOperands;
  251. }
  252. auto Rebuild(SemIR::InstId /*orig_inst_id*/, SemIR::Inst /*new_inst*/)
  253. -> SemIR::InstId override {
  254. CARBON_FATAL("unexpected rebuild, no insts should change");
  255. }
  256. bool* found_;
  257. };
  258. for (auto inst_id : requirements) {
  259. bool found = false;
  260. SubstFindDesignator callbacks(&context, &found);
  261. SubstInst(context, inst_id, callbacks);
  262. if (found) {
  263. return true;
  264. }
  265. }
  266. return false;
  267. }
  268. auto HandleParseNode(Context& context, Parse::WhereExprId node_id) -> bool {
  269. context.rewrites_stack().pop_back();
  270. // Remove `PeriodSelf` from name lookup, undoing the `Push` done for the
  271. // `WhereOperand`.
  272. context.scope_stack().Pop(/*check_unused=*/true);
  273. SemIR::InstId period_self_id =
  274. context.node_stack().Pop<Parse::NodeKind::WhereOperand>();
  275. SemIR::InstBlockId requirements_id = context.args_type_info_stack().Pop();
  276. if (!FindDesignator(context, requirements_id)) {
  277. CARBON_DIAGNOSTIC(WhereWithoutDesignator, Error,
  278. "`where` clause without a designator; expected `.Self` "
  279. "to appear in a requirement, or a member of `.Self`");
  280. context.emitter().Emit(node_id, WhereWithoutDesignator);
  281. period_self_id = SemIR::ErrorInst::InstId;
  282. }
  283. AddInstAndPush<SemIR::WhereExpr>(context, node_id,
  284. {.type_id = SemIR::TypeType::TypeId,
  285. .period_self_id = period_self_id,
  286. .requirements_id = requirements_id});
  287. return true;
  288. }
  289. } // namespace Carbon::Check