type_completion.cpp 25 KB

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