type_completion.cpp 51 KB

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