type_completion.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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/check/type_completion.h"
  5. #include "common/concepts.h"
  6. #include "llvm/ADT/SmallVector.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/check/cpp/import.h"
  9. #include "toolchain/check/facet_type.h"
  10. #include "toolchain/check/generic.h"
  11. #include "toolchain/check/inst.h"
  12. #include "toolchain/check/literal.h"
  13. #include "toolchain/check/type.h"
  14. #include "toolchain/diagnostics/emitter.h"
  15. #include "toolchain/diagnostics/format_providers.h"
  16. #include "toolchain/sem_ir/constant.h"
  17. #include "toolchain/sem_ir/facet_type_info.h"
  18. #include "toolchain/sem_ir/generic.h"
  19. #include "toolchain/sem_ir/ids.h"
  20. #include "toolchain/sem_ir/named_constraint.h"
  21. #include "toolchain/sem_ir/specific_interface.h"
  22. #include "toolchain/sem_ir/specific_named_constraint.h"
  23. #include "toolchain/sem_ir/type_info.h"
  24. #include "toolchain/sem_ir/typed_insts.h"
  25. namespace Carbon::Check {
  26. auto DiagnoseIncompleteClass(Context& context, SemIR::ClassId class_id)
  27. -> void {
  28. // The caller must provide context for any diagnostics in type completion.
  29. context.emitter().CheckHasContext();
  30. const auto& class_info = context.classes().Get(class_id);
  31. CARBON_CHECK(!class_info.is_complete(), "Class is not incomplete");
  32. if (class_info.has_definition_started()) {
  33. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Error,
  34. "class is incomplete within its definition");
  35. context.emitter().Emit(class_info.definition_id,
  36. ClassIncompleteWithinDefinition);
  37. } else {
  38. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Error,
  39. "class was forward declared here");
  40. context.emitter().Emit(class_info.latest_decl_id(),
  41. ClassForwardDeclaredHere);
  42. }
  43. }
  44. auto DiagnoseIncompleteInterface(Context& context,
  45. SemIR::InterfaceId interface_id) -> void {
  46. // The caller must provide context for any diagnostics in type completion.
  47. context.emitter().CheckHasContext();
  48. const auto& interface_info = context.interfaces().Get(interface_id);
  49. CARBON_CHECK(!interface_info.is_complete(), "Interface is not incomplete");
  50. if (interface_info.is_being_defined()) {
  51. CARBON_DIAGNOSTIC(InterfaceIncompleteWithinDefinition, Error,
  52. "interface is currently being defined");
  53. context.emitter().Emit(interface_info.definition_id,
  54. InterfaceIncompleteWithinDefinition);
  55. } else {
  56. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Error,
  57. "interface was forward declared here");
  58. context.emitter().Emit(interface_info.latest_decl_id(),
  59. InterfaceForwardDeclaredHere);
  60. }
  61. }
  62. auto DiagnoseAbstractClass(Context& context, SemIR::ClassId class_id,
  63. bool direct_use) -> void {
  64. // The caller must provide context for any diagnostics in type completion.
  65. context.emitter().CheckHasContext();
  66. const auto& class_info = context.classes().Get(class_id);
  67. CARBON_CHECK(
  68. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  69. "Class is not abstract");
  70. CARBON_DIAGNOSTIC(
  71. ClassAbstractHere, Error,
  72. "{0:=0:uses class that|=1:class} was declared abstract here",
  73. Diagnostics::IntAsSelect);
  74. context.emitter().Emit(class_info.definition_id, ClassAbstractHere,
  75. static_cast<int>(direct_use));
  76. }
  77. static auto DiagnoseIncompleteNamedConstraint(
  78. Context& context, SemIR::NamedConstraintId named_constraint_id) -> void {
  79. // The caller must provide context for any diagnostics in type completion.
  80. context.emitter().CheckHasContext();
  81. const auto& constraint = context.named_constraints().Get(named_constraint_id);
  82. CARBON_CHECK(!constraint.is_complete(), "Named constraint is not incomplete");
  83. if (constraint.is_being_defined()) {
  84. CARBON_DIAGNOSTIC(NamedConstraintIncompleteWithinDefinition, Error,
  85. "constraint is currently being defined");
  86. context.emitter().Emit(constraint.definition_id,
  87. NamedConstraintIncompleteWithinDefinition);
  88. } else {
  89. CARBON_DIAGNOSTIC(NamedConstraintForwardDeclaredHere, Error,
  90. "constraint was forward declared here");
  91. context.emitter().Emit(constraint.latest_decl_id(),
  92. NamedConstraintForwardDeclaredHere);
  93. }
  94. }
  95. // Returns true if either eval block contains an error.
  96. static auto SpecificHasError(Context& context, SemIR::SpecificId specific_id)
  97. -> bool {
  98. return specific_id.has_value() &&
  99. context.specifics().Get(specific_id).HasError();
  100. }
  101. static auto RequireCompleteFacetType(Context& context, SemIR::LocId loc_id,
  102. const SemIR::FacetType& facet_type,
  103. bool diagnose) -> bool {
  104. const auto& facet_type_info =
  105. context.facet_types().Get(facet_type.facet_type_id);
  106. for (auto extends : facet_type_info.extend_constraints) {
  107. auto interface_id = extends.interface_id;
  108. const auto& interface = context.interfaces().Get(interface_id);
  109. if (!interface.is_complete()) {
  110. if (diagnose) {
  111. DiagnoseIncompleteInterface(context, interface_id);
  112. }
  113. return false;
  114. }
  115. if (interface.generic_id.has_value()) {
  116. ResolveSpecificDefinition(context, loc_id, extends.specific_id);
  117. if (SpecificHasError(context, extends.specific_id)) {
  118. return false;
  119. }
  120. }
  121. auto interface_with_self_self_specific_args = context.inst_blocks().Get(
  122. context.specifics().GetArgsOrEmpty(context.generics().GetSelfSpecific(
  123. interface.generic_with_self_id)));
  124. auto self_facet = interface_with_self_self_specific_args.back();
  125. auto interface_with_self_specific_id = MakeSpecificWithInnerSelf(
  126. context, loc_id, interface.generic_id, interface.generic_with_self_id,
  127. extends.specific_id, context.constant_values().Get(self_facet));
  128. if (SpecificHasError(context, interface_with_self_specific_id)) {
  129. return false;
  130. }
  131. }
  132. for (auto extends : facet_type_info.extend_named_constraints) {
  133. auto named_constraint_id = extends.named_constraint_id;
  134. const auto& constraint =
  135. context.named_constraints().Get(named_constraint_id);
  136. if (!constraint.is_complete()) {
  137. if (diagnose) {
  138. DiagnoseIncompleteNamedConstraint(context, named_constraint_id);
  139. }
  140. return false;
  141. }
  142. if (constraint.generic_id.has_value()) {
  143. ResolveSpecificDefinition(context, loc_id, extends.specific_id);
  144. if (SpecificHasError(context, extends.specific_id)) {
  145. return false;
  146. }
  147. }
  148. auto constraint_with_self_self_specific_args = context.inst_blocks().Get(
  149. context.specifics().GetArgsOrEmpty(context.generics().GetSelfSpecific(
  150. constraint.generic_with_self_id)));
  151. auto self_facet = constraint_with_self_self_specific_args.back();
  152. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  153. context, loc_id, constraint.generic_id, constraint.generic_with_self_id,
  154. extends.specific_id, context.constant_values().Get(self_facet));
  155. if (SpecificHasError(context, constraint_with_self_specific_id)) {
  156. return false;
  157. }
  158. }
  159. return true;
  160. }
  161. namespace {
  162. // Worklist-based type completion mechanism.
  163. //
  164. // When attempting to complete a type, we may find other types that also need to
  165. // be completed: types nested within that type, and the value representation of
  166. // the type. In order to complete a type without recursing arbitrarily deeply,
  167. // we use a worklist of tasks:
  168. //
  169. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  170. // nested within a type to the work list.
  171. // - A `BuildInfo` step computes the `CompleteTypeInfo` for a type, once all of
  172. // its nested types are complete, and marks the type as complete.
  173. class TypeCompleter {
  174. public:
  175. // `context` mut not be null.
  176. TypeCompleter(Context* context, SemIR::LocId loc_id, bool diagnose)
  177. : context_(context), loc_id_(loc_id), diagnose_(diagnose) {}
  178. // Attempts to complete the given type. Returns true if it is now complete,
  179. // false if it could not be completed.
  180. auto Complete(SemIR::TypeId type_id) -> bool;
  181. private:
  182. enum class Phase : int8_t {
  183. // The next step is to add nested types to the list of types to complete.
  184. AddNestedIncompleteTypes,
  185. // The next step is to build the `CompleteTypeInfo` for the type.
  186. BuildInfo,
  187. };
  188. struct WorkItem {
  189. SemIR::TypeId type_id;
  190. Phase phase;
  191. };
  192. // Adds `type_id` to the work list, if it's not already complete.
  193. auto Push(SemIR::TypeId type_id) -> void;
  194. // Runs the next step.
  195. auto ProcessStep() -> bool;
  196. // Adds any types nested within `type_inst` that need to be complete for
  197. // `type_inst` to be complete to our work list.
  198. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool;
  199. // Makes an empty value representation, which is used for types that have no
  200. // state, such as empty structs and tuples.
  201. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr;
  202. // Makes a dependent value representation, which is used for symbolic types.
  203. auto MakeDependentValueRepr(SemIR::TypeId type_id) const -> SemIR::ValueRepr;
  204. // Makes a value representation that uses pass-by-copy, copying the given
  205. // type.
  206. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  207. SemIR::ValueRepr::AggregateKind aggregate_kind =
  208. SemIR::ValueRepr::NotAggregate) const
  209. -> SemIR::ValueRepr;
  210. // Makes a value representation that uses pass-by-address with the given
  211. // pointee type.
  212. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  213. SemIR::ValueRepr::AggregateKind aggregate_kind =
  214. SemIR::ValueRepr::NotAggregate) const
  215. -> SemIR::ValueRepr;
  216. // Gets the value representation of a nested type, which should already be
  217. // complete.
  218. auto GetNestedInfo(SemIR::TypeId nested_type_id) const
  219. -> SemIR::CompleteTypeInfo;
  220. template <typename InstT>
  221. requires(InstT::Kind.template IsAnyOf<
  222. SemIR::AutoType, SemIR::BoolType, SemIR::BoundMethodType,
  223. SemIR::CharLiteralType, SemIR::ErrorInst, SemIR::FacetType,
  224. SemIR::FloatLiteralType, SemIR::FloatType, SemIR::FormType,
  225. SemIR::IntType, SemIR::IntLiteralType, SemIR::NamespaceType,
  226. SemIR::PatternType, SemIR::PointerType,
  227. SemIR::RequireSpecificDefinitionType, SemIR::SpecificFunctionType,
  228. SemIR::TypeType, SemIR::VtableType, SemIR::WitnessType>())
  229. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  230. -> SemIR::CompleteTypeInfo {
  231. return {.value_repr = MakeCopyValueRepr(type_id)};
  232. }
  233. auto BuildStructOrTupleValueRepr(size_t num_elements,
  234. SemIR::TypeId elementwise_rep,
  235. bool same_as_object_rep) const
  236. -> SemIR::ValueRepr;
  237. auto BuildInfoForInst(SemIR::TypeId type_id,
  238. SemIR::StructType struct_type) const
  239. -> SemIR::CompleteTypeInfo;
  240. auto BuildInfoForInst(SemIR::TypeId type_id,
  241. SemIR::TupleType tuple_type) const
  242. -> SemIR::CompleteTypeInfo;
  243. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::ArrayType /*inst*/) const
  244. -> SemIR::CompleteTypeInfo;
  245. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ClassType inst) const
  246. -> SemIR::CompleteTypeInfo;
  247. template <typename InstT>
  248. requires(InstT::Kind.template IsAnyOf<
  249. SemIR::AssociatedEntityType, SemIR::CppOverloadSetType,
  250. SemIR::CppTemplateNameType, SemIR::FunctionType,
  251. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  252. SemIR::GenericInterfaceType, SemIR::GenericNamedConstraintType,
  253. SemIR::InstType, SemIR::UnboundElementType, SemIR::WhereExpr>())
  254. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  255. -> SemIR::CompleteTypeInfo {
  256. // These types have no runtime operations, so we use an empty value
  257. // representation.
  258. //
  259. // TODO: There is information we could model here:
  260. // - For an interface, we could use a witness.
  261. // - For an associated entity, we could use an index into the witness.
  262. // - For an unbound element, we could use an index or offset.
  263. return {.value_repr = MakeEmptyValueRepr()};
  264. }
  265. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ConstType inst) const
  266. -> SemIR::CompleteTypeInfo;
  267. auto BuildInfoForInst(SemIR::TypeId type_id,
  268. SemIR::CustomLayoutType inst) const
  269. -> SemIR::CompleteTypeInfo;
  270. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  271. SemIR::MaybeUnformedType inst) const
  272. -> SemIR::CompleteTypeInfo;
  273. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  274. SemIR::PartialType inst) const
  275. -> SemIR::CompleteTypeInfo;
  276. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  277. SemIR::ImplWitnessAssociatedConstant inst) const
  278. -> SemIR::CompleteTypeInfo;
  279. template <typename InstT>
  280. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  281. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT inst) const
  282. -> SemIR::CompleteTypeInfo {
  283. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  284. }
  285. template <typename InstT>
  286. requires(InstT::Kind.is_symbolic_when_type())
  287. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  288. -> SemIR::CompleteTypeInfo {
  289. return {.value_repr = MakeDependentValueRepr(type_id)};
  290. }
  291. // Builds and returns the `CompleteTypeInfo` for the given type. All nested
  292. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  293. auto BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  294. -> SemIR::CompleteTypeInfo;
  295. Context* context_;
  296. llvm::SmallVector<WorkItem> work_list_;
  297. SemIR::LocId loc_id_;
  298. bool diagnose_;
  299. };
  300. } // namespace
  301. auto TypeCompleter::Complete(SemIR::TypeId type_id) -> bool {
  302. Push(type_id);
  303. while (!work_list_.empty()) {
  304. if (!ProcessStep()) {
  305. return false;
  306. }
  307. }
  308. return true;
  309. }
  310. auto TypeCompleter::Push(SemIR::TypeId type_id) -> void {
  311. if (!context_->types().IsComplete(type_id)) {
  312. work_list_.push_back(
  313. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  314. }
  315. }
  316. auto TypeCompleter::ProcessStep() -> bool {
  317. auto [type_id, phase] = work_list_.back();
  318. // We might have enqueued the same type more than once. Just skip the
  319. // type if it's already complete.
  320. if (context_->types().IsComplete(type_id)) {
  321. work_list_.pop_back();
  322. return true;
  323. }
  324. auto inst_id = context_->types().GetTypeInstId(type_id);
  325. auto inst = context_->insts().Get(inst_id);
  326. auto old_work_list_size = work_list_.size();
  327. switch (phase) {
  328. case Phase::AddNestedIncompleteTypes:
  329. if (!AddNestedIncompleteTypes(inst)) {
  330. return false;
  331. }
  332. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  333. "AddNestedIncompleteTypes should not remove work items");
  334. work_list_[old_work_list_size - 1].phase = Phase::BuildInfo;
  335. break;
  336. case Phase::BuildInfo: {
  337. auto info = BuildInfo(type_id, inst);
  338. context_->types().SetComplete(type_id, info);
  339. CARBON_CHECK(old_work_list_size == work_list_.size(),
  340. "BuildInfo should not change work items");
  341. work_list_.pop_back();
  342. // Also complete the value representation type, if necessary. This
  343. // should never fail: the value representation shouldn't require any
  344. // additional nested types to be complete.
  345. if (!context_->types().IsComplete(info.value_repr.type_id)) {
  346. work_list_.push_back(
  347. {.type_id = info.value_repr.type_id, .phase = Phase::BuildInfo});
  348. }
  349. // For a pointer representation, the pointee also needs to be complete.
  350. if (info.value_repr.kind == SemIR::ValueRepr::Pointer) {
  351. if (info.value_repr.type_id == SemIR::ErrorInst::TypeId) {
  352. break;
  353. }
  354. auto pointee_type_id =
  355. context_->sem_ir().GetPointeeType(info.value_repr.type_id);
  356. if (!context_->types().IsComplete(pointee_type_id)) {
  357. work_list_.push_back(
  358. {.type_id = pointee_type_id, .phase = Phase::BuildInfo});
  359. }
  360. }
  361. break;
  362. }
  363. }
  364. return true;
  365. }
  366. auto TypeCompleter::AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  367. CARBON_KIND_SWITCH(type_inst) {
  368. case CARBON_KIND(SemIR::ArrayType inst): {
  369. Push(context_->types().GetTypeIdForTypeInstId(inst.element_type_inst_id));
  370. break;
  371. }
  372. case CARBON_KIND(SemIR::StructType inst): {
  373. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  374. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  375. }
  376. break;
  377. }
  378. case CARBON_KIND(SemIR::TupleType inst): {
  379. for (auto element_type_id : context_->types().GetBlockAsTypeIds(
  380. context_->inst_blocks().Get(inst.type_elements_id))) {
  381. Push(element_type_id);
  382. }
  383. break;
  384. }
  385. case CARBON_KIND(SemIR::ClassType inst): {
  386. auto& class_info = context_->classes().Get(inst.class_id);
  387. // If the class was imported from C++, ask Clang to try to complete it.
  388. if (!class_info.is_complete() && class_info.scope_id.has_value()) {
  389. auto& scope = context_->name_scopes().Get(class_info.scope_id);
  390. if (scope.clang_decl_context_id().has_value()) {
  391. if (!ImportClassDefinitionForClangDecl(
  392. *context_, inst.class_id, scope.clang_decl_context_id())) {
  393. // Clang produced a diagnostic. Don't produce one of our own.
  394. return false;
  395. }
  396. }
  397. }
  398. if (!class_info.is_complete()) {
  399. if (diagnose_) {
  400. DiagnoseIncompleteClass(*context_, inst.class_id);
  401. }
  402. return false;
  403. }
  404. if (inst.specific_id.has_value()) {
  405. ResolveSpecificDefinition(*context_, loc_id_, inst.specific_id);
  406. }
  407. if (auto adapted_type_id =
  408. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  409. adapted_type_id.has_value()) {
  410. Push(adapted_type_id);
  411. } else {
  412. Push(class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id));
  413. }
  414. break;
  415. }
  416. case CARBON_KIND(SemIR::ConstType inst): {
  417. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  418. break;
  419. }
  420. case CARBON_KIND(SemIR::CustomLayoutType inst): {
  421. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  422. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  423. }
  424. break;
  425. }
  426. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  427. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  428. break;
  429. }
  430. case CARBON_KIND(SemIR::PartialType inst): {
  431. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  432. break;
  433. }
  434. case CARBON_KIND(SemIR::FacetType inst): {
  435. if (!RequireCompleteFacetType(*context_, loc_id_, inst, diagnose_)) {
  436. return false;
  437. }
  438. break;
  439. }
  440. default:
  441. break;
  442. }
  443. return true;
  444. }
  445. auto TypeCompleter::MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  446. return {.kind = SemIR::ValueRepr::None,
  447. .type_id = GetTupleType(*context_, {})};
  448. }
  449. auto TypeCompleter::MakeDependentValueRepr(SemIR::TypeId type_id) const
  450. -> SemIR::ValueRepr {
  451. return {.kind = SemIR::ValueRepr::Dependent, .type_id = type_id};
  452. }
  453. auto TypeCompleter::MakeCopyValueRepr(
  454. SemIR::TypeId rep_id, SemIR::ValueRepr::AggregateKind aggregate_kind) const
  455. -> SemIR::ValueRepr {
  456. return {.kind = SemIR::ValueRepr::Copy,
  457. .aggregate_kind = aggregate_kind,
  458. .type_id = rep_id};
  459. }
  460. auto TypeCompleter::MakePointerValueRepr(
  461. SemIR::TypeId pointee_id,
  462. SemIR::ValueRepr::AggregateKind aggregate_kind) const -> SemIR::ValueRepr {
  463. // TODO: Should we add `const` qualification to `pointee_id`?
  464. return {.kind = SemIR::ValueRepr::Pointer,
  465. .aggregate_kind = aggregate_kind,
  466. .type_id = GetPointerType(
  467. *context_, context_->types().GetTypeInstId(pointee_id))};
  468. }
  469. auto TypeCompleter::GetNestedInfo(SemIR::TypeId nested_type_id) const
  470. -> SemIR::CompleteTypeInfo {
  471. CARBON_CHECK(context_->types().IsComplete(nested_type_id),
  472. "Nested type should already be complete");
  473. auto info = context_->types().GetCompleteTypeInfo(nested_type_id);
  474. CARBON_CHECK(info.value_repr.kind != SemIR::ValueRepr::Unknown,
  475. "Complete type should have a value representation");
  476. return info;
  477. }
  478. auto TypeCompleter::BuildStructOrTupleValueRepr(size_t num_elements,
  479. SemIR::TypeId elementwise_rep,
  480. bool same_as_object_rep) const
  481. -> SemIR::ValueRepr {
  482. SemIR::ValueRepr::AggregateKind aggregate_kind =
  483. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  484. : SemIR::ValueRepr::ValueAggregate;
  485. if (num_elements == 1) {
  486. // The value representation for a struct or tuple with a single element
  487. // is a struct or tuple containing the value representation of the
  488. // element.
  489. // TODO: Consider doing the same whenever `elementwise_rep` is
  490. // sufficiently small.
  491. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  492. }
  493. // For a struct or tuple with multiple fields, we use a pointer
  494. // to the elementwise value representation.
  495. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  496. }
  497. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  498. SemIR::StructType struct_type) const
  499. -> SemIR::CompleteTypeInfo {
  500. auto fields = context_->struct_type_fields().Get(struct_type.fields_id);
  501. if (fields.empty()) {
  502. return {.value_repr = MakeEmptyValueRepr()};
  503. }
  504. // Find the value representation for each field, and construct a struct
  505. // of value representations.
  506. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  507. value_rep_fields.reserve(fields.size());
  508. bool same_as_object_rep = true;
  509. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  510. for (auto field : fields) {
  511. auto field_type_id =
  512. context_->types().GetTypeIdForTypeInstId(field.type_inst_id);
  513. auto field_info = GetNestedInfo(field_type_id);
  514. if (!field_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  515. field_type_id)) {
  516. same_as_object_rep = false;
  517. field.type_inst_id =
  518. context_->types().GetTypeInstId(field_info.value_repr.type_id);
  519. }
  520. value_rep_fields.push_back(field);
  521. // Take the first non-None abstract_class_id, if any.
  522. if (field_info.abstract_class_id.has_value() &&
  523. !abstract_class_id.has_value()) {
  524. abstract_class_id = field_info.abstract_class_id;
  525. }
  526. }
  527. auto value_rep =
  528. same_as_object_rep
  529. ? type_id
  530. : GetStructType(
  531. *context_,
  532. context_->struct_type_fields().AddCanonical(value_rep_fields));
  533. return {.value_repr = BuildStructOrTupleValueRepr(fields.size(), value_rep,
  534. same_as_object_rep),
  535. .abstract_class_id = abstract_class_id};
  536. }
  537. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  538. SemIR::TupleType tuple_type) const
  539. -> SemIR::CompleteTypeInfo {
  540. // TODO: Share more code with structs.
  541. auto elements = context_->inst_blocks().Get(tuple_type.type_elements_id);
  542. if (elements.empty()) {
  543. return {.value_repr = MakeEmptyValueRepr()};
  544. }
  545. // Find the value representation for each element, and construct a tuple
  546. // of value representations.
  547. llvm::SmallVector<SemIR::InstId> value_rep_elements;
  548. value_rep_elements.reserve(elements.size());
  549. bool same_as_object_rep = true;
  550. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  551. for (auto element_type_id : context_->types().GetBlockAsTypeIds(elements)) {
  552. auto element_info = GetNestedInfo(element_type_id);
  553. if (!element_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  554. element_type_id)) {
  555. same_as_object_rep = false;
  556. }
  557. value_rep_elements.push_back(
  558. context_->types().GetTypeInstId(element_info.value_repr.type_id));
  559. // Take the first non-None abstract_class_id, if any.
  560. if (element_info.abstract_class_id.has_value() &&
  561. !abstract_class_id.has_value()) {
  562. abstract_class_id = element_info.abstract_class_id;
  563. }
  564. }
  565. auto value_rep = same_as_object_rep
  566. ? type_id
  567. : GetTupleType(*context_, value_rep_elements);
  568. return {.value_repr = BuildStructOrTupleValueRepr(elements.size(), value_rep,
  569. same_as_object_rep),
  570. .abstract_class_id = abstract_class_id};
  571. }
  572. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  573. SemIR::ArrayType /*inst*/) const
  574. -> SemIR::CompleteTypeInfo {
  575. // For arrays, it's convenient to always use a pointer representation,
  576. // even when the array has zero or one element, in order to support
  577. // indexing.
  578. return {.value_repr =
  579. MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate)};
  580. }
  581. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  582. SemIR::ClassType inst) const
  583. -> SemIR::CompleteTypeInfo {
  584. auto& class_info = context_->classes().Get(inst.class_id);
  585. auto abstract_class_id =
  586. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract
  587. ? inst.class_id
  588. : SemIR::ClassId::None;
  589. // The value representation of an adapter is the value representation of
  590. // its adapted type.
  591. if (auto adapted_type_id =
  592. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  593. adapted_type_id.has_value()) {
  594. auto info = GetNestedInfo(adapted_type_id);
  595. info.abstract_class_id = abstract_class_id;
  596. return info;
  597. }
  598. // Otherwise, the value representation for a class is a pointer to the
  599. // object representation.
  600. // TODO: Support customized value representations for classes.
  601. // TODO: Pick a better value representation when possible.
  602. return {.value_repr = MakePointerValueRepr(
  603. class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id),
  604. SemIR::ValueRepr::ObjectAggregate),
  605. .abstract_class_id = abstract_class_id};
  606. }
  607. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  608. SemIR::ConstType inst) const
  609. -> SemIR::CompleteTypeInfo {
  610. // The value representation of `const T` is the same as that of `T`.
  611. // Objects are not modifiable through their value representations.
  612. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  613. }
  614. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  615. SemIR::CustomLayoutType /*inst*/) const
  616. -> SemIR::CompleteTypeInfo {
  617. // TODO: Should we support other value representations for custom layout
  618. // types?
  619. return {.value_repr = MakePointerValueRepr(type_id)};
  620. }
  621. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  622. SemIR::MaybeUnformedType inst) const
  623. -> SemIR::CompleteTypeInfo {
  624. // `MaybeUnformed(T)` has the same value representation as `T` if that value
  625. // representation preserves all the bytes of the value, including any padding
  626. // bits. Otherwise we need to use a different representation.
  627. auto inner_type_id = context_->types().GetTypeIdForTypeInstId(inst.inner_id);
  628. auto nested = GetNestedInfo(inner_type_id);
  629. if (nested.value_repr.kind == SemIR::ValueRepr::Custom) {
  630. nested.value_repr = MakePointerValueRepr(type_id);
  631. } else if (nested.value_repr.kind == SemIR::ValueRepr::Copy) {
  632. auto type_inst = context_->types().GetAsInst(nested.value_repr.type_id);
  633. // TODO: Should ValueRepr::IsCopyOfObjectRepr return false for `bool`?
  634. if (!nested.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  635. inner_type_id) ||
  636. type_inst.Is<SemIR::BoolType>()) {
  637. nested.value_repr = MakePointerValueRepr(type_id);
  638. }
  639. // TODO: Handle any other types that we treat as having discarded padding
  640. // bits. For now there are no such types, as all class types and all structs
  641. // and tuples with more than one element are passed indirectly.
  642. }
  643. return nested;
  644. }
  645. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  646. SemIR::PartialType inst) const
  647. -> SemIR::CompleteTypeInfo {
  648. // The value representation of `partial T` is the same as that of `T`.
  649. // Objects are not modifiable through their value representations. However,
  650. // `partial T` is never abstract.
  651. return {
  652. .value_repr =
  653. GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id))
  654. .value_repr,
  655. .abstract_class_id = SemIR::ClassId::None};
  656. }
  657. auto TypeCompleter::BuildInfoForInst(
  658. SemIR::TypeId /*type_id*/, SemIR::ImplWitnessAssociatedConstant inst) const
  659. -> SemIR::CompleteTypeInfo {
  660. return GetNestedInfo(inst.type_id);
  661. }
  662. // Builds and returns the value representation for the given type. All nested
  663. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  664. auto TypeCompleter::BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  665. -> SemIR::CompleteTypeInfo {
  666. // Use overload resolution to select the implementation, producing compile
  667. // errors when BuildInfoForInst isn't defined for a given instruction.
  668. CARBON_KIND_SWITCH(inst) {
  669. #define CARBON_SEM_IR_INST_KIND(Name) \
  670. case CARBON_KIND(SemIR::Name typed_inst): { \
  671. return BuildInfoForInst(type_id, typed_inst); \
  672. }
  673. #include "toolchain/sem_ir/inst_kind.def"
  674. }
  675. }
  676. auto TryToCompleteType(Context& context, SemIR::TypeId type_id,
  677. SemIR::LocId loc_id, bool diagnose) -> bool {
  678. return TypeCompleter(&context, loc_id, diagnose).Complete(type_id);
  679. }
  680. auto CompleteTypeOrCheckFail(Context& context, SemIR::TypeId type_id) -> void {
  681. bool complete =
  682. TypeCompleter(&context, SemIR::LocId::None, false).Complete(type_id);
  683. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  684. context.types().GetAsInst(type_id));
  685. }
  686. auto RequireCompleteType(Context& context, SemIR::TypeId type_id,
  687. SemIR::LocId loc_id,
  688. DiagnosticContextFn diagnostic_context) -> bool {
  689. CARBON_CHECK(diagnostic_context);
  690. Diagnostics::ContextScope scope(&context.emitter(), diagnostic_context);
  691. if (!TypeCompleter(&context, loc_id, true).Complete(type_id)) {
  692. return false;
  693. }
  694. // For a symbolic type, create an instruction to require the corresponding
  695. // specific type to be complete.
  696. if (type_id.is_symbolic()) {
  697. // TODO: Deduplicate these.
  698. AddInstInNoBlock(
  699. context, loc_id,
  700. SemIR::RequireCompleteType{
  701. .type_id =
  702. GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  703. .complete_type_inst_id = context.types().GetTypeInstId(type_id)});
  704. }
  705. return true;
  706. }
  707. auto TryIsConcreteType(Context& context, SemIR::TypeId type_id,
  708. SemIR::LocId loc_id) -> bool {
  709. if (!TryToCompleteType(context, type_id, loc_id)) {
  710. return false;
  711. }
  712. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  713. CARBON_CHECK(complete_info.value_repr.type_id.has_value(),
  714. "TryIsConcreteType called for an incomplete type. Call "
  715. "TryToCompleteType first.");
  716. return !complete_info.abstract_class_id.has_value();
  717. }
  718. auto RequireConcreteType(Context& context, SemIR::TypeId type_id,
  719. SemIR::LocId loc_id,
  720. DiagnosticContextFn complete_type_diagnostic_context,
  721. DiagnosticContextFn concrete_type_diagnostic_context)
  722. -> bool {
  723. if (!RequireCompleteType(context, type_id, loc_id,
  724. complete_type_diagnostic_context)) {
  725. return false;
  726. }
  727. CARBON_CHECK(concrete_type_diagnostic_context);
  728. Diagnostics::ContextScope scope(&context.emitter(),
  729. concrete_type_diagnostic_context);
  730. // TODO: For symbolic types, should add an implicit constraint that they are
  731. // not abstract.
  732. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  733. CARBON_CHECK(complete_info.value_repr.type_id.has_value(),
  734. "RequireConcreteType called for an incomplete type. Call "
  735. "RequireCompleteType first.");
  736. if (!complete_info.abstract_class_id.has_value()) {
  737. return true;
  738. }
  739. bool direct_use = false;
  740. if (auto inst = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  741. if (inst->class_id == complete_info.abstract_class_id) {
  742. direct_use = true;
  743. }
  744. }
  745. DiagnoseAbstractClass(context, complete_info.abstract_class_id, direct_use);
  746. return false;
  747. }
  748. // Given a canonical facet value, or a type value, return a facet value.
  749. static auto GetSelfFacetValue(Context& context, SemIR::ConstantId self_const_id)
  750. -> SemIR::ConstantId {
  751. if (self_const_id == SemIR::ErrorInst::ConstantId) {
  752. return SemIR::ErrorInst::ConstantId;
  753. }
  754. auto self_inst_id = context.constant_values().GetInstId(self_const_id);
  755. auto type_id = context.insts().Get(self_inst_id).type_id();
  756. CARBON_CHECK(context.types().IsFacetType(type_id));
  757. if (context.types().Is<SemIR::FacetType>(type_id)) {
  758. return self_const_id;
  759. }
  760. return GetConstantFacetValueForType(
  761. context, context.types().GetAsTypeInstId(self_inst_id));
  762. }
  763. static auto IdentifyFacetType(Context& context, SemIR::LocId loc_id,
  764. SemIR::ConstantId self_const_id,
  765. const SemIR::FacetType& facet_type,
  766. bool allow_partially_identified, bool diagnose)
  767. -> SemIR::IdentifiedFacetTypeId {
  768. // While partially identified facet types end up in the store of
  769. // IdentifiedFacetTypes, we don't try to construct a key to look for them
  770. // here, so we will only early-out here for fully identified facet types. To
  771. // construct the key for a partially identified facet type we need to know the
  772. // set of required impls that it contains, which requires us to do most of the
  773. // work of identifying the facet type (though we could skip the mapping of
  774. // constant values into specifics).
  775. auto key =
  776. SemIR::IdentifiedFacetTypeKey{.facet_type_id = facet_type.facet_type_id,
  777. .self_const_id = self_const_id};
  778. if (auto identified_id = context.identified_facet_types().Lookup(key);
  779. identified_id.has_value()) {
  780. return identified_id;
  781. }
  782. struct SelfImplsFacetType {
  783. bool extend;
  784. SemIR::ConstantId self;
  785. SemIR::FacetTypeId facet_type;
  786. };
  787. // Work queue.
  788. llvm::SmallVector<SelfImplsFacetType> work = {
  789. {true, self_const_id, facet_type.facet_type_id}};
  790. // Outputs for the IdentifiedFacetType.
  791. bool partially_identified = false;
  792. llvm::SmallVector<SemIR::IdentifiedFacetType::RequiredImpl> extends;
  793. llvm::SmallVector<SemIR::IdentifiedFacetType::RequiredImpl> impls;
  794. while (!work.empty()) {
  795. SelfImplsFacetType next_impls = work.pop_back_val();
  796. bool facet_type_extends = next_impls.extend;
  797. auto self_const_id = GetCanonicalFacetOrTypeValue(context, next_impls.self);
  798. const auto& facet_type_info =
  799. context.facet_types().Get(next_impls.facet_type);
  800. auto self_and_interface = [&](SemIR::SpecificInterface interface)
  801. -> SemIR::IdentifiedFacetType::RequiredImpl {
  802. return {self_const_id, interface};
  803. };
  804. auto type_and_interface =
  805. [&](const SemIR::FacetTypeInfo::TypeImplsInterface& impls)
  806. -> SemIR::IdentifiedFacetType::RequiredImpl {
  807. return {context.constant_values().Get(impls.self_type),
  808. impls.specific_interface};
  809. };
  810. if (facet_type_extends) {
  811. llvm::append_range(extends,
  812. llvm::map_range(facet_type_info.extend_constraints,
  813. self_and_interface));
  814. } else {
  815. llvm::append_range(impls,
  816. llvm::map_range(facet_type_info.extend_constraints,
  817. self_and_interface));
  818. }
  819. llvm::append_range(impls,
  820. llvm::map_range(facet_type_info.self_impls_constraints,
  821. self_and_interface));
  822. llvm::append_range(impls,
  823. llvm::map_range(facet_type_info.type_impls_interfaces,
  824. type_and_interface));
  825. if (facet_type_info.extend_named_constraints.empty() &&
  826. facet_type_info.self_impls_named_constraints.empty() &&
  827. facet_type_info.type_impls_named_constraints.empty()) {
  828. continue;
  829. }
  830. // The self may have type TypeType. But the `Self` in a generic require decl
  831. // has type FacetType, so we need something similar to replace it in the
  832. // specific.
  833. auto self_facet = GetSelfFacetValue(context, self_const_id);
  834. for (auto extends : facet_type_info.extend_named_constraints) {
  835. const auto& constraint =
  836. context.named_constraints().Get(extends.named_constraint_id);
  837. llvm::ArrayRef<SemIR::RequireImplsId> require_impls_ids;
  838. if (constraint.is_complete()) {
  839. require_impls_ids = context.require_impls_blocks().Get(
  840. constraint.require_impls_block_id);
  841. } else if (allow_partially_identified) {
  842. partially_identified = true;
  843. if (constraint.is_being_defined()) {
  844. require_impls_ids = context.require_impls_stack().PeekForScope(
  845. extends.named_constraint_id);
  846. } else {
  847. continue;
  848. }
  849. } else {
  850. if (diagnose) {
  851. DiagnoseIncompleteNamedConstraint(context,
  852. extends.named_constraint_id);
  853. }
  854. return SemIR::IdentifiedFacetTypeId::None;
  855. }
  856. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  857. context, loc_id, constraint.generic_id,
  858. constraint.generic_with_self_id, extends.specific_id, self_facet);
  859. if (SpecificHasError(context, constraint_with_self_specific_id)) {
  860. return SemIR::IdentifiedFacetTypeId::None;
  861. }
  862. for (auto require_impls_id : llvm::reverse(require_impls_ids)) {
  863. const auto& require = context.require_impls().Get(require_impls_id);
  864. // Each require is in its own generic, with no additional bindings and
  865. // no definition, so that they can have their specifics independently
  866. // instantiated.
  867. auto require_specific_id = CopySpecificToGeneric(
  868. context, SemIR::LocId(require.decl_id),
  869. constraint_with_self_specific_id, require.generic_id);
  870. auto require_self = GetConstantValueInSpecific(
  871. context.sem_ir(), require_specific_id, require.self_id);
  872. auto require_facet_type = GetConstantValueInSpecific(
  873. context.sem_ir(), require_specific_id, require.facet_type_inst_id);
  874. if (require_self == SemIR::ErrorInst::ConstantId ||
  875. require_facet_type == SemIR::ErrorInst::ConstantId) {
  876. return SemIR::IdentifiedFacetTypeId::None;
  877. }
  878. auto facet_type_id =
  879. context.constant_values()
  880. .GetInstAs<SemIR::FacetType>(require_facet_type)
  881. .facet_type_id;
  882. bool extend = facet_type_extends && require.extend_self;
  883. work.push_back({extend, require_self, facet_type_id});
  884. }
  885. }
  886. for (auto impls : facet_type_info.self_impls_named_constraints) {
  887. const auto& constraint =
  888. context.named_constraints().Get(impls.named_constraint_id);
  889. llvm::ArrayRef<SemIR::RequireImplsId> require_impls_ids;
  890. if (constraint.is_complete()) {
  891. require_impls_ids = context.require_impls_blocks().Get(
  892. constraint.require_impls_block_id);
  893. } else if (allow_partially_identified) {
  894. partially_identified = true;
  895. if (constraint.is_being_defined()) {
  896. require_impls_ids = context.require_impls_stack().PeekForScope(
  897. impls.named_constraint_id);
  898. } else {
  899. continue;
  900. }
  901. } else {
  902. if (diagnose) {
  903. DiagnoseIncompleteNamedConstraint(context, impls.named_constraint_id);
  904. }
  905. return SemIR::IdentifiedFacetTypeId::None;
  906. }
  907. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  908. context, loc_id, constraint.generic_id,
  909. constraint.generic_with_self_id, impls.specific_id, self_facet);
  910. if (SpecificHasError(context, constraint_with_self_specific_id)) {
  911. return SemIR::IdentifiedFacetTypeId::None;
  912. }
  913. for (auto require_impls_id : llvm::reverse(require_impls_ids)) {
  914. const auto& require = context.require_impls().Get(require_impls_id);
  915. // Each require is in its own generic, with no additional bindings and
  916. // no definition, so that they can have their specifics independently
  917. // instantiated.
  918. auto require_specific_id = CopySpecificToGeneric(
  919. context, SemIR::LocId(require.decl_id),
  920. constraint_with_self_specific_id, require.generic_id);
  921. auto require_self = GetConstantValueInSpecific(
  922. context.sem_ir(), require_specific_id, require.self_id);
  923. auto require_facet_type = GetConstantValueInSpecific(
  924. context.sem_ir(), require_specific_id, require.facet_type_inst_id);
  925. if (require_self == SemIR::ErrorInst::ConstantId ||
  926. require_facet_type == SemIR::ErrorInst::ConstantId) {
  927. return SemIR::IdentifiedFacetTypeId::None;
  928. }
  929. auto facet_type_id =
  930. context.constant_values()
  931. .GetInstAs<SemIR::FacetType>(require_facet_type)
  932. .facet_type_id;
  933. work.push_back({false, require_self, facet_type_id});
  934. }
  935. }
  936. for (const auto& type_impls :
  937. facet_type_info.type_impls_named_constraints) {
  938. auto [self_type_inst_id, impls] = type_impls;
  939. const auto& constraint =
  940. context.named_constraints().Get(impls.named_constraint_id);
  941. llvm::ArrayRef<SemIR::RequireImplsId> require_impls_ids;
  942. if (constraint.is_complete()) {
  943. require_impls_ids = context.require_impls_blocks().Get(
  944. constraint.require_impls_block_id);
  945. } else if (allow_partially_identified) {
  946. partially_identified = true;
  947. if (constraint.is_being_defined()) {
  948. require_impls_ids = context.require_impls_stack().PeekForScope(
  949. impls.named_constraint_id);
  950. } else {
  951. continue;
  952. }
  953. } else {
  954. if (diagnose) {
  955. DiagnoseIncompleteNamedConstraint(context, impls.named_constraint_id);
  956. }
  957. return SemIR::IdentifiedFacetTypeId::None;
  958. }
  959. auto self_type_facet = GetSelfFacetValue(
  960. context, context.constant_values().Get(self_type_inst_id));
  961. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  962. context, loc_id, constraint.generic_id,
  963. constraint.generic_with_self_id, impls.specific_id, self_type_facet);
  964. if (SpecificHasError(context, constraint_with_self_specific_id)) {
  965. return SemIR::IdentifiedFacetTypeId::None;
  966. }
  967. for (auto require_impls_id : llvm::reverse(require_impls_ids)) {
  968. const auto& require = context.require_impls().Get(require_impls_id);
  969. // Each require is in its own generic, with no additional bindings and
  970. // no definition, so that they can have their specifics independently
  971. // instantiated.
  972. auto require_specific_id = CopySpecificToGeneric(
  973. context, SemIR::LocId(require.decl_id),
  974. constraint_with_self_specific_id, require.generic_id);
  975. auto require_self = GetConstantValueInSpecific(
  976. context.sem_ir(), require_specific_id, require.self_id);
  977. auto require_facet_type = GetConstantValueInSpecific(
  978. context.sem_ir(), require_specific_id, require.facet_type_inst_id);
  979. if (require_self == SemIR::ErrorInst::ConstantId ||
  980. require_facet_type == SemIR::ErrorInst::ConstantId) {
  981. return SemIR::IdentifiedFacetTypeId::None;
  982. }
  983. auto facet_type_id =
  984. context.constant_values()
  985. .GetInstAs<SemIR::FacetType>(require_facet_type)
  986. .facet_type_id;
  987. work.push_back({false, require_self, facet_type_id});
  988. }
  989. }
  990. }
  991. // TODO: Process other kinds of requirements.
  992. return context.identified_facet_types().Add(
  993. {key, partially_identified, extends, impls});
  994. }
  995. auto TryToIdentifyFacetType(Context& context, SemIR::LocId loc_id,
  996. SemIR::ConstantId self_const_id,
  997. const SemIR::FacetType& facet_type,
  998. bool allow_partially_identified)
  999. -> SemIR::IdentifiedFacetTypeId {
  1000. return IdentifyFacetType(context, loc_id, self_const_id, facet_type,
  1001. allow_partially_identified, /*diagnose=*/false);
  1002. }
  1003. auto RequireIdentifiedFacetType(Context& context, SemIR::LocId loc_id,
  1004. SemIR::ConstantId self_const_id,
  1005. const SemIR::FacetType& facet_type,
  1006. DiagnosticContextFn diagnostic_context,
  1007. bool diagnose) -> SemIR::IdentifiedFacetTypeId {
  1008. CARBON_CHECK(diagnostic_context);
  1009. Diagnostics::ContextScope scope(&context.emitter(), diagnostic_context);
  1010. return IdentifyFacetType(context, loc_id, self_const_id, facet_type,
  1011. /*allow_partially_identified=*/false, diagnose);
  1012. }
  1013. } // namespace Carbon::Check