type_completion.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. MakeDiagnosticBuilderFn 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. MakeDiagnosticBuilderFn 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. case CARBON_KIND(SemIR::FacetType inst): {
  251. if (context_.complete_facet_types()
  252. .TryGetId(inst.facet_type_id)
  253. .has_value()) {
  254. break;
  255. }
  256. const auto& facet_type_info =
  257. context_.facet_types().Get(inst.facet_type_id);
  258. SemIR::CompleteFacetType result;
  259. result.required_interfaces.reserve(
  260. facet_type_info.impls_constraints.size());
  261. // Every mentioned interface needs to be defined.
  262. for (auto impl_interface : facet_type_info.impls_constraints) {
  263. // TODO: expand named constraints
  264. auto interface_id = impl_interface.interface_id;
  265. const auto& interface = context_.interfaces().Get(interface_id);
  266. if (!interface.is_defined()) {
  267. if (diagnoser_) {
  268. auto builder = diagnoser_();
  269. NoteUndefinedInterface(context_, interface_id, builder);
  270. builder.Emit();
  271. }
  272. return false;
  273. }
  274. if (impl_interface.specific_id.has_value()) {
  275. ResolveSpecificDefinition(context_, loc_, impl_interface.specific_id);
  276. }
  277. result.required_interfaces.push_back(
  278. {.interface_id = interface_id,
  279. .specific_id = impl_interface.specific_id});
  280. }
  281. result.CanonicalizeRequiredInterfaces();
  282. // TODO: Distinguish interfaces that are required but would not be
  283. // implemented, such as those from `where .Self impls I`.
  284. result.num_to_impl = result.required_interfaces.size();
  285. // TODO: Process other kinds of requirements.
  286. context_.complete_facet_types().Add(inst.facet_type_id, result);
  287. break;
  288. }
  289. default:
  290. break;
  291. }
  292. return true;
  293. }
  294. auto TypeCompleter::MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  295. return {.kind = SemIR::ValueRepr::None,
  296. .type_id = GetTupleType(context_, {})};
  297. }
  298. auto TypeCompleter::MakeCopyValueRepr(
  299. SemIR::TypeId rep_id, SemIR::ValueRepr::AggregateKind aggregate_kind) const
  300. -> SemIR::ValueRepr {
  301. return {.kind = SemIR::ValueRepr::Copy,
  302. .aggregate_kind = aggregate_kind,
  303. .type_id = rep_id};
  304. }
  305. auto TypeCompleter::MakePointerValueRepr(
  306. SemIR::TypeId pointee_id,
  307. SemIR::ValueRepr::AggregateKind aggregate_kind) const -> SemIR::ValueRepr {
  308. // TODO: Should we add `const` qualification to `pointee_id`?
  309. return {.kind = SemIR::ValueRepr::Pointer,
  310. .aggregate_kind = aggregate_kind,
  311. .type_id = GetPointerType(context_, pointee_id)};
  312. }
  313. auto TypeCompleter::GetNestedInfo(SemIR::TypeId nested_type_id) const
  314. -> SemIR::CompleteTypeInfo {
  315. CARBON_CHECK(context_.types().IsComplete(nested_type_id),
  316. "Nested type should already be complete");
  317. auto info = context_.types().GetCompleteTypeInfo(nested_type_id);
  318. CARBON_CHECK(info.value_repr.kind != SemIR::ValueRepr::Unknown,
  319. "Complete type should have a value representation");
  320. return info;
  321. }
  322. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  323. SemIR::StringType /*inst*/) const
  324. -> SemIR::CompleteTypeInfo {
  325. // TODO: Decide on string value semantics. This should probably be a
  326. // custom value representation carrying a pointer and size or
  327. // similar.
  328. return {.value_repr = MakePointerValueRepr(type_id)};
  329. }
  330. auto TypeCompleter::BuildStructOrTupleValueRepr(size_t num_elements,
  331. SemIR::TypeId elementwise_rep,
  332. bool same_as_object_rep) const
  333. -> SemIR::ValueRepr {
  334. SemIR::ValueRepr::AggregateKind aggregate_kind =
  335. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  336. : SemIR::ValueRepr::ValueAggregate;
  337. if (num_elements == 1) {
  338. // The value representation for a struct or tuple with a single element
  339. // is a struct or tuple containing the value representation of the
  340. // element.
  341. // TODO: Consider doing the same whenever `elementwise_rep` is
  342. // sufficiently small.
  343. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  344. }
  345. // For a struct or tuple with multiple fields, we use a pointer
  346. // to the elementwise value representation.
  347. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  348. }
  349. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  350. SemIR::StructType struct_type) const
  351. -> SemIR::CompleteTypeInfo {
  352. auto fields = context_.struct_type_fields().Get(struct_type.fields_id);
  353. if (fields.empty()) {
  354. return {.value_repr = MakeEmptyValueRepr()};
  355. }
  356. // Find the value representation for each field, and construct a struct
  357. // of value representations.
  358. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  359. value_rep_fields.reserve(fields.size());
  360. bool same_as_object_rep = true;
  361. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  362. for (auto field : fields) {
  363. auto field_info = GetNestedInfo(field.type_id);
  364. if (!field_info.value_repr.IsCopyOfObjectRepr(context_.sem_ir(),
  365. field.type_id)) {
  366. same_as_object_rep = false;
  367. field.type_id = field_info.value_repr.type_id;
  368. }
  369. value_rep_fields.push_back(field);
  370. // Take the first non-None abstract_class_id, if any.
  371. if (field_info.abstract_class_id.has_value() &&
  372. !abstract_class_id.has_value()) {
  373. abstract_class_id = field_info.abstract_class_id;
  374. }
  375. }
  376. auto value_rep =
  377. same_as_object_rep
  378. ? type_id
  379. : GetStructType(context_, context_.struct_type_fields().AddCanonical(
  380. value_rep_fields));
  381. return {.value_repr = BuildStructOrTupleValueRepr(fields.size(), value_rep,
  382. same_as_object_rep),
  383. .abstract_class_id = abstract_class_id};
  384. }
  385. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  386. SemIR::TupleType tuple_type) const
  387. -> SemIR::CompleteTypeInfo {
  388. // TODO: Share more code with structs.
  389. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  390. if (elements.empty()) {
  391. return {.value_repr = MakeEmptyValueRepr()};
  392. }
  393. // Find the value representation for each element, and construct a tuple
  394. // of value representations.
  395. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  396. value_rep_elements.reserve(elements.size());
  397. bool same_as_object_rep = true;
  398. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  399. for (auto element_type_id : elements) {
  400. auto element_info = GetNestedInfo(element_type_id);
  401. if (!element_info.value_repr.IsCopyOfObjectRepr(context_.sem_ir(),
  402. element_type_id)) {
  403. same_as_object_rep = false;
  404. }
  405. value_rep_elements.push_back(element_info.value_repr.type_id);
  406. // Take the first non-None abstract_class_id, if any.
  407. if (element_info.abstract_class_id.has_value() &&
  408. !abstract_class_id.has_value()) {
  409. abstract_class_id = element_info.abstract_class_id;
  410. }
  411. }
  412. auto value_rep =
  413. same_as_object_rep ? type_id : GetTupleType(context_, value_rep_elements);
  414. return {.value_repr = BuildStructOrTupleValueRepr(elements.size(), value_rep,
  415. same_as_object_rep),
  416. .abstract_class_id = abstract_class_id};
  417. }
  418. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  419. SemIR::ArrayType /*inst*/) const
  420. -> SemIR::CompleteTypeInfo {
  421. // For arrays, it's convenient to always use a pointer representation,
  422. // even when the array has zero or one element, in order to support
  423. // indexing.
  424. return {.value_repr =
  425. MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate)};
  426. }
  427. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  428. SemIR::ClassType inst) const
  429. -> SemIR::CompleteTypeInfo {
  430. auto& class_info = context_.classes().Get(inst.class_id);
  431. auto abstract_class_id =
  432. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract
  433. ? inst.class_id
  434. : SemIR::ClassId::None;
  435. // The value representation of an adapter is the value representation of
  436. // its adapted type.
  437. if (auto adapted_type_id =
  438. class_info.GetAdaptedType(context_.sem_ir(), inst.specific_id);
  439. adapted_type_id.has_value()) {
  440. auto info = GetNestedInfo(adapted_type_id);
  441. info.abstract_class_id = abstract_class_id;
  442. return info;
  443. }
  444. // Otherwise, the value representation for a class is a pointer to the
  445. // object representation.
  446. // TODO: Support customized value representations for classes.
  447. // TODO: Pick a better value representation when possible.
  448. return {.value_repr = MakePointerValueRepr(
  449. class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id),
  450. SemIR::ValueRepr::ObjectAggregate),
  451. .abstract_class_id = abstract_class_id};
  452. }
  453. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  454. SemIR::ConstType inst) const
  455. -> SemIR::CompleteTypeInfo {
  456. // The value representation of `const T` is the same as that of `T`.
  457. // Objects are not modifiable through their value representations.
  458. return GetNestedInfo(inst.inner_id);
  459. }
  460. // Builds and returns the value representation for the given type. All nested
  461. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  462. auto TypeCompleter::BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  463. -> SemIR::CompleteTypeInfo {
  464. // Use overload resolution to select the implementation, producing compile
  465. // errors when BuildInfoForInst isn't defined for a given instruction.
  466. CARBON_KIND_SWITCH(inst) {
  467. #define CARBON_SEM_IR_INST_KIND(Name) \
  468. case CARBON_KIND(SemIR::Name typed_inst): { \
  469. return BuildInfoForInst(type_id, typed_inst); \
  470. }
  471. #include "toolchain/sem_ir/inst_kind.def"
  472. }
  473. }
  474. auto TryToCompleteType(Context& context, SemIR::TypeId type_id, SemIRLoc loc,
  475. MakeDiagnosticBuilderFn diagnoser) -> bool {
  476. return TypeCompleter(context, loc, diagnoser).Complete(type_id);
  477. }
  478. auto CompleteTypeOrCheckFail(Context& context, SemIR::TypeId type_id) -> void {
  479. bool complete =
  480. TypeCompleter(context, SemIR::LocId::None, nullptr).Complete(type_id);
  481. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  482. context.types().GetAsInst(type_id));
  483. }
  484. auto RequireCompleteType(Context& context, SemIR::TypeId type_id,
  485. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  486. -> bool {
  487. CARBON_CHECK(diagnoser);
  488. if (!TypeCompleter(context, loc_id, diagnoser).Complete(type_id)) {
  489. return false;
  490. }
  491. // For a symbolic type, create an instruction to require the corresponding
  492. // specific type to be complete.
  493. if (type_id.is_symbolic()) {
  494. // TODO: Deduplicate these.
  495. AddInstInNoBlock(
  496. context,
  497. SemIR::LocIdAndInst(
  498. loc_id, SemIR::RequireCompleteType{
  499. .type_id = GetSingletonType(
  500. context, SemIR::WitnessType::SingletonInstId),
  501. .complete_type_id = type_id}));
  502. }
  503. return true;
  504. }
  505. // Adds a note to a diagnostic explaining that a class is abstract.
  506. static auto NoteAbstractClass(Context& context, SemIR::ClassId class_id,
  507. bool direct_use, DiagnosticBuilder& builder)
  508. -> void {
  509. const auto& class_info = context.classes().Get(class_id);
  510. CARBON_CHECK(
  511. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  512. "Class is not abstract");
  513. CARBON_DIAGNOSTIC(
  514. ClassAbstractHere, Note,
  515. "{0:=0:uses class that|=1:class} was declared abstract here",
  516. IntAsSelect);
  517. builder.Note(class_info.definition_id, ClassAbstractHere,
  518. static_cast<int>(direct_use));
  519. }
  520. auto RequireConcreteType(Context& context, SemIR::TypeId type_id,
  521. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  522. MakeDiagnosticBuilderFn abstract_diagnoser) -> bool {
  523. // TODO: For symbolic types, should add an implicit constraint that they are
  524. // not abstract.
  525. CARBON_CHECK(abstract_diagnoser);
  526. // The representation of a facet type does not depend on its definition, so
  527. // they are considered "concrete" even when not complete.
  528. if (context.types().IsFacetType(type_id)) {
  529. return true;
  530. }
  531. if (!RequireCompleteType(context, type_id, loc_id, diagnoser)) {
  532. return false;
  533. }
  534. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  535. if (complete_info.abstract_class_id.has_value()) {
  536. auto builder = abstract_diagnoser();
  537. if (builder) {
  538. bool direct_use = false;
  539. if (auto inst = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  540. if (inst->class_id == complete_info.abstract_class_id) {
  541. direct_use = true;
  542. }
  543. }
  544. NoteAbstractClass(context, complete_info.abstract_class_id, direct_use,
  545. builder);
  546. builder.Emit();
  547. }
  548. return false;
  549. }
  550. return true;
  551. }
  552. auto RequireCompleteFacetType(Context& context, SemIR::TypeId type_id,
  553. SemIR::LocId loc_id,
  554. const SemIR::FacetType& facet_type,
  555. MakeDiagnosticBuilderFn diagnoser)
  556. -> SemIR::CompleteFacetTypeId {
  557. if (!RequireCompleteType(context, type_id, loc_id, diagnoser)) {
  558. return SemIR::CompleteFacetTypeId::None;
  559. }
  560. return context.complete_facet_types().TryGetId(facet_type.facet_type_id);
  561. }
  562. auto AsCompleteType(Context& context, SemIR::TypeId type_id,
  563. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  564. -> SemIR::TypeId {
  565. return RequireCompleteType(context, type_id, loc_id, diagnoser)
  566. ? type_id
  567. : SemIR::ErrorInst::SingletonTypeId;
  568. }
  569. // Returns the type `type_id` if it is a concrete type, or produces an
  570. // incomplete or abstract type error and returns an error type. This is a
  571. // convenience wrapper around `RequireConcreteType`.
  572. auto AsConcreteType(Context& context, SemIR::TypeId type_id,
  573. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  574. MakeDiagnosticBuilderFn abstract_diagnoser)
  575. -> SemIR::TypeId {
  576. return RequireConcreteType(context, type_id, loc_id, diagnoser,
  577. abstract_diagnoser)
  578. ? type_id
  579. : SemIR::ErrorInst::SingletonTypeId;
  580. }
  581. auto NoteIncompleteClass(Context& context, SemIR::ClassId class_id,
  582. DiagnosticBuilder& builder) -> void {
  583. const auto& class_info = context.classes().Get(class_id);
  584. CARBON_CHECK(!class_info.is_defined(), "Class is not incomplete");
  585. if (class_info.has_definition_started()) {
  586. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  587. "class is incomplete within its definition");
  588. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  589. } else {
  590. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  591. "class was forward declared here");
  592. builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
  593. }
  594. }
  595. auto NoteUndefinedInterface(Context& context, SemIR::InterfaceId interface_id,
  596. DiagnosticBuilder& builder) -> void {
  597. const auto& interface_info = context.interfaces().Get(interface_id);
  598. CARBON_CHECK(!interface_info.is_defined(), "Interface is not incomplete");
  599. if (interface_info.is_being_defined()) {
  600. CARBON_DIAGNOSTIC(InterfaceUndefinedWithinDefinition, Note,
  601. "interface is currently being defined");
  602. builder.Note(interface_info.definition_id,
  603. InterfaceUndefinedWithinDefinition);
  604. } else {
  605. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  606. "interface was forward declared here");
  607. builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
  608. }
  609. }
  610. } // namespace Carbon::Check