handle_return_statement.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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/context.h"
  5. #include "toolchain/check/return.h"
  6. namespace Carbon::Check {
  7. auto HandleReturnStatementStart(Context& context, Parse::NodeId parse_node)
  8. -> bool {
  9. // No action, just a bracketing node.
  10. context.node_stack().Push(parse_node);
  11. return true;
  12. }
  13. auto HandleReturnVarModifier(Context& context, Parse::NodeId parse_node)
  14. -> bool {
  15. // No action, just a bracketing node.
  16. context.node_stack().Push(parse_node);
  17. return true;
  18. }
  19. auto HandleReturnStatement(Context& context, Parse::NodeId parse_node) -> bool {
  20. switch (
  21. context.parse_tree().node_kind(context.node_stack().PeekParseNode())) {
  22. case Parse::NodeKind::ReturnStatementStart:
  23. // This is a `return;` statement.
  24. context.node_stack()
  25. .PopAndDiscardSoloParseNode<Parse::NodeKind::ReturnStatementStart>();
  26. BuildReturnWithNoExpr(context, parse_node);
  27. break;
  28. case Parse::NodeKind::ReturnVarModifier:
  29. // This is a `return var;` statement.
  30. context.node_stack()
  31. .PopAndDiscardSoloParseNode<Parse::NodeKind::ReturnVarModifier>();
  32. context.node_stack()
  33. .PopAndDiscardSoloParseNode<Parse::NodeKind::ReturnStatementStart>();
  34. BuildReturnVar(context, parse_node);
  35. break;
  36. default:
  37. // This is a `return <expression>;` statement.
  38. auto expr_id = context.node_stack().PopExpr();
  39. context.node_stack()
  40. .PopAndDiscardSoloParseNode<Parse::NodeKind::ReturnStatementStart>();
  41. BuildReturnWithExpr(context, parse_node, expr_id);
  42. break;
  43. }
  44. // Switch to a new, unreachable, empty instruction block. This typically won't
  45. // contain any semantics IR, but it can do if there are statements following
  46. // the `return` statement.
  47. context.inst_block_stack().Pop();
  48. context.inst_block_stack().PushUnreachable();
  49. return true;
  50. }
  51. } // namespace Carbon::Check