type_completion.cpp 31 KB

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