handle_require.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. SemIR::TypeId facet_type_type_id;
  137. const SemIR::IdentifiedFacetType* identified;
  138. };
  139. // Returns nullopt if a diagnostic has been emitted and the `require` decl is
  140. // not valid.
  141. static auto ValidateRequire(Context& context, SemIR::LocId loc_id,
  142. SemIR::TypeInstId self_inst_id,
  143. SemIR::InstId constraint_inst_id,
  144. SemIR::InstId scope_inst_id)
  145. -> std::optional<ValidateRequireResult> {
  146. auto constraint_constant_value_id =
  147. context.constant_values().Get(constraint_inst_id);
  148. auto constraint_type_id =
  149. SemIR::TypeId::ForTypeConstant(constraint_constant_value_id);
  150. auto constraint_facet_type =
  151. context.types().TryGetAs<SemIR::FacetType>(constraint_type_id);
  152. if (!constraint_facet_type) {
  153. if (constraint_constant_value_id != SemIR::ErrorInst::ConstantId) {
  154. CARBON_DIAGNOSTIC(
  155. RequireImplsMissingFacetType, Error,
  156. "`require` declaration constrained by a non-facet type; "
  157. "expected an `interface` or `constraint` name after `impls`");
  158. context.emitter().Emit(constraint_inst_id, RequireImplsMissingFacetType);
  159. }
  160. // Can't continue without a constraint to use.
  161. return std::nullopt;
  162. }
  163. auto identified_facet_type_id =
  164. RequireIdentifiedFacetType(context, *constraint_facet_type, [&] {
  165. CARBON_DIAGNOSTIC(
  166. RequireImplsUnidentifiedFacetType, Error,
  167. "facet type {0} cannot be identified in `require` declaration",
  168. InstIdAsType);
  169. return context.emitter().Build(constraint_inst_id,
  170. RequireImplsUnidentifiedFacetType,
  171. constraint_inst_id);
  172. });
  173. if (!identified_facet_type_id.has_value()) {
  174. // The constraint can't be used. A diagnostic was emitted by
  175. // RequireIdentifiedFacetType().
  176. return std::nullopt;
  177. }
  178. const auto& identified =
  179. context.identified_facet_types().Get(identified_facet_type_id);
  180. if (!TypeStructureReferencesSelf(context, self_inst_id, identified)) {
  181. CARBON_DIAGNOSTIC(RequireImplsMissingSelf, Error,
  182. "no `Self` reference found in `require` declaration; "
  183. "`Self` must appear in the self-type or as a generic "
  184. "parameter for each `interface` or `constraint`");
  185. context.emitter().Emit(loc_id, RequireImplsMissingSelf);
  186. return std::nullopt;
  187. }
  188. if (scope_inst_id == SemIR::ErrorInst::InstId) {
  189. // `require` is in the wrong scope.
  190. return std::nullopt;
  191. }
  192. if (self_inst_id == SemIR::ErrorInst::InstId ||
  193. constraint_inst_id == SemIR::ErrorInst::InstId) {
  194. // Can't build a useful `require` with an error, it couldn't do anything.
  195. return std::nullopt;
  196. }
  197. return ValidateRequireResult{.facet_type = *constraint_facet_type,
  198. .facet_type_type_id = constraint_type_id,
  199. .identified = &identified};
  200. }
  201. auto HandleParseNode(Context& context, Parse::RequireDeclId node_id) -> bool {
  202. auto [constraint_node_id, constraint_inst_id] =
  203. context.node_stack().PopExprWithNodeId();
  204. auto [self_node_id, self_inst_id] =
  205. context.node_stack().PopWithNodeId<Parse::NodeCategory::RequireImpls>();
  206. auto decl_block_id = context.inst_block_stack().Pop();
  207. // Process modifiers.
  208. auto introducer =
  209. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Require>();
  210. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Extend);
  211. auto scope_inst_id =
  212. context.node_stack().Pop<Parse::NodeKind::RequireIntroducer>();
  213. auto validated = ValidateRequire(context, node_id, self_inst_id,
  214. constraint_inst_id, scope_inst_id);
  215. if (!validated) {
  216. DiscardGenericDecl(context);
  217. return true;
  218. }
  219. auto [constraint_facet_type, constraint_type_id, identified] = *validated;
  220. if (identified->required_interfaces().empty()) {
  221. // A `require T impls type` adds no actual constraints, so nothing to do.
  222. DiscardGenericDecl(context);
  223. return true;
  224. }
  225. bool extend = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend);
  226. auto require_impls_decl =
  227. SemIR::RequireImplsDecl{// To be filled in after.
  228. .require_impls_id = SemIR::RequireImplsId::None,
  229. .decl_block_id = decl_block_id};
  230. auto decl_id = AddPlaceholderInst(context, node_id, require_impls_decl);
  231. auto require_impls_id = context.require_impls().Add(
  232. {.self_id = self_inst_id,
  233. .facet_type_inst_id =
  234. context.types().GetAsTypeInstId(constraint_inst_id),
  235. .facet_type_id = constraint_facet_type.facet_type_id,
  236. .extend_self = extend,
  237. .decl_id = decl_id,
  238. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  239. .generic_id = BuildGenericDecl(context, decl_id)});
  240. require_impls_decl.require_impls_id = require_impls_id;
  241. ReplaceInstBeforeConstantUse(context, decl_id, require_impls_decl);
  242. // We look for a complete type after BuildGenericDecl, so that the resulting
  243. // RequireCompleteType instruction is part of the enclosing interface or named
  244. // constraint generic definition. Then requiring enclosing entity to be
  245. // complete will resolve that definition (via ResolveSpecificDefinition()) and
  246. // also construct a specific for the `constraint_inst_id`, finding any
  247. // monomorphization errors that result.
  248. if (extend) {
  249. if (!RequireCompleteType(
  250. context, constraint_type_id, SemIR::LocId(constraint_inst_id), [&] {
  251. CARBON_DIAGNOSTIC(RequireImplsIncompleteFacetType, Error,
  252. "`extend require` of incomplete facet type {0}",
  253. InstIdAsType);
  254. return context.emitter().Build(constraint_inst_id,
  255. RequireImplsIncompleteFacetType,
  256. constraint_inst_id);
  257. })) {
  258. return true;
  259. }
  260. }
  261. context.require_impls_stack().AppendToTop(require_impls_id);
  262. return true;
  263. }
  264. } // namespace Carbon::Check