type_completion.cpp 26 KB

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