type_completion.cpp 31 KB

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