semantics_handle_if_expression.cpp 2.4 KB

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