type_completion.cpp 26 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. #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, SemIR::LocId loc_id,
  30. MakeDiagnosticBuilderFn diagnoser)
  31. : context_(context), loc_id_(loc_id), 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(InstT::Kind.template IsAnyOf<
  74. SemIR::AutoType, SemIR::BoolType, SemIR::BoundMethodType,
  75. SemIR::ErrorInst, SemIR::FacetType, SemIR::FloatType,
  76. SemIR::IntType, SemIR::IntLiteralType, SemIR::LegacyFloatType,
  77. SemIR::NamespaceType, SemIR::PointerType,
  78. SemIR::SpecificFunctionType, SemIR::TypeType, SemIR::VtableType,
  79. 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::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. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  120. SemIR::ImplWitnessAssociatedConstant inst) const
  121. -> SemIR::CompleteTypeInfo;
  122. template <typename InstT>
  123. requires(InstT::Kind.constant_kind() ==
  124. SemIR::InstConstantKind::SymbolicOnly ||
  125. InstT::Kind.is_type() == SemIR::InstIsType::Never)
  126. auto BuildInfoForInst(SemIR::TypeId type_id, InstT inst) const
  127. -> SemIR::CompleteTypeInfo {
  128. if constexpr (InstT::Kind.is_type() == SemIR::InstIsType::Never) {
  129. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  130. } else {
  131. // For symbolic types, we arbitrarily pick a copy representation.
  132. return {.value_repr = MakeCopyValueRepr(type_id)};
  133. }
  134. }
  135. // Builds and returns the `CompleteTypeInfo` for the given type. All nested
  136. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  137. auto BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  138. -> SemIR::CompleteTypeInfo;
  139. Context* context_;
  140. llvm::SmallVector<WorkItem> work_list_;
  141. SemIR::LocId loc_id_;
  142. MakeDiagnosticBuilderFn diagnoser_;
  143. };
  144. } // namespace
  145. auto TypeCompleter::Complete(SemIR::TypeId type_id) -> bool {
  146. Push(type_id);
  147. while (!work_list_.empty()) {
  148. if (!ProcessStep()) {
  149. return false;
  150. }
  151. }
  152. return true;
  153. }
  154. auto TypeCompleter::Push(SemIR::TypeId type_id) -> void {
  155. if (!context_->types().IsComplete(type_id)) {
  156. work_list_.push_back(
  157. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  158. }
  159. }
  160. auto TypeCompleter::ProcessStep() -> bool {
  161. auto [type_id, phase] = work_list_.back();
  162. // We might have enqueued the same type more than once. Just skip the
  163. // type if it's already complete.
  164. if (context_->types().IsComplete(type_id)) {
  165. work_list_.pop_back();
  166. return true;
  167. }
  168. auto inst_id = context_->types().GetInstId(type_id);
  169. auto inst = context_->insts().Get(inst_id);
  170. auto old_work_list_size = work_list_.size();
  171. switch (phase) {
  172. case Phase::AddNestedIncompleteTypes:
  173. if (!AddNestedIncompleteTypes(inst)) {
  174. return false;
  175. }
  176. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  177. "AddNestedIncompleteTypes should not remove work items");
  178. work_list_[old_work_list_size - 1].phase = Phase::BuildInfo;
  179. break;
  180. case Phase::BuildInfo: {
  181. auto info = BuildInfo(type_id, inst);
  182. context_->types().SetComplete(type_id, info);
  183. CARBON_CHECK(old_work_list_size == work_list_.size(),
  184. "BuildInfo should not change work items");
  185. work_list_.pop_back();
  186. // Also complete the value representation type, if necessary. This
  187. // should never fail: the value representation shouldn't require any
  188. // additional nested types to be complete.
  189. if (!context_->types().IsComplete(info.value_repr.type_id)) {
  190. work_list_.push_back(
  191. {.type_id = info.value_repr.type_id, .phase = Phase::BuildInfo});
  192. }
  193. // For a pointer representation, the pointee also needs to be complete.
  194. if (info.value_repr.kind == SemIR::ValueRepr::Pointer) {
  195. if (info.value_repr.type_id == SemIR::ErrorInst::TypeId) {
  196. break;
  197. }
  198. auto pointee_type_id =
  199. context_->sem_ir().GetPointeeType(info.value_repr.type_id);
  200. if (!context_->types().IsComplete(pointee_type_id)) {
  201. work_list_.push_back(
  202. {.type_id = pointee_type_id, .phase = Phase::BuildInfo});
  203. }
  204. }
  205. break;
  206. }
  207. }
  208. return true;
  209. }
  210. auto TypeCompleter::AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  211. CARBON_KIND_SWITCH(type_inst) {
  212. case CARBON_KIND(SemIR::ArrayType inst): {
  213. Push(context_->types().GetTypeIdForTypeInstId(inst.element_type_inst_id));
  214. break;
  215. }
  216. case CARBON_KIND(SemIR::StructType inst): {
  217. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  218. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  219. }
  220. break;
  221. }
  222. case CARBON_KIND(SemIR::TupleType inst): {
  223. for (auto element_type_id : context_->types().GetBlockAsTypeIds(
  224. context_->inst_blocks().Get(inst.type_elements_id))) {
  225. Push(element_type_id);
  226. }
  227. break;
  228. }
  229. case CARBON_KIND(SemIR::ClassType inst): {
  230. auto& class_info = context_->classes().Get(inst.class_id);
  231. if (!class_info.is_complete()) {
  232. if (diagnoser_) {
  233. auto builder = diagnoser_();
  234. NoteIncompleteClass(*context_, inst.class_id, builder);
  235. builder.Emit();
  236. }
  237. return false;
  238. }
  239. if (inst.specific_id.has_value()) {
  240. ResolveSpecificDefinition(*context_, loc_id_, inst.specific_id);
  241. }
  242. if (auto adapted_type_id =
  243. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  244. adapted_type_id.has_value()) {
  245. Push(adapted_type_id);
  246. } else {
  247. Push(class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id));
  248. }
  249. break;
  250. }
  251. case CARBON_KIND(SemIR::ConstType inst): {
  252. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  253. break;
  254. }
  255. case CARBON_KIND(SemIR::FacetType inst): {
  256. auto identified_id = RequireIdentifiedFacetType(*context_, inst);
  257. const auto& identified =
  258. context_->identified_facet_types().Get(identified_id);
  259. // Every mentioned interface needs to be complete.
  260. for (auto req_interface : identified.required_interfaces()) {
  261. auto interface_id = req_interface.interface_id;
  262. const auto& interface = context_->interfaces().Get(interface_id);
  263. if (!interface.is_complete()) {
  264. if (diagnoser_) {
  265. auto builder = diagnoser_();
  266. NoteIncompleteInterface(*context_, interface_id, builder);
  267. builder.Emit();
  268. }
  269. return false;
  270. }
  271. if (req_interface.specific_id.has_value()) {
  272. ResolveSpecificDefinition(*context_, loc_id_,
  273. req_interface.specific_id);
  274. }
  275. }
  276. break;
  277. }
  278. default:
  279. break;
  280. }
  281. return true;
  282. }
  283. auto TypeCompleter::MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  284. return {.kind = SemIR::ValueRepr::None,
  285. .type_id = GetTupleType(*context_, {})};
  286. }
  287. auto TypeCompleter::MakeCopyValueRepr(
  288. SemIR::TypeId rep_id, SemIR::ValueRepr::AggregateKind aggregate_kind) const
  289. -> SemIR::ValueRepr {
  290. return {.kind = SemIR::ValueRepr::Copy,
  291. .aggregate_kind = aggregate_kind,
  292. .type_id = rep_id};
  293. }
  294. auto TypeCompleter::MakePointerValueRepr(
  295. SemIR::TypeId pointee_id,
  296. SemIR::ValueRepr::AggregateKind aggregate_kind) const -> SemIR::ValueRepr {
  297. // TODO: Should we add `const` qualification to `pointee_id`?
  298. return {.kind = SemIR::ValueRepr::Pointer,
  299. .aggregate_kind = aggregate_kind,
  300. .type_id = GetPointerType(*context_,
  301. context_->types().GetInstId(pointee_id))};
  302. }
  303. auto TypeCompleter::GetNestedInfo(SemIR::TypeId nested_type_id) const
  304. -> SemIR::CompleteTypeInfo {
  305. CARBON_CHECK(context_->types().IsComplete(nested_type_id),
  306. "Nested type should already be complete");
  307. auto info = context_->types().GetCompleteTypeInfo(nested_type_id);
  308. CARBON_CHECK(info.value_repr.kind != SemIR::ValueRepr::Unknown,
  309. "Complete type should have a value representation");
  310. return info;
  311. }
  312. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  313. SemIR::StringType /*inst*/) const
  314. -> SemIR::CompleteTypeInfo {
  315. // TODO: Decide on string value semantics. This should probably be a
  316. // custom value representation carrying a pointer and size or
  317. // similar.
  318. return {.value_repr = MakePointerValueRepr(type_id)};
  319. }
  320. auto TypeCompleter::BuildStructOrTupleValueRepr(size_t num_elements,
  321. SemIR::TypeId elementwise_rep,
  322. bool same_as_object_rep) const
  323. -> SemIR::ValueRepr {
  324. SemIR::ValueRepr::AggregateKind aggregate_kind =
  325. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  326. : SemIR::ValueRepr::ValueAggregate;
  327. if (num_elements == 1) {
  328. // The value representation for a struct or tuple with a single element
  329. // is a struct or tuple containing the value representation of the
  330. // element.
  331. // TODO: Consider doing the same whenever `elementwise_rep` is
  332. // sufficiently small.
  333. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  334. }
  335. // For a struct or tuple with multiple fields, we use a pointer
  336. // to the elementwise value representation.
  337. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  338. }
  339. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  340. SemIR::StructType struct_type) const
  341. -> SemIR::CompleteTypeInfo {
  342. auto fields = context_->struct_type_fields().Get(struct_type.fields_id);
  343. if (fields.empty()) {
  344. return {.value_repr = MakeEmptyValueRepr()};
  345. }
  346. // Find the value representation for each field, and construct a struct
  347. // of value representations.
  348. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  349. value_rep_fields.reserve(fields.size());
  350. bool same_as_object_rep = true;
  351. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  352. for (auto field : fields) {
  353. auto field_type_id =
  354. context_->types().GetTypeIdForTypeInstId(field.type_inst_id);
  355. auto field_info = GetNestedInfo(field_type_id);
  356. if (!field_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  357. field_type_id)) {
  358. same_as_object_rep = false;
  359. field.type_inst_id =
  360. context_->types().GetInstId(field_info.value_repr.type_id);
  361. }
  362. value_rep_fields.push_back(field);
  363. // Take the first non-None abstract_class_id, if any.
  364. if (field_info.abstract_class_id.has_value() &&
  365. !abstract_class_id.has_value()) {
  366. abstract_class_id = field_info.abstract_class_id;
  367. }
  368. }
  369. auto value_rep =
  370. same_as_object_rep
  371. ? type_id
  372. : GetStructType(
  373. *context_,
  374. context_->struct_type_fields().AddCanonical(value_rep_fields));
  375. return {.value_repr = BuildStructOrTupleValueRepr(fields.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::TupleType tuple_type) const
  381. -> SemIR::CompleteTypeInfo {
  382. // TODO: Share more code with structs.
  383. auto elements = context_->inst_blocks().Get(tuple_type.type_elements_id);
  384. if (elements.empty()) {
  385. return {.value_repr = MakeEmptyValueRepr()};
  386. }
  387. // Find the value representation for each element, and construct a tuple
  388. // of value representations.
  389. llvm::SmallVector<SemIR::InstId> value_rep_elements;
  390. value_rep_elements.reserve(elements.size());
  391. bool same_as_object_rep = true;
  392. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  393. for (auto element_type_id : context_->types().GetBlockAsTypeIds(elements)) {
  394. auto element_info = GetNestedInfo(element_type_id);
  395. if (!element_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  396. element_type_id)) {
  397. same_as_object_rep = false;
  398. }
  399. value_rep_elements.push_back(
  400. context_->types().GetInstId(element_info.value_repr.type_id));
  401. // Take the first non-None abstract_class_id, if any.
  402. if (element_info.abstract_class_id.has_value() &&
  403. !abstract_class_id.has_value()) {
  404. abstract_class_id = element_info.abstract_class_id;
  405. }
  406. }
  407. auto value_rep = same_as_object_rep
  408. ? type_id
  409. : GetTupleType(*context_, value_rep_elements);
  410. return {.value_repr = BuildStructOrTupleValueRepr(elements.size(), value_rep,
  411. same_as_object_rep),
  412. .abstract_class_id = abstract_class_id};
  413. }
  414. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  415. SemIR::ArrayType /*inst*/) const
  416. -> SemIR::CompleteTypeInfo {
  417. // For arrays, it's convenient to always use a pointer representation,
  418. // even when the array has zero or one element, in order to support
  419. // indexing.
  420. return {.value_repr =
  421. MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate)};
  422. }
  423. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  424. SemIR::ClassType inst) const
  425. -> SemIR::CompleteTypeInfo {
  426. auto& class_info = context_->classes().Get(inst.class_id);
  427. auto abstract_class_id =
  428. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract
  429. ? inst.class_id
  430. : SemIR::ClassId::None;
  431. // The value representation of an adapter is the value representation of
  432. // its adapted type.
  433. if (auto adapted_type_id =
  434. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  435. adapted_type_id.has_value()) {
  436. auto info = GetNestedInfo(adapted_type_id);
  437. info.abstract_class_id = abstract_class_id;
  438. return info;
  439. }
  440. // Otherwise, the value representation for a class is a pointer to the
  441. // object representation.
  442. // TODO: Support customized value representations for classes.
  443. // TODO: Pick a better value representation when possible.
  444. return {.value_repr = MakePointerValueRepr(
  445. class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id),
  446. SemIR::ValueRepr::ObjectAggregate),
  447. .abstract_class_id = abstract_class_id};
  448. }
  449. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  450. SemIR::ConstType inst) const
  451. -> SemIR::CompleteTypeInfo {
  452. // The value representation of `const T` is the same as that of `T`.
  453. // Objects are not modifiable through their value representations.
  454. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  455. }
  456. auto TypeCompleter::BuildInfoForInst(
  457. SemIR::TypeId /*type_id*/, SemIR::ImplWitnessAssociatedConstant inst) const
  458. -> SemIR::CompleteTypeInfo {
  459. return GetNestedInfo(inst.type_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,
  476. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  477. -> bool {
  478. return TypeCompleter(&context, loc_id, diagnoser).Complete(type_id);
  479. }
  480. auto CompleteTypeOrCheckFail(Context& context, SemIR::TypeId type_id) -> void {
  481. bool complete =
  482. TypeCompleter(&context, SemIR::LocId::None, nullptr).Complete(type_id);
  483. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  484. context.types().GetAsInst(type_id));
  485. }
  486. auto RequireCompleteType(Context& context, SemIR::TypeId type_id,
  487. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  488. -> bool {
  489. CARBON_CHECK(diagnoser);
  490. if (!TypeCompleter(&context, loc_id, diagnoser).Complete(type_id)) {
  491. return false;
  492. }
  493. // For a symbolic type, create an instruction to require the corresponding
  494. // specific type to be complete.
  495. if (type_id.is_symbolic()) {
  496. // TODO: Deduplicate these.
  497. AddInstInNoBlock(
  498. context, loc_id,
  499. SemIR::RequireCompleteType{
  500. .type_id =
  501. GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  502. .complete_type_inst_id = context.types().GetInstId(type_id)});
  503. }
  504. return true;
  505. }
  506. // Adds a note to a diagnostic explaining that a class is abstract.
  507. static auto NoteAbstractClass(Context& context, SemIR::ClassId class_id,
  508. bool direct_use, DiagnosticBuilder& builder)
  509. -> void {
  510. const auto& class_info = context.classes().Get(class_id);
  511. CARBON_CHECK(
  512. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  513. "Class is not abstract");
  514. CARBON_DIAGNOSTIC(
  515. ClassAbstractHere, Note,
  516. "{0:=0:uses class that|=1:class} was declared abstract here",
  517. Diagnostics::IntAsSelect);
  518. builder.Note(class_info.definition_id, ClassAbstractHere,
  519. static_cast<int>(direct_use));
  520. }
  521. auto RequireConcreteType(Context& context, SemIR::TypeId type_id,
  522. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  523. MakeDiagnosticBuilderFn abstract_diagnoser) -> bool {
  524. // TODO: For symbolic types, should add an implicit constraint that they are
  525. // not abstract.
  526. CARBON_CHECK(abstract_diagnoser);
  527. // The representation of a facet type does not depend on its definition, so
  528. // they are considered "concrete" even when not complete.
  529. if (context.types().IsFacetType(type_id)) {
  530. return true;
  531. }
  532. if (!RequireCompleteType(context, type_id, loc_id, diagnoser)) {
  533. return false;
  534. }
  535. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  536. if (complete_info.abstract_class_id.has_value()) {
  537. auto builder = abstract_diagnoser();
  538. if (builder) {
  539. bool direct_use = false;
  540. if (auto inst = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  541. if (inst->class_id == complete_info.abstract_class_id) {
  542. direct_use = true;
  543. }
  544. }
  545. NoteAbstractClass(context, complete_info.abstract_class_id, direct_use,
  546. builder);
  547. builder.Emit();
  548. }
  549. return false;
  550. }
  551. return true;
  552. }
  553. auto RequireIdentifiedFacetType(Context& context,
  554. const SemIR::FacetType& facet_type)
  555. -> SemIR::IdentifiedFacetTypeId {
  556. if (auto identified_id =
  557. context.identified_facet_types().TryGetId(facet_type.facet_type_id);
  558. identified_id.has_value()) {
  559. return identified_id;
  560. }
  561. const auto& facet_type_info =
  562. context.facet_types().Get(facet_type.facet_type_id);
  563. // TODO: expand named constraints
  564. // TODO: Process other kinds of requirements.
  565. return context.identified_facet_types().Add(
  566. facet_type.facet_type_id, {facet_type_info.extend_constraints,
  567. facet_type_info.self_impls_constraints});
  568. }
  569. auto AsCompleteType(Context& context, SemIR::TypeId type_id,
  570. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  571. -> SemIR::TypeId {
  572. return RequireCompleteType(context, type_id, loc_id, diagnoser)
  573. ? type_id
  574. : SemIR::ErrorInst::TypeId;
  575. }
  576. // Returns the type `type_id` if it is a concrete type, or produces an
  577. // incomplete or abstract type error and returns an error type. This is a
  578. // convenience wrapper around `RequireConcreteType`.
  579. auto AsConcreteType(Context& context, SemIR::TypeId type_id,
  580. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  581. MakeDiagnosticBuilderFn abstract_diagnoser)
  582. -> SemIR::TypeId {
  583. return RequireConcreteType(context, type_id, loc_id, diagnoser,
  584. abstract_diagnoser)
  585. ? type_id
  586. : SemIR::ErrorInst::TypeId;
  587. }
  588. auto NoteIncompleteClass(Context& context, SemIR::ClassId class_id,
  589. DiagnosticBuilder& builder) -> void {
  590. const auto& class_info = context.classes().Get(class_id);
  591. CARBON_CHECK(!class_info.is_complete(), "Class is not incomplete");
  592. if (class_info.has_definition_started()) {
  593. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  594. "class is incomplete within its definition");
  595. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  596. } else {
  597. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  598. "class was forward declared here");
  599. builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
  600. }
  601. }
  602. auto NoteIncompleteInterface(Context& context, SemIR::InterfaceId interface_id,
  603. DiagnosticBuilder& builder) -> void {
  604. const auto& interface_info = context.interfaces().Get(interface_id);
  605. CARBON_CHECK(!interface_info.is_complete(), "Interface is not incomplete");
  606. if (interface_info.is_being_defined()) {
  607. CARBON_DIAGNOSTIC(InterfaceIncompleteWithinDefinition, Note,
  608. "interface is currently being defined");
  609. builder.Note(interface_info.definition_id,
  610. InterfaceIncompleteWithinDefinition);
  611. } else {
  612. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  613. "interface was forward declared here");
  614. builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
  615. }
  616. }
  617. } // namespace Carbon::Check