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