type_completion.cpp 35 KB

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