convert.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  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/convert.h"
  5. #include <string>
  6. #include <utility>
  7. #include "common/check.h"
  8. #include "common/map.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/check/action.h"
  12. #include "toolchain/check/context.h"
  13. #include "toolchain/check/control_flow.h"
  14. #include "toolchain/check/diagnostic_helpers.h"
  15. #include "toolchain/check/eval.h"
  16. #include "toolchain/check/impl_lookup.h"
  17. #include "toolchain/check/inst.h"
  18. #include "toolchain/check/operator.h"
  19. #include "toolchain/check/pattern_match.h"
  20. #include "toolchain/check/type.h"
  21. #include "toolchain/check/type_completion.h"
  22. #include "toolchain/diagnostics/format_providers.h"
  23. #include "toolchain/sem_ir/copy_on_write_block.h"
  24. #include "toolchain/sem_ir/expr_info.h"
  25. #include "toolchain/sem_ir/file.h"
  26. #include "toolchain/sem_ir/generic.h"
  27. #include "toolchain/sem_ir/ids.h"
  28. #include "toolchain/sem_ir/inst.h"
  29. #include "toolchain/sem_ir/typed_insts.h"
  30. // TODO: This contains a lot of recursion. Consider removing it in order to
  31. // prevent accidents.
  32. // NOLINTBEGIN(misc-no-recursion)
  33. namespace Carbon::Check {
  34. // Marks the initializer `init_id` as initializing `target_id`.
  35. static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::InstId init_id,
  36. SemIR::InstId target_id,
  37. PendingBlock& target_block) -> void {
  38. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  39. if (return_slot_arg_id.has_value()) {
  40. // Replace the temporary in the return slot with a reference to our target.
  41. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  42. SemIR::TemporaryStorage::Kind,
  43. "Return slot for initializer does not contain a temporary; "
  44. "initialized multiple times? Have {0}",
  45. sem_ir.insts().Get(return_slot_arg_id));
  46. target_block.MergeReplacing(return_slot_arg_id, target_id);
  47. }
  48. }
  49. // Commits to using a temporary to store the result of the initializing
  50. // expression described by `init_id`, and returns the location of the
  51. // temporary. If `discarded` is `true`, the result is discarded, and no
  52. // temporary will be created if possible; if no temporary is created, the
  53. // return value will be `SemIR::InstId::None`.
  54. static auto FinalizeTemporary(Context& context, SemIR::InstId init_id,
  55. bool discarded) -> SemIR::InstId {
  56. auto& sem_ir = context.sem_ir();
  57. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  58. if (return_slot_arg_id.has_value()) {
  59. // The return slot should already have a materialized temporary in it.
  60. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  61. SemIR::TemporaryStorage::Kind,
  62. "Return slot for initializer does not contain a temporary; "
  63. "initialized multiple times? Have {0}",
  64. sem_ir.insts().Get(return_slot_arg_id));
  65. auto init = sem_ir.insts().Get(init_id);
  66. return AddInst<SemIR::Temporary>(context, sem_ir.insts().GetLocId(init_id),
  67. {.type_id = init.type_id(),
  68. .storage_id = return_slot_arg_id,
  69. .init_id = init_id});
  70. }
  71. if (discarded) {
  72. // Don't invent a temporary that we're going to discard.
  73. return SemIR::InstId::None;
  74. }
  75. // The initializer has no return slot, but we want to produce a temporary
  76. // object. Materialize one now.
  77. // TODO: Consider using `None` to mean that we immediately materialize and
  78. // initialize a temporary, rather than two separate instructions.
  79. auto init = sem_ir.insts().Get(init_id);
  80. auto loc_id = sem_ir.insts().GetLocId(init_id);
  81. auto temporary_id = AddInstWithCleanup<SemIR::TemporaryStorage>(
  82. context, loc_id, {.type_id = init.type_id()});
  83. return AddInst<SemIR::Temporary>(context, loc_id,
  84. {.type_id = init.type_id(),
  85. .storage_id = temporary_id,
  86. .init_id = init_id});
  87. }
  88. // Materialize a temporary to hold the result of the given expression if it is
  89. // an initializing expression.
  90. static auto MaterializeIfInitializing(Context& context, SemIR::InstId expr_id)
  91. -> SemIR::InstId {
  92. if (GetExprCategory(context.sem_ir(), expr_id) ==
  93. SemIR::ExprCategory::Initializing) {
  94. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  95. }
  96. return expr_id;
  97. }
  98. // Helper to allow `MakeElementAccessInst` to call `AddInst` with either a
  99. // `PendingBlock` or `Context` (defined in `inst.h`).
  100. template <typename AccessInstT>
  101. static auto AddInst(PendingBlock& block, SemIR::LocId loc_id, AccessInstT inst)
  102. -> SemIR::InstId {
  103. return block.AddInst<AccessInstT>(loc_id, inst);
  104. }
  105. // Creates and adds an instruction to perform element access into an aggregate.
  106. template <typename AccessInstT, typename InstBlockT>
  107. static auto MakeElementAccessInst(Context& context, SemIR::LocId loc_id,
  108. SemIR::InstId aggregate_id,
  109. SemIR::TypeId elem_type_id, InstBlockT& block,
  110. size_t i) -> SemIR::InstId {
  111. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  112. // TODO: Add a new instruction kind for indexing an array at a constant
  113. // index so that we don't need an integer literal instruction here, and
  114. // remove this special case.
  115. auto index_id = block.template AddInst<SemIR::IntValue>(
  116. loc_id, {.type_id = GetSingletonType(
  117. context, SemIR::IntLiteralType::SingletonInstId),
  118. .int_id = context.ints().Add(static_cast<int64_t>(i))});
  119. return AddInst<AccessInstT>(block, loc_id,
  120. {elem_type_id, aggregate_id, index_id});
  121. } else {
  122. return AddInst<AccessInstT>(
  123. block, loc_id, {elem_type_id, aggregate_id, SemIR::ElementIndex(i)});
  124. }
  125. }
  126. // Converts an element of one aggregate so that it can be used as an element of
  127. // another aggregate.
  128. //
  129. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  130. // element type, `src_field_index` is the index, and `SourceAccessInstT` is the
  131. // kind of instruction used to access the source element.
  132. //
  133. // For the target: `kind` is the kind of conversion or initialization,
  134. // `target_elem_type` is the element type. For initialization, `target_id` is
  135. // the destination, `target_block` is a pending block for target location
  136. // calculations that will be spliced as the return slot of the initializer if
  137. // necessary, `target_field_index` is the index, and `TargetAccessInstT` is the
  138. // kind of instruction used to access the destination element.
  139. template <typename SourceAccessInstT, typename TargetAccessInstT>
  140. static auto ConvertAggregateElement(
  141. Context& context, SemIR::LocId loc_id, SemIR::InstId src_id,
  142. SemIR::TypeId src_elem_type,
  143. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  144. ConversionTarget::Kind kind, SemIR::InstId target_id,
  145. SemIR::TypeId target_elem_type, PendingBlock* target_block,
  146. size_t src_field_index, size_t target_field_index) -> SemIR::InstId {
  147. // Compute the location of the source element. This goes into the current code
  148. // block, not into the target block.
  149. // TODO: Ideally we would discard this instruction if it's unused.
  150. auto src_elem_id = !src_literal_elems.empty()
  151. ? src_literal_elems[src_field_index]
  152. : MakeElementAccessInst<SourceAccessInstT>(
  153. context, loc_id, src_id, src_elem_type, context,
  154. src_field_index);
  155. // If we're performing a conversion rather than an initialization, we won't
  156. // have or need a target.
  157. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  158. if (!target.is_initializer()) {
  159. return Convert(context, loc_id, src_elem_id, target);
  160. }
  161. // Compute the location of the target element and initialize it.
  162. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  163. target.init_block = target_block;
  164. target.init_id = MakeElementAccessInst<TargetAccessInstT>(
  165. context, loc_id, target_id, target_elem_type, *target_block,
  166. target_field_index);
  167. return Convert(context, loc_id, src_elem_id, target);
  168. }
  169. // Performs a conversion from a tuple to an array type. This function only
  170. // converts the type, and does not perform a final conversion to the requested
  171. // expression category.
  172. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  173. SemIR::ArrayType array_type,
  174. SemIR::InstId value_id, ConversionTarget target)
  175. -> SemIR::InstId {
  176. auto& sem_ir = context.sem_ir();
  177. auto tuple_elem_types = sem_ir.type_blocks().Get(tuple_type.elements_id);
  178. auto value = sem_ir.insts().Get(value_id);
  179. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  180. // If we're initializing from a tuple literal, we will use its elements
  181. // directly. Otherwise, materialize a temporary if needed and index into the
  182. // result.
  183. llvm::ArrayRef<SemIR::InstId> literal_elems;
  184. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  185. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  186. } else {
  187. value_id = MaterializeIfInitializing(context, value_id);
  188. }
  189. // Check that the tuple is the right size.
  190. std::optional<uint64_t> array_bound =
  191. sem_ir.GetArrayBoundValue(array_type.bound_id);
  192. if (!array_bound) {
  193. // TODO: Should this fall back to using `ImplicitAs`?
  194. if (target.diagnose) {
  195. CARBON_DIAGNOSTIC(ArrayInitDependentBound, Error,
  196. "cannot initialize array with dependent bound from a "
  197. "list of initializers");
  198. context.emitter().Emit(value_loc_id, ArrayInitDependentBound);
  199. }
  200. return SemIR::ErrorInst::SingletonInstId;
  201. }
  202. if (tuple_elem_types.size() != array_bound) {
  203. if (target.diagnose) {
  204. CARBON_DIAGNOSTIC(ArrayInitFromLiteralArgCountMismatch, Error,
  205. "cannot initialize array of {0} element{0:s} from {1} "
  206. "initializer{1:s}",
  207. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  208. CARBON_DIAGNOSTIC(
  209. ArrayInitFromExprArgCountMismatch, Error,
  210. "cannot initialize array of {0} element{0:s} from tuple "
  211. "with {1} element{1:s}",
  212. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  213. context.emitter().Emit(value_loc_id,
  214. literal_elems.empty()
  215. ? ArrayInitFromExprArgCountMismatch
  216. : ArrayInitFromLiteralArgCountMismatch,
  217. *array_bound, tuple_elem_types.size());
  218. }
  219. return SemIR::ErrorInst::SingletonInstId;
  220. }
  221. PendingBlock target_block_storage(&context);
  222. PendingBlock* target_block =
  223. target.init_block ? target.init_block : &target_block_storage;
  224. // Arrays are always initialized in-place. Allocate a temporary as the
  225. // destination for the array initialization if we weren't given one.
  226. SemIR::InstId return_slot_arg_id = target.init_id;
  227. if (!target.init_id.has_value()) {
  228. return_slot_arg_id =
  229. target_block->AddInstWithCleanup<SemIR::TemporaryStorage>(
  230. value_loc_id, {.type_id = target.type_id});
  231. }
  232. // Initialize each element of the array from the corresponding element of the
  233. // tuple.
  234. // TODO: Annotate diagnostics coming from here with the array element index,
  235. // if initializing from a tuple literal.
  236. llvm::SmallVector<SemIR::InstId> inits;
  237. inits.reserve(*array_bound + 1);
  238. for (auto [i, src_type_id] : llvm::enumerate(tuple_elem_types)) {
  239. // TODO: This call recurses back into conversion. Switch to an iterative
  240. // approach.
  241. auto init_id =
  242. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  243. context, value_loc_id, value_id, src_type_id, literal_elems,
  244. ConversionTarget::FullInitializer, return_slot_arg_id,
  245. context.types().GetTypeIdForTypeInstId(
  246. array_type.element_type_inst_id),
  247. target_block, i, i);
  248. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  249. return SemIR::ErrorInst::SingletonInstId;
  250. }
  251. inits.push_back(init_id);
  252. }
  253. // Flush the temporary here if we didn't insert it earlier, so we can add a
  254. // reference to the return slot.
  255. target_block->InsertHere();
  256. return AddInst<SemIR::ArrayInit>(context, value_loc_id,
  257. {.type_id = target.type_id,
  258. .inits_id = sem_ir.inst_blocks().Add(inits),
  259. .dest_id = return_slot_arg_id});
  260. }
  261. // Performs a conversion from a tuple to a tuple type. This function only
  262. // converts the type, and does not perform a final conversion to the requested
  263. // expression category.
  264. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  265. SemIR::TupleType dest_type,
  266. SemIR::InstId value_id, ConversionTarget target)
  267. -> SemIR::InstId {
  268. auto& sem_ir = context.sem_ir();
  269. auto src_elem_types = sem_ir.type_blocks().Get(src_type.elements_id);
  270. auto dest_elem_types = sem_ir.type_blocks().Get(dest_type.elements_id);
  271. auto value = sem_ir.insts().Get(value_id);
  272. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  273. // If we're initializing from a tuple literal, we will use its elements
  274. // directly. Otherwise, materialize a temporary if needed and index into the
  275. // result.
  276. llvm::ArrayRef<SemIR::InstId> literal_elems;
  277. auto literal_elems_id = SemIR::InstBlockId::None;
  278. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  279. literal_elems_id = tuple_literal->elements_id;
  280. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  281. } else {
  282. value_id = MaterializeIfInitializing(context, value_id);
  283. }
  284. // Check that the tuples are the same size.
  285. if (src_elem_types.size() != dest_elem_types.size()) {
  286. if (target.diagnose) {
  287. CARBON_DIAGNOSTIC(
  288. TupleInitElementCountMismatch, Error,
  289. "cannot initialize tuple of {0} element{0:s} from tuple "
  290. "with {1} element{1:s}",
  291. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  292. context.emitter().Emit(value_loc_id, TupleInitElementCountMismatch,
  293. dest_elem_types.size(), src_elem_types.size());
  294. }
  295. return SemIR::ErrorInst::SingletonInstId;
  296. }
  297. // If we're forming an initializer, then we want an initializer for each
  298. // element. Otherwise, we want a value representation for each element.
  299. // Perform a final destination store if we're performing an in-place
  300. // initialization.
  301. bool is_init = target.is_initializer();
  302. ConversionTarget::Kind inner_kind =
  303. !is_init ? ConversionTarget::Value
  304. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  305. SemIR::InitRepr::InPlace
  306. ? ConversionTarget::FullInitializer
  307. : ConversionTarget::Initializer;
  308. // Initialize each element of the destination from the corresponding element
  309. // of the source.
  310. // TODO: Annotate diagnostics coming from here with the element index.
  311. auto new_block =
  312. literal_elems_id.has_value()
  313. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  314. : SemIR::CopyOnWriteInstBlock(
  315. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  316. src_elem_types.size()});
  317. for (auto [i, src_type_id, dest_type_id] :
  318. llvm::enumerate(src_elem_types, dest_elem_types)) {
  319. // TODO: This call recurses back into conversion. Switch to an iterative
  320. // approach.
  321. auto init_id =
  322. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  323. context, value_loc_id, value_id, src_type_id, literal_elems,
  324. inner_kind, target.init_id, dest_type_id, target.init_block, i, i);
  325. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  326. return SemIR::ErrorInst::SingletonInstId;
  327. }
  328. new_block.Set(i, init_id);
  329. }
  330. if (is_init) {
  331. target.init_block->InsertHere();
  332. return AddInst<SemIR::TupleInit>(context, value_loc_id,
  333. {.type_id = target.type_id,
  334. .elements_id = new_block.id(),
  335. .dest_id = target.init_id});
  336. } else {
  337. return AddInst<SemIR::TupleValue>(
  338. context, value_loc_id,
  339. {.type_id = target.type_id, .elements_id = new_block.id()});
  340. }
  341. }
  342. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  343. template <typename TargetAccessInstT>
  344. static auto ConvertStructToStructOrClass(Context& context,
  345. SemIR::StructType src_type,
  346. SemIR::StructType dest_type,
  347. SemIR::InstId value_id,
  348. ConversionTarget target)
  349. -> SemIR::InstId {
  350. static_assert(std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT> ||
  351. std::is_same_v<SemIR::StructAccess, TargetAccessInstT>);
  352. constexpr bool ToClass =
  353. std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT>;
  354. auto& sem_ir = context.sem_ir();
  355. auto src_elem_fields = sem_ir.struct_type_fields().Get(src_type.fields_id);
  356. auto dest_elem_fields = sem_ir.struct_type_fields().Get(dest_type.fields_id);
  357. bool dest_has_vptr = !dest_elem_fields.empty() &&
  358. dest_elem_fields.front().name_id == SemIR::NameId::Vptr;
  359. int dest_vptr_offset = (dest_has_vptr ? 1 : 0);
  360. auto dest_elem_fields_size = dest_elem_fields.size() - dest_vptr_offset;
  361. auto value = sem_ir.insts().Get(value_id);
  362. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  363. // If we're initializing from a struct literal, we will use its elements
  364. // directly. Otherwise, materialize a temporary if needed and index into the
  365. // result.
  366. llvm::ArrayRef<SemIR::InstId> literal_elems;
  367. auto literal_elems_id = SemIR::InstBlockId::None;
  368. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  369. literal_elems_id = struct_literal->elements_id;
  370. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  371. } else {
  372. value_id = MaterializeIfInitializing(context, value_id);
  373. }
  374. // Check that the structs are the same size.
  375. // TODO: If not, include the name of the first source field that doesn't
  376. // exist in the destination or vice versa in the diagnostic.
  377. if (src_elem_fields.size() != dest_elem_fields_size) {
  378. if (target.diagnose) {
  379. CARBON_DIAGNOSTIC(
  380. StructInitElementCountMismatch, Error,
  381. "cannot initialize {0:class|struct} with {1} field{1:s} from struct "
  382. "with {2} field{2:s}",
  383. Diagnostics::BoolAsSelect, Diagnostics::IntAsSelect,
  384. Diagnostics::IntAsSelect);
  385. context.emitter().Emit(value_loc_id, StructInitElementCountMismatch,
  386. ToClass, dest_elem_fields_size,
  387. src_elem_fields.size());
  388. }
  389. return SemIR::ErrorInst::SingletonInstId;
  390. }
  391. // Prepare to look up fields in the source by index.
  392. Map<SemIR::NameId, int32_t> src_field_indexes;
  393. if (src_type.fields_id != dest_type.fields_id) {
  394. for (auto [i, field] : llvm::enumerate(src_elem_fields)) {
  395. auto result = src_field_indexes.Insert(field.name_id, i);
  396. CARBON_CHECK(result.is_inserted(), "Duplicate field in source structure");
  397. }
  398. }
  399. // If we're forming an initializer, then we want an initializer for each
  400. // element. Otherwise, we want a value representation for each element.
  401. // Perform a final destination store if we're performing an in-place
  402. // initialization.
  403. bool is_init = target.is_initializer();
  404. ConversionTarget::Kind inner_kind =
  405. !is_init ? ConversionTarget::Value
  406. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  407. SemIR::InitRepr::InPlace
  408. ? ConversionTarget::FullInitializer
  409. : ConversionTarget::Initializer;
  410. // Initialize each element of the destination from the corresponding element
  411. // of the source.
  412. // TODO: Annotate diagnostics coming from here with the element index.
  413. auto new_block =
  414. literal_elems_id.has_value() && !dest_has_vptr
  415. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  416. : SemIR::CopyOnWriteInstBlock(
  417. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  418. dest_elem_fields.size()});
  419. for (auto [i, dest_field] : llvm::enumerate(dest_elem_fields)) {
  420. if (dest_field.name_id == SemIR::NameId::Vptr) {
  421. if constexpr (!ToClass) {
  422. CARBON_FATAL("Only classes should have vptrs.");
  423. }
  424. target.init_block->InsertHere();
  425. auto dest_id =
  426. AddInst<SemIR::ClassElementAccess>(context, value_loc_id,
  427. {.type_id = dest_field.type_id,
  428. .base_id = target.init_id,
  429. .index = SemIR::ElementIndex(i)});
  430. auto vtable_ptr_id = AddInst<SemIR::VtablePtr>(
  431. context, value_loc_id, {.type_id = dest_field.type_id});
  432. auto init_id =
  433. AddInst<SemIR::InitializeFrom>(context, value_loc_id,
  434. {.type_id = dest_field.type_id,
  435. .src_id = vtable_ptr_id,
  436. .dest_id = dest_id});
  437. new_block.Set(i, init_id);
  438. continue;
  439. }
  440. // Find the matching source field.
  441. auto src_field_index = i;
  442. if (src_type.fields_id != dest_type.fields_id) {
  443. if (auto lookup = src_field_indexes.Lookup(dest_field.name_id)) {
  444. src_field_index = lookup.value();
  445. } else {
  446. if (target.diagnose) {
  447. if (literal_elems_id.has_value()) {
  448. CARBON_DIAGNOSTIC(
  449. StructInitMissingFieldInLiteral, Error,
  450. "missing value for field `{0}` in struct initialization",
  451. SemIR::NameId);
  452. context.emitter().Emit(value_loc_id,
  453. StructInitMissingFieldInLiteral,
  454. dest_field.name_id);
  455. } else {
  456. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  457. "cannot convert from struct type {0} to {1}: "
  458. "missing field `{2}` in source type",
  459. TypeOfInstId, SemIR::TypeId, SemIR::NameId);
  460. context.emitter().Emit(value_loc_id,
  461. StructInitMissingFieldInConversion, value_id,
  462. target.type_id, dest_field.name_id);
  463. }
  464. }
  465. return SemIR::ErrorInst::SingletonInstId;
  466. }
  467. }
  468. auto src_field = src_elem_fields[src_field_index];
  469. // TODO: This call recurses back into conversion. Switch to an iterative
  470. // approach.
  471. auto init_id =
  472. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  473. context, value_loc_id, value_id, src_field.type_id, literal_elems,
  474. inner_kind, target.init_id, dest_field.type_id, target.init_block,
  475. src_field_index, src_field_index + dest_vptr_offset);
  476. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  477. return SemIR::ErrorInst::SingletonInstId;
  478. }
  479. new_block.Set(i, init_id);
  480. }
  481. if (ToClass) {
  482. target.init_block->InsertHere();
  483. CARBON_CHECK(is_init,
  484. "Converting directly to a class value is not supported");
  485. return AddInst<SemIR::ClassInit>(context, value_loc_id,
  486. {.type_id = target.type_id,
  487. .elements_id = new_block.id(),
  488. .dest_id = target.init_id});
  489. } else if (is_init) {
  490. target.init_block->InsertHere();
  491. return AddInst<SemIR::StructInit>(context, value_loc_id,
  492. {.type_id = target.type_id,
  493. .elements_id = new_block.id(),
  494. .dest_id = target.init_id});
  495. } else {
  496. return AddInst<SemIR::StructValue>(
  497. context, value_loc_id,
  498. {.type_id = target.type_id, .elements_id = new_block.id()});
  499. }
  500. }
  501. // Performs a conversion from a struct to a struct type. This function only
  502. // converts the type, and does not perform a final conversion to the requested
  503. // expression category.
  504. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  505. SemIR::StructType dest_type,
  506. SemIR::InstId value_id,
  507. ConversionTarget target) -> SemIR::InstId {
  508. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  509. context, src_type, dest_type, value_id, target);
  510. }
  511. // Performs a conversion from a struct to a class type. This function only
  512. // converts the type, and does not perform a final conversion to the requested
  513. // expression category.
  514. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  515. SemIR::ClassType dest_type,
  516. SemIR::InstId value_id,
  517. ConversionTarget target) -> SemIR::InstId {
  518. PendingBlock target_block(&context);
  519. auto& dest_class_info = context.classes().Get(dest_type.class_id);
  520. CARBON_CHECK(dest_class_info.inheritance_kind != SemIR::Class::Abstract);
  521. auto object_repr_id =
  522. dest_class_info.GetObjectRepr(context.sem_ir(), dest_type.specific_id);
  523. if (object_repr_id == SemIR::ErrorInst::SingletonTypeId) {
  524. return SemIR::ErrorInst::SingletonInstId;
  525. }
  526. auto dest_struct_type =
  527. context.types().GetAs<SemIR::StructType>(object_repr_id);
  528. // If we're trying to create a class value, form a temporary for the value to
  529. // point to.
  530. bool need_temporary = !target.is_initializer();
  531. if (need_temporary) {
  532. target.kind = ConversionTarget::Initializer;
  533. target.init_block = &target_block;
  534. target.init_id = target_block.AddInstWithCleanup<SemIR::TemporaryStorage>(
  535. context.insts().GetLocId(value_id), {.type_id = target.type_id});
  536. }
  537. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  538. context, src_type, dest_struct_type, value_id, target);
  539. if (need_temporary) {
  540. target_block.InsertHere();
  541. result_id =
  542. AddInst<SemIR::Temporary>(context, context.insts().GetLocId(value_id),
  543. {.type_id = target.type_id,
  544. .storage_id = target.init_id,
  545. .init_id = result_id});
  546. }
  547. return result_id;
  548. }
  549. // An inheritance path is a sequence of `BaseDecl`s and corresponding base types
  550. // in order from derived to base.
  551. using InheritancePath =
  552. llvm::SmallVector<std::pair<SemIR::InstId, SemIR::TypeId>>;
  553. // Computes the inheritance path from class `derived_id` to class `base_id`.
  554. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  555. static auto ComputeInheritancePath(Context& context, SemIRLoc loc,
  556. SemIR::TypeId derived_id,
  557. SemIR::TypeId base_id)
  558. -> std::optional<InheritancePath> {
  559. // We intend for NRVO to be applied to `result`. All `return` statements in
  560. // this function should `return result;`.
  561. std::optional<InheritancePath> result(std::in_place);
  562. if (!TryToCompleteType(context, derived_id, loc)) {
  563. // TODO: Should we give an error here? If we don't, and there is an
  564. // inheritance path when the class is defined, we may have a coherence
  565. // problem.
  566. result = std::nullopt;
  567. return result;
  568. }
  569. while (derived_id != base_id) {
  570. auto derived_class_type =
  571. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  572. if (!derived_class_type) {
  573. result = std::nullopt;
  574. break;
  575. }
  576. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  577. auto base_type_id = derived_class.GetBaseType(
  578. context.sem_ir(), derived_class_type->specific_id);
  579. if (!base_type_id.has_value()) {
  580. result = std::nullopt;
  581. break;
  582. }
  583. result->push_back({derived_class.base_id, base_type_id});
  584. derived_id = base_type_id;
  585. }
  586. return result;
  587. }
  588. // Performs a conversion from a derived class value or reference to a base class
  589. // value or reference.
  590. static auto ConvertDerivedToBase(Context& context, SemIR::LocId loc_id,
  591. SemIR::InstId value_id,
  592. const InheritancePath& path) -> SemIR::InstId {
  593. // Materialize a temporary if necessary.
  594. value_id = ConvertToValueOrRefExpr(context, value_id);
  595. // Add a series of `.base` accesses.
  596. for (auto [base_id, base_type_id] : path) {
  597. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  598. value_id = AddInst<SemIR::ClassElementAccess>(context, loc_id,
  599. {.type_id = base_type_id,
  600. .base_id = value_id,
  601. .index = base_decl.index});
  602. }
  603. return value_id;
  604. }
  605. // Performs a conversion from a derived class pointer to a base class pointer.
  606. static auto ConvertDerivedPointerToBasePointer(
  607. Context& context, SemIR::LocId loc_id, SemIR::PointerType src_ptr_type,
  608. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  609. const InheritancePath& path) -> SemIR::InstId {
  610. // Form `*p`.
  611. ptr_id = ConvertToValueExpr(context, ptr_id);
  612. auto ref_id = AddInst<SemIR::Deref>(
  613. context, loc_id,
  614. {.type_id =
  615. context.types().GetTypeIdForTypeInstId(src_ptr_type.pointee_id),
  616. .pointer_id = ptr_id});
  617. // Convert as a reference expression.
  618. ref_id = ConvertDerivedToBase(context, loc_id, ref_id, path);
  619. // Take the address.
  620. return AddInst<SemIR::AddrOf>(
  621. context, loc_id, {.type_id = dest_ptr_type_id, .lvalue_id = ref_id});
  622. }
  623. // Returns whether `category` is a valid expression category to produce as a
  624. // result of a conversion with kind `target_kind`, or at most needs a temporary
  625. // to be materialized.
  626. static auto IsValidExprCategoryForConversionTarget(
  627. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  628. switch (target_kind) {
  629. case ConversionTarget::Value:
  630. return category == SemIR::ExprCategory::Value;
  631. case ConversionTarget::ValueOrRef:
  632. case ConversionTarget::Discarded:
  633. return category == SemIR::ExprCategory::Value ||
  634. category == SemIR::ExprCategory::DurableRef ||
  635. category == SemIR::ExprCategory::EphemeralRef ||
  636. category == SemIR::ExprCategory::Initializing;
  637. case ConversionTarget::ExplicitAs:
  638. return true;
  639. case ConversionTarget::Initializer:
  640. case ConversionTarget::FullInitializer:
  641. return category == SemIR::ExprCategory::Initializing;
  642. }
  643. }
  644. // Determines whether the initialization representation of the type is a copy of
  645. // the value representation.
  646. static auto InitReprIsCopyOfValueRepr(const SemIR::File& sem_ir,
  647. SemIR::TypeId type_id) -> bool {
  648. // The initializing representation is a copy of the value representation if
  649. // they're both copies of the object representation.
  650. return SemIR::InitRepr::ForType(sem_ir, type_id).IsCopyOfObjectRepr() &&
  651. SemIR::ValueRepr::ForType(sem_ir, type_id)
  652. .IsCopyOfObjectRepr(sem_ir, type_id);
  653. }
  654. // Determines whether we can pull a value directly out of an initializing
  655. // expression of type `type_id` to initialize a target of type `type_id` and
  656. // kind `target_kind`.
  657. static auto CanUseValueOfInitializer(const SemIR::File& sem_ir,
  658. SemIR::TypeId type_id,
  659. ConversionTarget::Kind target_kind)
  660. -> bool {
  661. if (!IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  662. target_kind)) {
  663. // We don't want a value expression.
  664. return false;
  665. }
  666. // We can pull a value out of an initializing expression if it holds one.
  667. return InitReprIsCopyOfValueRepr(sem_ir, type_id);
  668. }
  669. // Returns the non-adapter type that is compatible with the specified type.
  670. static auto GetTransitiveAdaptedType(Context& context, SemIR::TypeId type_id)
  671. -> SemIR::TypeId {
  672. // If the type is an adapter, its object representation type is its compatible
  673. // non-adapter type.
  674. while (auto class_type =
  675. context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  676. auto& class_info = context.classes().Get(class_type->class_id);
  677. auto adapted_type_id =
  678. class_info.GetAdaptedType(context.sem_ir(), class_type->specific_id);
  679. if (!adapted_type_id.has_value()) {
  680. break;
  681. }
  682. type_id = adapted_type_id;
  683. }
  684. // Otherwise, the type itself is a non-adapter type.
  685. return type_id;
  686. }
  687. static auto DiagnoseConversionFailureToConstraintValue(
  688. Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  689. SemIR::TypeId target_type_id) -> void {
  690. CARBON_DCHECK(target_type_id == SemIR::TypeType::SingletonTypeId ||
  691. context.types().Is<SemIR::FacetType>(target_type_id));
  692. auto type_of_expr_id = context.insts().Get(expr_id).type_id();
  693. CARBON_CHECK(context.types().IsFacetType(type_of_expr_id));
  694. // If the source type is/has a facet value, then we can include its
  695. // FacetType in the diagnostic to help explain what interfaces the
  696. // source type implements.
  697. auto facet_value_inst_id = SemIR::InstId::None;
  698. if (auto facet_access_type =
  699. context.insts().TryGetAs<SemIR::FacetAccessType>(expr_id)) {
  700. facet_value_inst_id = facet_access_type->facet_value_inst_id;
  701. } else if (context.types().Is<SemIR::FacetType>(type_of_expr_id)) {
  702. facet_value_inst_id = expr_id;
  703. }
  704. if (facet_value_inst_id.has_value()) {
  705. CARBON_DIAGNOSTIC(ConversionFailureFacetToFacet, Error,
  706. "cannot convert type {0} that implements {1} into type "
  707. "implementing {2}",
  708. InstIdAsType, TypeOfInstId, SemIR::TypeId);
  709. context.emitter().Emit(loc_id, ConversionFailureFacetToFacet, expr_id,
  710. facet_value_inst_id, target_type_id);
  711. } else {
  712. CARBON_DIAGNOSTIC(ConversionFailureTypeToFacet, Error,
  713. "cannot convert type {0} into type implementing {1}",
  714. InstIdAsType, SemIR::TypeId);
  715. context.emitter().Emit(loc_id, ConversionFailureTypeToFacet, expr_id,
  716. target_type_id);
  717. }
  718. }
  719. static auto PerformBuiltinConversion(Context& context, SemIR::LocId loc_id,
  720. SemIR::InstId value_id,
  721. ConversionTarget target) -> SemIR::InstId {
  722. auto& sem_ir = context.sem_ir();
  723. auto value = sem_ir.insts().Get(value_id);
  724. auto value_type_id = value.type_id();
  725. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  726. // Various forms of implicit conversion are supported as builtin conversions,
  727. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  728. // prelude. There are a few reasons we need to perform some of these
  729. // conversions as builtins:
  730. //
  731. // 1) Conversions from struct and tuple *literals* have special rules that
  732. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  733. // recurse into the elements of the literal before performing
  734. // initialization in order to avoid unnecessary conversions between
  735. // expression categories that would be performed by `ImplicitAs.Convert`.
  736. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  737. // the value of the facet, not only its type, and therefore cannot be
  738. // modeled by `ImplicitAs`.
  739. // 3) Some of these conversions are used while checking the library
  740. // definition of `ImplicitAs` itself or implementations of it.
  741. //
  742. // We also expect to see better performance by avoiding an `impl` lookup for
  743. // common conversions.
  744. //
  745. // TODO: We should provide a debugging flag to turn off as many of these
  746. // builtin conversions as we can so that we can test that they do the same
  747. // thing as the library implementations.
  748. //
  749. // The builtin conversions that correspond to `impl`s in the library all
  750. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  751. // being specialized in any of these cases.
  752. // If the value is already of the right kind and expression category, there's
  753. // nothing to do. Performing a conversion would decompose and rebuild tuples
  754. // and structs, so it's important that we bail out early in this case.
  755. if (value_type_id == target.type_id) {
  756. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  757. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  758. return value_id;
  759. }
  760. // If the source is an initializing expression, we may be able to pull a
  761. // value right out of it.
  762. if (value_cat == SemIR::ExprCategory::Initializing &&
  763. CanUseValueOfInitializer(sem_ir, value_type_id, target.kind)) {
  764. return AddInst<SemIR::ValueOfInitializer>(
  765. context, loc_id, {.type_id = value_type_id, .init_id = value_id});
  766. }
  767. // PerformBuiltinConversion converts each part of a tuple or struct, even
  768. // when the types are the same. This is not done for classes since they have
  769. // to define their conversions as part of their api.
  770. //
  771. // If a class adapts a tuple or struct, we convert each of its parts when
  772. // there's no other conversion going on (the source and target types are the
  773. // same). To do so, we have to insert a conversion of the value up to the
  774. // foundation and back down, and a conversion of the initializing object if
  775. // there is one.
  776. //
  777. // Implementation note: We do the conversion through a call to
  778. // PerformBuiltinConversion() call rather than a Convert() call to avoid
  779. // extraneous `converted` semir instructions on the adapted types, and as a
  780. // shortcut to doing the explicit calls to walk the parts of the
  781. // tuple/struct which happens inside PerformBuiltinConversion().
  782. if (auto foundation_type_id =
  783. GetTransitiveAdaptedType(context, value_type_id);
  784. foundation_type_id != value_type_id &&
  785. (context.types().Is<SemIR::TupleType>(foundation_type_id) ||
  786. context.types().Is<SemIR::StructType>(foundation_type_id))) {
  787. auto foundation_value_id = AddInst<SemIR::AsCompatible>(
  788. context, loc_id,
  789. {.type_id = foundation_type_id, .source_id = value_id});
  790. auto foundation_init_id = target.init_id;
  791. if (foundation_init_id != SemIR::InstId::None) {
  792. foundation_init_id = target.init_block->AddInst<SemIR::AsCompatible>(
  793. loc_id,
  794. {.type_id = foundation_type_id, .source_id = target.init_id});
  795. }
  796. {
  797. // While the types are the same, the conversion can still fail if it
  798. // performs a copy while converting the value to another category, and
  799. // the type (or some part of it) is not copyable.
  800. Diagnostics::AnnotationScope annotate_diagnostics(
  801. &context.emitter(), [&](auto& builder) {
  802. CARBON_DIAGNOSTIC(InCopy, Note, "in copy of {0}", TypeOfInstId);
  803. builder.Note(value_id, InCopy, value_id);
  804. });
  805. foundation_value_id =
  806. PerformBuiltinConversion(context, loc_id, foundation_value_id,
  807. {.kind = target.kind,
  808. .type_id = foundation_type_id,
  809. .init_id = foundation_init_id,
  810. .init_block = target.init_block,
  811. .diagnose = target.diagnose});
  812. if (foundation_value_id == SemIR::ErrorInst::SingletonInstId) {
  813. return SemIR::ErrorInst::SingletonInstId;
  814. }
  815. }
  816. return AddInst<SemIR::AsCompatible>(
  817. context, loc_id,
  818. {.type_id = target.type_id, .source_id = foundation_value_id});
  819. }
  820. }
  821. // T explicitly converts to U if T is compatible with U.
  822. if (target.kind == ConversionTarget::Kind::ExplicitAs &&
  823. target.type_id != value_type_id) {
  824. auto target_foundation_id =
  825. GetTransitiveAdaptedType(context, target.type_id);
  826. auto value_foundation_id = GetTransitiveAdaptedType(context, value_type_id);
  827. if (target_foundation_id == value_foundation_id) {
  828. // For a struct or tuple literal, perform a category conversion if
  829. // necessary.
  830. if (SemIR::GetExprCategory(context.sem_ir(), value_id) ==
  831. SemIR::ExprCategory::Mixed) {
  832. value_id = PerformBuiltinConversion(context, loc_id, value_id,
  833. {.kind = ConversionTarget::Value,
  834. .type_id = value_type_id,
  835. .diagnose = target.diagnose});
  836. }
  837. return AddInst<SemIR::AsCompatible>(
  838. context, loc_id, {.type_id = target.type_id, .source_id = value_id});
  839. }
  840. }
  841. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  842. // converts to Ui.
  843. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  844. if (auto src_tuple_type =
  845. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  846. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  847. value_id, target);
  848. }
  849. }
  850. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  851. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  852. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  853. // to Ui.
  854. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  855. if (auto src_struct_type =
  856. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  857. return ConvertStructToStruct(context, *src_struct_type,
  858. *target_struct_type, value_id, target);
  859. }
  860. }
  861. // A tuple (T1, T2, ..., Tn) converts to array(T, n) if each Ti converts to T.
  862. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  863. if (auto src_tuple_type =
  864. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  865. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  866. value_id, target);
  867. }
  868. }
  869. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  870. // if it converts to the struct type that is the class's representation type
  871. // (a struct with the same fields as the class, plus a base field where
  872. // relevant).
  873. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  874. if (auto src_struct_type =
  875. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  876. if (!context.classes()
  877. .Get(target_class_type->class_id)
  878. .adapt_id.has_value()) {
  879. return ConvertStructToClass(context, *src_struct_type,
  880. *target_class_type, value_id, target);
  881. }
  882. }
  883. // An expression of type T converts to U if T is a class derived from U.
  884. if (auto path = ComputeInheritancePath(context, loc_id, value_type_id,
  885. target.type_id);
  886. path && !path->empty()) {
  887. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  888. }
  889. }
  890. // A pointer T* converts to U* if T is a class derived from U.
  891. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  892. if (auto src_pointer_type =
  893. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  894. if (auto path =
  895. ComputeInheritancePath(context, loc_id,
  896. context.types().GetTypeIdForTypeInstId(
  897. src_pointer_type->pointee_id),
  898. context.types().GetTypeIdForTypeInstId(
  899. target_pointer_type->pointee_id));
  900. path && !path->empty()) {
  901. return ConvertDerivedPointerToBasePointer(
  902. context, loc_id, *src_pointer_type, target.type_id, value_id,
  903. *path);
  904. }
  905. }
  906. }
  907. if (target.type_id == SemIR::TypeType::SingletonTypeId) {
  908. // A tuple of types converts to type `type`.
  909. // TODO: This should apply even for non-literal tuples.
  910. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  911. llvm::SmallVector<SemIR::TypeId> type_ids;
  912. for (auto tuple_inst_id :
  913. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  914. // TODO: This call recurses back into conversion. Switch to an
  915. // iterative approach.
  916. type_ids.push_back(
  917. ExprAsType(context, loc_id, tuple_inst_id, target.diagnose)
  918. .type_id);
  919. }
  920. auto tuple_type_id = GetTupleType(context, type_ids);
  921. return sem_ir.types().GetInstId(tuple_type_id);
  922. }
  923. // `{}` converts to `{} as type`.
  924. // TODO: This conversion should also be performed for a non-literal value
  925. // of type `{}`.
  926. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  927. struct_literal &&
  928. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  929. value_id = sem_ir.types().GetInstId(value_type_id);
  930. }
  931. // Facet type conversions: a value T of facet type F1 can be implicitly
  932. // converted to facet type F2 if T satisfies the requirements of F2.
  933. //
  934. // TODO: Support this conversion in general. For now we only support it in
  935. // the case where F1 is a facet type and F2 is `type`.
  936. // TODO: Support converting tuple and struct values to facet types,
  937. // combining the above conversions and this one in a single conversion.
  938. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  939. return AddInst<SemIR::FacetAccessType>(
  940. context, loc_id,
  941. {.type_id = target.type_id, .facet_value_inst_id = value_id});
  942. }
  943. }
  944. if (target.type_id != value_type_id &&
  945. sem_ir.types().Is<SemIR::FacetType>(target.type_id) &&
  946. (sem_ir.types().Is<SemIR::TypeType>(value_type_id) ||
  947. sem_ir.types().Is<SemIR::FacetType>(value_type_id))) {
  948. // The value is a type or facet value, so it has a constant value. We get
  949. // that to unwrap things like NameRef and get to the underlying type or
  950. // facet value instruction so that we can use `TryGetAs`.
  951. auto const_value_id = sem_ir.constant_values().GetConstantInstId(value_id);
  952. // TODO: Runtime facet values should be allowed to convert based on their
  953. // FacetTypes, but we assume constant values for impl lookup at the moment.
  954. if (!const_value_id.has_value()) {
  955. context.TODO(loc_id, "conversion of runtime facet value");
  956. const_value_id = SemIR::ErrorInst::SingletonInstId;
  957. }
  958. if (auto facet_access_type_inst =
  959. sem_ir.insts().TryGetAs<SemIR::FacetAccessType>(const_value_id)) {
  960. // Conversion from a `FacetAccessType` to a `FacetValue` of the target
  961. // `FacetType` if the instruction in the `FacetAccessType` is of a
  962. // `FacetType` that satisfies the requirements of the target `FacetType`.
  963. // If the `FacetType` exactly matches the target `FacetType` then we can
  964. // shortcut and use that value, and avoid impl lookup.
  965. auto facet_value_inst_id = facet_access_type_inst->facet_value_inst_id;
  966. if (sem_ir.insts().Get(facet_value_inst_id).type_id() == target.type_id) {
  967. return facet_value_inst_id;
  968. }
  969. }
  970. // Conversion from a facet value (which has type `FacetType`) or a type
  971. // value (which has type `TypeType`) to a facet value. We can do this if the
  972. // type satisfies the requirements of the target `FacetType`, as determined
  973. // by finding impl witnesses for the target FacetType.
  974. auto lookup_result = LookupImplWitness(
  975. context, loc_id, sem_ir.constant_values().Get(const_value_id),
  976. sem_ir.types().GetConstantId(target.type_id));
  977. if (lookup_result.has_value()) {
  978. if (lookup_result.has_error_value()) {
  979. return SemIR::ErrorInst::SingletonInstId;
  980. } else {
  981. // We bind the input value to the target `FacetType` with a
  982. // `FacetValue`, which requires an instruction of type `TypeType`. So if
  983. // we are converting from a facet value, we get its `type` via an extra
  984. // `FacetAccessType` instruction.
  985. auto type_inst_id = SemIR::InstId::None;
  986. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  987. type_inst_id =
  988. AddInst(context, loc_id,
  989. SemIR::FacetAccessType{
  990. .type_id = SemIR::TypeType::SingletonTypeId,
  991. .facet_value_inst_id = const_value_id,
  992. });
  993. } else {
  994. type_inst_id = const_value_id;
  995. }
  996. return AddInst<SemIR::FacetValue>(
  997. context, loc_id,
  998. {.type_id = target.type_id,
  999. .type_inst_id = type_inst_id,
  1000. .witnesses_block_id = lookup_result.inst_block_id()});
  1001. }
  1002. } else {
  1003. // If impl lookup fails, don't keep looking for another way to convert.
  1004. // See https://github.com/carbon-language/carbon-lang/issues/5122.
  1005. // TODO: Pass this function into `LookupImplWitness` so it can construct
  1006. // the error add notes explaining failure.
  1007. if (target.diagnose) {
  1008. DiagnoseConversionFailureToConstraintValue(context, loc_id, value_id,
  1009. target.type_id);
  1010. }
  1011. return SemIR::ErrorInst::SingletonInstId;
  1012. }
  1013. }
  1014. // No builtin conversion applies.
  1015. return value_id;
  1016. }
  1017. // Given a value expression, form a corresponding initializer that copies from
  1018. // that value, if it is possible to do so.
  1019. static auto PerformCopy(Context& context, SemIR::InstId expr_id, bool diagnose)
  1020. -> SemIR::InstId {
  1021. auto expr = context.insts().Get(expr_id);
  1022. auto type_id = expr.type_id();
  1023. if (type_id == SemIR::ErrorInst::SingletonTypeId) {
  1024. return SemIR::ErrorInst::SingletonInstId;
  1025. }
  1026. if (InitReprIsCopyOfValueRepr(context.sem_ir(), type_id)) {
  1027. // For simple by-value types, no explicit action is required. Initializing
  1028. // from a value expression is treated as copying the value.
  1029. return expr_id;
  1030. }
  1031. // TODO: We don't yet have rules for whether and when a class type is
  1032. // copyable, or how to perform the copy.
  1033. if (diagnose) {
  1034. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  1035. "cannot copy value of type {0}", TypeOfInstId);
  1036. context.emitter().Emit(expr_id, CopyOfUncopyableType, expr_id);
  1037. }
  1038. return SemIR::ErrorInst::SingletonInstId;
  1039. }
  1040. auto PerformAction(Context& context, SemIR::LocId loc_id,
  1041. SemIR::ConvertToValueAction action) -> SemIR::InstId {
  1042. return Convert(
  1043. context, loc_id, action.inst_id,
  1044. {.kind = ConversionTarget::Value, .type_id = action.target_type_id});
  1045. }
  1046. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  1047. ConversionTarget target) -> SemIR::InstId {
  1048. auto& sem_ir = context.sem_ir();
  1049. auto orig_expr_id = expr_id;
  1050. // Start by making sure both sides are non-errors. If any part is an error,
  1051. // the result is an error and we shouldn't diagnose.
  1052. if (sem_ir.insts().Get(expr_id).type_id() ==
  1053. SemIR::ErrorInst::SingletonTypeId ||
  1054. target.type_id == SemIR::ErrorInst::SingletonTypeId) {
  1055. return SemIR::ErrorInst::SingletonInstId;
  1056. }
  1057. if (SemIR::GetExprCategory(sem_ir, expr_id) == SemIR::ExprCategory::NotExpr) {
  1058. // TODO: We currently encounter this for use of namespaces and functions.
  1059. // We should provide a better diagnostic for inappropriate use of
  1060. // namespace names, and allow use of functions as values.
  1061. if (target.diagnose) {
  1062. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  1063. "expression cannot be used as a value");
  1064. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  1065. }
  1066. return SemIR::ErrorInst::SingletonInstId;
  1067. }
  1068. // We can only perform initialization for complete, non-abstract types. Note
  1069. // that `RequireConcreteType` returns true for facet types, since their
  1070. // representation is fixed. This allows us to support using the `Self` of an
  1071. // interface inside its definition.
  1072. if (!RequireConcreteType(
  1073. context, target.type_id, loc_id,
  1074. [&] {
  1075. CARBON_CHECK(!target.is_initializer(),
  1076. "Initialization of incomplete types is expected to be "
  1077. "caught elsewhere.");
  1078. if (!target.diagnose) {
  1079. return context.emitter().BuildSuppressed();
  1080. }
  1081. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  1082. "forming value of incomplete type {0}",
  1083. SemIR::TypeId);
  1084. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  1085. "invalid use of incomplete type {0}",
  1086. SemIR::TypeId);
  1087. return context.emitter().Build(
  1088. loc_id,
  1089. target.kind == ConversionTarget::Value
  1090. ? IncompleteTypeInValueConversion
  1091. : IncompleteTypeInConversion,
  1092. target.type_id);
  1093. },
  1094. [&] {
  1095. if (!target.diagnose || !target.is_initializer()) {
  1096. return context.emitter().BuildSuppressed();
  1097. }
  1098. CARBON_DIAGNOSTIC(AbstractTypeInInit, Error,
  1099. "initialization of abstract type {0}",
  1100. SemIR::TypeId);
  1101. return context.emitter().Build(loc_id, AbstractTypeInInit,
  1102. target.type_id);
  1103. })) {
  1104. return SemIR::ErrorInst::SingletonInstId;
  1105. }
  1106. // Check whether any builtin conversion applies.
  1107. expr_id = PerformBuiltinConversion(context, loc_id, expr_id, target);
  1108. if (expr_id == SemIR::ErrorInst::SingletonInstId) {
  1109. return expr_id;
  1110. }
  1111. // Defer the action if it's dependent. We do this now rather than before
  1112. // attempting any conversion so that we can still perform builtin conversions
  1113. // on dependent arguments. This matters for things like converting a
  1114. // `template T:! SomeInterface` to `type`, where it's important to form a
  1115. // `FacetAccessType` when checking the template. But when running the action
  1116. // later, we need to try builtin conversions again, because one may apply that
  1117. // didn't apply in the template definition.
  1118. // TODO: Support this for targets other than `Value`.
  1119. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id &&
  1120. target.kind == ConversionTarget::Value &&
  1121. (OperandIsDependent(context, expr_id) ||
  1122. OperandIsDependent(context, target.type_id))) {
  1123. return AddDependentActionSplice(
  1124. context, loc_id,
  1125. SemIR::ConvertToValueAction{.type_id = SemIR::InstType::SingletonTypeId,
  1126. .inst_id = expr_id,
  1127. .target_type_id = target.type_id},
  1128. target.type_id);
  1129. }
  1130. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  1131. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id) {
  1132. SemIR::InstId interface_args[] = {
  1133. context.types().GetInstId(target.type_id)};
  1134. Operator op = {
  1135. .interface_name = target.kind == ConversionTarget::ExplicitAs
  1136. ? llvm::StringLiteral("As")
  1137. : llvm::StringLiteral("ImplicitAs"),
  1138. .interface_args_ref = interface_args,
  1139. .op_name = "Convert",
  1140. };
  1141. expr_id = BuildUnaryOperator(context, loc_id, op, expr_id, [&] {
  1142. if (!target.diagnose) {
  1143. return context.emitter().BuildSuppressed();
  1144. }
  1145. if (target.type_id == SemIR::TypeType::SingletonTypeId ||
  1146. sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1147. CARBON_DIAGNOSTIC(
  1148. ConversionFailureNonTypeToFacet, Error,
  1149. "cannot{0:| implicitly} convert non-type value of type {1} "
  1150. "{2:to|into type implementing} {3}{0: with `as`|}",
  1151. Diagnostics::BoolAsSelect, TypeOfInstId, Diagnostics::BoolAsSelect,
  1152. SemIR::TypeId);
  1153. return context.emitter().Build(
  1154. loc_id, ConversionFailureNonTypeToFacet,
  1155. target.kind == ConversionTarget::ExplicitAs, expr_id,
  1156. target.type_id == SemIR::TypeType::SingletonTypeId, target.type_id);
  1157. } else {
  1158. CARBON_DIAGNOSTIC(ConversionFailure, Error,
  1159. "cannot{0:| implicitly} convert expression of type "
  1160. "{1} to {2}{0: with `as`|}",
  1161. Diagnostics::BoolAsSelect, TypeOfInstId,
  1162. SemIR::TypeId);
  1163. return context.emitter().Build(
  1164. loc_id, ConversionFailure,
  1165. target.kind == ConversionTarget::ExplicitAs, expr_id,
  1166. target.type_id);
  1167. }
  1168. });
  1169. // Pull a value directly out of the initializer if possible and wanted.
  1170. if (expr_id != SemIR::ErrorInst::SingletonInstId &&
  1171. CanUseValueOfInitializer(sem_ir, target.type_id, target.kind)) {
  1172. expr_id = AddInst<SemIR::ValueOfInitializer>(
  1173. context, loc_id, {.type_id = target.type_id, .init_id = expr_id});
  1174. }
  1175. }
  1176. // Track that we performed a type conversion, if we did so.
  1177. if (orig_expr_id != expr_id) {
  1178. expr_id = AddInst<SemIR::Converted>(context, loc_id,
  1179. {.type_id = target.type_id,
  1180. .original_id = orig_expr_id,
  1181. .result_id = expr_id});
  1182. }
  1183. // For `as`, don't perform any value category conversions. In particular, an
  1184. // identity conversion shouldn't change the expression category.
  1185. if (target.kind == ConversionTarget::ExplicitAs) {
  1186. return expr_id;
  1187. }
  1188. // Now perform any necessary value category conversions.
  1189. switch (SemIR::GetExprCategory(sem_ir, expr_id)) {
  1190. case SemIR::ExprCategory::NotExpr:
  1191. case SemIR::ExprCategory::Mixed:
  1192. CARBON_FATAL("Unexpected expression {0} after builtin conversions",
  1193. sem_ir.insts().Get(expr_id));
  1194. case SemIR::ExprCategory::Error:
  1195. return SemIR::ErrorInst::SingletonInstId;
  1196. case SemIR::ExprCategory::Initializing:
  1197. if (target.is_initializer()) {
  1198. if (orig_expr_id == expr_id) {
  1199. // Don't fill in the return slot if we created the expression through
  1200. // a conversion. In that case, we will have created it with the
  1201. // target already set.
  1202. // TODO: Find a better way to track whether we need to do this.
  1203. MarkInitializerFor(sem_ir, expr_id, target.init_id,
  1204. *target.init_block);
  1205. }
  1206. break;
  1207. }
  1208. // Commit to using a temporary for this initializing expression.
  1209. // TODO: Don't create a temporary if the initializing representation
  1210. // is already a value representation.
  1211. expr_id = FinalizeTemporary(context, expr_id,
  1212. target.kind == ConversionTarget::Discarded);
  1213. // We now have an ephemeral reference.
  1214. [[fallthrough]];
  1215. case SemIR::ExprCategory::DurableRef:
  1216. case SemIR::ExprCategory::EphemeralRef:
  1217. // If a reference expression is an acceptable result, we're done.
  1218. if (target.kind == ConversionTarget::ValueOrRef ||
  1219. target.kind == ConversionTarget::Discarded) {
  1220. break;
  1221. }
  1222. // If we have a reference and don't want one, form a value binding.
  1223. // TODO: Support types with custom value representations.
  1224. expr_id = AddInst<SemIR::BindValue>(
  1225. context, context.insts().GetLocId(expr_id),
  1226. {.type_id = target.type_id, .value_id = expr_id});
  1227. // We now have a value expression.
  1228. [[fallthrough]];
  1229. case SemIR::ExprCategory::Value:
  1230. // When initializing from a value, perform a copy.
  1231. if (target.is_initializer()) {
  1232. expr_id = PerformCopy(context, expr_id, target.diagnose);
  1233. }
  1234. break;
  1235. }
  1236. // Perform a final destination store, if necessary.
  1237. if (target.kind == ConversionTarget::FullInitializer) {
  1238. if (auto init_rep = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  1239. init_rep.kind == SemIR::InitRepr::ByCopy) {
  1240. target.init_block->InsertHere();
  1241. expr_id = AddInst<SemIR::InitializeFrom>(context, loc_id,
  1242. {.type_id = target.type_id,
  1243. .src_id = expr_id,
  1244. .dest_id = target.init_id});
  1245. }
  1246. }
  1247. return expr_id;
  1248. }
  1249. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId target_id,
  1250. SemIR::InstId value_id) -> SemIR::InstId {
  1251. PendingBlock target_block(&context);
  1252. return Convert(context, loc_id, value_id,
  1253. {.kind = ConversionTarget::Initializer,
  1254. .type_id = context.insts().Get(target_id).type_id(),
  1255. .init_id = target_id,
  1256. .init_block = &target_block});
  1257. }
  1258. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  1259. -> SemIR::InstId {
  1260. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  1261. {.kind = ConversionTarget::Value,
  1262. .type_id = context.insts().Get(expr_id).type_id()});
  1263. }
  1264. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  1265. -> SemIR::InstId {
  1266. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  1267. {.kind = ConversionTarget::ValueOrRef,
  1268. .type_id = context.insts().Get(expr_id).type_id()});
  1269. }
  1270. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1271. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1272. -> SemIR::InstId {
  1273. return Convert(context, loc_id, expr_id,
  1274. {.kind = ConversionTarget::Value, .type_id = type_id});
  1275. }
  1276. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1277. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1278. -> SemIR::InstId {
  1279. return Convert(context, loc_id, expr_id,
  1280. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1281. }
  1282. // Like ConvertToValueOfType but failure to convert does not result in
  1283. // diagnostics. An ErrorInst instruction is still returned on failure.
  1284. auto TryConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1285. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1286. -> SemIR::InstId {
  1287. return Convert(
  1288. context, loc_id, expr_id,
  1289. {.kind = ConversionTarget::Value, .type_id = type_id, .diagnose = false});
  1290. }
  1291. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1292. SemIR::InstId value_id) -> SemIR::InstId {
  1293. return ConvertToValueOfType(
  1294. context, loc_id, value_id,
  1295. GetSingletonType(context, SemIR::BoolType::SingletonInstId));
  1296. }
  1297. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1298. SemIR::InstId value_id, SemIR::TypeId type_id)
  1299. -> SemIR::InstId {
  1300. return Convert(context, as_node, value_id,
  1301. {.kind = ConversionTarget::ExplicitAs, .type_id = type_id});
  1302. }
  1303. // TODO: Consider moving this to pattern_match.h.
  1304. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1305. SemIR::InstId self_id,
  1306. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1307. SemIR::InstId return_slot_arg_id,
  1308. const SemIR::Function& callee,
  1309. SemIR::SpecificId callee_specific_id)
  1310. -> SemIR::InstBlockId {
  1311. // The callee reference can be invalidated by conversions, so ensure all reads
  1312. // from it are done before conversion calls.
  1313. auto callee_decl_id = callee.latest_decl_id();
  1314. auto param_patterns =
  1315. context.inst_blocks().GetOrEmpty(callee.param_patterns_id);
  1316. auto return_slot_pattern_id = callee.return_slot_pattern_id;
  1317. // The caller should have ensured this callee has the right arity.
  1318. CARBON_CHECK(arg_refs.size() == param_patterns.size());
  1319. if (callee.self_param_id.has_value() && !self_id.has_value()) {
  1320. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1321. "missing object argument in method call");
  1322. CARBON_DIAGNOSTIC(InCallToFunction, Note, "calling function declared here");
  1323. context.emitter()
  1324. .Build(call_loc_id, MissingObjectInMethodCall)
  1325. .Note(callee_decl_id, InCallToFunction)
  1326. .Emit();
  1327. self_id = SemIR::ErrorInst::SingletonInstId;
  1328. }
  1329. return CallerPatternMatch(context, callee_specific_id, callee.self_param_id,
  1330. callee.param_patterns_id, return_slot_pattern_id,
  1331. self_id, arg_refs, return_slot_arg_id);
  1332. }
  1333. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  1334. bool diagnose) -> TypeExpr {
  1335. auto type_inst_id = ConvertToValueOfType(context, loc_id, value_id,
  1336. SemIR::TypeType::SingletonTypeId);
  1337. if (type_inst_id == SemIR::ErrorInst::SingletonInstId) {
  1338. return {.inst_id = type_inst_id,
  1339. .type_id = SemIR::ErrorInst::SingletonTypeId};
  1340. }
  1341. auto type_const_id = context.constant_values().Get(type_inst_id);
  1342. if (!type_const_id.is_constant()) {
  1343. if (diagnose) {
  1344. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1345. "cannot evaluate type expression");
  1346. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1347. }
  1348. return {.inst_id = SemIR::ErrorInst::SingletonInstId,
  1349. .type_id = SemIR::ErrorInst::SingletonTypeId};
  1350. }
  1351. return {.inst_id = type_inst_id,
  1352. .type_id = context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1353. }
  1354. } // namespace Carbon::Check
  1355. // NOLINTEND(misc-no-recursion)