type_completion.cpp 26 KB

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