type_completion.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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 "common/concepts.h"
  6. #include "llvm/ADT/SmallVector.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/check/cpp/import.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/check/inst.h"
  11. #include "toolchain/check/literal.h"
  12. #include "toolchain/check/type.h"
  13. #include "toolchain/diagnostics/format_providers.h"
  14. #include "toolchain/sem_ir/constant.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/specific_named_constraint.h"
  17. #include "toolchain/sem_ir/type_info.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. auto NoteIncompleteClass(Context& context, SemIR::ClassId class_id,
  21. DiagnosticBuilder& builder) -> void {
  22. const auto& class_info = context.classes().Get(class_id);
  23. CARBON_CHECK(!class_info.is_complete(), "Class is not incomplete");
  24. if (class_info.has_definition_started()) {
  25. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  26. "class is incomplete within its definition");
  27. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  28. } else {
  29. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  30. "class was forward declared here");
  31. builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
  32. }
  33. }
  34. auto NoteIncompleteInterface(Context& context, SemIR::InterfaceId interface_id,
  35. DiagnosticBuilder& builder) -> void {
  36. const auto& interface_info = context.interfaces().Get(interface_id);
  37. CARBON_CHECK(!interface_info.is_complete(), "Interface is not incomplete");
  38. if (interface_info.is_being_defined()) {
  39. CARBON_DIAGNOSTIC(InterfaceIncompleteWithinDefinition, Note,
  40. "interface is currently being defined");
  41. builder.Note(interface_info.definition_id,
  42. InterfaceIncompleteWithinDefinition);
  43. } else {
  44. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  45. "interface was forward declared here");
  46. builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
  47. }
  48. }
  49. static auto NoteIncompleteNamedConstraint(
  50. Context& context, SemIR::NamedConstraintId named_constraint_id,
  51. DiagnosticBuilder& builder) -> void {
  52. const auto& constraint = context.named_constraints().Get(named_constraint_id);
  53. CARBON_CHECK(!constraint.is_complete(), "Named constraint is not incomplete");
  54. if (constraint.is_being_defined()) {
  55. CARBON_DIAGNOSTIC(NamedConstraintIncompleteWithinDefinition, Note,
  56. "constraint is currently being defined");
  57. builder.Note(constraint.definition_id,
  58. NamedConstraintIncompleteWithinDefinition);
  59. } else {
  60. CARBON_DIAGNOSTIC(NamedConstraintForwardDeclaredHere, Note,
  61. "constraint was forward declared here");
  62. builder.Note(constraint.latest_decl_id(),
  63. NamedConstraintForwardDeclaredHere);
  64. }
  65. }
  66. template <typename T>
  67. requires SameAsOneOf<T, SemIR::Interface, SemIR::NamedConstraint>
  68. static auto ForEachRequireImpls(
  69. Context& context, const T& entity,
  70. llvm::function_ref<auto(const SemIR::RequireImpls&)->void> f) -> void {
  71. for (auto require_impls_id :
  72. context.require_impls_blocks().Get(entity.require_impls_block_id)) {
  73. const auto& require = context.require_impls().Get(require_impls_id);
  74. f(require);
  75. }
  76. }
  77. namespace {
  78. // Worklist-based type completion mechanism.
  79. //
  80. // When attempting to complete a type, we may find other types that also need to
  81. // be completed: types nested within that type, and the value representation of
  82. // the type. In order to complete a type without recursing arbitrarily deeply,
  83. // we use a worklist of tasks:
  84. //
  85. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  86. // nested within a type to the work list.
  87. // - A `BuildInfo` step computes the `CompleteTypeInfo` for a type, once all of
  88. // its nested types are complete, and marks the type as complete.
  89. class TypeCompleter {
  90. public:
  91. // `context` mut not be null.
  92. TypeCompleter(Context* context, SemIR::LocId loc_id,
  93. MakeDiagnosticBuilderFn diagnoser)
  94. : context_(context), loc_id_(loc_id), diagnoser_(diagnoser) {}
  95. // Attempts to complete the given type. Returns true if it is now complete,
  96. // false if it could not be completed.
  97. auto Complete(SemIR::TypeId type_id) -> bool;
  98. private:
  99. enum class Phase : int8_t {
  100. // The next step is to add nested types to the list of types to complete.
  101. AddNestedIncompleteTypes,
  102. // The next step is to build the `CompleteTypeInfo` for the type.
  103. BuildInfo,
  104. };
  105. struct WorkItem {
  106. SemIR::TypeId type_id;
  107. Phase phase;
  108. };
  109. // Adds `type_id` to the work list, if it's not already complete.
  110. auto Push(SemIR::TypeId type_id) -> void;
  111. // Runs the next step.
  112. auto ProcessStep() -> bool;
  113. // Adds any types nested within `type_inst` that need to be complete for
  114. // `type_inst` to be complete to our work list.
  115. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool;
  116. // Makes an empty value representation, which is used for types that have no
  117. // state, such as empty structs and tuples.
  118. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr;
  119. // Makes a dependent value representation, which is used for symbolic types.
  120. auto MakeDependentValueRepr(SemIR::TypeId type_id) const -> SemIR::ValueRepr;
  121. // Makes a value representation that uses pass-by-copy, copying the given
  122. // type.
  123. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  124. SemIR::ValueRepr::AggregateKind aggregate_kind =
  125. SemIR::ValueRepr::NotAggregate) const
  126. -> SemIR::ValueRepr;
  127. // Makes a value representation that uses pass-by-address with the given
  128. // pointee type.
  129. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  130. SemIR::ValueRepr::AggregateKind aggregate_kind =
  131. SemIR::ValueRepr::NotAggregate) const
  132. -> SemIR::ValueRepr;
  133. // Gets the value representation of a nested type, which should already be
  134. // complete.
  135. auto GetNestedInfo(SemIR::TypeId nested_type_id) const
  136. -> SemIR::CompleteTypeInfo;
  137. template <typename InstT>
  138. requires(InstT::Kind.template IsAnyOf<
  139. SemIR::AutoType, SemIR::BoolType, SemIR::BoundMethodType,
  140. SemIR::CharLiteralType, SemIR::ErrorInst, SemIR::FacetType,
  141. SemIR::FloatLiteralType, SemIR::FloatType, SemIR::IntType,
  142. SemIR::IntLiteralType, SemIR::NamespaceType, SemIR::PatternType,
  143. SemIR::PointerType, SemIR::SpecificFunctionType, SemIR::TypeType,
  144. SemIR::VtableType, SemIR::WitnessType>())
  145. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  146. -> SemIR::CompleteTypeInfo {
  147. return {.value_repr = MakeCopyValueRepr(type_id)};
  148. }
  149. auto BuildStructOrTupleValueRepr(size_t num_elements,
  150. SemIR::TypeId elementwise_rep,
  151. bool same_as_object_rep) const
  152. -> SemIR::ValueRepr;
  153. auto BuildInfoForInst(SemIR::TypeId type_id,
  154. SemIR::StructType struct_type) const
  155. -> SemIR::CompleteTypeInfo;
  156. auto BuildInfoForInst(SemIR::TypeId type_id,
  157. SemIR::TupleType tuple_type) const
  158. -> SemIR::CompleteTypeInfo;
  159. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::ArrayType /*inst*/) const
  160. -> SemIR::CompleteTypeInfo;
  161. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ClassType inst) const
  162. -> SemIR::CompleteTypeInfo;
  163. template <typename InstT>
  164. requires(InstT::Kind.template IsAnyOf<
  165. SemIR::AssociatedEntityType, SemIR::CppOverloadSetType,
  166. SemIR::FunctionType, SemIR::FunctionTypeWithSelfType,
  167. SemIR::GenericClassType, SemIR::GenericInterfaceType,
  168. SemIR::GenericNamedConstraintType, SemIR::InstType,
  169. SemIR::UnboundElementType, SemIR::WhereExpr>())
  170. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  171. -> SemIR::CompleteTypeInfo {
  172. // These types have no runtime operations, so we use an empty value
  173. // representation.
  174. //
  175. // TODO: There is information we could model here:
  176. // - For an interface, we could use a witness.
  177. // - For an associated entity, we could use an index into the witness.
  178. // - For an unbound element, we could use an index or offset.
  179. return {.value_repr = MakeEmptyValueRepr()};
  180. }
  181. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ConstType inst) const
  182. -> SemIR::CompleteTypeInfo;
  183. auto BuildInfoForInst(SemIR::TypeId type_id,
  184. SemIR::CustomLayoutType inst) const
  185. -> SemIR::CompleteTypeInfo;
  186. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  187. SemIR::MaybeUnformedType inst) const
  188. -> SemIR::CompleteTypeInfo;
  189. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  190. SemIR::PartialType inst) const
  191. -> SemIR::CompleteTypeInfo;
  192. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  193. SemIR::ImplWitnessAssociatedConstant inst) const
  194. -> SemIR::CompleteTypeInfo;
  195. template <typename InstT>
  196. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  197. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT inst) const
  198. -> SemIR::CompleteTypeInfo {
  199. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  200. }
  201. template <typename InstT>
  202. requires(InstT::Kind.is_symbolic_when_type())
  203. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  204. -> SemIR::CompleteTypeInfo {
  205. return {.value_repr = MakeDependentValueRepr(type_id)};
  206. }
  207. // Builds and returns the `CompleteTypeInfo` for the given type. All nested
  208. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  209. auto BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  210. -> SemIR::CompleteTypeInfo;
  211. Context* context_;
  212. llvm::SmallVector<WorkItem> work_list_;
  213. SemIR::LocId loc_id_;
  214. MakeDiagnosticBuilderFn diagnoser_;
  215. };
  216. } // namespace
  217. auto TypeCompleter::Complete(SemIR::TypeId type_id) -> bool {
  218. Push(type_id);
  219. while (!work_list_.empty()) {
  220. if (!ProcessStep()) {
  221. return false;
  222. }
  223. }
  224. return true;
  225. }
  226. auto TypeCompleter::Push(SemIR::TypeId type_id) -> void {
  227. if (!context_->types().IsComplete(type_id)) {
  228. work_list_.push_back(
  229. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  230. }
  231. }
  232. auto TypeCompleter::ProcessStep() -> bool {
  233. auto [type_id, phase] = work_list_.back();
  234. // We might have enqueued the same type more than once. Just skip the
  235. // type if it's already complete.
  236. if (context_->types().IsComplete(type_id)) {
  237. work_list_.pop_back();
  238. return true;
  239. }
  240. auto inst_id = context_->types().GetInstId(type_id);
  241. auto inst = context_->insts().Get(inst_id);
  242. auto old_work_list_size = work_list_.size();
  243. switch (phase) {
  244. case Phase::AddNestedIncompleteTypes:
  245. if (!AddNestedIncompleteTypes(inst)) {
  246. return false;
  247. }
  248. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  249. "AddNestedIncompleteTypes should not remove work items");
  250. work_list_[old_work_list_size - 1].phase = Phase::BuildInfo;
  251. break;
  252. case Phase::BuildInfo: {
  253. auto info = BuildInfo(type_id, inst);
  254. context_->types().SetComplete(type_id, info);
  255. CARBON_CHECK(old_work_list_size == work_list_.size(),
  256. "BuildInfo should not change work items");
  257. work_list_.pop_back();
  258. // Also complete the value representation type, if necessary. This
  259. // should never fail: the value representation shouldn't require any
  260. // additional nested types to be complete.
  261. if (!context_->types().IsComplete(info.value_repr.type_id)) {
  262. work_list_.push_back(
  263. {.type_id = info.value_repr.type_id, .phase = Phase::BuildInfo});
  264. }
  265. // For a pointer representation, the pointee also needs to be complete.
  266. if (info.value_repr.kind == SemIR::ValueRepr::Pointer) {
  267. if (info.value_repr.type_id == SemIR::ErrorInst::TypeId) {
  268. break;
  269. }
  270. auto pointee_type_id =
  271. context_->sem_ir().GetPointeeType(info.value_repr.type_id);
  272. if (!context_->types().IsComplete(pointee_type_id)) {
  273. work_list_.push_back(
  274. {.type_id = pointee_type_id, .phase = Phase::BuildInfo});
  275. }
  276. }
  277. break;
  278. }
  279. }
  280. return true;
  281. }
  282. auto TypeCompleter::AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  283. CARBON_KIND_SWITCH(type_inst) {
  284. case CARBON_KIND(SemIR::ArrayType inst): {
  285. Push(context_->types().GetTypeIdForTypeInstId(inst.element_type_inst_id));
  286. break;
  287. }
  288. case CARBON_KIND(SemIR::StructType inst): {
  289. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  290. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  291. }
  292. break;
  293. }
  294. case CARBON_KIND(SemIR::TupleType inst): {
  295. for (auto element_type_id : context_->types().GetBlockAsTypeIds(
  296. context_->inst_blocks().Get(inst.type_elements_id))) {
  297. Push(element_type_id);
  298. }
  299. break;
  300. }
  301. case CARBON_KIND(SemIR::ClassType inst): {
  302. auto& class_info = context_->classes().Get(inst.class_id);
  303. // If the class was imported from C++, ask Clang to try to complete it.
  304. if (!class_info.is_complete() && class_info.scope_id.has_value()) {
  305. auto& scope = context_->name_scopes().Get(class_info.scope_id);
  306. if (scope.clang_decl_context_id().has_value()) {
  307. if (!ImportClassDefinitionForClangDecl(
  308. *context_, loc_id_, inst.class_id,
  309. scope.clang_decl_context_id())) {
  310. // Clang produced a diagnostic. Don't produce one of our own.
  311. return false;
  312. }
  313. }
  314. }
  315. if (!class_info.is_complete()) {
  316. if (diagnoser_) {
  317. auto builder = diagnoser_();
  318. NoteIncompleteClass(*context_, inst.class_id, builder);
  319. builder.Emit();
  320. }
  321. return false;
  322. }
  323. if (inst.specific_id.has_value()) {
  324. ResolveSpecificDefinition(*context_, loc_id_, inst.specific_id);
  325. }
  326. if (auto adapted_type_id =
  327. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  328. adapted_type_id.has_value()) {
  329. Push(adapted_type_id);
  330. } else {
  331. Push(class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id));
  332. }
  333. break;
  334. }
  335. case CARBON_KIND(SemIR::ConstType inst): {
  336. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  337. break;
  338. }
  339. case CARBON_KIND(SemIR::CustomLayoutType inst): {
  340. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  341. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  342. }
  343. break;
  344. }
  345. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  346. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  347. break;
  348. }
  349. case CARBON_KIND(SemIR::PartialType inst): {
  350. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  351. break;
  352. }
  353. case CARBON_KIND(SemIR::FacetType inst): {
  354. auto identified_id =
  355. RequireIdentifiedFacetType(*context_, inst, diagnoser_);
  356. if (!identified_id.has_value()) {
  357. return false;
  358. }
  359. const auto& identified =
  360. context_->identified_facet_types().Get(identified_id);
  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)` has the same value representation as `T` if that value
  564. // representation preserves all the bytes of the value, including any padding
  565. // bits. Otherwise we need to use a different representation.
  566. auto inner_type_id = context_->types().GetTypeIdForTypeInstId(inst.inner_id);
  567. auto nested = GetNestedInfo(inner_type_id);
  568. if (nested.value_repr.kind == SemIR::ValueRepr::Custom) {
  569. nested.value_repr = MakePointerValueRepr(type_id);
  570. } else if (nested.value_repr.kind == SemIR::ValueRepr::Copy) {
  571. auto type_inst = context_->types().GetAsInst(nested.value_repr.type_id);
  572. // TODO: Should ValueRepr::IsCopyOfObjectRepr return false for `bool`?
  573. if (!nested.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  574. inner_type_id) ||
  575. type_inst.Is<SemIR::BoolType>()) {
  576. nested.value_repr = MakePointerValueRepr(type_id);
  577. }
  578. // TODO: Handle any other types that we treat as having discarded padding
  579. // bits. For now there are no such types, as all class types and all structs
  580. // and tuples with more than one element are passed indirectly.
  581. }
  582. return nested;
  583. }
  584. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  585. SemIR::PartialType inst) const
  586. -> SemIR::CompleteTypeInfo {
  587. // The value representation of `partial T` is the same as that of `T`.
  588. // Objects are not modifiable through their value representations.
  589. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  590. }
  591. auto TypeCompleter::BuildInfoForInst(
  592. SemIR::TypeId /*type_id*/, SemIR::ImplWitnessAssociatedConstant inst) const
  593. -> SemIR::CompleteTypeInfo {
  594. return GetNestedInfo(inst.type_id);
  595. }
  596. // Builds and returns the value representation for the given type. All nested
  597. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  598. auto TypeCompleter::BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  599. -> SemIR::CompleteTypeInfo {
  600. // Use overload resolution to select the implementation, producing compile
  601. // errors when BuildInfoForInst isn't defined for a given instruction.
  602. CARBON_KIND_SWITCH(inst) {
  603. #define CARBON_SEM_IR_INST_KIND(Name) \
  604. case CARBON_KIND(SemIR::Name typed_inst): { \
  605. return BuildInfoForInst(type_id, typed_inst); \
  606. }
  607. #include "toolchain/sem_ir/inst_kind.def"
  608. }
  609. }
  610. auto TryToCompleteType(Context& context, SemIR::TypeId type_id,
  611. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  612. -> bool {
  613. return TypeCompleter(&context, loc_id, diagnoser).Complete(type_id);
  614. }
  615. auto CompleteTypeOrCheckFail(Context& context, SemIR::TypeId type_id) -> void {
  616. bool complete =
  617. TypeCompleter(&context, SemIR::LocId::None, nullptr).Complete(type_id);
  618. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  619. context.types().GetAsInst(type_id));
  620. }
  621. auto RequireCompleteType(Context& context, SemIR::TypeId type_id,
  622. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  623. -> bool {
  624. CARBON_CHECK(diagnoser);
  625. if (!TypeCompleter(&context, loc_id, diagnoser).Complete(type_id)) {
  626. return false;
  627. }
  628. // For a symbolic type, create an instruction to require the corresponding
  629. // specific type to be complete.
  630. if (type_id.is_symbolic()) {
  631. // TODO: Deduplicate these.
  632. AddInstInNoBlock(
  633. context, loc_id,
  634. SemIR::RequireCompleteType{
  635. .type_id =
  636. GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  637. .complete_type_inst_id = context.types().GetInstId(type_id)});
  638. }
  639. return true;
  640. }
  641. // Adds a note to a diagnostic explaining that a class is abstract.
  642. static auto NoteAbstractClass(Context& context, SemIR::ClassId class_id,
  643. bool direct_use, DiagnosticBuilder& builder)
  644. -> void {
  645. const auto& class_info = context.classes().Get(class_id);
  646. CARBON_CHECK(
  647. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  648. "Class is not abstract");
  649. CARBON_DIAGNOSTIC(
  650. ClassAbstractHere, Note,
  651. "{0:=0:uses class that|=1:class} was declared abstract here",
  652. Diagnostics::IntAsSelect);
  653. builder.Note(class_info.definition_id, ClassAbstractHere,
  654. static_cast<int>(direct_use));
  655. }
  656. auto RequireConcreteType(Context& context, SemIR::TypeId type_id,
  657. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  658. MakeDiagnosticBuilderFn abstract_diagnoser) -> bool {
  659. // TODO: For symbolic types, should add an implicit constraint that they are
  660. // not abstract.
  661. CARBON_CHECK(abstract_diagnoser);
  662. // The representation of a facet type does not depend on its definition, so
  663. // they are considered "concrete" even when not complete.
  664. if (context.types().IsFacetType(type_id)) {
  665. return true;
  666. }
  667. if (!RequireCompleteType(context, type_id, loc_id, diagnoser)) {
  668. return false;
  669. }
  670. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  671. if (complete_info.abstract_class_id.has_value()) {
  672. auto builder = abstract_diagnoser();
  673. if (builder) {
  674. bool direct_use = false;
  675. if (auto inst = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  676. if (inst->class_id == complete_info.abstract_class_id) {
  677. direct_use = true;
  678. }
  679. }
  680. NoteAbstractClass(context, complete_info.abstract_class_id, direct_use,
  681. builder);
  682. builder.Emit();
  683. }
  684. return false;
  685. }
  686. return true;
  687. }
  688. // Require all named constraints in the facet type are identified. For a named
  689. // constraint, this means the constraint definition is complete.
  690. static auto RequireIdentifiedNamedConstraints(
  691. Context& context, const SemIR::FacetTypeInfo& facet_type_info,
  692. MakeDiagnosticBuilderFn diagnoser) -> bool {
  693. auto named_constraint_ids = llvm::map_range(
  694. llvm::concat<const SemIR::SpecificNamedConstraint>(
  695. facet_type_info.extend_named_constraints,
  696. facet_type_info.self_impls_named_constraints),
  697. [](SemIR::SpecificNamedConstraint s) { return s.named_constraint_id; });
  698. for (auto named_constraint_id : named_constraint_ids) {
  699. const auto& constraint =
  700. context.named_constraints().Get(named_constraint_id);
  701. if (!constraint.is_complete()) {
  702. if (diagnoser) {
  703. auto builder = diagnoser();
  704. NoteIncompleteNamedConstraint(context, named_constraint_id, builder);
  705. builder.Emit();
  706. }
  707. return false;
  708. }
  709. }
  710. return true;
  711. }
  712. auto RequireIdentifiedFacetType(Context& context,
  713. const SemIR::FacetType& facet_type,
  714. MakeDiagnosticBuilderFn diagnoser)
  715. -> SemIR::IdentifiedFacetTypeId {
  716. if (auto identified_id =
  717. context.identified_facet_types().TryGetId(facet_type.facet_type_id);
  718. identified_id.has_value()) {
  719. return identified_id;
  720. }
  721. // Work queue.
  722. llvm::SmallVector<SemIR::FacetTypeId> extend_facet_types = {
  723. facet_type.facet_type_id};
  724. llvm::SmallVector<SemIR::FacetTypeId> impls_facet_types;
  725. // Outputs for the IdentifiedFacetType.
  726. llvm::SmallVector<SemIR::SpecificInterface> extends;
  727. llvm::SmallVector<SemIR::SpecificInterface> self_impls;
  728. while (true) {
  729. auto next_facet_type_id = SemIR::FacetTypeId::None;
  730. bool facet_type_extends = false;
  731. if (!extend_facet_types.empty()) {
  732. next_facet_type_id = extend_facet_types.pop_back_val();
  733. facet_type_extends = true;
  734. } else if (!impls_facet_types.empty()) {
  735. next_facet_type_id = impls_facet_types.pop_back_val();
  736. facet_type_extends = false;
  737. } else {
  738. break;
  739. }
  740. const auto& facet_type_info = context.facet_types().Get(next_facet_type_id);
  741. if (!RequireIdentifiedNamedConstraints(context, facet_type_info,
  742. diagnoser)) {
  743. return SemIR::IdentifiedFacetTypeId::None;
  744. }
  745. if (facet_type_extends) {
  746. llvm::append_range(extends, facet_type_info.extend_constraints);
  747. } else {
  748. llvm::append_range(self_impls, facet_type_info.extend_constraints);
  749. }
  750. llvm::append_range(self_impls, facet_type_info.self_impls_constraints);
  751. for (auto extend : facet_type_info.extend_named_constraints) {
  752. const auto& constraint =
  753. context.named_constraints().Get(extend.named_constraint_id);
  754. ForEachRequireImpls(
  755. context, constraint, [&](const SemIR::RequireImpls& require) {
  756. if (facet_type_extends && require.extend_self) {
  757. extend_facet_types.push_back(require.facet_type_id);
  758. } else {
  759. impls_facet_types.push_back(require.facet_type_id);
  760. }
  761. });
  762. }
  763. for (auto impls : facet_type_info.self_impls_named_constraints) {
  764. const auto& constraint =
  765. context.named_constraints().Get(impls.named_constraint_id);
  766. ForEachRequireImpls(context, constraint,
  767. [&](const SemIR::RequireImpls& require) {
  768. impls_facet_types.push_back(require.facet_type_id);
  769. });
  770. }
  771. }
  772. // TODO: Process other kinds of requirements.
  773. return context.identified_facet_types().Add(facet_type.facet_type_id,
  774. {extends, self_impls});
  775. }
  776. auto AsCompleteType(Context& context, SemIR::TypeId type_id,
  777. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  778. -> SemIR::TypeId {
  779. return RequireCompleteType(context, type_id, loc_id, diagnoser)
  780. ? type_id
  781. : SemIR::ErrorInst::TypeId;
  782. }
  783. // Returns the type `type_id` if it is a concrete type, or produces an
  784. // incomplete or abstract type error and returns an error type. This is a
  785. // convenience wrapper around `RequireConcreteType`.
  786. auto AsConcreteType(Context& context, SemIR::TypeId type_id,
  787. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  788. MakeDiagnosticBuilderFn abstract_diagnoser)
  789. -> SemIR::TypeId {
  790. return RequireConcreteType(context, type_id, loc_id, diagnoser,
  791. abstract_diagnoser)
  792. ? type_id
  793. : SemIR::ErrorInst::TypeId;
  794. }
  795. } // namespace Carbon::Check