handle_require.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. // TODO: We could simplify with a call to ExprAsType, like below?
  68. auto self_facet_as_type = AddTypeInst<SemIR::FacetAccessType>(
  69. context, node_id,
  70. {.type_id = SemIR::TypeType::TypeId,
  71. .facet_value_inst_id = self_inst_id});
  72. context.node_stack().Push(node_id, self_facet_as_type);
  73. return true;
  74. }
  75. auto HandleParseNode(Context& context, Parse::RequireTypeImplsId node_id)
  76. -> bool {
  77. auto [self_node_id, self_inst_id] = context.node_stack().PopExprWithNodeId();
  78. auto self_type = ExprAsType(context, self_node_id, self_inst_id);
  79. const auto& introducer = context.decl_introducer_state_stack().innermost();
  80. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  81. if (self_type.type_id != SemIR::ErrorInst::TypeId) {
  82. CARBON_DIAGNOSTIC(RequireImplsExtendWithExplicitSelf, Error,
  83. "`extend require impls` with explicit type");
  84. // TODO: If the explicit self-type matches a lookup of NameId::SelfType,
  85. // add a note to the diagnostic: "remove the explicit `Self` type here",
  86. // and continue without an ErrorInst. See ExtendImplSelfAsDefault.
  87. context.emitter().Emit(self_node_id, RequireImplsExtendWithExplicitSelf);
  88. }
  89. self_type.inst_id = SemIR::ErrorInst::TypeInstId;
  90. }
  91. context.node_stack().Push(node_id, self_type.inst_id);
  92. return true;
  93. }
  94. static auto TypeStructureReferencesSelf(
  95. Context& context, SemIR::TypeInstId inst_id,
  96. const SemIR::IdentifiedFacetType& identified_facet_type) -> bool {
  97. auto find_self = [&](SemIR::TypeIterator& type_iter) -> bool {
  98. while (true) {
  99. auto step = type_iter.Next();
  100. if (step.Is<SemIR::TypeIterator::Step::Done>()) {
  101. break;
  102. }
  103. CARBON_KIND_SWITCH(step.any) {
  104. case CARBON_KIND(SemIR::TypeIterator::Step::Error _): {
  105. // Don't generate more diagnostics.
  106. return true;
  107. }
  108. case CARBON_KIND(SemIR::TypeIterator::Step::SymbolicBinding bind): {
  109. if (context.entity_names().Get(bind.entity_name_id).name_id ==
  110. SemIR::NameId::SelfType) {
  111. return true;
  112. }
  113. break;
  114. }
  115. default:
  116. break;
  117. }
  118. }
  119. return false;
  120. };
  121. {
  122. SemIR::TypeIterator type_iter(&context.sem_ir());
  123. type_iter.Add(context.constant_values().GetConstantTypeInstId(inst_id));
  124. if (find_self(type_iter)) {
  125. return true;
  126. }
  127. }
  128. if (identified_facet_type.required_impls().empty()) {
  129. return false;
  130. }
  131. for (auto [_, specific_interface] : identified_facet_type.required_impls()) {
  132. SemIR::TypeIterator type_iter(&context.sem_ir());
  133. type_iter.Add(specific_interface);
  134. if (!find_self(type_iter)) {
  135. return false;
  136. }
  137. }
  138. return true;
  139. }
  140. struct ValidateRequireResult {
  141. // The TypeId of a FacetType.
  142. SemIR::TypeId constraint_type_id;
  143. const SemIR::IdentifiedFacetType* identified_facet_type;
  144. };
  145. // Returns nullopt if a diagnostic has been emitted and the `require` decl is
  146. // not valid.
  147. static auto ValidateRequire(Context& context, SemIR::LocId loc_id,
  148. SemIR::TypeInstId self_inst_id,
  149. SemIR::InstId constraint_inst_id,
  150. SemIR::InstId scope_inst_id)
  151. -> std::optional<ValidateRequireResult> {
  152. auto self_constant_value_id = context.constant_values().Get(self_inst_id);
  153. auto constraint_constant_value_id =
  154. context.constant_values().Get(constraint_inst_id);
  155. if (self_constant_value_id == SemIR::ErrorInst::ConstantId ||
  156. constraint_constant_value_id == SemIR::ErrorInst::ConstantId ||
  157. scope_inst_id == SemIR::ErrorInst::InstId) {
  158. // An error was already diagnosed, don't diagnose another. We can't build a
  159. // useful `require` with an error, it couldn't do anything.
  160. return std::nullopt;
  161. }
  162. auto constraint_type_id =
  163. SemIR::TypeId::ForTypeConstant(constraint_constant_value_id);
  164. auto constraint_facet_type =
  165. context.types().TryGetAs<SemIR::FacetType>(constraint_type_id);
  166. if (!constraint_facet_type) {
  167. CARBON_DIAGNOSTIC(
  168. RequireImplsMissingFacetType, Error,
  169. "`require` declaration constrained by a non-facet type; "
  170. "expected an `interface` or `constraint` name after `impls`");
  171. context.emitter().Emit(constraint_inst_id, RequireImplsMissingFacetType);
  172. // Can't continue without a constraint to use.
  173. return std::nullopt;
  174. }
  175. auto identified_facet_type_id = RequireIdentifiedFacetType(
  176. context, SemIR::LocId(constraint_inst_id), self_constant_value_id,
  177. *constraint_facet_type, [&] {
  178. CARBON_DIAGNOSTIC(
  179. RequireImplsUnidentifiedFacetType, Error,
  180. "facet type {0} cannot be identified in `require` declaration",
  181. InstIdAsType);
  182. return context.emitter().Build(constraint_inst_id,
  183. RequireImplsUnidentifiedFacetType,
  184. constraint_inst_id);
  185. });
  186. if (!identified_facet_type_id.has_value()) {
  187. // The constraint can't be used. A diagnostic was emitted by
  188. // RequireIdentifiedFacetType().
  189. return std::nullopt;
  190. }
  191. const auto& identified =
  192. context.identified_facet_types().Get(identified_facet_type_id);
  193. if (!TypeStructureReferencesSelf(context, self_inst_id, identified)) {
  194. CARBON_DIAGNOSTIC(RequireImplsMissingSelf, Error,
  195. "no `Self` reference found in `require` declaration; "
  196. "`Self` must appear in the self-type or as a generic "
  197. "parameter for each `interface` or `constraint`");
  198. context.emitter().Emit(loc_id, RequireImplsMissingSelf);
  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. bool extend = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend);
  215. auto scope_inst_id =
  216. context.node_stack().Pop<Parse::NodeKind::RequireIntroducer>();
  217. auto validated = ValidateRequire(context, node_id, self_inst_id,
  218. constraint_inst_id, scope_inst_id);
  219. if (!validated) {
  220. // In an `extend` decl, errors get propagated into the parent scope just as
  221. // names do.
  222. if (extend) {
  223. auto scope_id = context.scope_stack().PeekNameScopeId();
  224. context.name_scopes().Get(scope_id).set_has_error();
  225. }
  226. DiscardGenericDecl(context);
  227. return true;
  228. }
  229. auto [constraint_type_id, identified_facet_type] = *validated;
  230. if (identified_facet_type->required_impls().empty()) {
  231. // A `require T impls type` adds no actual constraints, so nothing to do.
  232. // This is not an error though.
  233. DiscardGenericDecl(context);
  234. return true;
  235. }
  236. auto require_impls_decl =
  237. SemIR::RequireImplsDecl{// To be filled in after.
  238. .require_impls_id = SemIR::RequireImplsId::None,
  239. .decl_block_id = decl_block_id};
  240. auto decl_id = AddPlaceholderInst(context, node_id, require_impls_decl);
  241. auto require_impls_id = context.require_impls().Add(
  242. {.self_id = self_inst_id,
  243. .facet_type_inst_id =
  244. context.types().GetAsTypeInstId(constraint_inst_id),
  245. .extend_self = extend,
  246. .decl_id = decl_id,
  247. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  248. .generic_id = BuildGenericDecl(context, decl_id)});
  249. require_impls_decl.require_impls_id = require_impls_id;
  250. ReplaceInstBeforeConstantUse(context, decl_id, require_impls_decl);
  251. // We look for a complete type after BuildGenericDecl, so that the resulting
  252. // RequireCompleteType instruction is part of the enclosing interface or named
  253. // constraint generic definition. Then requiring enclosing entity to be
  254. // complete will resolve that definition (via ResolveSpecificDefinition()) and
  255. // also construct a specific for the `constraint_inst_id`, finding any
  256. // monomorphization errors that result.
  257. if (extend) {
  258. if (!RequireCompleteType(
  259. context, constraint_type_id, SemIR::LocId(constraint_inst_id), [&] {
  260. CARBON_DIAGNOSTIC(RequireImplsIncompleteFacetType, Error,
  261. "`extend require` of incomplete facet type {0}",
  262. InstIdAsType);
  263. return context.emitter().Build(constraint_inst_id,
  264. RequireImplsIncompleteFacetType,
  265. constraint_inst_id);
  266. })) {
  267. return true;
  268. }
  269. // The extended scope instruction must be part of the enclosing scope (and
  270. // generic). A specific for the enclosing scope will be applied to it when
  271. // using the instruction later. To do so, we wrap the constraint facet type
  272. // it in a SpecificConstant, which preserves the require declaration's
  273. // specific along with the facet type.
  274. auto constraint_id_in_self_specific = AddTypeInst<SemIR::SpecificConstant>(
  275. context, node_id,
  276. {.type_id = SemIR::TypeType::TypeId,
  277. .inst_id = constraint_inst_id,
  278. .specific_id = context.generics().GetSelfSpecific(
  279. context.require_impls().Get(require_impls_id).generic_id)});
  280. auto enclosing_scope_id = context.scope_stack().PeekNameScopeId();
  281. auto& enclosing_scope = context.name_scopes().Get(enclosing_scope_id);
  282. enclosing_scope.AddExtendedScope(constraint_id_in_self_specific);
  283. }
  284. context.require_impls_stack().AppendToTop(require_impls_id);
  285. return true;
  286. }
  287. } // namespace Carbon::Check