handle_require.cpp 14 KB

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