type_completion.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  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 type info for a type with an empty value representation, which is
  200. // used for types that have no state, such as empty structs and tuples.
  201. auto MakeEmptyTypeInfo() const -> SemIR::CompleteTypeInfo;
  202. // Makes type info for a type with a dependent value representation, which is
  203. // used for symbolic types.
  204. auto MakeDependentTypeInfo(SemIR::TypeId type_id) const
  205. -> SemIR::CompleteTypeInfo;
  206. // Makes a value representation that uses pass-by-copy, copying the given
  207. // type.
  208. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  209. SemIR::ValueRepr::AggregateKind aggregate_kind =
  210. SemIR::ValueRepr::NotAggregate) const
  211. -> SemIR::ValueRepr;
  212. // Makes a value representation that uses pass-by-address with the given
  213. // pointee type.
  214. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  215. SemIR::ValueRepr::AggregateKind aggregate_kind =
  216. SemIR::ValueRepr::NotAggregate) const
  217. -> SemIR::ValueRepr;
  218. // Gets the type info for a nested type, which should already be complete.
  219. auto GetNestedInfo(SemIR::TypeId nested_type_id) const
  220. -> SemIR::CompleteTypeInfo;
  221. template <typename InstT>
  222. requires(InstT::Kind.template IsAnyOf<
  223. SemIR::AutoType, SemIR::BoundMethodType, SemIR::CharLiteralType,
  224. SemIR::ErrorInst, SemIR::FacetType, SemIR::FloatLiteralType,
  225. SemIR::FormType, SemIR::IntLiteralType, SemIR::NamespaceType,
  226. SemIR::PatternType, SemIR::RequireSpecificDefinitionType,
  227. SemIR::SpecificFunctionType, SemIR::TypeType, SemIR::VtableType,
  228. SemIR::WitnessType>())
  229. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  230. -> SemIR::CompleteTypeInfo {
  231. // These types are empty at runtime but have values to copy at compile time.
  232. return {.value_repr = MakeCopyValueRepr(type_id),
  233. .object_layout = SemIR::ObjectLayout::Empty()};
  234. }
  235. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::BoolType inst) const
  236. -> SemIR::CompleteTypeInfo;
  237. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::PointerType inst) const
  238. -> SemIR::CompleteTypeInfo;
  239. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::IntType inst) const
  240. -> SemIR::CompleteTypeInfo;
  241. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::FloatType inst) const
  242. -> SemIR::CompleteTypeInfo;
  243. auto BuildStructOrTupleValueRepr(size_t num_elements,
  244. SemIR::TypeId elementwise_rep,
  245. bool same_as_object_rep) const
  246. -> SemIR::ValueRepr;
  247. auto BuildInfoForInst(SemIR::TypeId type_id,
  248. SemIR::StructType struct_type) const
  249. -> SemIR::CompleteTypeInfo;
  250. auto BuildInfoForInst(SemIR::TypeId type_id,
  251. SemIR::TupleType tuple_type) const
  252. -> SemIR::CompleteTypeInfo;
  253. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::ArrayType /*inst*/) const
  254. -> SemIR::CompleteTypeInfo;
  255. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ClassType inst) const
  256. -> SemIR::CompleteTypeInfo;
  257. template <typename InstT>
  258. requires(InstT::Kind.template IsAnyOf<
  259. SemIR::AssociatedEntityType, SemIR::CppOverloadSetType,
  260. SemIR::CppTemplateNameType, SemIR::FunctionType,
  261. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  262. SemIR::GenericInterfaceType, SemIR::GenericNamedConstraintType,
  263. SemIR::InstType, SemIR::UnboundElementType, SemIR::WhereExpr>())
  264. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  265. -> SemIR::CompleteTypeInfo {
  266. // These types have no runtime operations, so we use an empty value
  267. // representation.
  268. //
  269. // TODO: There is information we could model here:
  270. // - For an interface, we could use a witness.
  271. // - For an associated entity, we could use an index into the witness.
  272. // - For an unbound element, we could use an index or offset.
  273. return MakeEmptyTypeInfo();
  274. }
  275. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ConstType inst) const
  276. -> SemIR::CompleteTypeInfo;
  277. auto BuildInfoForInst(SemIR::TypeId type_id,
  278. SemIR::CustomLayoutType inst) const
  279. -> SemIR::CompleteTypeInfo;
  280. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  281. SemIR::MaybeUnformedType inst) const
  282. -> SemIR::CompleteTypeInfo;
  283. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  284. SemIR::PartialType inst) const
  285. -> SemIR::CompleteTypeInfo;
  286. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  287. SemIR::ImplWitnessAssociatedConstant inst) const
  288. -> SemIR::CompleteTypeInfo;
  289. template <typename InstT>
  290. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  291. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT inst) const
  292. -> SemIR::CompleteTypeInfo {
  293. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  294. }
  295. template <typename InstT>
  296. requires(InstT::Kind.is_symbolic_when_type())
  297. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  298. -> SemIR::CompleteTypeInfo {
  299. return MakeDependentTypeInfo(type_id);
  300. }
  301. // Builds and returns the `CompleteTypeInfo` for the given type. All nested
  302. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  303. auto BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  304. -> SemIR::CompleteTypeInfo;
  305. Context* context_;
  306. llvm::SmallVector<WorkItem> work_list_;
  307. SemIR::LocId loc_id_;
  308. bool diagnose_;
  309. };
  310. } // namespace
  311. auto TypeCompleter::Complete(SemIR::TypeId type_id) -> bool {
  312. Push(type_id);
  313. while (!work_list_.empty()) {
  314. if (!ProcessStep()) {
  315. return false;
  316. }
  317. }
  318. return true;
  319. }
  320. auto TypeCompleter::Push(SemIR::TypeId type_id) -> void {
  321. if (!context_->types().IsComplete(type_id)) {
  322. work_list_.push_back(
  323. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  324. }
  325. }
  326. auto TypeCompleter::ProcessStep() -> bool {
  327. auto [type_id, phase] = work_list_.back();
  328. // We might have enqueued the same type more than once. Just skip the
  329. // type if it's already complete.
  330. if (context_->types().IsComplete(type_id)) {
  331. work_list_.pop_back();
  332. return true;
  333. }
  334. auto inst_id = context_->types().GetTypeInstId(type_id);
  335. auto inst = context_->insts().Get(inst_id);
  336. auto old_work_list_size = work_list_.size();
  337. switch (phase) {
  338. case Phase::AddNestedIncompleteTypes:
  339. if (!AddNestedIncompleteTypes(inst)) {
  340. return false;
  341. }
  342. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  343. "AddNestedIncompleteTypes should not remove work items");
  344. work_list_[old_work_list_size - 1].phase = Phase::BuildInfo;
  345. break;
  346. case Phase::BuildInfo: {
  347. auto info = BuildInfo(type_id, inst);
  348. context_->types().SetComplete(type_id, info);
  349. CARBON_CHECK(old_work_list_size == work_list_.size(),
  350. "BuildInfo should not change work items");
  351. work_list_.pop_back();
  352. // Also complete the value representation type, if necessary. This
  353. // should never fail: the value representation shouldn't require any
  354. // additional nested types to be complete.
  355. if (!context_->types().IsComplete(info.value_repr.type_id)) {
  356. work_list_.push_back(
  357. {.type_id = info.value_repr.type_id, .phase = Phase::BuildInfo});
  358. }
  359. // For a pointer representation, the pointee also needs to be complete.
  360. if (info.value_repr.kind == SemIR::ValueRepr::Pointer) {
  361. if (info.value_repr.type_id == SemIR::ErrorInst::TypeId) {
  362. break;
  363. }
  364. auto pointee_type_id =
  365. context_->sem_ir().GetPointeeType(info.value_repr.type_id);
  366. if (!context_->types().IsComplete(pointee_type_id)) {
  367. work_list_.push_back(
  368. {.type_id = pointee_type_id, .phase = Phase::BuildInfo});
  369. }
  370. }
  371. break;
  372. }
  373. }
  374. return true;
  375. }
  376. auto TypeCompleter::AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  377. CARBON_KIND_SWITCH(type_inst) {
  378. case CARBON_KIND(SemIR::ArrayType inst): {
  379. Push(context_->types().GetTypeIdForTypeInstId(inst.element_type_inst_id));
  380. break;
  381. }
  382. case CARBON_KIND(SemIR::StructType inst): {
  383. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  384. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  385. }
  386. break;
  387. }
  388. case CARBON_KIND(SemIR::TupleType inst): {
  389. for (auto element_type_id : context_->types().GetBlockAsTypeIds(
  390. context_->inst_blocks().Get(inst.type_elements_id))) {
  391. Push(element_type_id);
  392. }
  393. break;
  394. }
  395. case CARBON_KIND(SemIR::ClassType inst): {
  396. auto& class_info = context_->classes().Get(inst.class_id);
  397. // If the class was imported from C++, ask Clang to try to complete it.
  398. if (!class_info.is_complete() && class_info.scope_id.has_value()) {
  399. auto& scope = context_->name_scopes().Get(class_info.scope_id);
  400. if (scope.clang_decl_context_id().has_value()) {
  401. if (!ImportClassDefinitionForClangDecl(
  402. *context_, inst.class_id, scope.clang_decl_context_id())) {
  403. // Clang produced a diagnostic. Don't produce one of our own.
  404. return false;
  405. }
  406. }
  407. }
  408. if (!class_info.is_complete()) {
  409. if (diagnose_) {
  410. DiagnoseIncompleteClass(*context_, inst.class_id);
  411. }
  412. return false;
  413. }
  414. if (inst.specific_id.has_value()) {
  415. ResolveSpecificDefinition(*context_, loc_id_, inst.specific_id);
  416. }
  417. if (auto adapted_type_id =
  418. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  419. adapted_type_id.has_value()) {
  420. Push(adapted_type_id);
  421. } else {
  422. Push(class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id));
  423. }
  424. break;
  425. }
  426. case CARBON_KIND(SemIR::ConstType inst): {
  427. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  428. break;
  429. }
  430. case CARBON_KIND(SemIR::CustomLayoutType inst): {
  431. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  432. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  433. }
  434. break;
  435. }
  436. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  437. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  438. break;
  439. }
  440. case CARBON_KIND(SemIR::PartialType inst): {
  441. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  442. break;
  443. }
  444. case CARBON_KIND(SemIR::FacetType inst): {
  445. if (!RequireCompleteFacetType(*context_, loc_id_, inst, diagnose_)) {
  446. return false;
  447. }
  448. break;
  449. }
  450. default:
  451. break;
  452. }
  453. return true;
  454. }
  455. auto TypeCompleter::MakeEmptyTypeInfo() const -> SemIR::CompleteTypeInfo {
  456. return {.value_repr = {.kind = SemIR::ValueRepr::None,
  457. .type_id = GetTupleType(*context_, {})},
  458. .object_layout = SemIR::ObjectLayout::Empty()};
  459. }
  460. auto TypeCompleter::MakeDependentTypeInfo(SemIR::TypeId type_id) const
  461. -> SemIR::CompleteTypeInfo {
  462. return {
  463. .value_repr = {.kind = SemIR::ValueRepr::Dependent, .type_id = type_id},
  464. .object_layout = SemIR::ObjectLayout()};
  465. }
  466. auto TypeCompleter::MakeCopyValueRepr(
  467. SemIR::TypeId rep_id, SemIR::ValueRepr::AggregateKind aggregate_kind) const
  468. -> SemIR::ValueRepr {
  469. return {.kind = SemIR::ValueRepr::Copy,
  470. .aggregate_kind = aggregate_kind,
  471. .type_id = rep_id};
  472. }
  473. auto TypeCompleter::MakePointerValueRepr(
  474. SemIR::TypeId pointee_id,
  475. SemIR::ValueRepr::AggregateKind aggregate_kind) const -> SemIR::ValueRepr {
  476. // TODO: Should we add `const` qualification to `pointee_id`?
  477. return {.kind = SemIR::ValueRepr::Pointer,
  478. .aggregate_kind = aggregate_kind,
  479. .type_id = GetPointerType(
  480. *context_, context_->types().GetTypeInstId(pointee_id))};
  481. }
  482. auto TypeCompleter::GetNestedInfo(SemIR::TypeId nested_type_id) const
  483. -> SemIR::CompleteTypeInfo {
  484. CARBON_CHECK(context_->types().IsComplete(nested_type_id),
  485. "Nested type should already be complete");
  486. auto info = context_->types().GetCompleteTypeInfo(nested_type_id);
  487. CARBON_CHECK(info.value_repr.kind != SemIR::ValueRepr::Unknown,
  488. "Complete type should have a value representation");
  489. return info;
  490. }
  491. auto TypeCompleter::BuildStructOrTupleValueRepr(size_t num_elements,
  492. SemIR::TypeId elementwise_rep,
  493. bool same_as_object_rep) const
  494. -> SemIR::ValueRepr {
  495. SemIR::ValueRepr::AggregateKind aggregate_kind =
  496. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  497. : SemIR::ValueRepr::ValueAggregate;
  498. if (num_elements == 1) {
  499. // The value representation for a struct or tuple with a single element
  500. // is a struct or tuple containing the value representation of the
  501. // element.
  502. // TODO: Consider doing the same whenever `elementwise_rep` is
  503. // sufficiently small.
  504. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  505. }
  506. // For a struct or tuple with multiple fields, we use a pointer
  507. // to the elementwise value representation.
  508. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  509. }
  510. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  511. SemIR::StructType struct_type) const
  512. -> SemIR::CompleteTypeInfo {
  513. auto fields = context_->struct_type_fields().Get(struct_type.fields_id);
  514. if (fields.empty()) {
  515. return MakeEmptyTypeInfo();
  516. }
  517. // Find the value representation for each field, and construct a struct
  518. // of value representations.
  519. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  520. value_rep_fields.reserve(fields.size());
  521. bool same_as_object_rep = true;
  522. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  523. SemIR::ObjectLayout layout = SemIR::ObjectLayout::Empty();
  524. for (auto field : fields) {
  525. auto field_type_id =
  526. context_->types().GetTypeIdForTypeInstId(field.type_inst_id);
  527. auto field_info = GetNestedInfo(field_type_id);
  528. if (!field_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  529. field_type_id)) {
  530. same_as_object_rep = false;
  531. field.type_inst_id =
  532. context_->types().GetTypeInstId(field_info.value_repr.type_id);
  533. }
  534. value_rep_fields.push_back(field);
  535. // Take the first non-None abstract_class_id, if any.
  536. if (field_info.abstract_class_id.has_value() &&
  537. !abstract_class_id.has_value()) {
  538. abstract_class_id = field_info.abstract_class_id;
  539. }
  540. // Accumulate layout.
  541. layout.TryAppendField(field_info.object_layout);
  542. }
  543. auto value_rep =
  544. same_as_object_rep
  545. ? type_id
  546. : GetStructType(
  547. *context_,
  548. context_->struct_type_fields().AddCanonical(value_rep_fields));
  549. return {.value_repr = BuildStructOrTupleValueRepr(fields.size(), value_rep,
  550. same_as_object_rep),
  551. .object_layout = layout,
  552. .abstract_class_id = abstract_class_id};
  553. }
  554. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  555. SemIR::TupleType tuple_type) const
  556. -> SemIR::CompleteTypeInfo {
  557. // TODO: Share more code with structs.
  558. auto elements = context_->inst_blocks().Get(tuple_type.type_elements_id);
  559. if (elements.empty()) {
  560. return MakeEmptyTypeInfo();
  561. }
  562. // Find the value representation for each element, and construct a tuple
  563. // of value representations.
  564. llvm::SmallVector<SemIR::InstId> value_rep_elements;
  565. value_rep_elements.reserve(elements.size());
  566. bool same_as_object_rep = true;
  567. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  568. SemIR::ObjectLayout layout = SemIR::ObjectLayout::Empty();
  569. for (auto element_type_id : context_->types().GetBlockAsTypeIds(elements)) {
  570. auto element_info = GetNestedInfo(element_type_id);
  571. if (!element_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  572. element_type_id)) {
  573. same_as_object_rep = false;
  574. }
  575. value_rep_elements.push_back(
  576. context_->types().GetTypeInstId(element_info.value_repr.type_id));
  577. // Take the first non-None abstract_class_id, if any.
  578. if (element_info.abstract_class_id.has_value() &&
  579. !abstract_class_id.has_value()) {
  580. abstract_class_id = element_info.abstract_class_id;
  581. }
  582. // Accumulate layout.
  583. layout.TryAppendField(element_info.object_layout);
  584. }
  585. auto value_rep = same_as_object_rep
  586. ? type_id
  587. : GetTupleType(*context_, value_rep_elements);
  588. return {.value_repr = BuildStructOrTupleValueRepr(elements.size(), value_rep,
  589. same_as_object_rep),
  590. .object_layout = layout,
  591. .abstract_class_id = abstract_class_id};
  592. }
  593. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  594. SemIR::ArrayType array_type) const
  595. -> SemIR::CompleteTypeInfo {
  596. // For arrays, it's convenient to always use a pointer representation,
  597. // even when the array has zero or one element, in order to support
  598. // indexing.
  599. auto element_type_id =
  600. context_->types().GetTypeIdForTypeInstId(array_type.element_type_inst_id);
  601. auto element_info = GetNestedInfo(element_type_id);
  602. SemIR::ObjectLayout layout;
  603. if (element_info.object_layout.has_value()) {
  604. if (auto bound = context_->sem_ir().GetZExtIntValue(array_type.bound_id)) {
  605. layout =
  606. SemIR::ObjectLayout::ForArray(element_info.object_layout, *bound);
  607. }
  608. }
  609. return {.value_repr =
  610. MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate),
  611. .object_layout = layout};
  612. }
  613. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  614. SemIR::BoolType /*inst*/) const
  615. -> SemIR::CompleteTypeInfo {
  616. // TODO: Decide whether to use a size of `1` here, like `Core.Int(1)`. One
  617. // concern is that {.a: bool, .b: bool} would be laid out with the bools at
  618. // offsets 0 and 8, which on big-endian systems would imply the MSB stores the
  619. // value not the LSB. Consider right-aligning fields on big-endian systems
  620. // instead (except when bit-packing, by whatever means we support that).
  621. return {.value_repr = MakeCopyValueRepr(type_id),
  622. .object_layout = {.size = SemIR::ObjectSize::Bytes(1),
  623. .alignment = SemIR::ObjectSize::Bytes(1)}};
  624. }
  625. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  626. SemIR::PointerType /*inst*/) const
  627. -> SemIR::CompleteTypeInfo {
  628. return {.value_repr = MakeCopyValueRepr(type_id),
  629. .object_layout = context_->sem_ir().GetPointerLayout()};
  630. }
  631. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  632. SemIR::IntType inst) const
  633. -> SemIR::CompleteTypeInfo {
  634. SemIR::ObjectLayout layout;
  635. if (auto bit_width = context_->sem_ir().GetZExtIntValue(inst.bit_width_id)) {
  636. auto size = SemIR::ObjectSize::Bits(*bit_width);
  637. // TODO: The upper bound for alignment here should be target-specific.
  638. auto align = SemIR::ObjectSize::Bits(
  639. std::clamp<int64_t>(llvm::PowerOf2Ceil(*bit_width), 8, 256));
  640. layout = {.size = size, .alignment = align};
  641. }
  642. return {.value_repr = MakeCopyValueRepr(type_id), .object_layout = layout};
  643. }
  644. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  645. SemIR::FloatType inst) const
  646. -> SemIR::CompleteTypeInfo {
  647. SemIR::ObjectLayout layout;
  648. if (auto bit_width = context_->sem_ir().GetZExtIntValue(inst.bit_width_id)) {
  649. auto size = SemIR::ObjectSize::Bits(*bit_width);
  650. // TODO: Pick a suitable alignment here. For some targets, we may want to
  651. // use 32-bit alignment for f64 (and f80). For now we round up to a power
  652. // of 2.
  653. auto align = SemIR::ObjectSize::Bits(llvm::PowerOf2Ceil(*bit_width));
  654. layout = {.size = size, .alignment = align};
  655. }
  656. return {.value_repr = MakeCopyValueRepr(type_id), .object_layout = layout};
  657. }
  658. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  659. SemIR::ClassType inst) const
  660. -> SemIR::CompleteTypeInfo {
  661. auto& class_info = context_->classes().Get(inst.class_id);
  662. auto abstract_class_id =
  663. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract
  664. ? inst.class_id
  665. : SemIR::ClassId::None;
  666. // The object and value representation of an adapter are the object and value
  667. // representation of its adapted type.
  668. if (auto adapted_type_id =
  669. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  670. adapted_type_id.has_value()) {
  671. auto info = GetNestedInfo(adapted_type_id);
  672. info.abstract_class_id = abstract_class_id;
  673. return info;
  674. }
  675. // Otherwise, the value representation for a class is a pointer to the
  676. // object representation, which was computed when the class was defined.
  677. auto object_repr_type_id =
  678. class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id);
  679. // TODO: Support customized value representations for classes.
  680. // TODO: Pick a better value representation when possible.
  681. return {.value_repr = MakePointerValueRepr(object_repr_type_id,
  682. SemIR::ValueRepr::ObjectAggregate),
  683. .object_layout = GetNestedInfo(object_repr_type_id).object_layout,
  684. .abstract_class_id = abstract_class_id};
  685. }
  686. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  687. SemIR::ConstType inst) const
  688. -> SemIR::CompleteTypeInfo {
  689. // The object and value representation of `const T` are the same as those of
  690. // `T`. Objects are not modifiable through their value representations.
  691. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  692. }
  693. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  694. SemIR::CustomLayoutType inst) const
  695. -> SemIR::CompleteTypeInfo {
  696. // TODO: Should we support other value representations for custom layout
  697. // types?
  698. const auto& layout = context_->custom_layouts().Get(inst.layout_id);
  699. return {.value_repr = MakePointerValueRepr(type_id),
  700. .object_layout = {
  701. .size = layout[SemIR::CustomLayoutId::SizeIndex],
  702. .alignment = layout[SemIR::CustomLayoutId::AlignIndex]}};
  703. }
  704. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  705. SemIR::MaybeUnformedType inst) const
  706. -> SemIR::CompleteTypeInfo {
  707. // `MaybeUnformed(T)` has the same value representation as `T` if that value
  708. // representation preserves all the bytes of the value, including any padding
  709. // bits. Otherwise we need to use a different representation.
  710. auto inner_type_id = context_->types().GetTypeIdForTypeInstId(inst.inner_id);
  711. auto nested = GetNestedInfo(inner_type_id);
  712. if (nested.value_repr.kind == SemIR::ValueRepr::Custom) {
  713. nested.value_repr = MakePointerValueRepr(type_id);
  714. } else if (nested.value_repr.kind == SemIR::ValueRepr::Copy) {
  715. auto type_inst = context_->types().GetAsInst(nested.value_repr.type_id);
  716. // TODO: Should ValueRepr::IsCopyOfObjectRepr return false for `bool`?
  717. if (!nested.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  718. inner_type_id) ||
  719. type_inst.Is<SemIR::BoolType>()) {
  720. nested.value_repr = MakePointerValueRepr(type_id);
  721. }
  722. // TODO: Handle any other types that we treat as having discarded padding
  723. // bits. For now there are no such types, as all class types and all structs
  724. // and tuples with more than one element are passed indirectly.
  725. }
  726. return nested;
  727. }
  728. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  729. SemIR::PartialType inst) const
  730. -> SemIR::CompleteTypeInfo {
  731. // The value representation of `partial T` is the same as that of `T`.
  732. // Objects are not modifiable through their value representations. However,
  733. // `partial T` is never abstract.
  734. auto inner_type_id = context_->types().GetTypeIdForTypeInstId(inst.inner_id);
  735. auto info = GetNestedInfo(inner_type_id);
  736. info.abstract_class_id = SemIR::ClassId::None;
  737. return info;
  738. }
  739. auto TypeCompleter::BuildInfoForInst(
  740. SemIR::TypeId /*type_id*/, SemIR::ImplWitnessAssociatedConstant inst) const
  741. -> SemIR::CompleteTypeInfo {
  742. return GetNestedInfo(inst.type_id);
  743. }
  744. // Builds and returns the value representation for the given type. All nested
  745. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  746. auto TypeCompleter::BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  747. -> SemIR::CompleteTypeInfo {
  748. // Use overload resolution to select the implementation, producing compile
  749. // errors when BuildInfoForInst isn't defined for a given instruction.
  750. CARBON_KIND_SWITCH(inst) {
  751. #define CARBON_SEM_IR_INST_KIND(Name) \
  752. case CARBON_KIND(SemIR::Name typed_inst): { \
  753. return BuildInfoForInst(type_id, typed_inst); \
  754. }
  755. #include "toolchain/sem_ir/inst_kind.def"
  756. }
  757. }
  758. auto TryToCompleteType(Context& context, SemIR::TypeId type_id,
  759. SemIR::LocId loc_id, bool diagnose) -> bool {
  760. return TypeCompleter(&context, loc_id, diagnose).Complete(type_id);
  761. }
  762. auto CompleteTypeOrCheckFail(Context& context, SemIR::TypeId type_id) -> void {
  763. bool complete =
  764. TypeCompleter(&context, SemIR::LocId::None, false).Complete(type_id);
  765. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  766. context.types().GetAsInst(type_id));
  767. }
  768. auto RequireCompleteType(Context& context, SemIR::TypeId type_id,
  769. SemIR::LocId loc_id,
  770. DiagnosticContextFn diagnostic_context) -> bool {
  771. CARBON_CHECK(diagnostic_context);
  772. Diagnostics::ContextScope scope(&context.emitter(), diagnostic_context);
  773. if (!TypeCompleter(&context, loc_id, true).Complete(type_id)) {
  774. return false;
  775. }
  776. // For a symbolic type, create an instruction to require the corresponding
  777. // specific type to be complete.
  778. if (type_id.is_symbolic()) {
  779. // TODO: Deduplicate these.
  780. AddInstInNoBlock(
  781. context, loc_id,
  782. SemIR::RequireCompleteType{
  783. .type_id =
  784. GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  785. .complete_type_inst_id = context.types().GetTypeInstId(type_id)});
  786. }
  787. return true;
  788. }
  789. auto TryIsConcreteType(Context& context, SemIR::TypeId type_id,
  790. SemIR::LocId loc_id) -> bool {
  791. if (!TryToCompleteType(context, type_id, loc_id)) {
  792. return false;
  793. }
  794. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  795. CARBON_CHECK(complete_info.value_repr.type_id.has_value(),
  796. "TryIsConcreteType called for an incomplete type. Call "
  797. "TryToCompleteType first.");
  798. return !complete_info.abstract_class_id.has_value();
  799. }
  800. auto RequireConcreteType(Context& context, SemIR::TypeId type_id,
  801. SemIR::LocId loc_id,
  802. DiagnosticContextFn complete_type_diagnostic_context,
  803. DiagnosticContextFn concrete_type_diagnostic_context)
  804. -> bool {
  805. if (!RequireCompleteType(context, type_id, loc_id,
  806. complete_type_diagnostic_context)) {
  807. return false;
  808. }
  809. CARBON_CHECK(concrete_type_diagnostic_context);
  810. Diagnostics::ContextScope scope(&context.emitter(),
  811. concrete_type_diagnostic_context);
  812. // TODO: For symbolic types, should add an implicit constraint that they are
  813. // not abstract.
  814. const auto& complete_info = context.types().GetCompleteTypeInfo(type_id);
  815. CARBON_CHECK(complete_info.value_repr.type_id.has_value(),
  816. "RequireConcreteType called for an incomplete type. Call "
  817. "RequireCompleteType first.");
  818. if (!complete_info.IsAbstract()) {
  819. return true;
  820. }
  821. bool direct_use = false;
  822. if (auto inst = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  823. if (inst->class_id == complete_info.abstract_class_id) {
  824. direct_use = true;
  825. }
  826. }
  827. DiagnoseAbstractClass(context, complete_info.abstract_class_id, direct_use);
  828. return false;
  829. }
  830. // Given a canonical facet value, or a type value, return a facet value.
  831. static auto GetSelfFacetValue(Context& context, SemIR::ConstantId self_const_id)
  832. -> SemIR::ConstantId {
  833. if (self_const_id == SemIR::ErrorInst::ConstantId) {
  834. return SemIR::ErrorInst::ConstantId;
  835. }
  836. auto self_inst_id = context.constant_values().GetInstId(self_const_id);
  837. auto type_id = context.insts().Get(self_inst_id).type_id();
  838. CARBON_CHECK(context.types().IsFacetType(type_id));
  839. if (context.types().Is<SemIR::FacetType>(type_id)) {
  840. return self_const_id;
  841. }
  842. return GetConstantFacetValueForType(
  843. context, context.types().GetAsTypeInstId(self_inst_id));
  844. }
  845. static auto IdentifyFacetType(Context& context, SemIR::LocId loc_id,
  846. SemIR::ConstantId self_const_id,
  847. const SemIR::FacetType& facet_type,
  848. bool allow_partially_identified, bool diagnose)
  849. -> SemIR::IdentifiedFacetTypeId {
  850. // While partially identified facet types end up in the store of
  851. // IdentifiedFacetTypes, we don't try to construct a key to look for them
  852. // here, so we will only early-out here for fully identified facet types. To
  853. // construct the key for a partially identified facet type we need to know the
  854. // set of required impls that it contains, which requires us to do most of the
  855. // work of identifying the facet type (though we could skip the mapping of
  856. // constant values into specifics).
  857. auto key =
  858. SemIR::IdentifiedFacetTypeKey{.facet_type_id = facet_type.facet_type_id,
  859. .self_const_id = self_const_id};
  860. if (auto identified_id = context.identified_facet_types().Lookup(key);
  861. identified_id.has_value()) {
  862. return identified_id;
  863. }
  864. struct SelfImplsFacetType {
  865. bool extend;
  866. SemIR::ConstantId self;
  867. SemIR::FacetTypeId facet_type;
  868. };
  869. // Work queue.
  870. llvm::SmallVector<SelfImplsFacetType> work = {
  871. {true, self_const_id, facet_type.facet_type_id}};
  872. // Outputs for the IdentifiedFacetType.
  873. bool partially_identified = false;
  874. llvm::SmallVector<SemIR::IdentifiedFacetType::RequiredImpl> extends;
  875. llvm::SmallVector<SemIR::IdentifiedFacetType::RequiredImpl> impls;
  876. while (!work.empty()) {
  877. SelfImplsFacetType next_impls = work.pop_back_val();
  878. bool facet_type_extends = next_impls.extend;
  879. auto self_const_id = GetCanonicalFacetOrTypeValue(context, next_impls.self);
  880. const auto& facet_type_info =
  881. context.facet_types().Get(next_impls.facet_type);
  882. auto self_and_interface = [&](SemIR::SpecificInterface interface)
  883. -> SemIR::IdentifiedFacetType::RequiredImpl {
  884. return {self_const_id, interface};
  885. };
  886. auto type_and_interface =
  887. [&](const SemIR::FacetTypeInfo::TypeImplsInterface& impls)
  888. -> SemIR::IdentifiedFacetType::RequiredImpl {
  889. return {context.constant_values().Get(impls.self_type),
  890. impls.specific_interface};
  891. };
  892. if (facet_type_extends) {
  893. llvm::append_range(extends,
  894. llvm::map_range(facet_type_info.extend_constraints,
  895. self_and_interface));
  896. } else {
  897. llvm::append_range(impls,
  898. llvm::map_range(facet_type_info.extend_constraints,
  899. self_and_interface));
  900. }
  901. llvm::append_range(impls,
  902. llvm::map_range(facet_type_info.self_impls_constraints,
  903. self_and_interface));
  904. llvm::append_range(impls,
  905. llvm::map_range(facet_type_info.type_impls_interfaces,
  906. type_and_interface));
  907. if (facet_type_info.extend_named_constraints.empty() &&
  908. facet_type_info.self_impls_named_constraints.empty() &&
  909. facet_type_info.type_impls_named_constraints.empty()) {
  910. continue;
  911. }
  912. // The self may have type TypeType. But the `Self` in a generic require decl
  913. // has type FacetType, so we need something similar to replace it in the
  914. // specific.
  915. auto self_facet = GetSelfFacetValue(context, self_const_id);
  916. for (auto extends : facet_type_info.extend_named_constraints) {
  917. const auto& constraint =
  918. context.named_constraints().Get(extends.named_constraint_id);
  919. llvm::ArrayRef<SemIR::RequireImplsId> require_impls_ids;
  920. if (constraint.is_complete()) {
  921. require_impls_ids = context.require_impls_blocks().Get(
  922. constraint.require_impls_block_id);
  923. } else if (allow_partially_identified) {
  924. partially_identified = true;
  925. if (constraint.is_being_defined()) {
  926. require_impls_ids = context.require_impls_stack().PeekForScope(
  927. extends.named_constraint_id);
  928. } else {
  929. continue;
  930. }
  931. } else {
  932. if (diagnose) {
  933. DiagnoseIncompleteNamedConstraint(context,
  934. extends.named_constraint_id);
  935. }
  936. return SemIR::IdentifiedFacetTypeId::None;
  937. }
  938. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  939. context, loc_id, constraint.generic_id,
  940. constraint.generic_with_self_id, extends.specific_id, self_facet);
  941. if (SpecificHasError(context, constraint_with_self_specific_id)) {
  942. return SemIR::IdentifiedFacetTypeId::None;
  943. }
  944. for (auto require_impls_id : llvm::reverse(require_impls_ids)) {
  945. const auto& require = context.require_impls().Get(require_impls_id);
  946. // Each require is in its own generic, with no additional bindings and
  947. // no definition, so that they can have their specifics independently
  948. // instantiated.
  949. auto require_specific_id = CopySpecificToGeneric(
  950. context, SemIR::LocId(require.decl_id),
  951. constraint_with_self_specific_id, require.generic_id);
  952. auto require_self = GetConstantValueInSpecific(
  953. context.sem_ir(), require_specific_id, require.self_id);
  954. auto require_facet_type = GetConstantValueInSpecific(
  955. context.sem_ir(), require_specific_id, require.facet_type_inst_id);
  956. if (require_self == SemIR::ErrorInst::ConstantId ||
  957. require_facet_type == SemIR::ErrorInst::ConstantId) {
  958. return SemIR::IdentifiedFacetTypeId::None;
  959. }
  960. auto facet_type_id =
  961. context.constant_values()
  962. .GetInstAs<SemIR::FacetType>(require_facet_type)
  963. .facet_type_id;
  964. bool extend = facet_type_extends && require.extend_self;
  965. work.push_back({extend, require_self, facet_type_id});
  966. }
  967. }
  968. for (auto impls : facet_type_info.self_impls_named_constraints) {
  969. const auto& constraint =
  970. context.named_constraints().Get(impls.named_constraint_id);
  971. llvm::ArrayRef<SemIR::RequireImplsId> require_impls_ids;
  972. if (constraint.is_complete()) {
  973. require_impls_ids = context.require_impls_blocks().Get(
  974. constraint.require_impls_block_id);
  975. } else if (allow_partially_identified) {
  976. partially_identified = true;
  977. if (constraint.is_being_defined()) {
  978. require_impls_ids = context.require_impls_stack().PeekForScope(
  979. impls.named_constraint_id);
  980. } else {
  981. continue;
  982. }
  983. } else {
  984. if (diagnose) {
  985. DiagnoseIncompleteNamedConstraint(context, impls.named_constraint_id);
  986. }
  987. return SemIR::IdentifiedFacetTypeId::None;
  988. }
  989. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  990. context, loc_id, constraint.generic_id,
  991. constraint.generic_with_self_id, impls.specific_id, self_facet);
  992. if (SpecificHasError(context, constraint_with_self_specific_id)) {
  993. return SemIR::IdentifiedFacetTypeId::None;
  994. }
  995. for (auto require_impls_id : llvm::reverse(require_impls_ids)) {
  996. const auto& require = context.require_impls().Get(require_impls_id);
  997. // Each require is in its own generic, with no additional bindings and
  998. // no definition, so that they can have their specifics independently
  999. // instantiated.
  1000. auto require_specific_id = CopySpecificToGeneric(
  1001. context, SemIR::LocId(require.decl_id),
  1002. constraint_with_self_specific_id, require.generic_id);
  1003. auto require_self = GetConstantValueInSpecific(
  1004. context.sem_ir(), require_specific_id, require.self_id);
  1005. auto require_facet_type = GetConstantValueInSpecific(
  1006. context.sem_ir(), require_specific_id, require.facet_type_inst_id);
  1007. if (require_self == SemIR::ErrorInst::ConstantId ||
  1008. require_facet_type == SemIR::ErrorInst::ConstantId) {
  1009. return SemIR::IdentifiedFacetTypeId::None;
  1010. }
  1011. auto facet_type_id =
  1012. context.constant_values()
  1013. .GetInstAs<SemIR::FacetType>(require_facet_type)
  1014. .facet_type_id;
  1015. work.push_back({false, require_self, facet_type_id});
  1016. }
  1017. }
  1018. for (const auto& type_impls :
  1019. facet_type_info.type_impls_named_constraints) {
  1020. auto [self_type_inst_id, impls] = type_impls;
  1021. const auto& constraint =
  1022. context.named_constraints().Get(impls.named_constraint_id);
  1023. llvm::ArrayRef<SemIR::RequireImplsId> require_impls_ids;
  1024. if (constraint.is_complete()) {
  1025. require_impls_ids = context.require_impls_blocks().Get(
  1026. constraint.require_impls_block_id);
  1027. } else if (allow_partially_identified) {
  1028. partially_identified = true;
  1029. if (constraint.is_being_defined()) {
  1030. require_impls_ids = context.require_impls_stack().PeekForScope(
  1031. impls.named_constraint_id);
  1032. } else {
  1033. continue;
  1034. }
  1035. } else {
  1036. if (diagnose) {
  1037. DiagnoseIncompleteNamedConstraint(context, impls.named_constraint_id);
  1038. }
  1039. return SemIR::IdentifiedFacetTypeId::None;
  1040. }
  1041. auto self_type_facet = GetSelfFacetValue(
  1042. context, context.constant_values().Get(self_type_inst_id));
  1043. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  1044. context, loc_id, constraint.generic_id,
  1045. constraint.generic_with_self_id, impls.specific_id, self_type_facet);
  1046. if (SpecificHasError(context, constraint_with_self_specific_id)) {
  1047. return SemIR::IdentifiedFacetTypeId::None;
  1048. }
  1049. for (auto require_impls_id : llvm::reverse(require_impls_ids)) {
  1050. const auto& require = context.require_impls().Get(require_impls_id);
  1051. // Each require is in its own generic, with no additional bindings and
  1052. // no definition, so that they can have their specifics independently
  1053. // instantiated.
  1054. auto require_specific_id = CopySpecificToGeneric(
  1055. context, SemIR::LocId(require.decl_id),
  1056. constraint_with_self_specific_id, require.generic_id);
  1057. auto require_self = GetConstantValueInSpecific(
  1058. context.sem_ir(), require_specific_id, require.self_id);
  1059. auto require_facet_type = GetConstantValueInSpecific(
  1060. context.sem_ir(), require_specific_id, require.facet_type_inst_id);
  1061. if (require_self == SemIR::ErrorInst::ConstantId ||
  1062. require_facet_type == SemIR::ErrorInst::ConstantId) {
  1063. return SemIR::IdentifiedFacetTypeId::None;
  1064. }
  1065. auto facet_type_id =
  1066. context.constant_values()
  1067. .GetInstAs<SemIR::FacetType>(require_facet_type)
  1068. .facet_type_id;
  1069. work.push_back({false, require_self, facet_type_id});
  1070. }
  1071. }
  1072. }
  1073. // TODO: Process other kinds of requirements.
  1074. return context.identified_facet_types().Add(
  1075. {key, partially_identified, extends, impls});
  1076. }
  1077. auto TryToIdentifyFacetType(Context& context, SemIR::LocId loc_id,
  1078. SemIR::ConstantId self_const_id,
  1079. const SemIR::FacetType& facet_type,
  1080. bool allow_partially_identified)
  1081. -> SemIR::IdentifiedFacetTypeId {
  1082. return IdentifyFacetType(context, loc_id, self_const_id, facet_type,
  1083. allow_partially_identified, /*diagnose=*/false);
  1084. }
  1085. auto RequireIdentifiedFacetType(Context& context, SemIR::LocId loc_id,
  1086. SemIR::ConstantId self_const_id,
  1087. const SemIR::FacetType& facet_type,
  1088. DiagnosticContextFn diagnostic_context,
  1089. bool diagnose) -> SemIR::IdentifiedFacetTypeId {
  1090. CARBON_CHECK(diagnostic_context);
  1091. Diagnostics::ContextScope scope(&context.emitter(), diagnostic_context);
  1092. return IdentifyFacetType(context, loc_id, self_const_id, facet_type,
  1093. /*allow_partially_identified=*/false, diagnose);
  1094. }
  1095. } // namespace Carbon::Check