type_completion.cpp 28 KB

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