type_completion.cpp 28 KB

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