semantics_handle_if_expression.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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/semantics/semantics_context.h"
  5. namespace Carbon {
  6. auto SemanticsHandleIfExpressionIf(SemanticsContext& context,
  7. ParseTree::Node if_node) -> bool {
  8. auto cond_value_id = context.node_stack().Pop<SemanticsNodeId>();
  9. context.node_stack().Push(if_node);
  10. // Convert the condition to `bool`, and branch on it.
  11. cond_value_id = context.ImplicitAsBool(if_node, cond_value_id);
  12. auto then_block_id =
  13. context.AddDominatedBlockAndBranchIf(if_node, cond_value_id);
  14. auto else_block_id = context.AddDominatedBlockAndBranch(if_node);
  15. // Push the `else` block and `then` block, and start emitting the `then`.
  16. context.node_block_stack().Pop();
  17. context.node_block_stack().Push(else_block_id);
  18. context.node_block_stack().Push(then_block_id);
  19. context.AddCurrentCodeBlockToFunction();
  20. return true;
  21. }
  22. auto SemanticsHandleIfExpressionThen(SemanticsContext& context,
  23. ParseTree::Node then_node) -> bool {
  24. context.node_stack().Push(then_node, context.node_block_stack().Pop());
  25. context.AddCurrentCodeBlockToFunction();
  26. return true;
  27. }
  28. auto SemanticsHandleIfExpressionElse(SemanticsContext& context,
  29. ParseTree::Node else_node) -> bool {
  30. auto else_value_id = context.node_stack().Pop<SemanticsNodeId>();
  31. auto [then_node, then_end_block_id] =
  32. context.node_stack().PopWithParseNode<SemanticsNodeBlockId>(
  33. ParseNodeKind::IfExpressionThen);
  34. auto then_value_id = context.node_stack().Pop<SemanticsNodeId>();
  35. auto if_node =
  36. context.node_stack().PopForSoloParseNode(ParseNodeKind::IfExpressionIf);
  37. // Convert the `else` value to the `then` value's type, and finish the `else`
  38. // block.
  39. // TODO: Find a common type, and convert both operands to it instead.
  40. auto result_type_id = context.semantics_ir().GetNode(then_value_id).type_id();
  41. else_value_id =
  42. context.ImplicitAsRequired(else_node, else_value_id, result_type_id);
  43. auto else_end_block_id = context.node_block_stack().Pop();
  44. // Create a resumption block and branches to it.
  45. auto chosen_value_id = context.AddConvergenceBlockWithArgAndPush(
  46. if_node,
  47. {{then_end_block_id, then_value_id}, {else_end_block_id, else_value_id}});
  48. context.AddCurrentCodeBlockToFunction();
  49. // Push the result value.
  50. context.node_stack().Push(if_node, chosen_value_id);
  51. return true;
  52. }
  53. } // namespace Carbon