type_completion.cpp 38 KB

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