type_completion.cpp 35 KB

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