type_completion.cpp 29 KB

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