handle_require.cpp 10 KB

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