type_completion.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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 "llvm/ADT/SmallVector.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/cpp/import.h"
  8. #include "toolchain/check/generic.h"
  9. #include "toolchain/check/inst.h"
  10. #include "toolchain/check/type.h"
  11. #include "toolchain/diagnostics/format_providers.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/typed_insts.h"
  14. namespace Carbon::Check {
  15. namespace {
  16. // Worklist-based type completion mechanism.
  17. //
  18. // When attempting to complete a type, we may find other types that also need to
  19. // be completed: types nested within that type, and the value representation of
  20. // the type. In order to complete a type without recursing arbitrarily deeply,
  21. // we use a worklist of tasks:
  22. //
  23. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  24. // nested within a type to the work list.
  25. // - A `BuildInfo` step computes the `CompleteTypeInfo` for a type, once all of
  26. // its nested types are complete, and marks the type as complete.
  27. class TypeCompleter {
  28. public:
  29. // `context` mut not be null.
  30. TypeCompleter(Context* context, SemIR::LocId loc_id,
  31. MakeDiagnosticBuilderFn diagnoser)
  32. : context_(context), loc_id_(loc_id), diagnoser_(diagnoser) {}
  33. // Attempts to complete the given type. Returns true if it is now complete,
  34. // false if it could not be completed.
  35. auto Complete(SemIR::TypeId type_id) -> bool;
  36. private:
  37. enum class Phase : int8_t {
  38. // The next step is to add nested types to the list of types to complete.
  39. AddNestedIncompleteTypes,
  40. // The next step is to build the `CompleteTypeInfo` for the type.
  41. BuildInfo,
  42. };
  43. struct WorkItem {
  44. SemIR::TypeId type_id;
  45. Phase phase;
  46. };
  47. // Adds `type_id` to the work list, if it's not already complete.
  48. auto Push(SemIR::TypeId type_id) -> void;
  49. // Runs the next step.
  50. auto ProcessStep() -> bool;
  51. // Adds any types nested within `type_inst` that need to be complete for
  52. // `type_inst` to be complete to our work list.
  53. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool;
  54. // Makes an empty value representation, which is used for types that have no
  55. // state, such as empty structs and tuples.
  56. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr;
  57. // Makes a dependent value representation, which is used for symbolic types.
  58. auto MakeDependentValueRepr(SemIR::TypeId type_id) const -> SemIR::ValueRepr;
  59. // Makes a value representation that uses pass-by-copy, copying the given
  60. // type.
  61. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  62. SemIR::ValueRepr::AggregateKind aggregate_kind =
  63. SemIR::ValueRepr::NotAggregate) const
  64. -> SemIR::ValueRepr;
  65. // Makes a value representation that uses pass-by-address with the given
  66. // pointee type.
  67. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  68. SemIR::ValueRepr::AggregateKind aggregate_kind =
  69. SemIR::ValueRepr::NotAggregate) const
  70. -> SemIR::ValueRepr;
  71. // Gets the value representation of a nested type, which should already be
  72. // complete.
  73. auto GetNestedInfo(SemIR::TypeId nested_type_id) const
  74. -> SemIR::CompleteTypeInfo;
  75. template <typename InstT>
  76. requires(InstT::Kind.template IsAnyOf<
  77. SemIR::AutoType, SemIR::BoolType, SemIR::BoundMethodType,
  78. SemIR::CharLiteralType, SemIR::ErrorInst, SemIR::FacetType,
  79. SemIR::FloatLiteralType, SemIR::FloatType, SemIR::IntType,
  80. SemIR::IntLiteralType, SemIR::NamespaceType, SemIR::PatternType,
  81. SemIR::PointerType, SemIR::SpecificFunctionType, SemIR::TypeType,
  82. SemIR::VtableType, SemIR::WitnessType>())
  83. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  84. -> SemIR::CompleteTypeInfo {
  85. return {.value_repr = MakeCopyValueRepr(type_id)};
  86. }
  87. auto BuildStructOrTupleValueRepr(size_t num_elements,
  88. SemIR::TypeId elementwise_rep,
  89. bool same_as_object_rep) const
  90. -> SemIR::ValueRepr;
  91. auto BuildInfoForInst(SemIR::TypeId type_id,
  92. SemIR::StructType struct_type) const
  93. -> SemIR::CompleteTypeInfo;
  94. auto BuildInfoForInst(SemIR::TypeId type_id,
  95. SemIR::TupleType tuple_type) const
  96. -> SemIR::CompleteTypeInfo;
  97. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::ArrayType /*inst*/) const
  98. -> SemIR::CompleteTypeInfo;
  99. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ClassType inst) const
  100. -> SemIR::CompleteTypeInfo;
  101. template <typename InstT>
  102. requires(InstT::Kind.template IsAnyOf<
  103. SemIR::AssociatedEntityType, SemIR::CppOverloadSetType,
  104. SemIR::FunctionType, SemIR::FunctionTypeWithSelfType,
  105. SemIR::GenericClassType, SemIR::GenericInterfaceType,
  106. SemIR::InstType, SemIR::UnboundElementType, SemIR::WhereExpr>())
  107. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  108. -> SemIR::CompleteTypeInfo {
  109. // These types have no runtime operations, so we use an empty value
  110. // representation.
  111. //
  112. // TODO: There is information we could model here:
  113. // - For an interface, we could use a witness.
  114. // - For an associated entity, we could use an index into the witness.
  115. // - For an unbound element, we could use an index or offset.
  116. return {.value_repr = MakeEmptyValueRepr()};
  117. }
  118. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ConstType inst) const
  119. -> SemIR::CompleteTypeInfo;
  120. auto BuildInfoForInst(SemIR::TypeId type_id,
  121. SemIR::CustomLayoutType inst) const
  122. -> SemIR::CompleteTypeInfo;
  123. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  124. SemIR::MaybeUnformedType inst) const
  125. -> SemIR::CompleteTypeInfo;
  126. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  127. SemIR::PartialType inst) const
  128. -> SemIR::CompleteTypeInfo;
  129. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  130. SemIR::ImplWitnessAssociatedConstant inst) const
  131. -> SemIR::CompleteTypeInfo;
  132. template <typename InstT>
  133. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  134. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT inst) const
  135. -> SemIR::CompleteTypeInfo {
  136. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  137. }
  138. template <typename InstT>
  139. requires(InstT::Kind.is_symbolic_when_type())
  140. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  141. -> SemIR::CompleteTypeInfo {
  142. return {.value_repr = MakeDependentValueRepr(type_id)};
  143. }
  144. // Builds and returns the `CompleteTypeInfo` for the given type. All nested
  145. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  146. auto BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  147. -> SemIR::CompleteTypeInfo;
  148. Context* context_;
  149. llvm::SmallVector<WorkItem> work_list_;
  150. SemIR::LocId loc_id_;
  151. MakeDiagnosticBuilderFn diagnoser_;
  152. };
  153. } // namespace
  154. auto TypeCompleter::Complete(SemIR::TypeId type_id) -> bool {
  155. Push(type_id);
  156. while (!work_list_.empty()) {
  157. if (!ProcessStep()) {
  158. return false;
  159. }
  160. }
  161. return true;
  162. }
  163. auto TypeCompleter::Push(SemIR::TypeId type_id) -> void {
  164. if (!context_->types().IsComplete(type_id)) {
  165. work_list_.push_back(
  166. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  167. }
  168. }
  169. auto TypeCompleter::ProcessStep() -> bool {
  170. auto [type_id, phase] = work_list_.back();
  171. // We might have enqueued the same type more than once. Just skip the
  172. // type if it's already complete.
  173. if (context_->types().IsComplete(type_id)) {
  174. work_list_.pop_back();
  175. return true;
  176. }
  177. auto inst_id = context_->types().GetInstId(type_id);
  178. auto inst = context_->insts().Get(inst_id);
  179. auto old_work_list_size = work_list_.size();
  180. switch (phase) {
  181. case Phase::AddNestedIncompleteTypes:
  182. if (!AddNestedIncompleteTypes(inst)) {
  183. return false;
  184. }
  185. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  186. "AddNestedIncompleteTypes should not remove work items");
  187. work_list_[old_work_list_size - 1].phase = Phase::BuildInfo;
  188. break;
  189. case Phase::BuildInfo: {
  190. auto info = BuildInfo(type_id, inst);
  191. context_->types().SetComplete(type_id, info);
  192. CARBON_CHECK(old_work_list_size == work_list_.size(),
  193. "BuildInfo should not change work items");
  194. work_list_.pop_back();
  195. // Also complete the value representation type, if necessary. This
  196. // should never fail: the value representation shouldn't require any
  197. // additional nested types to be complete.
  198. if (!context_->types().IsComplete(info.value_repr.type_id)) {
  199. work_list_.push_back(
  200. {.type_id = info.value_repr.type_id, .phase = Phase::BuildInfo});
  201. }
  202. // For a pointer representation, the pointee also needs to be complete.
  203. if (info.value_repr.kind == SemIR::ValueRepr::Pointer) {
  204. if (info.value_repr.type_id == SemIR::ErrorInst::TypeId) {
  205. break;
  206. }
  207. auto pointee_type_id =
  208. context_->sem_ir().GetPointeeType(info.value_repr.type_id);
  209. if (!context_->types().IsComplete(pointee_type_id)) {
  210. work_list_.push_back(
  211. {.type_id = pointee_type_id, .phase = Phase::BuildInfo});
  212. }
  213. }
  214. break;
  215. }
  216. }
  217. return true;
  218. }
  219. auto TypeCompleter::AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  220. CARBON_KIND_SWITCH(type_inst) {
  221. case CARBON_KIND(SemIR::ArrayType inst): {
  222. Push(context_->types().GetTypeIdForTypeInstId(inst.element_type_inst_id));
  223. break;
  224. }
  225. case CARBON_KIND(SemIR::StructType inst): {
  226. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  227. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  228. }
  229. break;
  230. }
  231. case CARBON_KIND(SemIR::TupleType inst): {
  232. for (auto element_type_id : context_->types().GetBlockAsTypeIds(
  233. context_->inst_blocks().Get(inst.type_elements_id))) {
  234. Push(element_type_id);
  235. }
  236. break;
  237. }
  238. case CARBON_KIND(SemIR::ClassType inst): {
  239. auto& class_info = context_->classes().Get(inst.class_id);
  240. // If the class was imported from C++, ask Clang to try to complete it.
  241. if (!class_info.is_complete() && class_info.scope_id.has_value()) {
  242. auto& scope = context_->name_scopes().Get(class_info.scope_id);
  243. if (scope.clang_decl_context_id().has_value()) {
  244. if (!ImportClassDefinitionForClangDecl(
  245. *context_, loc_id_, inst.class_id,
  246. scope.clang_decl_context_id())) {
  247. // Clang produced a diagnostic. Don't produce one of our own.
  248. return false;
  249. }
  250. }
  251. }
  252. if (!class_info.is_complete()) {
  253. if (diagnoser_) {
  254. auto builder = diagnoser_();
  255. NoteIncompleteClass(*context_, inst.class_id, builder);
  256. builder.Emit();
  257. }
  258. return false;
  259. }
  260. if (inst.specific_id.has_value()) {
  261. ResolveSpecificDefinition(*context_, loc_id_, inst.specific_id);
  262. }
  263. if (auto adapted_type_id =
  264. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  265. adapted_type_id.has_value()) {
  266. Push(adapted_type_id);
  267. } else {
  268. Push(class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id));
  269. }
  270. break;
  271. }
  272. case CARBON_KIND(SemIR::ConstType inst): {
  273. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  274. break;
  275. }
  276. case CARBON_KIND(SemIR::CustomLayoutType inst): {
  277. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  278. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  279. }
  280. break;
  281. }
  282. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  283. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  284. break;
  285. }
  286. case CARBON_KIND(SemIR::PartialType inst): {
  287. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  288. break;
  289. }
  290. case CARBON_KIND(SemIR::FacetType inst): {
  291. auto identified_id = RequireIdentifiedFacetType(*context_, inst);
  292. const auto& identified =
  293. context_->identified_facet_types().Get(identified_id);
  294. // Every mentioned interface needs to be complete.
  295. for (auto req_interface : identified.required_interfaces()) {
  296. auto interface_id = req_interface.interface_id;
  297. const auto& interface = context_->interfaces().Get(interface_id);
  298. if (!interface.is_complete()) {
  299. if (diagnoser_) {
  300. auto builder = diagnoser_();
  301. NoteIncompleteInterface(*context_, interface_id, builder);
  302. builder.Emit();
  303. }
  304. return false;
  305. }
  306. if (req_interface.specific_id.has_value()) {
  307. ResolveSpecificDefinition(*context_, loc_id_,
  308. req_interface.specific_id);
  309. }
  310. }
  311. break;
  312. }
  313. default:
  314. break;
  315. }
  316. return true;
  317. }
  318. auto TypeCompleter::MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  319. return {.kind = SemIR::ValueRepr::None,
  320. .type_id = GetTupleType(*context_, {})};
  321. }
  322. auto TypeCompleter::MakeDependentValueRepr(SemIR::TypeId type_id) const
  323. -> SemIR::ValueRepr {
  324. return {.kind = SemIR::ValueRepr::Dependent, .type_id = type_id};
  325. }
  326. auto TypeCompleter::MakeCopyValueRepr(
  327. SemIR::TypeId rep_id, SemIR::ValueRepr::AggregateKind aggregate_kind) const
  328. -> SemIR::ValueRepr {
  329. return {.kind = SemIR::ValueRepr::Copy,
  330. .aggregate_kind = aggregate_kind,
  331. .type_id = rep_id};
  332. }
  333. auto TypeCompleter::MakePointerValueRepr(
  334. SemIR::TypeId pointee_id,
  335. SemIR::ValueRepr::AggregateKind aggregate_kind) const -> SemIR::ValueRepr {
  336. // TODO: Should we add `const` qualification to `pointee_id`?
  337. return {.kind = SemIR::ValueRepr::Pointer,
  338. .aggregate_kind = aggregate_kind,
  339. .type_id = GetPointerType(*context_,
  340. context_->types().GetInstId(pointee_id))};
  341. }
  342. auto TypeCompleter::GetNestedInfo(SemIR::TypeId nested_type_id) const
  343. -> SemIR::CompleteTypeInfo {
  344. CARBON_CHECK(context_->types().IsComplete(nested_type_id),
  345. "Nested type should already be complete");
  346. auto info = context_->types().GetCompleteTypeInfo(nested_type_id);
  347. CARBON_CHECK(info.value_repr.kind != SemIR::ValueRepr::Unknown,
  348. "Complete type should have a value representation");
  349. return info;
  350. }
  351. auto TypeCompleter::BuildStructOrTupleValueRepr(size_t num_elements,
  352. SemIR::TypeId elementwise_rep,
  353. bool same_as_object_rep) const
  354. -> SemIR::ValueRepr {
  355. SemIR::ValueRepr::AggregateKind aggregate_kind =
  356. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  357. : SemIR::ValueRepr::ValueAggregate;
  358. if (num_elements == 1) {
  359. // The value representation for a struct or tuple with a single element
  360. // is a struct or tuple containing the value representation of the
  361. // element.
  362. // TODO: Consider doing the same whenever `elementwise_rep` is
  363. // sufficiently small.
  364. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  365. }
  366. // For a struct or tuple with multiple fields, we use a pointer
  367. // to the elementwise value representation.
  368. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  369. }
  370. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  371. SemIR::StructType struct_type) const
  372. -> SemIR::CompleteTypeInfo {
  373. auto fields = context_->struct_type_fields().Get(struct_type.fields_id);
  374. if (fields.empty()) {
  375. return {.value_repr = MakeEmptyValueRepr()};
  376. }
  377. // Find the value representation for each field, and construct a struct
  378. // of value representations.
  379. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  380. value_rep_fields.reserve(fields.size());
  381. bool same_as_object_rep = true;
  382. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  383. for (auto field : fields) {
  384. auto field_type_id =
  385. context_->types().GetTypeIdForTypeInstId(field.type_inst_id);
  386. auto field_info = GetNestedInfo(field_type_id);
  387. if (!field_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  388. field_type_id)) {
  389. same_as_object_rep = false;
  390. field.type_inst_id =
  391. context_->types().GetInstId(field_info.value_repr.type_id);
  392. }
  393. value_rep_fields.push_back(field);
  394. // Take the first non-None abstract_class_id, if any.
  395. if (field_info.abstract_class_id.has_value() &&
  396. !abstract_class_id.has_value()) {
  397. abstract_class_id = field_info.abstract_class_id;
  398. }
  399. }
  400. auto value_rep =
  401. same_as_object_rep
  402. ? type_id
  403. : GetStructType(
  404. *context_,
  405. context_->struct_type_fields().AddCanonical(value_rep_fields));
  406. return {.value_repr = BuildStructOrTupleValueRepr(fields.size(), value_rep,
  407. same_as_object_rep),
  408. .abstract_class_id = abstract_class_id};
  409. }
  410. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  411. SemIR::TupleType tuple_type) const
  412. -> SemIR::CompleteTypeInfo {
  413. // TODO: Share more code with structs.
  414. auto elements = context_->inst_blocks().Get(tuple_type.type_elements_id);
  415. if (elements.empty()) {
  416. return {.value_repr = MakeEmptyValueRepr()};
  417. }
  418. // Find the value representation for each element, and construct a tuple
  419. // of value representations.
  420. llvm::SmallVector<SemIR::InstId> value_rep_elements;
  421. value_rep_elements.reserve(elements.size());
  422. bool same_as_object_rep = true;
  423. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  424. for (auto element_type_id : context_->types().GetBlockAsTypeIds(elements)) {
  425. auto element_info = GetNestedInfo(element_type_id);
  426. if (!element_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  427. element_type_id)) {
  428. same_as_object_rep = false;
  429. }
  430. value_rep_elements.push_back(
  431. context_->types().GetInstId(element_info.value_repr.type_id));
  432. // Take the first non-None abstract_class_id, if any.
  433. if (element_info.abstract_class_id.has_value() &&
  434. !abstract_class_id.has_value()) {
  435. abstract_class_id = element_info.abstract_class_id;
  436. }
  437. }
  438. auto value_rep = same_as_object_rep
  439. ? type_id
  440. : GetTupleType(*context_, value_rep_elements);
  441. return {.value_repr = BuildStructOrTupleValueRepr(elements.size(), value_rep,
  442. same_as_object_rep),
  443. .abstract_class_id = abstract_class_id};
  444. }
  445. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  446. SemIR::ArrayType /*inst*/) const
  447. -> SemIR::CompleteTypeInfo {
  448. // For arrays, it's convenient to always use a pointer representation,
  449. // even when the array has zero or one element, in order to support
  450. // indexing.
  451. return {.value_repr =
  452. MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate)};
  453. }
  454. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  455. SemIR::ClassType inst) const
  456. -> SemIR::CompleteTypeInfo {
  457. auto& class_info = context_->classes().Get(inst.class_id);
  458. auto abstract_class_id =
  459. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract
  460. ? inst.class_id
  461. : SemIR::ClassId::None;
  462. // The value representation of an adapter is the value representation of
  463. // its adapted type.
  464. if (auto adapted_type_id =
  465. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  466. adapted_type_id.has_value()) {
  467. auto info = GetNestedInfo(adapted_type_id);
  468. info.abstract_class_id = abstract_class_id;
  469. return info;
  470. }
  471. // Otherwise, the value representation for a class is a pointer to the
  472. // object representation.
  473. // TODO: Support customized value representations for classes.
  474. // TODO: Pick a better value representation when possible.
  475. return {.value_repr = MakePointerValueRepr(
  476. class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id),
  477. SemIR::ValueRepr::ObjectAggregate),
  478. .abstract_class_id = abstract_class_id};
  479. }
  480. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  481. SemIR::ConstType inst) const
  482. -> SemIR::CompleteTypeInfo {
  483. // The value representation of `const T` is the same as that of `T`.
  484. // Objects are not modifiable through their value representations.
  485. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  486. }
  487. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  488. SemIR::CustomLayoutType /*inst*/) const
  489. -> SemIR::CompleteTypeInfo {
  490. // TODO: Should we support other value representations for custom layout
  491. // types?
  492. return {.value_repr = MakePointerValueRepr(type_id)};
  493. }
  494. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  495. SemIR::MaybeUnformedType /*inst*/) const
  496. -> SemIR::CompleteTypeInfo {
  497. // `MaybeUnformed(T)` always has a pointer value representation, regardless of
  498. // `T`'s value representation.
  499. return {.value_repr = MakePointerValueRepr(type_id)};
  500. }
  501. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  502. SemIR::PartialType inst) const
  503. -> SemIR::CompleteTypeInfo {
  504. // The value representation of `partial T` is the same as that of `T`.
  505. // Objects are not modifiable through their value representations.
  506. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  507. }
  508. auto TypeCompleter::BuildInfoForInst(
  509. SemIR::TypeId /*type_id*/, SemIR::ImplWitnessAssociatedConstant inst) const
  510. -> SemIR::CompleteTypeInfo {
  511. return GetNestedInfo(inst.type_id);
  512. }
  513. // Builds and returns the value representation for the given type. All nested
  514. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  515. auto TypeCompleter::BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  516. -> SemIR::CompleteTypeInfo {
  517. // Use overload resolution to select the implementation, producing compile
  518. // errors when BuildInfoForInst isn't defined for a given instruction.
  519. CARBON_KIND_SWITCH(inst) {
  520. #define CARBON_SEM_IR_INST_KIND(Name) \
  521. case CARBON_KIND(SemIR::Name typed_inst): { \
  522. return BuildInfoForInst(type_id, typed_inst); \
  523. }
  524. #include "toolchain/sem_ir/inst_kind.def"
  525. }
  526. }
  527. auto TryToCompleteType(Context& context, SemIR::TypeId type_id,
  528. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  529. -> bool {
  530. return TypeCompleter(&context, loc_id, diagnoser).Complete(type_id);
  531. }
  532. auto CompleteTypeOrCheckFail(Context& context, SemIR::TypeId type_id) -> void {
  533. bool complete =
  534. TypeCompleter(&context, SemIR::LocId::None, nullptr).Complete(type_id);
  535. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  536. context.types().GetAsInst(type_id));
  537. }
  538. auto RequireCompleteType(Context& context, SemIR::TypeId type_id,
  539. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  540. -> bool {
  541. CARBON_CHECK(diagnoser);
  542. if (!TypeCompleter(&context, loc_id, diagnoser).Complete(type_id)) {
  543. return false;
  544. }
  545. // For a symbolic type, create an instruction to require the corresponding
  546. // specific type to be complete.
  547. if (type_id.is_symbolic()) {
  548. // TODO: Deduplicate these.
  549. AddInstInNoBlock(
  550. context, loc_id,
  551. SemIR::RequireCompleteType{
  552. .type_id =
  553. GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  554. .complete_type_inst_id = context.types().GetInstId(type_id)});
  555. }
  556. return true;
  557. }
  558. // Adds a note to a diagnostic explaining that a class is abstract.
  559. static auto NoteAbstractClass(Context& context, SemIR::ClassId class_id,
  560. bool direct_use, DiagnosticBuilder& builder)
  561. -> void {
  562. const auto& class_info = context.classes().Get(class_id);
  563. CARBON_CHECK(
  564. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  565. "Class is not abstract");
  566. CARBON_DIAGNOSTIC(
  567. ClassAbstractHere, Note,
  568. "{0:=0:uses class that|=1:class} was declared abstract here",
  569. Diagnostics::IntAsSelect);
  570. builder.Note(class_info.definition_id, ClassAbstractHere,
  571. static_cast<int>(direct_use));
  572. }
  573. auto RequireConcreteType(Context& context, SemIR::TypeId type_id,
  574. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  575. MakeDiagnosticBuilderFn abstract_diagnoser) -> bool {
  576. // TODO: For symbolic types, should add an implicit constraint that they are
  577. // not abstract.
  578. CARBON_CHECK(abstract_diagnoser);
  579. // The representation of a facet type does not depend on its definition, so
  580. // they are considered "concrete" even when not complete.
  581. if (context.types().IsFacetType(type_id)) {
  582. return true;
  583. }
  584. if (!RequireCompleteType(context, type_id, loc_id, diagnoser)) {
  585. return false;
  586. }
  587. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  588. if (complete_info.abstract_class_id.has_value()) {
  589. auto builder = abstract_diagnoser();
  590. if (builder) {
  591. bool direct_use = false;
  592. if (auto inst = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  593. if (inst->class_id == complete_info.abstract_class_id) {
  594. direct_use = true;
  595. }
  596. }
  597. NoteAbstractClass(context, complete_info.abstract_class_id, direct_use,
  598. builder);
  599. builder.Emit();
  600. }
  601. return false;
  602. }
  603. return true;
  604. }
  605. auto RequireIdentifiedFacetType(Context& context,
  606. const SemIR::FacetType& facet_type)
  607. -> SemIR::IdentifiedFacetTypeId {
  608. if (auto identified_id =
  609. context.identified_facet_types().TryGetId(facet_type.facet_type_id);
  610. identified_id.has_value()) {
  611. return identified_id;
  612. }
  613. const auto& facet_type_info =
  614. context.facet_types().Get(facet_type.facet_type_id);
  615. // TODO: expand named constraints
  616. // TODO: Process other kinds of requirements.
  617. return context.identified_facet_types().Add(
  618. facet_type.facet_type_id, {facet_type_info.extend_constraints,
  619. facet_type_info.self_impls_constraints});
  620. }
  621. auto AsCompleteType(Context& context, SemIR::TypeId type_id,
  622. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  623. -> SemIR::TypeId {
  624. return RequireCompleteType(context, type_id, loc_id, diagnoser)
  625. ? type_id
  626. : SemIR::ErrorInst::TypeId;
  627. }
  628. // Returns the type `type_id` if it is a concrete type, or produces an
  629. // incomplete or abstract type error and returns an error type. This is a
  630. // convenience wrapper around `RequireConcreteType`.
  631. auto AsConcreteType(Context& context, SemIR::TypeId type_id,
  632. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  633. MakeDiagnosticBuilderFn abstract_diagnoser)
  634. -> SemIR::TypeId {
  635. return RequireConcreteType(context, type_id, loc_id, diagnoser,
  636. abstract_diagnoser)
  637. ? type_id
  638. : SemIR::ErrorInst::TypeId;
  639. }
  640. auto NoteIncompleteClass(Context& context, SemIR::ClassId class_id,
  641. DiagnosticBuilder& builder) -> void {
  642. const auto& class_info = context.classes().Get(class_id);
  643. CARBON_CHECK(!class_info.is_complete(), "Class is not incomplete");
  644. if (class_info.has_definition_started()) {
  645. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  646. "class is incomplete within its definition");
  647. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  648. } else {
  649. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  650. "class was forward declared here");
  651. builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
  652. }
  653. }
  654. auto NoteIncompleteInterface(Context& context, SemIR::InterfaceId interface_id,
  655. DiagnosticBuilder& builder) -> void {
  656. const auto& interface_info = context.interfaces().Get(interface_id);
  657. CARBON_CHECK(!interface_info.is_complete(), "Interface is not incomplete");
  658. if (interface_info.is_being_defined()) {
  659. CARBON_DIAGNOSTIC(InterfaceIncompleteWithinDefinition, Note,
  660. "interface is currently being defined");
  661. builder.Note(interface_info.definition_id,
  662. InterfaceIncompleteWithinDefinition);
  663. } else {
  664. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  665. "interface was forward declared here");
  666. builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
  667. }
  668. }
  669. } // namespace Carbon::Check