semantics_handle_if_expression.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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().PopExpression();
  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().PopExpression();
  31. auto [then_node, then_end_block_id] =
  32. context.node_stack().PopWithParseNode<ParseNodeKind::IfExpressionThen>();
  33. auto then_value_id = context.node_stack().PopExpression();
  34. auto if_node =
  35. context.node_stack().PopForSoloParseNode<ParseNodeKind::IfExpressionIf>();
  36. // Convert the `else` value to the `then` value's type, and finish the `else`
  37. // block.
  38. // TODO: Find a common type, and convert both operands to it instead.
  39. auto result_type_id = context.semantics_ir().GetNode(then_value_id).type_id();
  40. else_value_id =
  41. context.ImplicitAsRequired(else_node, else_value_id, result_type_id);
  42. auto else_end_block_id = context.node_block_stack().Pop();
  43. // Create a resumption block and branches to it.
  44. auto chosen_value_id = context.AddConvergenceBlockWithArgAndPush(
  45. if_node,
  46. {{then_end_block_id, then_value_id}, {else_end_block_id, else_value_id}});
  47. context.AddCurrentCodeBlockToFunction();
  48. // Push the result value.
  49. context.node_stack().Push(else_node, chosen_value_id);
  50. return true;
  51. }
  52. } // namespace Carbon