type_completion.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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 "llvm/ADT/SmallVector.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/generic.h"
  8. #include "toolchain/check/inst.h"
  9. #include "toolchain/check/type.h"
  10. #include "toolchain/diagnostics/format_providers.h"
  11. #include "toolchain/sem_ir/ids.h"
  12. namespace Carbon::Check {
  13. namespace {
  14. // Worklist-based type completion mechanism.
  15. //
  16. // When attempting to complete a type, we may find other types that also need to
  17. // be completed: types nested within that type, and the value representation of
  18. // the type. In order to complete a type without recursing arbitrarily deeply,
  19. // we use a worklist of tasks:
  20. //
  21. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  22. // nested within a type to the work list.
  23. // - A `BuildInfo` step computes the `CompleteTypeInfo` for a type, once all of
  24. // its nested types are complete, and marks the type as complete.
  25. class TypeCompleter {
  26. public:
  27. TypeCompleter(Context& context, SemIRLoc loc,
  28. Context::BuildDiagnosticFn diagnoser)
  29. : context_(context), loc_(loc), diagnoser_(diagnoser) {}
  30. // Attempts to complete the given type. Returns true if it is now complete,
  31. // false if it could not be completed.
  32. auto Complete(SemIR::TypeId type_id) -> bool;
  33. private:
  34. enum class Phase : int8_t {
  35. // The next step is to add nested types to the list of types to complete.
  36. AddNestedIncompleteTypes,
  37. // The next step is to build the `CompleteTypeInfo` for the type.
  38. BuildInfo,
  39. };
  40. struct WorkItem {
  41. SemIR::TypeId type_id;
  42. Phase phase;
  43. };
  44. // Adds `type_id` to the work list, if it's not already complete.
  45. auto Push(SemIR::TypeId type_id) -> void;
  46. // Runs the next step.
  47. auto ProcessStep() -> bool;
  48. // Adds any types nested within `type_inst` that need to be complete for
  49. // `type_inst` to be complete to our work list.
  50. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool;
  51. // Makes an empty value representation, which is used for types that have no
  52. // state, such as empty structs and tuples.
  53. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr;
  54. // Makes a value representation that uses pass-by-copy, copying the given
  55. // type.
  56. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  57. SemIR::ValueRepr::AggregateKind aggregate_kind =
  58. SemIR::ValueRepr::NotAggregate) const
  59. -> SemIR::ValueRepr;
  60. // Makes a value representation that uses pass-by-address with the given
  61. // pointee type.
  62. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  63. SemIR::ValueRepr::AggregateKind aggregate_kind =
  64. SemIR::ValueRepr::NotAggregate) const
  65. -> SemIR::ValueRepr;
  66. // Gets the value representation of a nested type, which should already be
  67. // complete.
  68. auto GetNestedInfo(SemIR::TypeId nested_type_id) const
  69. -> SemIR::CompleteTypeInfo;
  70. template <typename InstT>
  71. requires(
  72. InstT::Kind.template IsAnyOf<
  73. SemIR::AutoType, SemIR::BoolType, SemIR::BoundMethodType,
  74. SemIR::ErrorInst, SemIR::FloatType, SemIR::IntType,
  75. SemIR::IntLiteralType, SemIR::LegacyFloatType, SemIR::NamespaceType,
  76. SemIR::PointerType, SemIR::SpecificFunctionType, SemIR::TypeType,
  77. SemIR::VtableType, SemIR::WitnessType>())
  78. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  79. -> SemIR::CompleteTypeInfo {
  80. return {.value_repr = MakeCopyValueRepr(type_id)};
  81. }
  82. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::StringType /*inst*/) const
  83. -> SemIR::CompleteTypeInfo;
  84. auto BuildStructOrTupleValueRepr(size_t num_elements,
  85. SemIR::TypeId elementwise_rep,
  86. bool same_as_object_rep) const
  87. -> SemIR::ValueRepr;
  88. auto BuildInfoForInst(SemIR::TypeId type_id,
  89. SemIR::StructType struct_type) const
  90. -> SemIR::CompleteTypeInfo;
  91. auto BuildInfoForInst(SemIR::TypeId type_id,
  92. SemIR::TupleType tuple_type) const
  93. -> SemIR::CompleteTypeInfo;
  94. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::ArrayType /*inst*/) const
  95. -> SemIR::CompleteTypeInfo;
  96. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ClassType inst) const
  97. -> SemIR::CompleteTypeInfo;
  98. template <typename InstT>
  99. requires(InstT::Kind.template IsAnyOf<
  100. SemIR::AssociatedEntityType, SemIR::FacetType, SemIR::FunctionType,
  101. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  102. SemIR::GenericInterfaceType, SemIR::UnboundElementType,
  103. SemIR::WhereExpr>())
  104. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  105. -> SemIR::CompleteTypeInfo {
  106. // These types have no runtime operations, so we use an empty value
  107. // representation.
  108. //
  109. // TODO: There is information we could model here:
  110. // - For an interface, we could use a witness.
  111. // - For an associated entity, we could use an index into the witness.
  112. // - For an unbound element, we could use an index or offset.
  113. return {.value_repr = MakeEmptyValueRepr()};
  114. }
  115. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ConstType inst) const
  116. -> SemIR::CompleteTypeInfo;
  117. template <typename InstT>
  118. requires(InstT::Kind.constant_kind() ==
  119. SemIR::InstConstantKind::SymbolicOnly ||
  120. InstT::Kind.is_type() == SemIR::InstIsType::Never)
  121. auto BuildInfoForInst(SemIR::TypeId type_id, InstT inst) const
  122. -> SemIR::CompleteTypeInfo {
  123. if constexpr (InstT::Kind.is_type() == SemIR::InstIsType::Never) {
  124. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  125. } else {
  126. // For symbolic types, we arbitrarily pick a copy representation.
  127. return {.value_repr = MakeCopyValueRepr(type_id)};
  128. }
  129. }
  130. // Builds and returns the `CompleteTypeInfo` for the given type. All nested
  131. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  132. auto BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  133. -> SemIR::CompleteTypeInfo;
  134. Context& context_;
  135. llvm::SmallVector<WorkItem> work_list_;
  136. SemIRLoc loc_;
  137. Context::BuildDiagnosticFn diagnoser_;
  138. };
  139. } // namespace
  140. auto TypeCompleter::Complete(SemIR::TypeId type_id) -> bool {
  141. Push(type_id);
  142. while (!work_list_.empty()) {
  143. if (!ProcessStep()) {
  144. return false;
  145. }
  146. }
  147. return true;
  148. }
  149. auto TypeCompleter::Push(SemIR::TypeId type_id) -> void {
  150. if (!context_.types().IsComplete(type_id)) {
  151. work_list_.push_back(
  152. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  153. }
  154. }
  155. auto TypeCompleter::ProcessStep() -> bool {
  156. auto [type_id, phase] = work_list_.back();
  157. // We might have enqueued the same type more than once. Just skip the
  158. // type if it's already complete.
  159. if (context_.types().IsComplete(type_id)) {
  160. work_list_.pop_back();
  161. return true;
  162. }
  163. auto inst_id = context_.types().GetInstId(type_id);
  164. auto inst = context_.insts().Get(inst_id);
  165. auto old_work_list_size = work_list_.size();
  166. switch (phase) {
  167. case Phase::AddNestedIncompleteTypes:
  168. if (!AddNestedIncompleteTypes(inst)) {
  169. return false;
  170. }
  171. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  172. "AddNestedIncompleteTypes should not remove work items");
  173. work_list_[old_work_list_size - 1].phase = Phase::BuildInfo;
  174. break;
  175. case Phase::BuildInfo: {
  176. auto info = BuildInfo(type_id, inst);
  177. context_.types().SetComplete(type_id, info);
  178. CARBON_CHECK(old_work_list_size == work_list_.size(),
  179. "BuildInfo should not change work items");
  180. work_list_.pop_back();
  181. // Also complete the value representation type, if necessary. This
  182. // should never fail: the value representation shouldn't require any
  183. // additional nested types to be complete.
  184. if (!context_.types().IsComplete(info.value_repr.type_id)) {
  185. work_list_.push_back(
  186. {.type_id = info.value_repr.type_id, .phase = Phase::BuildInfo});
  187. }
  188. // For a pointer representation, the pointee also needs to be complete.
  189. if (info.value_repr.kind == SemIR::ValueRepr::Pointer) {
  190. if (info.value_repr.type_id == SemIR::ErrorInst::SingletonTypeId) {
  191. break;
  192. }
  193. auto pointee_type_id =
  194. context_.sem_ir().GetPointeeType(info.value_repr.type_id);
  195. if (!context_.types().IsComplete(pointee_type_id)) {
  196. work_list_.push_back(
  197. {.type_id = pointee_type_id, .phase = Phase::BuildInfo});
  198. }
  199. }
  200. break;
  201. }
  202. }
  203. return true;
  204. }
  205. auto TypeCompleter::AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  206. CARBON_KIND_SWITCH(type_inst) {
  207. case CARBON_KIND(SemIR::ArrayType inst): {
  208. Push(inst.element_type_id);
  209. break;
  210. }
  211. case CARBON_KIND(SemIR::StructType inst): {
  212. for (auto field : context_.struct_type_fields().Get(inst.fields_id)) {
  213. Push(field.type_id);
  214. }
  215. break;
  216. }
  217. case CARBON_KIND(SemIR::TupleType inst): {
  218. for (auto element_type_id :
  219. context_.type_blocks().Get(inst.elements_id)) {
  220. Push(element_type_id);
  221. }
  222. break;
  223. }
  224. case CARBON_KIND(SemIR::ClassType inst): {
  225. auto& class_info = context_.classes().Get(inst.class_id);
  226. if (!class_info.is_defined()) {
  227. if (diagnoser_) {
  228. auto builder = diagnoser_();
  229. NoteIncompleteClass(context_, inst.class_id, builder);
  230. builder.Emit();
  231. }
  232. return false;
  233. }
  234. if (inst.specific_id.has_value()) {
  235. ResolveSpecificDefinition(context_, loc_, inst.specific_id);
  236. }
  237. if (auto adapted_type_id =
  238. class_info.GetAdaptedType(context_.sem_ir(), inst.specific_id);
  239. adapted_type_id.has_value()) {
  240. Push(adapted_type_id);
  241. } else {
  242. Push(class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id));
  243. }
  244. break;
  245. }
  246. case CARBON_KIND(SemIR::ConstType inst): {
  247. Push(inst.inner_id);
  248. break;
  249. }
  250. default:
  251. break;
  252. }
  253. return true;
  254. }
  255. auto TypeCompleter::MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  256. return {.kind = SemIR::ValueRepr::None,
  257. .type_id = GetTupleType(context_, {})};
  258. }
  259. auto TypeCompleter::MakeCopyValueRepr(
  260. SemIR::TypeId rep_id, SemIR::ValueRepr::AggregateKind aggregate_kind) const
  261. -> SemIR::ValueRepr {
  262. return {.kind = SemIR::ValueRepr::Copy,
  263. .aggregate_kind = aggregate_kind,
  264. .type_id = rep_id};
  265. }
  266. auto TypeCompleter::MakePointerValueRepr(
  267. SemIR::TypeId pointee_id,
  268. SemIR::ValueRepr::AggregateKind aggregate_kind) const -> SemIR::ValueRepr {
  269. // TODO: Should we add `const` qualification to `pointee_id`?
  270. return {.kind = SemIR::ValueRepr::Pointer,
  271. .aggregate_kind = aggregate_kind,
  272. .type_id = GetPointerType(context_, pointee_id)};
  273. }
  274. auto TypeCompleter::GetNestedInfo(SemIR::TypeId nested_type_id) const
  275. -> SemIR::CompleteTypeInfo {
  276. CARBON_CHECK(context_.types().IsComplete(nested_type_id),
  277. "Nested type should already be complete");
  278. auto info = context_.types().GetCompleteTypeInfo(nested_type_id);
  279. CARBON_CHECK(info.value_repr.kind != SemIR::ValueRepr::Unknown,
  280. "Complete type should have a value representation");
  281. return info;
  282. }
  283. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  284. SemIR::StringType /*inst*/) const
  285. -> SemIR::CompleteTypeInfo {
  286. // TODO: Decide on string value semantics. This should probably be a
  287. // custom value representation carrying a pointer and size or
  288. // similar.
  289. return {.value_repr = MakePointerValueRepr(type_id)};
  290. }
  291. auto TypeCompleter::BuildStructOrTupleValueRepr(size_t num_elements,
  292. SemIR::TypeId elementwise_rep,
  293. bool same_as_object_rep) const
  294. -> SemIR::ValueRepr {
  295. SemIR::ValueRepr::AggregateKind aggregate_kind =
  296. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  297. : SemIR::ValueRepr::ValueAggregate;
  298. if (num_elements == 1) {
  299. // The value representation for a struct or tuple with a single element
  300. // is a struct or tuple containing the value representation of the
  301. // element.
  302. // TODO: Consider doing the same whenever `elementwise_rep` is
  303. // sufficiently small.
  304. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  305. }
  306. // For a struct or tuple with multiple fields, we use a pointer
  307. // to the elementwise value representation.
  308. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  309. }
  310. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  311. SemIR::StructType struct_type) const
  312. -> SemIR::CompleteTypeInfo {
  313. auto fields = context_.struct_type_fields().Get(struct_type.fields_id);
  314. if (fields.empty()) {
  315. return {.value_repr = MakeEmptyValueRepr()};
  316. }
  317. // Find the value representation for each field, and construct a struct
  318. // of value representations.
  319. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  320. value_rep_fields.reserve(fields.size());
  321. bool same_as_object_rep = true;
  322. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  323. for (auto field : fields) {
  324. auto field_info = GetNestedInfo(field.type_id);
  325. if (!field_info.value_repr.IsCopyOfObjectRepr(context_.sem_ir(),
  326. field.type_id)) {
  327. same_as_object_rep = false;
  328. field.type_id = field_info.value_repr.type_id;
  329. }
  330. value_rep_fields.push_back(field);
  331. // Take the first non-None abstract_class_id, if any.
  332. if (field_info.abstract_class_id.has_value() &&
  333. !abstract_class_id.has_value()) {
  334. abstract_class_id = field_info.abstract_class_id;
  335. }
  336. }
  337. auto value_rep =
  338. same_as_object_rep
  339. ? type_id
  340. : GetStructType(context_, context_.struct_type_fields().AddCanonical(
  341. value_rep_fields));
  342. return {.value_repr = BuildStructOrTupleValueRepr(fields.size(), value_rep,
  343. same_as_object_rep),
  344. .abstract_class_id = abstract_class_id};
  345. }
  346. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  347. SemIR::TupleType tuple_type) const
  348. -> SemIR::CompleteTypeInfo {
  349. // TODO: Share more code with structs.
  350. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  351. if (elements.empty()) {
  352. return {.value_repr = MakeEmptyValueRepr()};
  353. }
  354. // Find the value representation for each element, and construct a tuple
  355. // of value representations.
  356. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  357. value_rep_elements.reserve(elements.size());
  358. bool same_as_object_rep = true;
  359. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  360. for (auto element_type_id : elements) {
  361. auto element_info = GetNestedInfo(element_type_id);
  362. if (!element_info.value_repr.IsCopyOfObjectRepr(context_.sem_ir(),
  363. element_type_id)) {
  364. same_as_object_rep = false;
  365. }
  366. value_rep_elements.push_back(element_info.value_repr.type_id);
  367. // Take the first non-None abstract_class_id, if any.
  368. if (element_info.abstract_class_id.has_value() &&
  369. !abstract_class_id.has_value()) {
  370. abstract_class_id = element_info.abstract_class_id;
  371. }
  372. }
  373. auto value_rep =
  374. same_as_object_rep ? type_id : GetTupleType(context_, value_rep_elements);
  375. return {.value_repr = BuildStructOrTupleValueRepr(elements.size(), value_rep,
  376. same_as_object_rep),
  377. .abstract_class_id = abstract_class_id};
  378. }
  379. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  380. SemIR::ArrayType /*inst*/) const
  381. -> SemIR::CompleteTypeInfo {
  382. // For arrays, it's convenient to always use a pointer representation,
  383. // even when the array has zero or one element, in order to support
  384. // indexing.
  385. return {.value_repr =
  386. MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate)};
  387. }
  388. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  389. SemIR::ClassType inst) const
  390. -> SemIR::CompleteTypeInfo {
  391. auto& class_info = context_.classes().Get(inst.class_id);
  392. auto abstract_class_id =
  393. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract
  394. ? inst.class_id
  395. : SemIR::ClassId::None;
  396. // The value representation of an adapter is the value representation of
  397. // its adapted type.
  398. if (auto adapted_type_id =
  399. class_info.GetAdaptedType(context_.sem_ir(), inst.specific_id);
  400. adapted_type_id.has_value()) {
  401. auto info = GetNestedInfo(adapted_type_id);
  402. info.abstract_class_id = abstract_class_id;
  403. return info;
  404. }
  405. // Otherwise, the value representation for a class is a pointer to the
  406. // object representation.
  407. // TODO: Support customized value representations for classes.
  408. // TODO: Pick a better value representation when possible.
  409. return {.value_repr = MakePointerValueRepr(
  410. class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id),
  411. SemIR::ValueRepr::ObjectAggregate),
  412. .abstract_class_id = abstract_class_id};
  413. }
  414. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  415. SemIR::ConstType inst) const
  416. -> SemIR::CompleteTypeInfo {
  417. // The value representation of `const T` is the same as that of `T`.
  418. // Objects are not modifiable through their value representations.
  419. return GetNestedInfo(inst.inner_id);
  420. }
  421. // Builds and returns the value representation for the given type. All nested
  422. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  423. auto TypeCompleter::BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  424. -> SemIR::CompleteTypeInfo {
  425. // Use overload resolution to select the implementation, producing compile
  426. // errors when BuildInfoForInst isn't defined for a given instruction.
  427. CARBON_KIND_SWITCH(inst) {
  428. #define CARBON_SEM_IR_INST_KIND(Name) \
  429. case CARBON_KIND(SemIR::Name typed_inst): { \
  430. return BuildInfoForInst(type_id, typed_inst); \
  431. }
  432. #include "toolchain/sem_ir/inst_kind.def"
  433. }
  434. }
  435. auto TryToCompleteType(Context& context, SemIR::TypeId type_id, SemIRLoc loc,
  436. Context::BuildDiagnosticFn diagnoser) -> bool {
  437. return TypeCompleter(context, loc, diagnoser).Complete(type_id);
  438. }
  439. auto CompleteTypeOrCheckFail(Context& context, SemIR::TypeId type_id) -> void {
  440. bool complete =
  441. TypeCompleter(context, SemIR::LocId::None, nullptr).Complete(type_id);
  442. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  443. context.types().GetAsInst(type_id));
  444. }
  445. auto RequireCompleteType(Context& context, SemIR::TypeId type_id,
  446. SemIR::LocId loc_id,
  447. Context::BuildDiagnosticFn diagnoser) -> bool {
  448. CARBON_CHECK(diagnoser);
  449. if (!TypeCompleter(context, loc_id, diagnoser).Complete(type_id)) {
  450. return false;
  451. }
  452. // For a symbolic type, create an instruction to require the corresponding
  453. // specific type to be complete.
  454. if (type_id.AsConstantId().is_symbolic()) {
  455. // TODO: Deduplicate these.
  456. AddInstInNoBlock(
  457. context,
  458. SemIR::LocIdAndInst(
  459. loc_id, SemIR::RequireCompleteType{
  460. .type_id = GetSingletonType(
  461. context, SemIR::WitnessType::SingletonInstId),
  462. .complete_type_id = type_id}));
  463. }
  464. return true;
  465. }
  466. // Adds a note to a diagnostic explaining that a class is abstract.
  467. static auto NoteAbstractClass(Context& context, SemIR::ClassId class_id,
  468. bool direct_use,
  469. Context::DiagnosticBuilder& builder) -> void {
  470. const auto& class_info = context.classes().Get(class_id);
  471. CARBON_CHECK(
  472. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  473. "Class is not abstract");
  474. CARBON_DIAGNOSTIC(
  475. ClassAbstractHere, Note,
  476. "{0:=0:uses class that|=1:class} was declared abstract here",
  477. IntAsSelect);
  478. builder.Note(class_info.definition_id, ClassAbstractHere,
  479. static_cast<int>(direct_use));
  480. }
  481. auto RequireConcreteType(Context& context, SemIR::TypeId type_id,
  482. SemIR::LocId loc_id,
  483. Context::BuildDiagnosticFn diagnoser,
  484. Context::BuildDiagnosticFn abstract_diagnoser)
  485. -> bool {
  486. // TODO: For symbolic types, should add a RequireConcreteType instruction,
  487. // like RequireCompleteType.
  488. CARBON_CHECK(abstract_diagnoser);
  489. if (!RequireCompleteType(context, type_id, loc_id, diagnoser)) {
  490. return false;
  491. }
  492. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  493. if (complete_info.abstract_class_id.has_value()) {
  494. auto builder = abstract_diagnoser();
  495. if (builder) {
  496. bool direct_use = false;
  497. if (auto inst = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  498. if (inst->class_id == complete_info.abstract_class_id) {
  499. direct_use = true;
  500. }
  501. }
  502. NoteAbstractClass(context, complete_info.abstract_class_id, direct_use,
  503. builder);
  504. builder.Emit();
  505. }
  506. return false;
  507. }
  508. return true;
  509. }
  510. static auto AddCompleteFacetType(Context& context, SemIR::LocId loc_id,
  511. SemIR::FacetTypeId facet_type_id,
  512. FacetTypeContext context_for_diagnostics)
  513. -> SemIR::CompleteFacetTypeId {
  514. const auto& facet_type_info = context.facet_types().Get(facet_type_id);
  515. SemIR::CompleteFacetType result;
  516. result.required_interfaces.reserve(facet_type_info.impls_constraints.size());
  517. // Every mentioned interface needs to be defined.
  518. for (auto impl_interface : facet_type_info.impls_constraints) {
  519. // TODO: expand named constraints
  520. auto interface_id = impl_interface.interface_id;
  521. const auto& interface = context.interfaces().Get(interface_id);
  522. if (!interface.is_defined()) {
  523. CARBON_DIAGNOSTIC(
  524. ResolveFacetTypeWithUndefinedInterface, Error,
  525. "{0:=0:member access into|=1:impl of} undefined interface {1}",
  526. IntAsSelect, SemIR::NameId);
  527. auto builder = context.emitter().Build(
  528. loc_id, ResolveFacetTypeWithUndefinedInterface,
  529. static_cast<int>(context_for_diagnostics), interface.name_id);
  530. NoteUndefinedInterface(context, interface_id, builder);
  531. builder.Emit();
  532. return SemIR::CompleteFacetTypeId::None;
  533. }
  534. if (impl_interface.specific_id.has_value()) {
  535. ResolveSpecificDefinition(context, loc_id, impl_interface.specific_id);
  536. }
  537. result.required_interfaces.push_back(
  538. {.interface_id = interface_id,
  539. .specific_id = impl_interface.specific_id});
  540. }
  541. // TODO: Sort and deduplicate result.required_interfaces. For now, we have at
  542. // most one.
  543. CARBON_CHECK(result.required_interfaces.size() <= 1);
  544. // TODO: Distinguish interfaces that are required but would not be
  545. // implemented, such as those from `where .Self impls I`.
  546. result.num_to_impl = result.required_interfaces.size();
  547. return context.complete_facet_types().Add(facet_type_id, result);
  548. }
  549. // TODO: RequireCompleteType should do these checks, this should just return
  550. // additional information.
  551. auto RequireCompleteFacetType(Context& context, SemIR::TypeId type_id,
  552. SemIR::LocId loc_id,
  553. const SemIR::FacetType& facet_type,
  554. FacetTypeContext context_for_diagnostics)
  555. -> SemIR::CompleteFacetTypeId {
  556. if (!RequireCompleteType(
  557. context, type_id, loc_id, [&]() -> Context::DiagnosticBuilder {
  558. CARBON_FATAL("Unreachable, facet types are always complete.");
  559. })) {
  560. return SemIR::CompleteFacetTypeId::None;
  561. }
  562. auto complete_id =
  563. context.complete_facet_types().TryGetId(facet_type.facet_type_id);
  564. if (!complete_id.has_value()) {
  565. complete_id = AddCompleteFacetType(
  566. context, loc_id, facet_type.facet_type_id, context_for_diagnostics);
  567. }
  568. return complete_id;
  569. }
  570. auto AsCompleteType(Context& context, SemIR::TypeId type_id,
  571. SemIR::LocId loc_id, Context::BuildDiagnosticFn diagnoser)
  572. -> SemIR::TypeId {
  573. return RequireCompleteType(context, type_id, loc_id, diagnoser)
  574. ? type_id
  575. : SemIR::ErrorInst::SingletonTypeId;
  576. }
  577. // Returns the type `type_id` if it is a concrete type, or produces an
  578. // incomplete or abstract type error and returns an error type. This is a
  579. // convenience wrapper around `RequireConcreteType`.
  580. auto AsConcreteType(Context& context, SemIR::TypeId type_id,
  581. SemIR::LocId loc_id, Context::BuildDiagnosticFn diagnoser,
  582. Context::BuildDiagnosticFn abstract_diagnoser)
  583. -> SemIR::TypeId {
  584. return RequireConcreteType(context, type_id, loc_id, diagnoser,
  585. abstract_diagnoser)
  586. ? type_id
  587. : SemIR::ErrorInst::SingletonTypeId;
  588. }
  589. auto NoteIncompleteClass(Context& context, SemIR::ClassId class_id,
  590. Context::DiagnosticBuilder& builder) -> void {
  591. const auto& class_info = context.classes().Get(class_id);
  592. CARBON_CHECK(!class_info.is_defined(), "Class is not incomplete");
  593. if (class_info.has_definition_started()) {
  594. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  595. "class is incomplete within its definition");
  596. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  597. } else {
  598. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  599. "class was forward declared here");
  600. builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
  601. }
  602. }
  603. auto NoteUndefinedInterface(Context& context, SemIR::InterfaceId interface_id,
  604. Context::DiagnosticBuilder& builder) -> void {
  605. const auto& interface_info = context.interfaces().Get(interface_id);
  606. CARBON_CHECK(!interface_info.is_defined(), "Interface is not incomplete");
  607. if (interface_info.is_being_defined()) {
  608. CARBON_DIAGNOSTIC(InterfaceUndefinedWithinDefinition, Note,
  609. "interface is currently being defined");
  610. builder.Note(interface_info.definition_id,
  611. InterfaceUndefinedWithinDefinition);
  612. } else {
  613. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  614. "interface was forward declared here");
  615. builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
  616. }
  617. }
  618. } // namespace Carbon::Check