handle_require.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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/generic.h"
  8. #include "toolchain/check/handle.h"
  9. #include "toolchain/check/inst.h"
  10. #include "toolchain/check/modifiers.h"
  11. #include "toolchain/check/name_lookup.h"
  12. #include "toolchain/check/subst.h"
  13. #include "toolchain/check/type.h"
  14. #include "toolchain/check/type_completion.h"
  15. #include "toolchain/parse/node_ids.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/named_constraint.h"
  18. #include "toolchain/sem_ir/type_iterator.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::Check {
  21. auto HandleParseNode(Context& context, Parse::RequireIntroducerId node_id)
  22. -> bool {
  23. // Require decls are always generic, since everything in an `interface` or
  24. // `constraint` is generic over `Self`.
  25. StartGenericDecl(context);
  26. // Create an instruction block to hold the instructions created for the type
  27. // and constraint.
  28. context.inst_block_stack().Push();
  29. // Optional modifiers follow.
  30. context.decl_introducer_state_stack().Push<Lex::TokenKind::Require>();
  31. auto scope_id = context.scope_stack().PeekNameScopeId();
  32. auto scope_inst_id = context.name_scopes().Get(scope_id).inst_id();
  33. auto scope_inst = context.insts().Get(scope_inst_id);
  34. if (!scope_inst.Is<SemIR::InterfaceDecl>() &&
  35. !scope_inst.Is<SemIR::NamedConstraintDecl>()) {
  36. CARBON_DIAGNOSTIC(
  37. RequireInWrongScope, Error,
  38. "`require` can only be used in an `interface` or `constraint`");
  39. context.emitter().Emit(node_id, RequireInWrongScope);
  40. scope_inst_id = SemIR::ErrorInst::InstId;
  41. }
  42. context.node_stack().Push(node_id, scope_inst_id);
  43. return true;
  44. }
  45. auto HandleParseNode(Context& context, Parse::RequireDefaultSelfImplsId node_id)
  46. -> bool {
  47. auto scope_inst_id =
  48. context.node_stack().Peek<Parse::NodeKind::RequireIntroducer>();
  49. if (scope_inst_id == SemIR::ErrorInst::InstId) {
  50. context.node_stack().Push(node_id, SemIR::ErrorInst::TypeInstId);
  51. return true;
  52. }
  53. auto scope_id = context.scope_stack().PeekNameScopeId();
  54. auto lookup_result =
  55. LookupNameInExactScope(context, node_id, SemIR::NameId::SelfType,
  56. scope_id, context.name_scopes().Get(scope_id),
  57. /*is_being_declared=*/false);
  58. CARBON_CHECK(lookup_result.is_found());
  59. auto self_inst_id = lookup_result.target_inst_id();
  60. auto self_type_id = context.insts().Get(self_inst_id).type_id();
  61. CARBON_CHECK(context.types().Is<SemIR::FacetType>(self_type_id));
  62. auto self_facet_as_type = AddTypeInst<SemIR::FacetAccessType>(
  63. context, node_id,
  64. {.type_id = SemIR::TypeType::TypeId,
  65. .facet_value_inst_id = self_inst_id});
  66. context.node_stack().Push(node_id, self_facet_as_type);
  67. return true;
  68. }
  69. auto HandleParseNode(Context& context, Parse::RequireTypeImplsId node_id)
  70. -> bool {
  71. auto [self_node_id, self_inst_id] = context.node_stack().PopExprWithNodeId();
  72. auto self_type = ExprAsType(context, self_node_id, self_inst_id);
  73. context.node_stack().Push(node_id, self_type.inst_id);
  74. return true;
  75. }
  76. static auto TypeStructureReferencesSelf(
  77. Context& context, SemIR::TypeInstId inst_id,
  78. const SemIR::IdentifiedFacetType& identified_facet_type) -> bool {
  79. if (inst_id == SemIR::ErrorInst::TypeInstId) {
  80. // Don't generate more diagnostics.
  81. return true;
  82. }
  83. auto find_self = [&](SemIR::TypeIterator& type_iter) -> bool {
  84. while (true) {
  85. auto step = type_iter.Next();
  86. if (step.Is<SemIR::TypeIterator::Step::Done>()) {
  87. break;
  88. }
  89. CARBON_KIND_SWITCH(step.any) {
  90. case CARBON_KIND(SemIR::TypeIterator::Step::Error _): {
  91. // Don't generate more diagnostics.
  92. return true;
  93. }
  94. case CARBON_KIND(SemIR::TypeIterator::Step::SymbolicBinding bind): {
  95. if (context.entity_names().Get(bind.entity_name_id).name_id ==
  96. SemIR::NameId::SelfType) {
  97. return true;
  98. }
  99. break;
  100. }
  101. default:
  102. break;
  103. }
  104. }
  105. return false;
  106. };
  107. {
  108. SemIR::TypeIterator type_iter(&context.sem_ir());
  109. type_iter.Add(context.constant_values().GetConstantTypeInstId(inst_id));
  110. if (find_self(type_iter)) {
  111. return true;
  112. }
  113. }
  114. if (identified_facet_type.required_interfaces().empty()) {
  115. return false;
  116. }
  117. for (auto specific_interface : identified_facet_type.required_interfaces()) {
  118. SemIR::TypeIterator type_iter(&context.sem_ir());
  119. type_iter.Add(specific_interface);
  120. if (!find_self(type_iter)) {
  121. return false;
  122. }
  123. }
  124. return true;
  125. }
  126. struct ValidateRequireResult {
  127. SemIR::FacetType facet_type;
  128. const SemIR::IdentifiedFacetType* identified;
  129. };
  130. // Returns nullopt if a diagnostic has been emitted and the `require` decl is
  131. // not valid.
  132. static auto ValidateRequire(Context& context, SemIR::LocId loc_id,
  133. SemIR::TypeInstId self_inst_id,
  134. SemIR::InstId constraint_inst_id,
  135. SemIR::InstId scope_inst_id)
  136. -> std::optional<ValidateRequireResult> {
  137. auto constraint_constant_value_inst_id =
  138. context.constant_values().GetConstantInstId(constraint_inst_id);
  139. auto constraint_facet_type = context.insts().TryGetAs<SemIR::FacetType>(
  140. constraint_constant_value_inst_id);
  141. if (!constraint_facet_type) {
  142. if (constraint_constant_value_inst_id != SemIR::ErrorInst::InstId) {
  143. CARBON_DIAGNOSTIC(
  144. RequireImplsMissingFacetType, Error,
  145. "`require` declaration constrained by a non-facet type; "
  146. "expected an `interface` or `constraint` name after `impls`");
  147. context.emitter().Emit(constraint_inst_id, RequireImplsMissingFacetType);
  148. }
  149. // Can't continue without a constraint to use.
  150. return std::nullopt;
  151. }
  152. auto identified_facet_type_id =
  153. RequireIdentifiedFacetType(context, *constraint_facet_type, [&] {
  154. CARBON_DIAGNOSTIC(
  155. RequireImplsUnidentifiedFacetType, Error,
  156. "facet type {0} cannot be identified in `require` declaration",
  157. InstIdAsType);
  158. return context.emitter().Build(constraint_inst_id,
  159. RequireImplsUnidentifiedFacetType,
  160. constraint_inst_id);
  161. });
  162. if (!identified_facet_type_id.has_value()) {
  163. // The constraint can't be used. A diagnostic was emitted by
  164. // RequireIdentifiedFacetType().
  165. return std::nullopt;
  166. }
  167. const auto& identified =
  168. context.identified_facet_types().Get(identified_facet_type_id);
  169. if (!TypeStructureReferencesSelf(context, self_inst_id, identified)) {
  170. CARBON_DIAGNOSTIC(RequireImplsMissingSelf, Error,
  171. "no `Self` reference found in `require` declaration; "
  172. "`Self` must appear in the self-type or as a generic "
  173. "parameter for each `interface` or `constraint`");
  174. context.emitter().Emit(loc_id, RequireImplsMissingSelf);
  175. return std::nullopt;
  176. }
  177. if (scope_inst_id == SemIR::ErrorInst::InstId) {
  178. // `require` is in the wrong scope.
  179. return std::nullopt;
  180. }
  181. if (self_inst_id == SemIR::ErrorInst::InstId ||
  182. constraint_inst_id == SemIR::ErrorInst::InstId) {
  183. // Can't build a useful `require` with an error, it couldn't do anything.
  184. return std::nullopt;
  185. }
  186. return ValidateRequireResult{.facet_type = *constraint_facet_type,
  187. .identified = &identified};
  188. }
  189. auto HandleParseNode(Context& context, Parse::RequireDeclId node_id) -> bool {
  190. auto [constraint_node_id, constraint_inst_id] =
  191. context.node_stack().PopExprWithNodeId();
  192. auto [self_node_id, self_inst_id] =
  193. context.node_stack().PopWithNodeId<Parse::NodeCategory::RequireImpls>();
  194. auto decl_block_id = context.inst_block_stack().Pop();
  195. // Process modifiers.
  196. auto introducer =
  197. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Require>();
  198. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Extend);
  199. auto scope_inst_id =
  200. context.node_stack().Pop<Parse::NodeKind::RequireIntroducer>();
  201. auto validated = ValidateRequire(context, node_id, self_inst_id,
  202. constraint_inst_id, scope_inst_id);
  203. if (!validated) {
  204. DiscardGenericDecl(context);
  205. return true;
  206. }
  207. auto [constraint_facet_type, identified] = *validated;
  208. if (identified->required_interfaces().empty()) {
  209. // A `require T impls type` adds no actual constraints, so nothing to do.
  210. DiscardGenericDecl(context);
  211. return true;
  212. }
  213. auto require_impls_decl =
  214. SemIR::RequireImplsDecl{// To be filled in after.
  215. .require_impls_id = SemIR::RequireImplsId::None,
  216. .decl_block_id = decl_block_id};
  217. auto decl_id = AddPlaceholderInst(context, node_id, require_impls_decl);
  218. auto require_impls_id = context.require_impls().Add(
  219. {.self_id = self_inst_id,
  220. .facet_type_inst_id =
  221. context.types().GetAsTypeInstId(constraint_inst_id),
  222. .facet_type_id = constraint_facet_type.facet_type_id,
  223. .decl_id = decl_id,
  224. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  225. .generic_id = BuildGenericDecl(context, decl_id)});
  226. require_impls_decl.require_impls_id = require_impls_id;
  227. ReplaceInstBeforeConstantUse(context, decl_id, require_impls_decl);
  228. context.require_impls_stack().AppendToTop(require_impls_id);
  229. return true;
  230. }
  231. } // namespace Carbon::Check