type_completion.cpp 38 KB

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