type_completion.cpp 29 KB

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