type_completion.cpp 28 KB

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