type_completion.cpp 51 KB

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