type_completion.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/type_completion.h"
  5. #include "common/concepts.h"
  6. #include "llvm/ADT/SmallVector.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/check/cpp/import.h"
  9. #include "toolchain/check/facet_type.h"
  10. #include "toolchain/check/generic.h"
  11. #include "toolchain/check/inst.h"
  12. #include "toolchain/check/literal.h"
  13. #include "toolchain/check/type.h"
  14. #include "toolchain/diagnostics/emitter.h"
  15. #include "toolchain/diagnostics/format_providers.h"
  16. #include "toolchain/sem_ir/constant.h"
  17. #include "toolchain/sem_ir/facet_type_info.h"
  18. #include "toolchain/sem_ir/generic.h"
  19. #include "toolchain/sem_ir/ids.h"
  20. #include "toolchain/sem_ir/specific_interface.h"
  21. #include "toolchain/sem_ir/specific_named_constraint.h"
  22. #include "toolchain/sem_ir/type_info.h"
  23. #include "toolchain/sem_ir/typed_insts.h"
  24. namespace Carbon::Check {
  25. auto DiagnoseIncompleteClass(Context& context, SemIR::ClassId class_id)
  26. -> void {
  27. // The caller must provide context for any diagnostics in type completion.
  28. context.emitter().CheckHasContext();
  29. const auto& class_info = context.classes().Get(class_id);
  30. CARBON_CHECK(!class_info.is_complete(), "Class is not incomplete");
  31. if (class_info.has_definition_started()) {
  32. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Error,
  33. "class is incomplete within its definition");
  34. context.emitter().Emit(class_info.definition_id,
  35. ClassIncompleteWithinDefinition);
  36. } else {
  37. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Error,
  38. "class was forward declared here");
  39. context.emitter().Emit(class_info.latest_decl_id(),
  40. ClassForwardDeclaredHere);
  41. }
  42. }
  43. auto DiagnoseIncompleteInterface(Context& context,
  44. SemIR::InterfaceId interface_id) -> void {
  45. // The caller must provide context for any diagnostics in type completion.
  46. context.emitter().CheckHasContext();
  47. const auto& interface_info = context.interfaces().Get(interface_id);
  48. CARBON_CHECK(!interface_info.is_complete(), "Interface is not incomplete");
  49. if (interface_info.is_being_defined()) {
  50. CARBON_DIAGNOSTIC(InterfaceIncompleteWithinDefinition, Error,
  51. "interface is currently being defined");
  52. context.emitter().Emit(interface_info.definition_id,
  53. InterfaceIncompleteWithinDefinition);
  54. } else {
  55. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Error,
  56. "interface was forward declared here");
  57. context.emitter().Emit(interface_info.latest_decl_id(),
  58. InterfaceForwardDeclaredHere);
  59. }
  60. }
  61. auto DiagnoseAbstractClass(Context& context, SemIR::ClassId class_id,
  62. bool direct_use) -> void {
  63. // The caller must provide context for any diagnostics in type completion.
  64. context.emitter().CheckHasContext();
  65. const auto& class_info = context.classes().Get(class_id);
  66. CARBON_CHECK(
  67. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  68. "Class is not abstract");
  69. CARBON_DIAGNOSTIC(
  70. ClassAbstractHere, Error,
  71. "{0:=0:uses class that|=1:class} was declared abstract here",
  72. Diagnostics::IntAsSelect);
  73. context.emitter().Emit(class_info.definition_id, ClassAbstractHere,
  74. static_cast<int>(direct_use));
  75. }
  76. static auto DiagnoseIncompleteNamedConstraint(
  77. Context& context, SemIR::NamedConstraintId named_constraint_id) -> void {
  78. // The caller must provide context for any diagnostics in type completion.
  79. context.emitter().CheckHasContext();
  80. const auto& constraint = context.named_constraints().Get(named_constraint_id);
  81. CARBON_CHECK(!constraint.is_complete(), "Named constraint is not incomplete");
  82. if (constraint.is_being_defined()) {
  83. CARBON_DIAGNOSTIC(NamedConstraintIncompleteWithinDefinition, Error,
  84. "constraint is currently being defined");
  85. context.emitter().Emit(constraint.definition_id,
  86. NamedConstraintIncompleteWithinDefinition);
  87. } else {
  88. CARBON_DIAGNOSTIC(NamedConstraintForwardDeclaredHere, Error,
  89. "constraint was forward declared here");
  90. context.emitter().Emit(constraint.latest_decl_id(),
  91. NamedConstraintForwardDeclaredHere);
  92. }
  93. }
  94. // TODO: Have the resolved specific know whether any instructions in the
  95. // declaration or definition contain an ErrorInst, instead of having to do a
  96. // linear scan here.
  97. static auto SpecificContainsError(Context& context,
  98. SemIR::SpecificId specific_id) -> bool {
  99. if (!specific_id.has_value()) {
  100. return false;
  101. }
  102. const auto& specific = context.specifics().Get(specific_id);
  103. auto block_ids = {specific.decl_block_id, specific.definition_block_id};
  104. for (auto block_id : block_ids) {
  105. if (block_id.has_value()) {
  106. for (auto inst_id : context.inst_blocks().Get(block_id)) {
  107. if (context.constant_values().Get(inst_id) ==
  108. SemIR::ErrorInst::ConstantId) {
  109. return true;
  110. }
  111. }
  112. }
  113. }
  114. return false;
  115. }
  116. static auto RequireCompleteFacetType(Context& context, SemIR::LocId loc_id,
  117. const SemIR::FacetType& facet_type,
  118. bool diagnose) -> bool {
  119. const auto& facet_type_info =
  120. context.facet_types().Get(facet_type.facet_type_id);
  121. for (auto extends : facet_type_info.extend_constraints) {
  122. auto interface_id = extends.interface_id;
  123. const auto& interface = context.interfaces().Get(interface_id);
  124. if (!interface.is_complete()) {
  125. if (diagnose) {
  126. DiagnoseIncompleteInterface(context, interface_id);
  127. }
  128. return false;
  129. }
  130. if (interface.generic_id.has_value()) {
  131. ResolveSpecificDefinition(context, loc_id, extends.specific_id);
  132. if (SpecificContainsError(context, extends.specific_id)) {
  133. return false;
  134. }
  135. }
  136. auto interface_with_self_self_specific_args = context.inst_blocks().Get(
  137. context.specifics().GetArgsOrEmpty(context.generics().GetSelfSpecific(
  138. interface.generic_with_self_id)));
  139. auto self_facet = interface_with_self_self_specific_args.back();
  140. auto interface_with_self_specific_id = MakeSpecificWithInnerSelf(
  141. context, loc_id, interface.generic_id, interface.generic_with_self_id,
  142. extends.specific_id, context.constant_values().Get(self_facet));
  143. if (SpecificContainsError(context, interface_with_self_specific_id)) {
  144. return false;
  145. }
  146. }
  147. for (auto extends : facet_type_info.extend_named_constraints) {
  148. auto named_constraint_id = extends.named_constraint_id;
  149. const auto& constraint =
  150. context.named_constraints().Get(named_constraint_id);
  151. if (!constraint.is_complete()) {
  152. if (diagnose) {
  153. DiagnoseIncompleteNamedConstraint(context, named_constraint_id);
  154. }
  155. return false;
  156. }
  157. if (constraint.generic_id.has_value()) {
  158. ResolveSpecificDefinition(context, loc_id, extends.specific_id);
  159. if (SpecificContainsError(context, extends.specific_id)) {
  160. return false;
  161. }
  162. }
  163. auto constraint_with_self_self_specific_args = context.inst_blocks().Get(
  164. context.specifics().GetArgsOrEmpty(context.generics().GetSelfSpecific(
  165. constraint.generic_with_self_id)));
  166. auto self_facet = constraint_with_self_self_specific_args.back();
  167. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  168. context, loc_id, constraint.generic_id, constraint.generic_with_self_id,
  169. extends.specific_id, context.constant_values().Get(self_facet));
  170. if (SpecificContainsError(context, constraint_with_self_specific_id)) {
  171. return false;
  172. }
  173. }
  174. return true;
  175. }
  176. namespace {
  177. // Worklist-based type completion mechanism.
  178. //
  179. // When attempting to complete a type, we may find other types that also need to
  180. // be completed: types nested within that type, and the value representation of
  181. // the type. In order to complete a type without recursing arbitrarily deeply,
  182. // we use a worklist of tasks:
  183. //
  184. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  185. // nested within a type to the work list.
  186. // - A `BuildInfo` step computes the `CompleteTypeInfo` for a type, once all of
  187. // its nested types are complete, and marks the type as complete.
  188. class TypeCompleter {
  189. public:
  190. // `context` mut not be null.
  191. TypeCompleter(Context* context, SemIR::LocId loc_id, bool diagnose)
  192. : context_(context), loc_id_(loc_id), diagnose_(diagnose) {}
  193. // Attempts to complete the given type. Returns true if it is now complete,
  194. // false if it could not be completed.
  195. auto Complete(SemIR::TypeId type_id) -> bool;
  196. private:
  197. enum class Phase : int8_t {
  198. // The next step is to add nested types to the list of types to complete.
  199. AddNestedIncompleteTypes,
  200. // The next step is to build the `CompleteTypeInfo` for the type.
  201. BuildInfo,
  202. };
  203. struct WorkItem {
  204. SemIR::TypeId type_id;
  205. Phase phase;
  206. };
  207. // Adds `type_id` to the work list, if it's not already complete.
  208. auto Push(SemIR::TypeId type_id) -> void;
  209. // Runs the next step.
  210. auto ProcessStep() -> bool;
  211. // Adds any types nested within `type_inst` that need to be complete for
  212. // `type_inst` to be complete to our work list.
  213. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool;
  214. // Makes an empty value representation, which is used for types that have no
  215. // state, such as empty structs and tuples.
  216. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr;
  217. // Makes a dependent value representation, which is used for symbolic types.
  218. auto MakeDependentValueRepr(SemIR::TypeId type_id) const -> SemIR::ValueRepr;
  219. // Makes a value representation that uses pass-by-copy, copying the given
  220. // type.
  221. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  222. SemIR::ValueRepr::AggregateKind aggregate_kind =
  223. SemIR::ValueRepr::NotAggregate) const
  224. -> SemIR::ValueRepr;
  225. // Makes a value representation that uses pass-by-address with the given
  226. // pointee type.
  227. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  228. SemIR::ValueRepr::AggregateKind aggregate_kind =
  229. SemIR::ValueRepr::NotAggregate) const
  230. -> SemIR::ValueRepr;
  231. // Gets the value representation of a nested type, which should already be
  232. // complete.
  233. auto GetNestedInfo(SemIR::TypeId nested_type_id) const
  234. -> SemIR::CompleteTypeInfo;
  235. template <typename InstT>
  236. requires(InstT::Kind.template IsAnyOf<
  237. SemIR::AutoType, SemIR::BoolType, SemIR::BoundMethodType,
  238. SemIR::CharLiteralType, SemIR::ErrorInst, SemIR::FacetType,
  239. SemIR::FloatLiteralType, SemIR::FloatType, SemIR::FormType,
  240. SemIR::IntType, SemIR::IntLiteralType, SemIR::NamespaceType,
  241. SemIR::PatternType, SemIR::PointerType,
  242. SemIR::RequireSpecificDefinitionType, SemIR::SpecificFunctionType,
  243. SemIR::TypeType, SemIR::VtableType, SemIR::WitnessType>())
  244. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  245. -> SemIR::CompleteTypeInfo {
  246. return {.value_repr = MakeCopyValueRepr(type_id)};
  247. }
  248. auto BuildStructOrTupleValueRepr(size_t num_elements,
  249. SemIR::TypeId elementwise_rep,
  250. bool same_as_object_rep) const
  251. -> SemIR::ValueRepr;
  252. auto BuildInfoForInst(SemIR::TypeId type_id,
  253. SemIR::StructType struct_type) const
  254. -> SemIR::CompleteTypeInfo;
  255. auto BuildInfoForInst(SemIR::TypeId type_id,
  256. SemIR::TupleType tuple_type) const
  257. -> SemIR::CompleteTypeInfo;
  258. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::ArrayType /*inst*/) const
  259. -> SemIR::CompleteTypeInfo;
  260. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ClassType inst) const
  261. -> SemIR::CompleteTypeInfo;
  262. template <typename InstT>
  263. requires(InstT::Kind.template IsAnyOf<
  264. SemIR::AssociatedEntityType, SemIR::CppOverloadSetType,
  265. SemIR::CppTemplateNameType, SemIR::FunctionType,
  266. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  267. SemIR::GenericInterfaceType, SemIR::GenericNamedConstraintType,
  268. SemIR::InstType, SemIR::UnboundElementType, SemIR::WhereExpr>())
  269. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  270. -> SemIR::CompleteTypeInfo {
  271. // These types have no runtime operations, so we use an empty value
  272. // representation.
  273. //
  274. // TODO: There is information we could model here:
  275. // - For an interface, we could use a witness.
  276. // - For an associated entity, we could use an index into the witness.
  277. // - For an unbound element, we could use an index or offset.
  278. return {.value_repr = MakeEmptyValueRepr()};
  279. }
  280. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ConstType inst) const
  281. -> SemIR::CompleteTypeInfo;
  282. auto BuildInfoForInst(SemIR::TypeId type_id,
  283. SemIR::CustomLayoutType inst) const
  284. -> SemIR::CompleteTypeInfo;
  285. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  286. SemIR::MaybeUnformedType inst) const
  287. -> SemIR::CompleteTypeInfo;
  288. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  289. SemIR::PartialType inst) const
  290. -> SemIR::CompleteTypeInfo;
  291. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  292. SemIR::ImplWitnessAssociatedConstant 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 {.value_repr = MakeDependentValueRepr(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::MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  461. return {.kind = SemIR::ValueRepr::None,
  462. .type_id = GetTupleType(*context_, {})};
  463. }
  464. auto TypeCompleter::MakeDependentValueRepr(SemIR::TypeId type_id) const
  465. -> SemIR::ValueRepr {
  466. return {.kind = SemIR::ValueRepr::Dependent, .type_id = type_id};
  467. }
  468. auto TypeCompleter::MakeCopyValueRepr(
  469. SemIR::TypeId rep_id, SemIR::ValueRepr::AggregateKind aggregate_kind) const
  470. -> SemIR::ValueRepr {
  471. return {.kind = SemIR::ValueRepr::Copy,
  472. .aggregate_kind = aggregate_kind,
  473. .type_id = rep_id};
  474. }
  475. auto TypeCompleter::MakePointerValueRepr(
  476. SemIR::TypeId pointee_id,
  477. SemIR::ValueRepr::AggregateKind aggregate_kind) const -> SemIR::ValueRepr {
  478. // TODO: Should we add `const` qualification to `pointee_id`?
  479. return {.kind = SemIR::ValueRepr::Pointer,
  480. .aggregate_kind = aggregate_kind,
  481. .type_id = GetPointerType(
  482. *context_, context_->types().GetTypeInstId(pointee_id))};
  483. }
  484. auto TypeCompleter::GetNestedInfo(SemIR::TypeId nested_type_id) const
  485. -> SemIR::CompleteTypeInfo {
  486. CARBON_CHECK(context_->types().IsComplete(nested_type_id),
  487. "Nested type should already be complete");
  488. auto info = context_->types().GetCompleteTypeInfo(nested_type_id);
  489. CARBON_CHECK(info.value_repr.kind != SemIR::ValueRepr::Unknown,
  490. "Complete type should have a value representation");
  491. return info;
  492. }
  493. auto TypeCompleter::BuildStructOrTupleValueRepr(size_t num_elements,
  494. SemIR::TypeId elementwise_rep,
  495. bool same_as_object_rep) const
  496. -> SemIR::ValueRepr {
  497. SemIR::ValueRepr::AggregateKind aggregate_kind =
  498. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  499. : SemIR::ValueRepr::ValueAggregate;
  500. if (num_elements == 1) {
  501. // The value representation for a struct or tuple with a single element
  502. // is a struct or tuple containing the value representation of the
  503. // element.
  504. // TODO: Consider doing the same whenever `elementwise_rep` is
  505. // sufficiently small.
  506. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  507. }
  508. // For a struct or tuple with multiple fields, we use a pointer
  509. // to the elementwise value representation.
  510. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  511. }
  512. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  513. SemIR::StructType struct_type) const
  514. -> SemIR::CompleteTypeInfo {
  515. auto fields = context_->struct_type_fields().Get(struct_type.fields_id);
  516. if (fields.empty()) {
  517. return {.value_repr = MakeEmptyValueRepr()};
  518. }
  519. // Find the value representation for each field, and construct a struct
  520. // of value representations.
  521. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  522. value_rep_fields.reserve(fields.size());
  523. bool same_as_object_rep = true;
  524. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  525. for (auto field : fields) {
  526. auto field_type_id =
  527. context_->types().GetTypeIdForTypeInstId(field.type_inst_id);
  528. auto field_info = GetNestedInfo(field_type_id);
  529. if (!field_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  530. field_type_id)) {
  531. same_as_object_rep = false;
  532. field.type_inst_id =
  533. context_->types().GetTypeInstId(field_info.value_repr.type_id);
  534. }
  535. value_rep_fields.push_back(field);
  536. // Take the first non-None abstract_class_id, if any.
  537. if (field_info.abstract_class_id.has_value() &&
  538. !abstract_class_id.has_value()) {
  539. abstract_class_id = field_info.abstract_class_id;
  540. }
  541. }
  542. auto value_rep =
  543. same_as_object_rep
  544. ? type_id
  545. : GetStructType(
  546. *context_,
  547. context_->struct_type_fields().AddCanonical(value_rep_fields));
  548. return {.value_repr = BuildStructOrTupleValueRepr(fields.size(), value_rep,
  549. same_as_object_rep),
  550. .abstract_class_id = abstract_class_id};
  551. }
  552. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  553. SemIR::TupleType tuple_type) const
  554. -> SemIR::CompleteTypeInfo {
  555. // TODO: Share more code with structs.
  556. auto elements = context_->inst_blocks().Get(tuple_type.type_elements_id);
  557. if (elements.empty()) {
  558. return {.value_repr = MakeEmptyValueRepr()};
  559. }
  560. // Find the value representation for each element, and construct a tuple
  561. // of value representations.
  562. llvm::SmallVector<SemIR::InstId> value_rep_elements;
  563. value_rep_elements.reserve(elements.size());
  564. bool same_as_object_rep = true;
  565. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  566. for (auto element_type_id : context_->types().GetBlockAsTypeIds(elements)) {
  567. auto element_info = GetNestedInfo(element_type_id);
  568. if (!element_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  569. element_type_id)) {
  570. same_as_object_rep = false;
  571. }
  572. value_rep_elements.push_back(
  573. context_->types().GetTypeInstId(element_info.value_repr.type_id));
  574. // Take the first non-None abstract_class_id, if any.
  575. if (element_info.abstract_class_id.has_value() &&
  576. !abstract_class_id.has_value()) {
  577. abstract_class_id = element_info.abstract_class_id;
  578. }
  579. }
  580. auto value_rep = same_as_object_rep
  581. ? type_id
  582. : GetTupleType(*context_, value_rep_elements);
  583. return {.value_repr = BuildStructOrTupleValueRepr(elements.size(), value_rep,
  584. same_as_object_rep),
  585. .abstract_class_id = abstract_class_id};
  586. }
  587. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  588. SemIR::ArrayType /*inst*/) const
  589. -> SemIR::CompleteTypeInfo {
  590. // For arrays, it's convenient to always use a pointer representation,
  591. // even when the array has zero or one element, in order to support
  592. // indexing.
  593. return {.value_repr =
  594. MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate)};
  595. }
  596. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  597. SemIR::ClassType inst) const
  598. -> SemIR::CompleteTypeInfo {
  599. auto& class_info = context_->classes().Get(inst.class_id);
  600. auto abstract_class_id =
  601. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract
  602. ? inst.class_id
  603. : SemIR::ClassId::None;
  604. // The value representation of an adapter is the value representation of
  605. // its adapted type.
  606. if (auto adapted_type_id =
  607. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  608. adapted_type_id.has_value()) {
  609. auto info = GetNestedInfo(adapted_type_id);
  610. info.abstract_class_id = abstract_class_id;
  611. return info;
  612. }
  613. // Otherwise, the value representation for a class is a pointer to the
  614. // object representation.
  615. // TODO: Support customized value representations for classes.
  616. // TODO: Pick a better value representation when possible.
  617. return {.value_repr = MakePointerValueRepr(
  618. class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id),
  619. SemIR::ValueRepr::ObjectAggregate),
  620. .abstract_class_id = abstract_class_id};
  621. }
  622. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  623. SemIR::ConstType inst) const
  624. -> SemIR::CompleteTypeInfo {
  625. // The value representation of `const T` is the same as that of `T`.
  626. // Objects are not modifiable through their value representations.
  627. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  628. }
  629. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  630. SemIR::CustomLayoutType /*inst*/) const
  631. -> SemIR::CompleteTypeInfo {
  632. // TODO: Should we support other value representations for custom layout
  633. // types?
  634. return {.value_repr = MakePointerValueRepr(type_id)};
  635. }
  636. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  637. SemIR::MaybeUnformedType inst) const
  638. -> SemIR::CompleteTypeInfo {
  639. // `MaybeUnformed(T)` has the same value representation as `T` if that value
  640. // representation preserves all the bytes of the value, including any padding
  641. // bits. Otherwise we need to use a different representation.
  642. auto inner_type_id = context_->types().GetTypeIdForTypeInstId(inst.inner_id);
  643. auto nested = GetNestedInfo(inner_type_id);
  644. if (nested.value_repr.kind == SemIR::ValueRepr::Custom) {
  645. nested.value_repr = MakePointerValueRepr(type_id);
  646. } else if (nested.value_repr.kind == SemIR::ValueRepr::Copy) {
  647. auto type_inst = context_->types().GetAsInst(nested.value_repr.type_id);
  648. // TODO: Should ValueRepr::IsCopyOfObjectRepr return false for `bool`?
  649. if (!nested.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  650. inner_type_id) ||
  651. type_inst.Is<SemIR::BoolType>()) {
  652. nested.value_repr = MakePointerValueRepr(type_id);
  653. }
  654. // TODO: Handle any other types that we treat as having discarded padding
  655. // bits. For now there are no such types, as all class types and all structs
  656. // and tuples with more than one element are passed indirectly.
  657. }
  658. return nested;
  659. }
  660. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  661. SemIR::PartialType inst) const
  662. -> SemIR::CompleteTypeInfo {
  663. // The value representation of `partial T` is the same as that of `T`.
  664. // Objects are not modifiable through their value representations. However,
  665. // `partial T` is never abstract.
  666. return {
  667. .value_repr =
  668. GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id))
  669. .value_repr,
  670. .abstract_class_id = SemIR::ClassId::None};
  671. }
  672. auto TypeCompleter::BuildInfoForInst(
  673. SemIR::TypeId /*type_id*/, SemIR::ImplWitnessAssociatedConstant inst) const
  674. -> SemIR::CompleteTypeInfo {
  675. return GetNestedInfo(inst.type_id);
  676. }
  677. // Builds and returns the value representation for the given type. All nested
  678. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  679. auto TypeCompleter::BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  680. -> SemIR::CompleteTypeInfo {
  681. // Use overload resolution to select the implementation, producing compile
  682. // errors when BuildInfoForInst isn't defined for a given instruction.
  683. CARBON_KIND_SWITCH(inst) {
  684. #define CARBON_SEM_IR_INST_KIND(Name) \
  685. case CARBON_KIND(SemIR::Name typed_inst): { \
  686. return BuildInfoForInst(type_id, typed_inst); \
  687. }
  688. #include "toolchain/sem_ir/inst_kind.def"
  689. }
  690. }
  691. auto TryToCompleteType(Context& context, SemIR::TypeId type_id,
  692. SemIR::LocId loc_id, bool diagnose) -> bool {
  693. return TypeCompleter(&context, loc_id, diagnose).Complete(type_id);
  694. }
  695. auto CompleteTypeOrCheckFail(Context& context, SemIR::TypeId type_id) -> void {
  696. bool complete =
  697. TypeCompleter(&context, SemIR::LocId::None, false).Complete(type_id);
  698. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  699. context.types().GetAsInst(type_id));
  700. }
  701. auto RequireCompleteType(Context& context, SemIR::TypeId type_id,
  702. SemIR::LocId loc_id,
  703. DiagnosticContextFn diagnostic_context) -> bool {
  704. CARBON_CHECK(diagnostic_context);
  705. Diagnostics::ContextScope scope(&context.emitter(), diagnostic_context);
  706. if (!TypeCompleter(&context, loc_id, true).Complete(type_id)) {
  707. return false;
  708. }
  709. // For a symbolic type, create an instruction to require the corresponding
  710. // specific type to be complete.
  711. if (type_id.is_symbolic()) {
  712. // TODO: Deduplicate these.
  713. AddInstInNoBlock(
  714. context, loc_id,
  715. SemIR::RequireCompleteType{
  716. .type_id =
  717. GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  718. .complete_type_inst_id = context.types().GetTypeInstId(type_id)});
  719. }
  720. return true;
  721. }
  722. auto TryIsConcreteType(Context& context, SemIR::TypeId type_id,
  723. SemIR::LocId loc_id) -> bool {
  724. if (!TryToCompleteType(context, type_id, loc_id)) {
  725. return false;
  726. }
  727. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  728. CARBON_CHECK(complete_info.value_repr.type_id.has_value(),
  729. "TryIsConcreteType called for an incomplete type. Call "
  730. "TryToCompleteType first.");
  731. return !complete_info.abstract_class_id.has_value();
  732. }
  733. auto RequireConcreteType(Context& context, SemIR::TypeId type_id,
  734. SemIR::LocId loc_id,
  735. DiagnosticContextFn complete_type_diagnostic_context,
  736. DiagnosticContextFn concrete_type_diagnostic_context)
  737. -> bool {
  738. if (!RequireCompleteType(context, type_id, loc_id,
  739. complete_type_diagnostic_context)) {
  740. return false;
  741. }
  742. CARBON_CHECK(concrete_type_diagnostic_context);
  743. Diagnostics::ContextScope scope(&context.emitter(),
  744. concrete_type_diagnostic_context);
  745. // TODO: For symbolic types, should add an implicit constraint that they are
  746. // not abstract.
  747. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  748. CARBON_CHECK(complete_info.value_repr.type_id.has_value(),
  749. "RequireConcreteType called for an incomplete type. Call "
  750. "RequireCompleteType first.");
  751. if (!complete_info.abstract_class_id.has_value()) {
  752. return true;
  753. }
  754. bool direct_use = false;
  755. if (auto inst = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  756. if (inst->class_id == complete_info.abstract_class_id) {
  757. direct_use = true;
  758. }
  759. }
  760. DiagnoseAbstractClass(context, complete_info.abstract_class_id, direct_use);
  761. return false;
  762. }
  763. // Require all named constraints in the facet type are identified. For a named
  764. // constraint, this means the constraint definition is complete.
  765. static auto RequireCompleteNamedConstraint(
  766. Context& context, SemIR::LocId loc_id,
  767. SemIR::NamedConstraintId constraint_id, SemIR::SpecificId specific_id,
  768. bool diagnose) -> bool {
  769. auto facet_type =
  770. FacetTypeFromNamedConstraint(context, constraint_id, specific_id);
  771. return RequireCompleteFacetType(context, loc_id, facet_type, diagnose);
  772. }
  773. // Given a canonical facet value, or a type value, return a facet value.
  774. static auto GetSelfFacetValue(Context& context, SemIR::ConstantId self_const_id)
  775. -> SemIR::ConstantId {
  776. if (self_const_id == SemIR::ErrorInst::ConstantId) {
  777. return SemIR::ErrorInst::ConstantId;
  778. }
  779. auto self_inst_id = context.constant_values().GetInstId(self_const_id);
  780. auto type_id = context.insts().Get(self_inst_id).type_id();
  781. CARBON_CHECK(context.types().IsFacetType(type_id));
  782. if (context.types().Is<SemIR::FacetType>(type_id)) {
  783. return self_const_id;
  784. }
  785. return GetConstantFacetValueForType(
  786. context, context.types().GetAsTypeInstId(self_inst_id));
  787. }
  788. auto RequireIdentifiedFacetType(Context& context, SemIR::LocId loc_id,
  789. SemIR::ConstantId self_const_id,
  790. const SemIR::FacetType& facet_type,
  791. DiagnosticContextFn diagnostic_context)
  792. -> SemIR::IdentifiedFacetTypeId {
  793. CARBON_CHECK(diagnostic_context);
  794. Diagnostics::ContextScope scope(&context.emitter(), diagnostic_context);
  795. auto key =
  796. SemIR::IdentifiedFacetTypeKey{.facet_type_id = facet_type.facet_type_id,
  797. .self_const_id = self_const_id};
  798. if (auto identified_id = context.identified_facet_types().Lookup(key);
  799. identified_id.has_value()) {
  800. return identified_id;
  801. }
  802. struct SelfImplsFacetType {
  803. SemIR::ConstantId self;
  804. SemIR::FacetTypeId facet_type;
  805. };
  806. // Work queue.
  807. llvm::SmallVector<SelfImplsFacetType> extend_facet_types = {
  808. {self_const_id, facet_type.facet_type_id}};
  809. llvm::SmallVector<SelfImplsFacetType> impls_facet_types;
  810. // Outputs for the IdentifiedFacetType.
  811. llvm::SmallVector<SemIR::IdentifiedFacetType::RequiredImpl> extends;
  812. llvm::SmallVector<SemIR::IdentifiedFacetType::RequiredImpl> impls;
  813. while (true) {
  814. SelfImplsFacetType next_impls = {SemIR::ConstantId::None,
  815. SemIR::FacetTypeId::None};
  816. bool facet_type_extends = false;
  817. if (!extend_facet_types.empty()) {
  818. next_impls = extend_facet_types.pop_back_val();
  819. facet_type_extends = true;
  820. } else if (!impls_facet_types.empty()) {
  821. next_impls = impls_facet_types.pop_back_val();
  822. facet_type_extends = false;
  823. } else {
  824. break;
  825. }
  826. auto self_const_id = GetCanonicalFacetOrTypeValue(context, next_impls.self);
  827. const auto& facet_type_info =
  828. context.facet_types().Get(next_impls.facet_type);
  829. auto self_and_interface = [&](SemIR::SpecificInterface interface)
  830. -> SemIR::IdentifiedFacetType::RequiredImpl {
  831. return {self_const_id, interface};
  832. };
  833. if (facet_type_extends) {
  834. llvm::append_range(extends,
  835. llvm::map_range(facet_type_info.extend_constraints,
  836. self_and_interface));
  837. } else {
  838. llvm::append_range(impls,
  839. llvm::map_range(facet_type_info.extend_constraints,
  840. self_and_interface));
  841. }
  842. llvm::append_range(impls,
  843. llvm::map_range(facet_type_info.self_impls_constraints,
  844. self_and_interface));
  845. if (facet_type_info.extend_named_constraints.empty() &&
  846. facet_type_info.self_impls_named_constraints.empty()) {
  847. continue;
  848. }
  849. // References to a named constraint require the constraint to be complete so
  850. // that we can enumerate all the required interfaces within.
  851. for (auto specific_constraint :
  852. llvm::concat<const SemIR::SpecificNamedConstraint>(
  853. facet_type_info.extend_named_constraints,
  854. facet_type_info.self_impls_named_constraints)) {
  855. if (!RequireCompleteNamedConstraint(
  856. context, loc_id, specific_constraint.named_constraint_id,
  857. specific_constraint.specific_id, true)) {
  858. return SemIR::IdentifiedFacetTypeId::None;
  859. }
  860. }
  861. // The self may have type TypeType. But the `Self` in a generic require decl
  862. // has type FacetType, so we need something similar to replace it in the
  863. // specific.
  864. auto self_facet = GetSelfFacetValue(context, self_const_id);
  865. for (auto extends : facet_type_info.extend_named_constraints) {
  866. const auto& constraint =
  867. context.named_constraints().Get(extends.named_constraint_id);
  868. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  869. context, loc_id, constraint.generic_id,
  870. constraint.generic_with_self_id, extends.specific_id, self_facet);
  871. for (auto require_impls_id : context.require_impls_blocks().Get(
  872. constraint.require_impls_block_id)) {
  873. const auto& require = context.require_impls().Get(require_impls_id);
  874. // Each require is in its own generic, with no additional bindings and
  875. // no definition, so that they can have their specifics independently
  876. // instantiated.
  877. auto require_specific_id = CopySpecificToGeneric(
  878. context, SemIR::LocId(require.decl_id),
  879. constraint_with_self_specific_id, require.generic_id);
  880. auto require_self = GetConstantValueInSpecific(
  881. context.sem_ir(), require_specific_id, require.self_id);
  882. auto require_facet_type = GetConstantValueInSpecific(
  883. context.sem_ir(), require_specific_id, require.facet_type_inst_id);
  884. if (require_self == SemIR::ErrorInst::ConstantId ||
  885. require_facet_type == SemIR::ErrorInst::ConstantId) {
  886. return SemIR::IdentifiedFacetTypeId::None;
  887. }
  888. // TODO: Add and use constant_values().GetAs<SemIR::FacetType>().
  889. auto facet_type_inst_id =
  890. context.constant_values().GetInstId(require_facet_type);
  891. auto facet_type_id = context.insts()
  892. .GetAs<SemIR::FacetType>(facet_type_inst_id)
  893. .facet_type_id;
  894. if (facet_type_extends && require.extend_self) {
  895. extend_facet_types.push_back({require_self, facet_type_id});
  896. } else {
  897. impls_facet_types.push_back({require_self, facet_type_id});
  898. }
  899. }
  900. }
  901. for (auto impls : facet_type_info.self_impls_named_constraints) {
  902. const auto& constraint =
  903. context.named_constraints().Get(impls.named_constraint_id);
  904. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  905. context, loc_id, constraint.generic_id,
  906. constraint.generic_with_self_id, impls.specific_id, self_facet);
  907. for (auto require_impls_id : context.require_impls_blocks().Get(
  908. constraint.require_impls_block_id)) {
  909. const auto& require = context.require_impls().Get(require_impls_id);
  910. // Each require is in its own generic, with no additional bindings and
  911. // no definition, so that they can have their specifics independently
  912. // instantiated.
  913. auto require_specific_id = CopySpecificToGeneric(
  914. context, SemIR::LocId(require.decl_id),
  915. constraint_with_self_specific_id, require.generic_id);
  916. auto require_self = GetConstantValueInSpecific(
  917. context.sem_ir(), require_specific_id, require.self_id);
  918. auto require_facet_type = GetConstantValueInSpecific(
  919. context.sem_ir(), require_specific_id, require.facet_type_inst_id);
  920. if (require_self == SemIR::ErrorInst::ConstantId ||
  921. require_facet_type == SemIR::ErrorInst::ConstantId) {
  922. return SemIR::IdentifiedFacetTypeId::None;
  923. }
  924. // TODO: Add and use constant_values().GetAs<SemIR::FacetType>().
  925. auto facet_type_inst_id =
  926. context.constant_values().GetInstId(require_facet_type);
  927. auto facet_type_id = context.insts()
  928. .GetAs<SemIR::FacetType>(facet_type_inst_id)
  929. .facet_type_id;
  930. impls_facet_types.push_back({require_self, facet_type_id});
  931. }
  932. }
  933. }
  934. // TODO: Process other kinds of requirements.
  935. return context.identified_facet_types().Add({key, extends, impls});
  936. }
  937. } // namespace Carbon::Check