type_completion.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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. if (diagnoser_) {
  331. CARBON_DIAGNOSTIC(CppVoidIncomplete, Note,
  332. "`Cpp.void` is always-incomplete");
  333. diagnoser_().Note(SemIR::LocId::None, CppVoidIncomplete).Emit();
  334. }
  335. return false;
  336. }
  337. case CARBON_KIND(SemIR::CustomLayoutType inst): {
  338. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  339. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  340. }
  341. break;
  342. }
  343. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  344. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  345. break;
  346. }
  347. case CARBON_KIND(SemIR::PartialType inst): {
  348. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  349. break;
  350. }
  351. case CARBON_KIND(SemIR::FacetType inst): {
  352. // TODO: Get the complete facet type here.
  353. auto identified_id =
  354. RequireIdentifiedFacetType(*context_, inst, diagnoser_);
  355. if (!identified_id.has_value()) {
  356. return false;
  357. }
  358. const auto& identified =
  359. context_->identified_facet_types().Get(identified_id);
  360. // Every mentioned interface needs to be complete.
  361. for (auto req_interface : identified.required_interfaces()) {
  362. auto interface_id = req_interface.interface_id;
  363. const auto& interface = context_->interfaces().Get(interface_id);
  364. if (!interface.is_complete()) {
  365. if (diagnoser_) {
  366. auto builder = diagnoser_();
  367. NoteIncompleteInterface(*context_, interface_id, builder);
  368. builder.Emit();
  369. }
  370. return false;
  371. }
  372. if (req_interface.specific_id.has_value()) {
  373. ResolveSpecificDefinition(*context_, loc_id_,
  374. req_interface.specific_id);
  375. }
  376. }
  377. break;
  378. }
  379. default:
  380. break;
  381. }
  382. return true;
  383. }
  384. auto TypeCompleter::MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  385. return {.kind = SemIR::ValueRepr::None,
  386. .type_id = GetTupleType(*context_, {})};
  387. }
  388. auto TypeCompleter::MakeDependentValueRepr(SemIR::TypeId type_id) const
  389. -> SemIR::ValueRepr {
  390. return {.kind = SemIR::ValueRepr::Dependent, .type_id = type_id};
  391. }
  392. auto TypeCompleter::MakeCopyValueRepr(
  393. SemIR::TypeId rep_id, SemIR::ValueRepr::AggregateKind aggregate_kind) const
  394. -> SemIR::ValueRepr {
  395. return {.kind = SemIR::ValueRepr::Copy,
  396. .aggregate_kind = aggregate_kind,
  397. .type_id = rep_id};
  398. }
  399. auto TypeCompleter::MakePointerValueRepr(
  400. SemIR::TypeId pointee_id,
  401. SemIR::ValueRepr::AggregateKind aggregate_kind) const -> SemIR::ValueRepr {
  402. // TODO: Should we add `const` qualification to `pointee_id`?
  403. return {.kind = SemIR::ValueRepr::Pointer,
  404. .aggregate_kind = aggregate_kind,
  405. .type_id = GetPointerType(*context_,
  406. context_->types().GetInstId(pointee_id))};
  407. }
  408. auto TypeCompleter::GetNestedInfo(SemIR::TypeId nested_type_id) const
  409. -> SemIR::CompleteTypeInfo {
  410. CARBON_CHECK(context_->types().IsComplete(nested_type_id),
  411. "Nested type should already be complete");
  412. auto info = context_->types().GetCompleteTypeInfo(nested_type_id);
  413. CARBON_CHECK(info.value_repr.kind != SemIR::ValueRepr::Unknown,
  414. "Complete type should have a value representation");
  415. return info;
  416. }
  417. auto TypeCompleter::BuildStructOrTupleValueRepr(size_t num_elements,
  418. SemIR::TypeId elementwise_rep,
  419. bool same_as_object_rep) const
  420. -> SemIR::ValueRepr {
  421. SemIR::ValueRepr::AggregateKind aggregate_kind =
  422. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  423. : SemIR::ValueRepr::ValueAggregate;
  424. if (num_elements == 1) {
  425. // The value representation for a struct or tuple with a single element
  426. // is a struct or tuple containing the value representation of the
  427. // element.
  428. // TODO: Consider doing the same whenever `elementwise_rep` is
  429. // sufficiently small.
  430. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  431. }
  432. // For a struct or tuple with multiple fields, we use a pointer
  433. // to the elementwise value representation.
  434. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  435. }
  436. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  437. SemIR::StructType struct_type) const
  438. -> SemIR::CompleteTypeInfo {
  439. auto fields = context_->struct_type_fields().Get(struct_type.fields_id);
  440. if (fields.empty()) {
  441. return {.value_repr = MakeEmptyValueRepr()};
  442. }
  443. // Find the value representation for each field, and construct a struct
  444. // of value representations.
  445. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  446. value_rep_fields.reserve(fields.size());
  447. bool same_as_object_rep = true;
  448. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  449. for (auto field : fields) {
  450. auto field_type_id =
  451. context_->types().GetTypeIdForTypeInstId(field.type_inst_id);
  452. auto field_info = GetNestedInfo(field_type_id);
  453. if (!field_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  454. field_type_id)) {
  455. same_as_object_rep = false;
  456. field.type_inst_id =
  457. context_->types().GetInstId(field_info.value_repr.type_id);
  458. }
  459. value_rep_fields.push_back(field);
  460. // Take the first non-None abstract_class_id, if any.
  461. if (field_info.abstract_class_id.has_value() &&
  462. !abstract_class_id.has_value()) {
  463. abstract_class_id = field_info.abstract_class_id;
  464. }
  465. }
  466. auto value_rep =
  467. same_as_object_rep
  468. ? type_id
  469. : GetStructType(
  470. *context_,
  471. context_->struct_type_fields().AddCanonical(value_rep_fields));
  472. return {.value_repr = BuildStructOrTupleValueRepr(fields.size(), value_rep,
  473. same_as_object_rep),
  474. .abstract_class_id = abstract_class_id};
  475. }
  476. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  477. SemIR::TupleType tuple_type) const
  478. -> SemIR::CompleteTypeInfo {
  479. // TODO: Share more code with structs.
  480. auto elements = context_->inst_blocks().Get(tuple_type.type_elements_id);
  481. if (elements.empty()) {
  482. return {.value_repr = MakeEmptyValueRepr()};
  483. }
  484. // Find the value representation for each element, and construct a tuple
  485. // of value representations.
  486. llvm::SmallVector<SemIR::InstId> value_rep_elements;
  487. value_rep_elements.reserve(elements.size());
  488. bool same_as_object_rep = true;
  489. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  490. for (auto element_type_id : context_->types().GetBlockAsTypeIds(elements)) {
  491. auto element_info = GetNestedInfo(element_type_id);
  492. if (!element_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  493. element_type_id)) {
  494. same_as_object_rep = false;
  495. }
  496. value_rep_elements.push_back(
  497. context_->types().GetInstId(element_info.value_repr.type_id));
  498. // Take the first non-None abstract_class_id, if any.
  499. if (element_info.abstract_class_id.has_value() &&
  500. !abstract_class_id.has_value()) {
  501. abstract_class_id = element_info.abstract_class_id;
  502. }
  503. }
  504. auto value_rep = same_as_object_rep
  505. ? type_id
  506. : GetTupleType(*context_, value_rep_elements);
  507. return {.value_repr = BuildStructOrTupleValueRepr(elements.size(), value_rep,
  508. same_as_object_rep),
  509. .abstract_class_id = abstract_class_id};
  510. }
  511. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  512. SemIR::ArrayType /*inst*/) const
  513. -> SemIR::CompleteTypeInfo {
  514. // For arrays, it's convenient to always use a pointer representation,
  515. // even when the array has zero or one element, in order to support
  516. // indexing.
  517. return {.value_repr =
  518. MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate)};
  519. }
  520. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  521. SemIR::ClassType inst) const
  522. -> SemIR::CompleteTypeInfo {
  523. auto& class_info = context_->classes().Get(inst.class_id);
  524. auto abstract_class_id =
  525. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract
  526. ? inst.class_id
  527. : SemIR::ClassId::None;
  528. // The value representation of an adapter is the value representation of
  529. // its adapted type.
  530. if (auto adapted_type_id =
  531. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  532. adapted_type_id.has_value()) {
  533. auto info = GetNestedInfo(adapted_type_id);
  534. info.abstract_class_id = abstract_class_id;
  535. return info;
  536. }
  537. // Otherwise, the value representation for a class is a pointer to the
  538. // object representation.
  539. // TODO: Support customized value representations for classes.
  540. // TODO: Pick a better value representation when possible.
  541. return {.value_repr = MakePointerValueRepr(
  542. class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id),
  543. SemIR::ValueRepr::ObjectAggregate),
  544. .abstract_class_id = abstract_class_id};
  545. }
  546. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  547. SemIR::ConstType inst) const
  548. -> SemIR::CompleteTypeInfo {
  549. // The value representation of `const T` is the same as that of `T`.
  550. // Objects are not modifiable through their value representations.
  551. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  552. }
  553. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  554. SemIR::CustomLayoutType /*inst*/) const
  555. -> SemIR::CompleteTypeInfo {
  556. // TODO: Should we support other value representations for custom layout
  557. // types?
  558. return {.value_repr = MakePointerValueRepr(type_id)};
  559. }
  560. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  561. SemIR::MaybeUnformedType /*inst*/) const
  562. -> SemIR::CompleteTypeInfo {
  563. // `MaybeUnformed(T)` always has a pointer value representation, regardless of
  564. // `T`'s value representation.
  565. return {.value_repr = MakePointerValueRepr(type_id)};
  566. }
  567. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  568. SemIR::PartialType inst) const
  569. -> SemIR::CompleteTypeInfo {
  570. // The value representation of `partial T` is the same as that of `T`.
  571. // Objects are not modifiable through their value representations.
  572. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  573. }
  574. auto TypeCompleter::BuildInfoForInst(
  575. SemIR::TypeId /*type_id*/, SemIR::ImplWitnessAssociatedConstant inst) const
  576. -> SemIR::CompleteTypeInfo {
  577. return GetNestedInfo(inst.type_id);
  578. }
  579. // Builds and returns the value representation for the given type. All nested
  580. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  581. auto TypeCompleter::BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  582. -> SemIR::CompleteTypeInfo {
  583. // Use overload resolution to select the implementation, producing compile
  584. // errors when BuildInfoForInst isn't defined for a given instruction.
  585. CARBON_KIND_SWITCH(inst) {
  586. #define CARBON_SEM_IR_INST_KIND(Name) \
  587. case CARBON_KIND(SemIR::Name typed_inst): { \
  588. return BuildInfoForInst(type_id, typed_inst); \
  589. }
  590. #include "toolchain/sem_ir/inst_kind.def"
  591. }
  592. }
  593. auto TryToCompleteType(Context& context, SemIR::TypeId type_id,
  594. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  595. -> bool {
  596. return TypeCompleter(&context, loc_id, diagnoser).Complete(type_id);
  597. }
  598. auto CompleteTypeOrCheckFail(Context& context, SemIR::TypeId type_id) -> void {
  599. bool complete =
  600. TypeCompleter(&context, SemIR::LocId::None, nullptr).Complete(type_id);
  601. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  602. context.types().GetAsInst(type_id));
  603. }
  604. auto RequireCompleteType(Context& context, SemIR::TypeId type_id,
  605. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  606. -> bool {
  607. CARBON_CHECK(diagnoser);
  608. if (!TypeCompleter(&context, loc_id, diagnoser).Complete(type_id)) {
  609. return false;
  610. }
  611. // For a symbolic type, create an instruction to require the corresponding
  612. // specific type to be complete.
  613. if (type_id.is_symbolic()) {
  614. // TODO: Deduplicate these.
  615. AddInstInNoBlock(
  616. context, loc_id,
  617. SemIR::RequireCompleteType{
  618. .type_id =
  619. GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  620. .complete_type_inst_id = context.types().GetInstId(type_id)});
  621. }
  622. return true;
  623. }
  624. // Adds a note to a diagnostic explaining that a class is abstract.
  625. static auto NoteAbstractClass(Context& context, SemIR::ClassId class_id,
  626. bool direct_use, DiagnosticBuilder& builder)
  627. -> void {
  628. const auto& class_info = context.classes().Get(class_id);
  629. CARBON_CHECK(
  630. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  631. "Class is not abstract");
  632. CARBON_DIAGNOSTIC(
  633. ClassAbstractHere, Note,
  634. "{0:=0:uses class that|=1:class} was declared abstract here",
  635. Diagnostics::IntAsSelect);
  636. builder.Note(class_info.definition_id, ClassAbstractHere,
  637. static_cast<int>(direct_use));
  638. }
  639. auto RequireConcreteType(Context& context, SemIR::TypeId type_id,
  640. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  641. MakeDiagnosticBuilderFn abstract_diagnoser) -> bool {
  642. // TODO: For symbolic types, should add an implicit constraint that they are
  643. // not abstract.
  644. CARBON_CHECK(abstract_diagnoser);
  645. // The representation of a facet type does not depend on its definition, so
  646. // they are considered "concrete" even when not complete.
  647. if (context.types().IsFacetType(type_id)) {
  648. return true;
  649. }
  650. if (!RequireCompleteType(context, type_id, loc_id, diagnoser)) {
  651. return false;
  652. }
  653. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  654. if (complete_info.abstract_class_id.has_value()) {
  655. auto builder = abstract_diagnoser();
  656. if (builder) {
  657. bool direct_use = false;
  658. if (auto inst = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  659. if (inst->class_id == complete_info.abstract_class_id) {
  660. direct_use = true;
  661. }
  662. }
  663. NoteAbstractClass(context, complete_info.abstract_class_id, direct_use,
  664. builder);
  665. builder.Emit();
  666. }
  667. return false;
  668. }
  669. return true;
  670. }
  671. auto RequireIdentifiedFacetType(Context& context,
  672. const SemIR::FacetType& facet_type,
  673. MakeDiagnosticBuilderFn diagnoser)
  674. -> SemIR::IdentifiedFacetTypeId {
  675. if (auto identified_id =
  676. context.identified_facet_types().TryGetId(facet_type.facet_type_id);
  677. identified_id.has_value()) {
  678. return identified_id;
  679. }
  680. const auto& facet_type_info =
  681. context.facet_types().Get(facet_type.facet_type_id);
  682. auto named_constraint_ids = llvm::map_range(
  683. llvm::concat<const SemIR::SpecificNamedConstraint>(
  684. facet_type_info.extend_named_constraints,
  685. facet_type_info.self_impls_named_constraints),
  686. [](SemIR::SpecificNamedConstraint s) { return s.named_constraint_id; });
  687. for (auto named_constraint_id : named_constraint_ids) {
  688. const auto& constraint =
  689. context.named_constraints().Get(named_constraint_id);
  690. if (!constraint.is_complete()) {
  691. if (diagnoser) {
  692. auto builder = diagnoser();
  693. NoteIncompleteNamedConstraint(context, named_constraint_id, builder);
  694. builder.Emit();
  695. }
  696. return SemIR::IdentifiedFacetTypeId::None;
  697. }
  698. }
  699. // TODO: expand named constraints
  700. // TODO: Process other kinds of requirements.
  701. return context.identified_facet_types().Add(
  702. facet_type.facet_type_id, {facet_type_info.extend_constraints,
  703. facet_type_info.self_impls_constraints});
  704. }
  705. auto AsCompleteType(Context& context, SemIR::TypeId type_id,
  706. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  707. -> SemIR::TypeId {
  708. return RequireCompleteType(context, type_id, loc_id, diagnoser)
  709. ? type_id
  710. : SemIR::ErrorInst::TypeId;
  711. }
  712. // Returns the type `type_id` if it is a concrete type, or produces an
  713. // incomplete or abstract type error and returns an error type. This is a
  714. // convenience wrapper around `RequireConcreteType`.
  715. auto AsConcreteType(Context& context, SemIR::TypeId type_id,
  716. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  717. MakeDiagnosticBuilderFn abstract_diagnoser)
  718. -> SemIR::TypeId {
  719. return RequireConcreteType(context, type_id, loc_id, diagnoser,
  720. abstract_diagnoser)
  721. ? type_id
  722. : SemIR::ErrorInst::TypeId;
  723. }
  724. } // namespace Carbon::Check