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,
  8. Parse::ReturnStatementStartId node_id) -> bool {
  9. // No action, just a bracketing node.
  10. context.node_stack().Push(node_id);
  11. return true;
  12. }
  13. auto HandleReturnVarModifier(Context& context,
  14. Parse::ReturnVarModifierId node_id) -> bool {
  15. // No action, just a bracketing node.
  16. context.node_stack().Push(node_id);
  17. return true;
  18. }
  19. auto HandleReturnStatement(Context& context, Parse::ReturnStatementId node_id)
  20. -> bool {
  21. switch (context.node_stack().PeekNodeKind()) {
  22. case Parse::NodeKind::ReturnStatementStart:
  23. // This is a `return;` statement.
  24. context.node_stack()
  25. .PopAndDiscardSoloNodeId<Parse::NodeKind::ReturnStatementStart>();
  26. BuildReturnWithNoExpr(context, node_id);
  27. break;
  28. case Parse::NodeKind::ReturnVarModifier:
  29. // This is a `return var;` statement.
  30. context.node_stack()
  31. .PopAndDiscardSoloNodeId<Parse::NodeKind::ReturnVarModifier>();
  32. context.node_stack()
  33. .PopAndDiscardSoloNodeId<Parse::NodeKind::ReturnStatementStart>();
  34. BuildReturnVar(context, node_id);
  35. break;
  36. default:
  37. // This is a `return <expression>;` statement.
  38. auto expr_id = context.node_stack().PopExpr();
  39. context.node_stack()
  40. .PopAndDiscardSoloNodeId<Parse::NodeKind::ReturnStatementStart>();
  41. BuildReturnWithExpr(context, node_id, 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