handle_require.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. if (self_type_id == SemIR::ErrorInst::TypeId) {
  63. context.node_stack().Push(node_id, SemIR::ErrorInst::TypeInstId);
  64. return true;
  65. }
  66. CARBON_CHECK(context.types().Is<SemIR::FacetType>(self_type_id));
  67. auto self_facet_as_type = AddTypeInst<SemIR::FacetAccessType>(
  68. context, node_id,
  69. {.type_id = SemIR::TypeType::TypeId,
  70. .facet_value_inst_id = self_inst_id});
  71. context.node_stack().Push(node_id, self_facet_as_type);
  72. return true;
  73. }
  74. auto HandleParseNode(Context& context, Parse::RequireTypeImplsId node_id)
  75. -> bool {
  76. auto [self_node_id, self_inst_id] = context.node_stack().PopExprWithNodeId();
  77. auto introducer = context.decl_introducer_state_stack().innermost();
  78. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  79. CARBON_DIAGNOSTIC(RequireImplsExtendWithExplicitSelf, Error,
  80. "`extend require impls` with explicit type");
  81. context.emitter().Emit(self_node_id, RequireImplsExtendWithExplicitSelf);
  82. self_inst_id = SemIR::ErrorInst::InstId;
  83. }
  84. auto self_type = ExprAsType(context, self_node_id, self_inst_id);
  85. context.node_stack().Push(node_id, self_type.inst_id);
  86. return true;
  87. }
  88. static auto TypeStructureReferencesSelf(
  89. Context& context, SemIR::TypeInstId inst_id,
  90. const SemIR::IdentifiedFacetType& identified_facet_type) -> bool {
  91. if (inst_id == SemIR::ErrorInst::TypeInstId) {
  92. // Don't generate more diagnostics.
  93. return true;
  94. }
  95. auto find_self = [&](SemIR::TypeIterator& type_iter) -> bool {
  96. while (true) {
  97. auto step = type_iter.Next();
  98. if (step.Is<SemIR::TypeIterator::Step::Done>()) {
  99. break;
  100. }
  101. CARBON_KIND_SWITCH(step.any) {
  102. case CARBON_KIND(SemIR::TypeIterator::Step::Error _): {
  103. // Don't generate more diagnostics.
  104. return true;
  105. }
  106. case CARBON_KIND(SemIR::TypeIterator::Step::SymbolicBinding bind): {
  107. if (context.entity_names().Get(bind.entity_name_id).name_id ==
  108. SemIR::NameId::SelfType) {
  109. return true;
  110. }
  111. break;
  112. }
  113. default:
  114. break;
  115. }
  116. }
  117. return false;
  118. };
  119. {
  120. SemIR::TypeIterator type_iter(&context.sem_ir());
  121. type_iter.Add(context.constant_values().GetConstantTypeInstId(inst_id));
  122. if (find_self(type_iter)) {
  123. return true;
  124. }
  125. }
  126. if (identified_facet_type.required_interfaces().empty()) {
  127. return false;
  128. }
  129. for (auto specific_interface : identified_facet_type.required_interfaces()) {
  130. SemIR::TypeIterator type_iter(&context.sem_ir());
  131. type_iter.Add(specific_interface);
  132. if (!find_self(type_iter)) {
  133. return false;
  134. }
  135. }
  136. return true;
  137. }
  138. struct ValidateRequireResult {
  139. // The TypeId of a FacetType.
  140. SemIR::TypeId constraint_type_id;
  141. const SemIR::IdentifiedFacetType* identified_facet_type;
  142. };
  143. // Returns nullopt if a diagnostic has been emitted and the `require` decl is
  144. // not valid.
  145. static auto ValidateRequire(Context& context, SemIR::LocId loc_id,
  146. SemIR::TypeInstId self_inst_id,
  147. SemIR::InstId constraint_inst_id,
  148. SemIR::InstId scope_inst_id)
  149. -> std::optional<ValidateRequireResult> {
  150. auto constraint_constant_value_id =
  151. context.constant_values().Get(constraint_inst_id);
  152. auto constraint_type_id =
  153. SemIR::TypeId::ForTypeConstant(constraint_constant_value_id);
  154. auto constraint_facet_type =
  155. context.types().TryGetAs<SemIR::FacetType>(constraint_type_id);
  156. if (!constraint_facet_type) {
  157. if (constraint_constant_value_id != SemIR::ErrorInst::ConstantId) {
  158. CARBON_DIAGNOSTIC(
  159. RequireImplsMissingFacetType, Error,
  160. "`require` declaration constrained by a non-facet type; "
  161. "expected an `interface` or `constraint` name after `impls`");
  162. context.emitter().Emit(constraint_inst_id, RequireImplsMissingFacetType);
  163. }
  164. // Can't continue without a constraint to use.
  165. return std::nullopt;
  166. }
  167. auto identified_facet_type_id = RequireIdentifiedFacetType(
  168. context, SemIR::LocId(constraint_inst_id), *constraint_facet_type, [&] {
  169. CARBON_DIAGNOSTIC(
  170. RequireImplsUnidentifiedFacetType, Error,
  171. "facet type {0} cannot be identified in `require` declaration",
  172. InstIdAsType);
  173. return context.emitter().Build(constraint_inst_id,
  174. RequireImplsUnidentifiedFacetType,
  175. constraint_inst_id);
  176. });
  177. if (!identified_facet_type_id.has_value()) {
  178. // The constraint can't be used. A diagnostic was emitted by
  179. // RequireIdentifiedFacetType().
  180. return std::nullopt;
  181. }
  182. const auto& identified =
  183. context.identified_facet_types().Get(identified_facet_type_id);
  184. if (!TypeStructureReferencesSelf(context, self_inst_id, identified)) {
  185. CARBON_DIAGNOSTIC(RequireImplsMissingSelf, Error,
  186. "no `Self` reference found in `require` declaration; "
  187. "`Self` must appear in the self-type or as a generic "
  188. "parameter for each `interface` or `constraint`");
  189. context.emitter().Emit(loc_id, RequireImplsMissingSelf);
  190. return std::nullopt;
  191. }
  192. if (scope_inst_id == SemIR::ErrorInst::InstId) {
  193. // `require` is in the wrong scope.
  194. return std::nullopt;
  195. }
  196. if (self_inst_id == SemIR::ErrorInst::InstId ||
  197. constraint_inst_id == SemIR::ErrorInst::InstId) {
  198. // Can't build a useful `require` with an error, it couldn't do anything.
  199. return std::nullopt;
  200. }
  201. return ValidateRequireResult{.constraint_type_id = constraint_type_id,
  202. .identified_facet_type = &identified};
  203. }
  204. auto HandleParseNode(Context& context, Parse::RequireDeclId node_id) -> bool {
  205. auto [constraint_node_id, constraint_inst_id] =
  206. context.node_stack().PopExprWithNodeId();
  207. auto [self_node_id, self_inst_id] =
  208. context.node_stack().PopWithNodeId<Parse::NodeCategory::RequireImpls>();
  209. auto decl_block_id = context.inst_block_stack().Pop();
  210. // Process modifiers.
  211. auto introducer =
  212. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Require>();
  213. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Extend);
  214. auto scope_inst_id =
  215. context.node_stack().Pop<Parse::NodeKind::RequireIntroducer>();
  216. auto validated = ValidateRequire(context, node_id, self_inst_id,
  217. constraint_inst_id, scope_inst_id);
  218. if (!validated) {
  219. DiscardGenericDecl(context);
  220. return true;
  221. }
  222. auto [constraint_type_id, identified_facet_type] = *validated;
  223. if (identified_facet_type->required_interfaces().empty()) {
  224. // A `require T impls type` adds no actual constraints, so nothing to do.
  225. DiscardGenericDecl(context);
  226. return true;
  227. }
  228. bool extend = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend);
  229. auto require_impls_decl =
  230. SemIR::RequireImplsDecl{// To be filled in after.
  231. .require_impls_id = SemIR::RequireImplsId::None,
  232. .decl_block_id = decl_block_id};
  233. auto decl_id = AddPlaceholderInst(context, node_id, require_impls_decl);
  234. auto require_impls_id = context.require_impls().Add(
  235. {.self_id = self_inst_id,
  236. .facet_type_inst_id =
  237. context.types().GetAsTypeInstId(constraint_inst_id),
  238. .extend_self = extend,
  239. .decl_id = decl_id,
  240. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  241. .generic_id = BuildGenericDecl(context, decl_id)});
  242. require_impls_decl.require_impls_id = require_impls_id;
  243. ReplaceInstBeforeConstantUse(context, decl_id, require_impls_decl);
  244. // We look for a complete type after BuildGenericDecl, so that the resulting
  245. // RequireCompleteType instruction is part of the enclosing interface or named
  246. // constraint generic definition. Then requiring enclosing entity to be
  247. // complete will resolve that definition (via ResolveSpecificDefinition()) and
  248. // also construct a specific for the `constraint_inst_id`, finding any
  249. // monomorphization errors that result.
  250. if (extend) {
  251. if (!RequireCompleteType(
  252. context, constraint_type_id, SemIR::LocId(constraint_inst_id), [&] {
  253. CARBON_DIAGNOSTIC(RequireImplsIncompleteFacetType, Error,
  254. "`extend require` of incomplete facet type {0}",
  255. InstIdAsType);
  256. return context.emitter().Build(constraint_inst_id,
  257. RequireImplsIncompleteFacetType,
  258. constraint_inst_id);
  259. })) {
  260. return true;
  261. }
  262. }
  263. context.require_impls_stack().AppendToTop(require_impls_id);
  264. return true;
  265. }
  266. } // namespace Carbon::Check