handle_require.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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::LocId loc_id, 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. CARBON_DIAGNOSTIC(
  130. RequireImplsMissingSelfEmptyFacetType, Error,
  131. "no `Self` reference found in `require` declaration; `Self` must "
  132. "appear in the self-type or as a generic argument for each required "
  133. "interface, but no interfaces were found");
  134. context.emitter().Emit(loc_id, RequireImplsMissingSelfEmptyFacetType);
  135. return false;
  136. }
  137. bool interfaces_all_reference_self = true;
  138. for (auto [_, specific_interface] : identified_facet_type.required_impls()) {
  139. SemIR::TypeIterator type_iter(&context.sem_ir());
  140. type_iter.Add(specific_interface);
  141. if (!find_self(type_iter)) {
  142. // TODO: The IdentifiedFacetType loses the location (since it's
  143. // canonical), but it would be nice to somehow point this diagnostic at
  144. // the particular interface in the facet type that is missing `Self`.
  145. CARBON_DIAGNOSTIC(
  146. RequireImplsMissingSelf, Error,
  147. "no `Self` reference found in `require` declaration; `Self` must "
  148. "appear in the self-type or as a generic argument for each required "
  149. "interface, but found interface `{0}` without a `Self` argument",
  150. SemIR::SpecificInterface);
  151. context.emitter().Emit(loc_id, RequireImplsMissingSelf,
  152. specific_interface);
  153. interfaces_all_reference_self = false;
  154. }
  155. }
  156. return interfaces_all_reference_self;
  157. }
  158. struct ValidateRequireResult {
  159. // The TypeId of a FacetType.
  160. SemIR::TypeId constraint_type_id;
  161. const SemIR::IdentifiedFacetType* identified_facet_type;
  162. };
  163. // Returns nullopt if a diagnostic has been emitted and the `require` decl is
  164. // not valid.
  165. static auto ValidateRequire(Context& context, SemIR::LocId loc_id,
  166. SemIR::TypeInstId self_inst_id,
  167. SemIR::InstId constraint_inst_id,
  168. SemIR::InstId scope_inst_id)
  169. -> std::optional<ValidateRequireResult> {
  170. auto self_constant_value_id = context.constant_values().Get(self_inst_id);
  171. auto constraint_constant_value_id =
  172. context.constant_values().Get(constraint_inst_id);
  173. if (self_constant_value_id == SemIR::ErrorInst::ConstantId ||
  174. constraint_constant_value_id == SemIR::ErrorInst::ConstantId ||
  175. scope_inst_id == SemIR::ErrorInst::InstId) {
  176. // An error was already diagnosed, don't diagnose another. We can't build a
  177. // useful `require` with an error, it couldn't do anything.
  178. return std::nullopt;
  179. }
  180. auto constraint_type_id =
  181. SemIR::TypeId::ForTypeConstant(constraint_constant_value_id);
  182. auto constraint_facet_type =
  183. context.types().TryGetAs<SemIR::FacetType>(constraint_type_id);
  184. if (!constraint_facet_type) {
  185. CARBON_DIAGNOSTIC(
  186. RequireImplsMissingFacetType, Error,
  187. "`require` declaration constrained by a non-facet type; "
  188. "expected an `interface` or `constraint` name after `impls`");
  189. context.emitter().Emit(constraint_inst_id, RequireImplsMissingFacetType);
  190. // Can't continue without a constraint to use.
  191. return std::nullopt;
  192. }
  193. auto identified_facet_type_id = RequireIdentifiedFacetType(
  194. context, SemIR::LocId(constraint_inst_id), self_constant_value_id,
  195. *constraint_facet_type, [&] {
  196. CARBON_DIAGNOSTIC(
  197. RequireImplsUnidentifiedFacetType, Error,
  198. "facet type {0} cannot be identified in `require` declaration",
  199. InstIdAsType);
  200. return context.emitter().Build(constraint_inst_id,
  201. RequireImplsUnidentifiedFacetType,
  202. constraint_inst_id);
  203. });
  204. if (!identified_facet_type_id.has_value()) {
  205. // The constraint can't be used. A diagnostic was emitted by
  206. // RequireIdentifiedFacetType().
  207. return std::nullopt;
  208. }
  209. const auto& identified =
  210. context.identified_facet_types().Get(identified_facet_type_id);
  211. if (!TypeStructureReferencesSelf(context, loc_id, self_inst_id, identified)) {
  212. return std::nullopt;
  213. }
  214. return ValidateRequireResult{.constraint_type_id = constraint_type_id,
  215. .identified_facet_type = &identified};
  216. }
  217. auto HandleParseNode(Context& context, Parse::RequireDeclId node_id) -> bool {
  218. auto [constraint_node_id, constraint_inst_id] =
  219. context.node_stack().PopExprWithNodeId();
  220. auto [self_node_id, self_inst_id] =
  221. context.node_stack().PopWithNodeId<Parse::NodeCategory::RequireImpls>();
  222. auto decl_block_id = context.inst_block_stack().Pop();
  223. // Process modifiers.
  224. auto introducer =
  225. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Require>();
  226. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Extend);
  227. bool extend = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend);
  228. auto scope_inst_id =
  229. context.node_stack().Pop<Parse::NodeKind::RequireIntroducer>();
  230. auto validated = ValidateRequire(context, node_id, self_inst_id,
  231. constraint_inst_id, scope_inst_id);
  232. if (!validated) {
  233. // In an `extend` decl, errors get propagated into the parent scope just as
  234. // names do.
  235. if (extend) {
  236. auto scope_id = context.scope_stack().PeekNameScopeId();
  237. context.name_scopes().Get(scope_id).set_has_error();
  238. }
  239. DiscardGenericDecl(context);
  240. return true;
  241. }
  242. auto [constraint_type_id, identified_facet_type] = *validated;
  243. if (identified_facet_type->required_impls().empty()) {
  244. // A `require T impls type` adds no actual constraints, so nothing to do.
  245. // This is not an error though.
  246. DiscardGenericDecl(context);
  247. return true;
  248. }
  249. auto require_impls_decl =
  250. SemIR::RequireImplsDecl{// To be filled in after.
  251. .require_impls_id = SemIR::RequireImplsId::None,
  252. .decl_block_id = decl_block_id};
  253. auto decl_id = AddPlaceholderInst(context, node_id, require_impls_decl);
  254. auto require_impls_id = context.require_impls().Add(
  255. {.self_id = self_inst_id,
  256. .facet_type_inst_id =
  257. context.types().GetAsTypeInstId(constraint_inst_id),
  258. .extend_self = extend,
  259. .decl_id = decl_id,
  260. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  261. .generic_id = BuildGenericDecl(context, decl_id)});
  262. require_impls_decl.require_impls_id = require_impls_id;
  263. ReplaceInstBeforeConstantUse(context, decl_id, require_impls_decl);
  264. // We look for a complete type after BuildGenericDecl, so that the resulting
  265. // RequireCompleteType instruction is part of the enclosing interface or named
  266. // constraint generic definition. Then requiring enclosing entity to be
  267. // complete will resolve that definition (via ResolveSpecificDefinition()) and
  268. // also construct a specific for the `constraint_inst_id`, finding any
  269. // monomorphization errors that result.
  270. if (extend) {
  271. if (!RequireCompleteType(
  272. context, constraint_type_id, SemIR::LocId(constraint_inst_id), [&] {
  273. CARBON_DIAGNOSTIC(RequireImplsIncompleteFacetType, Error,
  274. "`extend require` of incomplete facet type {0}",
  275. InstIdAsType);
  276. return context.emitter().Build(constraint_inst_id,
  277. RequireImplsIncompleteFacetType,
  278. constraint_inst_id);
  279. })) {
  280. return true;
  281. }
  282. // The generic of a require declaration is always inside an interface or
  283. // constraint, which makes its last generic binding the inner `Self` facet
  284. // of the interface/constraint definition. Thus the last argument of its
  285. // `self_specific` is that inner `Self`.
  286. auto self_specific_id = context.generics().GetSelfSpecific(
  287. context.require_impls().Get(require_impls_id).generic_id);
  288. const auto& self_specific = context.specifics().Get(self_specific_id);
  289. auto self_specific_args = context.inst_blocks().Get(self_specific.args_id);
  290. auto inner_self_inst_id = self_specific_args.back();
  291. // The extended scope instruction must be part of the enclosing scope (and
  292. // generic). A specific for the enclosing scope will be applied to it when
  293. // using the instruction later. To do so, we wrap the constraint facet type
  294. // it in a SpecificConstant, which preserves the require declaration's
  295. // specific along with the facet type.
  296. auto constraint_id_in_self_specific = AddTypeInst<SemIR::SpecificConstant>(
  297. context, node_id,
  298. {.type_id = SemIR::TypeType::TypeId,
  299. .inst_id = constraint_inst_id,
  300. .specific_id = self_specific_id});
  301. auto enclosing_scope_id = context.scope_stack().PeekNameScopeId();
  302. auto& enclosing_scope = context.name_scopes().Get(enclosing_scope_id);
  303. enclosing_scope.AddExtendedScope(
  304. {constraint_id_in_self_specific, inner_self_inst_id});
  305. }
  306. context.require_impls_stack().AppendToTop(require_impls_id);
  307. return true;
  308. }
  309. } // namespace Carbon::Check