handle_if_expr.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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/lex/token_kind.h"
  5. #include "toolchain/parse/context.h"
  6. #include "toolchain/parse/handle.h"
  7. namespace Carbon::Parse {
  8. auto HandleIfExprFinishCondition(Context& context) -> void {
  9. auto state = context.PopState();
  10. context.AddNode(NodeKind::IfExprIf, state.token, state.has_error);
  11. if (context.PositionIs(Lex::TokenKind::Then)) {
  12. context.PushState(State::IfExprFinishThen);
  13. context.ConsumeChecked(Lex::TokenKind::Then);
  14. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  15. } else {
  16. // TODO: Include the location of the `if` token.
  17. CARBON_DIAGNOSTIC(ExpectedThenAfterIf, Error,
  18. "Expected `then` after `if` condition.");
  19. if (!state.has_error) {
  20. context.emitter().Emit(*context.position(), ExpectedThenAfterIf);
  21. }
  22. // Add placeholders for `IfExprThen` and final `Expr`.
  23. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  24. /*has_error=*/true);
  25. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  26. /*has_error=*/true);
  27. context.ReturnErrorOnState();
  28. }
  29. }
  30. auto HandleIfExprFinishThen(Context& context) -> void {
  31. auto state = context.PopState();
  32. context.AddNode(NodeKind::IfExprThen, state.token, state.has_error);
  33. if (context.PositionIs(Lex::TokenKind::Else)) {
  34. context.PushState(State::IfExprFinishElse);
  35. context.ConsumeChecked(Lex::TokenKind::Else);
  36. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  37. } else {
  38. // TODO: Include the location of the `if` token.
  39. CARBON_DIAGNOSTIC(ExpectedElseAfterIf, Error,
  40. "Expected `else` after `if ... then ...`.");
  41. if (!state.has_error) {
  42. context.emitter().Emit(*context.position(), ExpectedElseAfterIf);
  43. }
  44. // Add placeholder for the final `Expr`.
  45. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  46. /*has_error=*/true);
  47. context.ReturnErrorOnState();
  48. }
  49. }
  50. auto HandleIfExprFinishElse(Context& context) -> void {
  51. auto else_state = context.PopState();
  52. // Propagate the location of `else`.
  53. auto if_state = context.PopState();
  54. if_state.token = else_state.token;
  55. if_state.has_error |= else_state.has_error;
  56. context.PushState(if_state);
  57. }
  58. auto HandleIfExprFinish(Context& context) -> void {
  59. auto state = context.PopState();
  60. context.AddNode(NodeKind::IfExprElse, state.token, state.has_error);
  61. }
  62. } // namespace Carbon::Parse