type_completion.cpp 32 KB

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