convert.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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 "llvm/ADT/STLExtras.h"
  9. #include "toolchain/check/context.h"
  10. #include "toolchain/diagnostics/diagnostic_kind.h"
  11. #include "toolchain/parse/node_kind.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/node.h"
  14. #include "toolchain/sem_ir/node_kind.h"
  15. namespace Carbon::Check {
  16. // Given an initializing expression, find its return slot. Returns `Invalid` if
  17. // there is no return slot, because the initialization is not performed in
  18. // place.
  19. static auto FindReturnSlotForInitializer(SemIR::File& semantics_ir,
  20. SemIR::NodeId init_id)
  21. -> SemIR::NodeId {
  22. SemIR::Node init = semantics_ir.GetNode(init_id);
  23. switch (init.kind()) {
  24. default:
  25. CARBON_FATAL() << "Initialization from unexpected node " << init;
  26. case SemIR::StructInit::Kind:
  27. case SemIR::TupleInit::Kind:
  28. // TODO: Track a return slot for these initializers.
  29. CARBON_FATAL() << init
  30. << " should be created with its return slot already "
  31. "filled in properly";
  32. case SemIR::InitializeFrom::Kind: {
  33. return init.As<SemIR::InitializeFrom>().dest_id;
  34. }
  35. case SemIR::Call::Kind: {
  36. auto call = init.As<SemIR::Call>();
  37. if (!SemIR::GetInitializingRepresentation(semantics_ir, call.type_id)
  38. .has_return_slot()) {
  39. return SemIR::NodeId::Invalid;
  40. }
  41. return semantics_ir.GetNodeBlock(call.args_id).back();
  42. }
  43. case SemIR::ArrayInit::Kind: {
  44. return semantics_ir
  45. .GetNodeBlock(init.As<SemIR::ArrayInit>().inits_and_return_slot_id)
  46. .back();
  47. }
  48. }
  49. }
  50. // Marks the initializer `init_id` as initializing `target_id`.
  51. static auto MarkInitializerFor(SemIR::File& semantics_ir, SemIR::NodeId init_id,
  52. SemIR::NodeId target_id,
  53. PendingBlock& target_block) -> void {
  54. auto return_slot_id = FindReturnSlotForInitializer(semantics_ir, init_id);
  55. if (return_slot_id.is_valid()) {
  56. // Replace the temporary in the return slot with a reference to our target.
  57. CARBON_CHECK(semantics_ir.GetNode(return_slot_id).kind() ==
  58. SemIR::TemporaryStorage::Kind)
  59. << "Return slot for initializer does not contain a temporary; "
  60. << "initialized multiple times? Have "
  61. << semantics_ir.GetNode(return_slot_id);
  62. target_block.MergeReplacing(return_slot_id, target_id);
  63. }
  64. }
  65. // Commits to using a temporary to store the result of the initializing
  66. // expression described by `init_id`, and returns the location of the
  67. // temporary. If `discarded` is `true`, the result is discarded, and no
  68. // temporary will be created if possible; if no temporary is created, the
  69. // return value will be `SemIR::NodeId::Invalid`.
  70. static auto FinalizeTemporary(Context& context, SemIR::NodeId init_id,
  71. bool discarded) -> SemIR::NodeId {
  72. auto& semantics_ir = context.semantics_ir();
  73. auto return_slot_id = FindReturnSlotForInitializer(semantics_ir, init_id);
  74. if (return_slot_id.is_valid()) {
  75. // The return slot should already have a materialized temporary in it.
  76. CARBON_CHECK(semantics_ir.GetNode(return_slot_id).kind() ==
  77. SemIR::TemporaryStorage::Kind)
  78. << "Return slot for initializer does not contain a temporary; "
  79. << "initialized multiple times? Have "
  80. << semantics_ir.GetNode(return_slot_id);
  81. auto init = semantics_ir.GetNode(init_id);
  82. return context.AddNode(SemIR::Temporary(init.parse_node(), init.type_id(),
  83. return_slot_id, init_id));
  84. }
  85. if (discarded) {
  86. // Don't invent a temporary that we're going to discard.
  87. return SemIR::NodeId::Invalid;
  88. }
  89. // The initializer has no return slot, but we want to produce a temporary
  90. // object. Materialize one now.
  91. // TODO: Consider using an invalid ID to mean that we immediately
  92. // materialize and initialize a temporary, rather than two separate
  93. // nodes.
  94. auto init = semantics_ir.GetNode(init_id);
  95. auto temporary_id = context.AddNode(
  96. SemIR::TemporaryStorage(init.parse_node(), init.type_id()));
  97. return context.AddNode(SemIR::Temporary(init.parse_node(), init.type_id(),
  98. temporary_id, init_id));
  99. }
  100. // Materialize a temporary to hold the result of the given expression if it is
  101. // an initializing expression.
  102. static auto MaterializeIfInitializing(Context& context, SemIR::NodeId expr_id)
  103. -> SemIR::NodeId {
  104. if (GetExpressionCategory(context.semantics_ir(), expr_id) ==
  105. SemIR::ExpressionCategory::Initializing) {
  106. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  107. }
  108. return expr_id;
  109. }
  110. // Creates and adds a node to perform element access into an aggregate.
  111. template <typename AccessNodeT, typename NodeBlockT>
  112. static auto MakeElemAccessNode(Context& context, Parse::Node parse_node,
  113. SemIR::NodeId aggregate_id,
  114. SemIR::TypeId elem_type_id, NodeBlockT& block,
  115. std::size_t i) {
  116. if constexpr (std::is_same_v<AccessNodeT, SemIR::ArrayIndex>) {
  117. // TODO: Add a new node kind for indexing an array at a constant index
  118. // so that we don't need an integer literal node here, and remove this
  119. // special case.
  120. auto index_id = block.AddNode(SemIR::IntegerLiteral(
  121. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::IntegerType),
  122. context.semantics_ir().AddInteger(llvm::APInt(32, i))));
  123. return block.AddNode(
  124. AccessNodeT(parse_node, elem_type_id, aggregate_id, index_id));
  125. } else {
  126. return block.AddNode(AccessNodeT(parse_node, elem_type_id, aggregate_id,
  127. SemIR::MemberIndex(i)));
  128. }
  129. }
  130. // Converts an element of one aggregate so that it can be used as an element of
  131. // another aggregate.
  132. //
  133. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  134. // element type, `i` is the index, and `SourceAccessNodeT` is the kind of node
  135. // used to access the source element.
  136. //
  137. // For the target: `kind` is the kind of conversion or initialization,
  138. // `target_elem_type` is the element type. For initialization, `target_id` is
  139. // the destination, `target_block` is a pending block for target location
  140. // calculations that will be spliced as the return slot of the initializer if
  141. // necessary, `i` is the index, and `TargetAccessNodeT` is the kind of node
  142. // used to access the destination element.
  143. template <typename SourceAccessNodeT, typename TargetAccessNodeT>
  144. static auto ConvertAggregateElement(
  145. Context& context, Parse::Node parse_node, SemIR::NodeId src_id,
  146. SemIR::TypeId src_elem_type,
  147. llvm::ArrayRef<SemIR::NodeId> src_literal_elems,
  148. ConversionTarget::Kind kind, SemIR::NodeId target_id,
  149. SemIR::TypeId target_elem_type, PendingBlock* target_block, std::size_t i) {
  150. // Compute the location of the source element. This goes into the current code
  151. // block, not into the target block.
  152. // TODO: Ideally we would discard this node if it's unused.
  153. auto src_elem_id =
  154. !src_literal_elems.empty()
  155. ? src_literal_elems[i]
  156. : MakeElemAccessNode<SourceAccessNodeT>(context, parse_node, src_id,
  157. src_elem_type, context, i);
  158. // If we're performing a conversion rather than an initialization, we won't
  159. // have or need a target.
  160. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  161. if (!target.is_initializer()) {
  162. return Convert(context, parse_node, src_elem_id, target);
  163. }
  164. // Compute the location of the target element and initialize it.
  165. PendingBlock::DiscardUnusedNodesScope scope(target_block);
  166. target.init_block = target_block;
  167. target.init_id = MakeElemAccessNode<TargetAccessNodeT>(
  168. context, parse_node, target_id, target_elem_type, *target_block, i);
  169. return Convert(context, parse_node, src_elem_id, target);
  170. }
  171. namespace {
  172. // A handle to a new block that may be modified, with copy-on-write semantics.
  173. //
  174. // The constructor is given the ID of an existing block that provides the
  175. // initial contents of the new block. The new block is lazily allocated; if no
  176. // modifications have been made, the `id()` function will return the original
  177. // block ID.
  178. //
  179. // This is intended to avoid an unnecessary block allocation in the case where
  180. // the new block ends up being exactly the same as the original block.
  181. class CopyOnWriteBlock {
  182. public:
  183. // Constructs the block. If `source_id` is valid, it is used as the initial
  184. // value of the block. Otherwise, uninitialized storage for `size` elements
  185. // is allocated.
  186. CopyOnWriteBlock(SemIR::File& file, SemIR::NodeBlockId source_id, size_t size)
  187. : file_(file), source_id_(source_id) {
  188. if (!source_id_.is_valid()) {
  189. id_ = file_.AddUninitializedNodeBlock(size);
  190. }
  191. }
  192. auto id() -> SemIR::NodeBlockId const { return id_; }
  193. auto Set(int i, SemIR::NodeId value) -> void {
  194. if (source_id_.is_valid() && file_.GetNodeBlock(id_)[i] == value) {
  195. return;
  196. }
  197. if (id_ == source_id_) {
  198. id_ = file_.AddNodeBlock(file_.GetNodeBlock(source_id_));
  199. }
  200. file_.GetNodeBlock(id_)[i] = value;
  201. }
  202. private:
  203. SemIR::File& file_;
  204. SemIR::NodeBlockId source_id_;
  205. SemIR::NodeBlockId id_ = source_id_;
  206. };
  207. } // namespace
  208. // Performs a conversion from a tuple to an array type. Does not perform a
  209. // final conversion to the requested expression category.
  210. static auto ConvertTupleToArray(Context& context,
  211. SemIR::TupleType::Data tuple_type,
  212. SemIR::ArrayType::Data array_type,
  213. SemIR::NodeId value_id, ConversionTarget target)
  214. -> SemIR::NodeId {
  215. auto& semantics_ir = context.semantics_ir();
  216. auto tuple_elem_types = semantics_ir.GetTypeBlock(tuple_type.elements_id);
  217. auto value = semantics_ir.GetNode(value_id);
  218. // If we're initializing from a tuple literal, we will use its elements
  219. // directly. Otherwise, materialize a temporary if needed and index into the
  220. // result.
  221. llvm::ArrayRef<SemIR::NodeId> literal_elems;
  222. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  223. literal_elems = semantics_ir.GetNodeBlock(tuple_literal->elements_id);
  224. } else {
  225. value_id = MaterializeIfInitializing(context, value_id);
  226. }
  227. // Check that the tuple is the right size.
  228. uint64_t array_bound = semantics_ir.GetArrayBoundValue(array_type.bound_id);
  229. if (tuple_elem_types.size() != array_bound) {
  230. CARBON_DIAGNOSTIC(
  231. ArrayInitFromLiteralArgCountMismatch, Error,
  232. "Cannot initialize array of {0} element(s) from {1} initializer(s).",
  233. uint64_t, size_t);
  234. CARBON_DIAGNOSTIC(ArrayInitFromExpressionArgCountMismatch, Error,
  235. "Cannot initialize array of {0} element(s) from tuple "
  236. "with {1} element(s).",
  237. uint64_t, size_t);
  238. context.emitter().Emit(value.parse_node(),
  239. literal_elems.empty()
  240. ? ArrayInitFromExpressionArgCountMismatch
  241. : ArrayInitFromLiteralArgCountMismatch,
  242. array_bound, tuple_elem_types.size());
  243. return SemIR::NodeId::BuiltinError;
  244. }
  245. PendingBlock target_block_storage(context);
  246. PendingBlock* target_block =
  247. target.init_block ? target.init_block : &target_block_storage;
  248. // Arrays are always initialized in-place. Allocate a temporary as the
  249. // destination for the array initialization if we weren't given one.
  250. SemIR::NodeId return_slot_id = target.init_id;
  251. if (!target.init_id.is_valid()) {
  252. return_slot_id = target_block->AddNode(
  253. SemIR::TemporaryStorage(value.parse_node(), target.type_id));
  254. }
  255. // Initialize each element of the array from the corresponding element of the
  256. // tuple.
  257. // TODO: Annotate diagnostics coming from here with the array element index,
  258. // if initializing from a tuple literal.
  259. llvm::SmallVector<SemIR::NodeId> inits;
  260. inits.reserve(array_bound + 1);
  261. for (auto [i, src_type_id] : llvm::enumerate(tuple_elem_types)) {
  262. // TODO: This call recurses back into conversion. Switch to an iterative
  263. // approach.
  264. auto init_id =
  265. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  266. context, value.parse_node(), value_id, src_type_id, literal_elems,
  267. ConversionTarget::FullInitializer, return_slot_id,
  268. array_type.element_type_id, target_block, i);
  269. if (init_id == SemIR::NodeId::BuiltinError) {
  270. return SemIR::NodeId::BuiltinError;
  271. }
  272. inits.push_back(init_id);
  273. }
  274. // The last element of the refs block contains the return slot for the array
  275. // initialization. Flush the temporary here if we didn't insert it earlier.
  276. target_block->InsertHere();
  277. inits.push_back(return_slot_id);
  278. return context.AddNode(SemIR::ArrayInit(value.parse_node(), target.type_id,
  279. value_id,
  280. semantics_ir.AddNodeBlock(inits)));
  281. }
  282. // Performs a conversion from a tuple to a tuple type. Does not perform a
  283. // final conversion to the requested expression category.
  284. static auto ConvertTupleToTuple(Context& context,
  285. SemIR::TupleType::Data src_type,
  286. SemIR::TupleType::Data dest_type,
  287. SemIR::NodeId value_id, ConversionTarget target)
  288. -> SemIR::NodeId {
  289. auto& semantics_ir = context.semantics_ir();
  290. auto src_elem_types = semantics_ir.GetTypeBlock(src_type.elements_id);
  291. auto dest_elem_types = semantics_ir.GetTypeBlock(dest_type.elements_id);
  292. auto value = semantics_ir.GetNode(value_id);
  293. // If we're initializing from a tuple literal, we will use its elements
  294. // directly. Otherwise, materialize a temporary if needed and index into the
  295. // result.
  296. llvm::ArrayRef<SemIR::NodeId> literal_elems;
  297. auto literal_elems_id = SemIR::NodeBlockId::Invalid;
  298. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  299. literal_elems_id = tuple_literal->elements_id;
  300. literal_elems = semantics_ir.GetNodeBlock(literal_elems_id);
  301. } else {
  302. value_id = MaterializeIfInitializing(context, value_id);
  303. }
  304. // Check that the tuples are the same size.
  305. if (src_elem_types.size() != dest_elem_types.size()) {
  306. CARBON_DIAGNOSTIC(TupleInitElementCountMismatch, Error,
  307. "Cannot initialize tuple of {0} element(s) from tuple "
  308. "with {1} element(s).",
  309. size_t, size_t);
  310. context.emitter().Emit(value.parse_node(), TupleInitElementCountMismatch,
  311. dest_elem_types.size(), src_elem_types.size());
  312. return SemIR::NodeId::BuiltinError;
  313. }
  314. // If we're forming an initializer, then we want an initializer for each
  315. // element. Otherwise, we want a value representation for each element.
  316. // Perform a final destination store if we're performing an in-place
  317. // initialization.
  318. bool is_init = target.is_initializer();
  319. ConversionTarget::Kind inner_kind =
  320. !is_init ? ConversionTarget::Value
  321. : SemIR::GetInitializingRepresentation(semantics_ir, target.type_id)
  322. .kind == SemIR::InitializingRepresentation::InPlace
  323. ? ConversionTarget::FullInitializer
  324. : ConversionTarget::Initializer;
  325. // Initialize each element of the destination from the corresponding element
  326. // of the source.
  327. // TODO: Annotate diagnostics coming from here with the element index.
  328. CopyOnWriteBlock new_block(semantics_ir, literal_elems_id,
  329. src_elem_types.size());
  330. for (auto [i, src_type_id, dest_type_id] :
  331. llvm::enumerate(src_elem_types, dest_elem_types)) {
  332. // TODO: This call recurses back into conversion. Switch to an iterative
  333. // approach.
  334. auto init_id =
  335. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  336. context, value.parse_node(), value_id, src_type_id, literal_elems,
  337. inner_kind, target.init_id, dest_type_id, target.init_block, i);
  338. if (init_id == SemIR::NodeId::BuiltinError) {
  339. return SemIR::NodeId::BuiltinError;
  340. }
  341. new_block.Set(i, init_id);
  342. }
  343. return is_init ? context.AddNode(SemIR::TupleInit(value.parse_node(),
  344. target.type_id, value_id,
  345. new_block.id()))
  346. : context.AddNode(SemIR::TupleValue(value.parse_node(),
  347. target.type_id, value_id,
  348. new_block.id()));
  349. }
  350. // Performs a conversion from a struct to a struct type. Does not perform a
  351. // final conversion to the requested expression category.
  352. static auto ConvertStructToStruct(Context& context,
  353. SemIR::StructType::Data src_type,
  354. SemIR::StructType::Data dest_type,
  355. SemIR::NodeId value_id,
  356. ConversionTarget target) -> SemIR::NodeId {
  357. auto& semantics_ir = context.semantics_ir();
  358. auto src_elem_fields = semantics_ir.GetNodeBlock(src_type.fields_id);
  359. auto dest_elem_fields = semantics_ir.GetNodeBlock(dest_type.fields_id);
  360. auto value = semantics_ir.GetNode(value_id);
  361. // If we're initializing from a struct literal, we will use its elements
  362. // directly. Otherwise, materialize a temporary if needed and index into the
  363. // result.
  364. llvm::ArrayRef<SemIR::NodeId> literal_elems;
  365. auto literal_elems_id = SemIR::NodeBlockId::Invalid;
  366. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  367. literal_elems_id = struct_literal->elements_id;
  368. literal_elems = semantics_ir.GetNodeBlock(literal_elems_id);
  369. } else {
  370. value_id = MaterializeIfInitializing(context, value_id);
  371. }
  372. // Check that the structs are the same size.
  373. // TODO: Check the field names are the same up to permutation, compute the
  374. // permutation, and use it below.
  375. if (src_elem_fields.size() != dest_elem_fields.size()) {
  376. CARBON_DIAGNOSTIC(StructInitElementCountMismatch, Error,
  377. "Cannot initialize struct of {0} element(s) from struct "
  378. "with {1} element(s).",
  379. size_t, size_t);
  380. context.emitter().Emit(value.parse_node(), StructInitElementCountMismatch,
  381. dest_elem_fields.size(), src_elem_fields.size());
  382. return SemIR::NodeId::BuiltinError;
  383. }
  384. // If we're forming an initializer, then we want an initializer for each
  385. // element. Otherwise, we want a value representation for each element.
  386. // Perform a final destination store if we're performing an in-place
  387. // initialization.
  388. bool is_init = target.is_initializer();
  389. ConversionTarget::Kind inner_kind =
  390. !is_init ? ConversionTarget::Value
  391. : SemIR::GetInitializingRepresentation(semantics_ir, target.type_id)
  392. .kind == SemIR::InitializingRepresentation::InPlace
  393. ? ConversionTarget::FullInitializer
  394. : ConversionTarget::Initializer;
  395. // Initialize each element of the destination from the corresponding element
  396. // of the source.
  397. // TODO: Annotate diagnostics coming from here with the element index.
  398. CopyOnWriteBlock new_block(semantics_ir, literal_elems_id,
  399. src_elem_fields.size());
  400. for (auto [i, src_field_id, dest_field_id] :
  401. llvm::enumerate(src_elem_fields, dest_elem_fields)) {
  402. auto src_field =
  403. semantics_ir.GetNodeAs<SemIR::StructTypeField>(src_field_id);
  404. auto dest_field =
  405. semantics_ir.GetNodeAs<SemIR::StructTypeField>(dest_field_id);
  406. if (src_field.name_id != dest_field.name_id) {
  407. CARBON_DIAGNOSTIC(
  408. StructInitFieldNameMismatch, Error,
  409. "Mismatched names for field {0} in struct initialization: "
  410. "source has field name `{1}`, destination has field name `{2}`.",
  411. size_t, llvm::StringRef, llvm::StringRef);
  412. context.emitter().Emit(value.parse_node(), StructInitFieldNameMismatch,
  413. i + 1, semantics_ir.GetString(src_field.name_id),
  414. semantics_ir.GetString(dest_field.name_id));
  415. return SemIR::NodeId::BuiltinError;
  416. }
  417. // TODO: This call recurses back into conversion. Switch to an iterative
  418. // approach.
  419. auto init_id =
  420. ConvertAggregateElement<SemIR::StructAccess, SemIR::StructAccess>(
  421. context, value.parse_node(), value_id, src_field.type_id,
  422. literal_elems, inner_kind, target.init_id, dest_field.type_id,
  423. target.init_block, i);
  424. if (init_id == SemIR::NodeId::BuiltinError) {
  425. return SemIR::NodeId::BuiltinError;
  426. }
  427. new_block.Set(i, init_id);
  428. }
  429. return is_init ? context.AddNode(SemIR::StructInit(value.parse_node(),
  430. target.type_id, value_id,
  431. new_block.id()))
  432. : context.AddNode(SemIR::StructValue(value.parse_node(),
  433. target.type_id, value_id,
  434. new_block.id()));
  435. }
  436. // Returns whether `category` is a valid expression category to produce as a
  437. // result of a conversion with kind `target_kind`, or at most needs a temporary
  438. // to be materialized.
  439. static bool IsValidExpressionCategoryForConversionTarget(
  440. SemIR::ExpressionCategory category, ConversionTarget::Kind target_kind) {
  441. switch (target_kind) {
  442. case ConversionTarget::Value:
  443. return category == SemIR::ExpressionCategory::Value;
  444. case ConversionTarget::ValueOrReference:
  445. case ConversionTarget::Discarded:
  446. return category == SemIR::ExpressionCategory::Value ||
  447. category == SemIR::ExpressionCategory::DurableReference ||
  448. category == SemIR::ExpressionCategory::EphemeralReference ||
  449. category == SemIR::ExpressionCategory::Initializing;
  450. case ConversionTarget::Initializer:
  451. case ConversionTarget::FullInitializer:
  452. return category == SemIR::ExpressionCategory::Initializing;
  453. }
  454. }
  455. static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node,
  456. SemIR::NodeId value_id,
  457. ConversionTarget target) -> SemIR::NodeId {
  458. auto& semantics_ir = context.semantics_ir();
  459. auto value = semantics_ir.GetNode(value_id);
  460. auto value_type_id = value.type_id();
  461. auto target_type_node = semantics_ir.GetNode(
  462. semantics_ir.GetTypeAllowBuiltinTypes(target.type_id));
  463. // Various forms of implicit conversion are supported as builtin conversions,
  464. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  465. // prelude. There are a few reasons we need to perform some of these
  466. // conversions as builtins:
  467. //
  468. // 1) Conversions from struct and tuple *literals* have special rules that
  469. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  470. // recurse into the elements of the literal before performing
  471. // initialization in order to avoid unnecessary conversions between
  472. // expression categories that would be performed by `ImplicitAs.Convert`.
  473. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  474. // the value of the facet, not only its type, and therefore cannot be
  475. // modeled by `ImplicitAs`.
  476. // 3) Some of these conversions are used while checking the library
  477. // definition of `ImplicitAs` itself or implementations of it.
  478. //
  479. // We also expect to see better performance by avoiding an `impl` lookup for
  480. // common conversions.
  481. //
  482. // TODO: We should provide a debugging flag to turn off as many of these
  483. // builtin conversions as we can so that we can test that they do the same
  484. // thing as the library implementations.
  485. //
  486. // The builtin conversions that correspond to `impl`s in the library all
  487. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  488. // being specialized in any of these cases.
  489. // If the value is already of the right kind and expression category, there's
  490. // nothing to do. Performing a conversion would decompose and rebuild tuples
  491. // and structs, so it's important that we bail out early in this case.
  492. if (value_type_id == target.type_id &&
  493. IsValidExpressionCategoryForConversionTarget(
  494. SemIR::GetExpressionCategory(semantics_ir, value_id), target.kind)) {
  495. return value_id;
  496. }
  497. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  498. // converts to Ui.
  499. if (auto target_tuple_type = target_type_node.TryAs<SemIR::TupleType>()) {
  500. auto value_type_node = semantics_ir.GetNode(
  501. semantics_ir.GetTypeAllowBuiltinTypes(value_type_id));
  502. if (auto src_tuple_type = value_type_node.TryAs<SemIR::TupleType>()) {
  503. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  504. value_id, target);
  505. }
  506. }
  507. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  508. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  509. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  510. // to Ui.
  511. if (auto target_struct_type = target_type_node.TryAs<SemIR::StructType>()) {
  512. auto value_type_node = semantics_ir.GetNode(
  513. semantics_ir.GetTypeAllowBuiltinTypes(value_type_id));
  514. if (auto src_struct_type = value_type_node.TryAs<SemIR::StructType>()) {
  515. return ConvertStructToStruct(context, *src_struct_type,
  516. *target_struct_type, value_id, target);
  517. }
  518. }
  519. // A tuple (T1, T2, ..., Tn) converts to [T; n] if each Ti converts to T.
  520. if (auto target_array_type = target_type_node.TryAs<SemIR::ArrayType>()) {
  521. auto value_type_node = semantics_ir.GetNode(
  522. semantics_ir.GetTypeAllowBuiltinTypes(value_type_id));
  523. if (auto src_tuple_type = value_type_node.TryAs<SemIR::TupleType>()) {
  524. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  525. value_id, target);
  526. }
  527. }
  528. if (target.type_id == SemIR::TypeId::TypeType) {
  529. // A tuple of types converts to type `type`.
  530. // TODO: This should apply even for non-literal tuples.
  531. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  532. llvm::SmallVector<SemIR::TypeId> type_ids;
  533. for (auto tuple_node_id :
  534. semantics_ir.GetNodeBlock(tuple_literal->elements_id)) {
  535. // TODO: This call recurses back into conversion. Switch to an
  536. // iterative approach.
  537. type_ids.push_back(
  538. ExpressionAsType(context, parse_node, tuple_node_id));
  539. }
  540. auto tuple_type_id =
  541. context.CanonicalizeTupleType(parse_node, std::move(type_ids));
  542. return semantics_ir.GetTypeAllowBuiltinTypes(tuple_type_id);
  543. }
  544. // `{}` converts to `{} as type`.
  545. // TODO: This conversion should also be performed for a non-literal value
  546. // of type `{}`.
  547. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  548. struct_literal &&
  549. struct_literal->elements_id == SemIR::NodeBlockId::Empty) {
  550. value_id = semantics_ir.GetTypeAllowBuiltinTypes(value_type_id);
  551. }
  552. }
  553. // No builtin conversion applies.
  554. return value_id;
  555. }
  556. auto Convert(Context& context, Parse::Node parse_node, SemIR::NodeId expr_id,
  557. ConversionTarget target) -> SemIR::NodeId {
  558. auto& semantics_ir = context.semantics_ir();
  559. auto orig_expr_id = expr_id;
  560. // Start by making sure both sides are valid. If any part is invalid, the
  561. // result is invalid and we shouldn't error.
  562. if (semantics_ir.GetNode(expr_id).type_id() == SemIR::TypeId::Error ||
  563. target.type_id == SemIR::TypeId::Error) {
  564. return SemIR::NodeId::BuiltinError;
  565. }
  566. if (SemIR::GetExpressionCategory(semantics_ir, expr_id) ==
  567. SemIR::ExpressionCategory::NotExpression) {
  568. // TODO: We currently encounter this for use of namespaces and functions.
  569. // We should provide a better diagnostic for inappropriate use of
  570. // namespace names, and allow use of functions as values.
  571. CARBON_DIAGNOSTIC(UseOfNonExpressionAsValue, Error,
  572. "Expression cannot be used as a value.");
  573. context.emitter().Emit(semantics_ir.GetNode(expr_id).parse_node(),
  574. UseOfNonExpressionAsValue);
  575. return SemIR::NodeId::BuiltinError;
  576. }
  577. // We can only perform initialization for complete types.
  578. if (!context.TryToCompleteType(target.type_id, [&] {
  579. CARBON_DIAGNOSTIC(IncompleteTypeInInitialization, Error,
  580. "Initialization of incomplete type `{0}`.",
  581. std::string);
  582. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  583. "Forming value of incomplete type `{0}`.",
  584. std::string);
  585. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  586. "Invalid use of incomplete type `{0}`.", std::string);
  587. return context.emitter().Build(
  588. parse_node,
  589. target.is_initializer() ? IncompleteTypeInInitialization
  590. : target.kind == ConversionTarget::Value
  591. ? IncompleteTypeInValueConversion
  592. : IncompleteTypeInConversion,
  593. context.semantics_ir().StringifyType(target.type_id, true));
  594. })) {
  595. return SemIR::NodeId::BuiltinError;
  596. }
  597. // Check whether any builtin conversion applies.
  598. expr_id = PerformBuiltinConversion(context, parse_node, expr_id, target);
  599. if (expr_id == SemIR::NodeId::BuiltinError) {
  600. return expr_id;
  601. }
  602. // If the types don't match at this point, we can't perform the conversion.
  603. // TODO: Look for an ImplicitAs impl.
  604. SemIR::Node expr = semantics_ir.GetNode(expr_id);
  605. if (expr.type_id() != target.type_id) {
  606. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  607. "Cannot implicitly convert from `{0}` to `{1}`.",
  608. std::string, std::string);
  609. context.emitter()
  610. .Build(parse_node, ImplicitAsConversionFailure,
  611. semantics_ir.StringifyType(expr.type_id()),
  612. semantics_ir.StringifyType(target.type_id))
  613. .Emit();
  614. return SemIR::NodeId::BuiltinError;
  615. }
  616. // Now perform any necessary value category conversions.
  617. switch (SemIR::GetExpressionCategory(semantics_ir, expr_id)) {
  618. case SemIR::ExpressionCategory::NotExpression:
  619. case SemIR::ExpressionCategory::Mixed:
  620. CARBON_FATAL() << "Unexpected expression " << expr
  621. << " after builtin conversions";
  622. case SemIR::ExpressionCategory::Error:
  623. return SemIR::NodeId::BuiltinError;
  624. case SemIR::ExpressionCategory::Initializing:
  625. if (target.is_initializer()) {
  626. if (orig_expr_id == expr_id) {
  627. // Don't fill in the return slot if we created the expression through
  628. // a conversion. In that case, we will have created it with the
  629. // target already set.
  630. // TODO: Find a better way to track whether we need to do this.
  631. MarkInitializerFor(semantics_ir, expr_id, target.init_id,
  632. *target.init_block);
  633. }
  634. break;
  635. }
  636. // Commit to using a temporary for this initializing expression.
  637. // TODO: Don't create a temporary if the initializing representation
  638. // is already a value representation.
  639. expr_id = FinalizeTemporary(context, expr_id,
  640. target.kind == ConversionTarget::Discarded);
  641. // We now have an ephemeral reference.
  642. [[fallthrough]];
  643. case SemIR::ExpressionCategory::DurableReference:
  644. case SemIR::ExpressionCategory::EphemeralReference: {
  645. // If we have a reference and don't want one, form a value binding.
  646. if (target.kind != ConversionTarget::ValueOrReference &&
  647. target.kind != ConversionTarget::Discarded) {
  648. // TODO: Support types with custom value representations.
  649. expr_id = context.AddNode(
  650. SemIR::BindValue(expr.parse_node(), expr.type_id(), expr_id));
  651. }
  652. break;
  653. }
  654. case SemIR::ExpressionCategory::Value:
  655. break;
  656. }
  657. // Perform a final destination store, if necessary.
  658. if (target.kind == ConversionTarget::FullInitializer) {
  659. if (auto init_rep =
  660. SemIR::GetInitializingRepresentation(semantics_ir, target.type_id);
  661. init_rep.kind == SemIR::InitializingRepresentation::ByCopy) {
  662. target.init_block->InsertHere();
  663. expr_id = context.AddNode(SemIR::InitializeFrom(
  664. parse_node, target.type_id, expr_id, target.init_id));
  665. }
  666. }
  667. return expr_id;
  668. }
  669. auto Initialize(Context& context, Parse::Node parse_node,
  670. SemIR::NodeId target_id, SemIR::NodeId value_id)
  671. -> SemIR::NodeId {
  672. PendingBlock target_block(context);
  673. return Convert(
  674. context, parse_node, value_id,
  675. {.kind = ConversionTarget::Initializer,
  676. .type_id = context.semantics_ir().GetNode(target_id).type_id(),
  677. .init_id = target_id,
  678. .init_block = &target_block});
  679. }
  680. auto ConvertToValueExpression(Context& context, SemIR::NodeId expr_id)
  681. -> SemIR::NodeId {
  682. auto expr = context.semantics_ir().GetNode(expr_id);
  683. return Convert(context, expr.parse_node(), expr_id,
  684. {.kind = ConversionTarget::Value, .type_id = expr.type_id()});
  685. }
  686. auto ConvertToValueOrReferenceExpression(Context& context,
  687. SemIR::NodeId expr_id)
  688. -> SemIR::NodeId {
  689. auto expr = context.semantics_ir().GetNode(expr_id);
  690. return Convert(
  691. context, expr.parse_node(), expr_id,
  692. {.kind = ConversionTarget::ValueOrReference, .type_id = expr.type_id()});
  693. }
  694. auto ConvertToValueOfType(Context& context, Parse::Node parse_node,
  695. SemIR::NodeId value_id, SemIR::TypeId type_id)
  696. -> SemIR::NodeId {
  697. return Convert(context, parse_node, value_id,
  698. {.kind = ConversionTarget::Value, .type_id = type_id});
  699. }
  700. auto ConvertToBoolValue(Context& context, Parse::Node parse_node,
  701. SemIR::NodeId value_id) -> SemIR::NodeId {
  702. return ConvertToValueOfType(
  703. context, parse_node, value_id,
  704. context.GetBuiltinType(SemIR::BuiltinKind::BoolType));
  705. }
  706. auto ConvertCallArgs(Context& context, Parse::Node call_parse_node,
  707. SemIR::NodeBlockId arg_refs_id,
  708. Parse::Node param_parse_node,
  709. SemIR::NodeBlockId param_refs_id, bool has_return_slot)
  710. -> bool {
  711. // If both arguments and parameters are empty, return quickly. Otherwise,
  712. // we'll fetch both so that errors are consistent.
  713. if (arg_refs_id == SemIR::NodeBlockId::Empty &&
  714. param_refs_id == SemIR::NodeBlockId::Empty) {
  715. return true;
  716. }
  717. auto arg_refs = context.semantics_ir().GetNodeBlock(arg_refs_id);
  718. auto param_refs = context.semantics_ir().GetNodeBlock(param_refs_id);
  719. if (has_return_slot) {
  720. // There's no entry in the parameter block for the return slot, so ignore
  721. // the corresponding entry in the argument block.
  722. // TODO: Consider adding the return slot to the parameter list.
  723. CARBON_CHECK(!arg_refs.empty()) << "missing return slot";
  724. arg_refs = arg_refs.drop_back();
  725. }
  726. // If sizes mismatch, fail early.
  727. if (arg_refs.size() != param_refs.size()) {
  728. CARBON_DIAGNOSTIC(CallArgCountMismatch, Error,
  729. "{0} argument(s) passed to function expecting "
  730. "{1} argument(s).",
  731. int, int);
  732. CARBON_DIAGNOSTIC(InCallToFunction, Note,
  733. "Calling function declared here.");
  734. context.emitter()
  735. .Build(call_parse_node, CallArgCountMismatch, arg_refs.size(),
  736. param_refs.size())
  737. .Note(param_parse_node, InCallToFunction)
  738. .Emit();
  739. return false;
  740. }
  741. if (param_refs.empty()) {
  742. return true;
  743. }
  744. int diag_param_index;
  745. DiagnosticAnnotationScope annotate_diagnostics(
  746. &context.emitter(), [&](auto& builder) {
  747. CARBON_DIAGNOSTIC(
  748. InCallToFunctionParam, Note,
  749. "Initializing parameter {0} of function declared here.", int);
  750. builder.Note(param_parse_node, InCallToFunctionParam,
  751. diag_param_index + 1);
  752. });
  753. // Check type conversions per-element.
  754. for (auto [i, value_id, param_ref] : llvm::enumerate(arg_refs, param_refs)) {
  755. diag_param_index = i;
  756. auto as_type_id = context.semantics_ir().GetNode(param_ref).type_id();
  757. // TODO: Convert to the proper expression category. For now, we assume
  758. // parameters are all `let` bindings.
  759. value_id =
  760. ConvertToValueOfType(context, call_parse_node, value_id, as_type_id);
  761. if (value_id == SemIR::NodeId::BuiltinError) {
  762. return false;
  763. }
  764. arg_refs[i] = value_id;
  765. }
  766. return true;
  767. }
  768. auto ExpressionAsType(Context& context, Parse::Node parse_node,
  769. SemIR::NodeId value_id) -> SemIR::TypeId {
  770. return context.CanonicalizeType(ConvertToValueOfType(
  771. context, parse_node, value_id, SemIR::TypeId::TypeType));
  772. }
  773. } // namespace Carbon::Check