type_completion.cpp 42 KB

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