handle_if_expr.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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(StateKind::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 invalid nodes to substitute for `IfExprThen` and the final `Expr`.
  23. context.AddInvalidParse(*context.position());
  24. context.AddInvalidParse(*context.position());
  25. context.ReturnErrorOnState();
  26. }
  27. }
  28. auto HandleIfExprFinishThen(Context& context) -> void {
  29. auto state = context.PopState();
  30. context.AddNode(NodeKind::IfExprThen, state.token, state.has_error);
  31. if (context.PositionIs(Lex::TokenKind::Else)) {
  32. context.PushState(StateKind::IfExprFinishElse);
  33. context.ConsumeChecked(Lex::TokenKind::Else);
  34. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  35. } else {
  36. // TODO: Include the location of the `if` token.
  37. CARBON_DIAGNOSTIC(ExpectedElseAfterIf, Error,
  38. "expected `else` after `if ... then ...`");
  39. if (!state.has_error) {
  40. context.emitter().Emit(*context.position(), ExpectedElseAfterIf);
  41. }
  42. // Add an invalid node to substitute for the final `Expr`.
  43. context.AddInvalidParse(*context.position());
  44. context.ReturnErrorOnState();
  45. }
  46. }
  47. auto HandleIfExprFinishElse(Context& context) -> void {
  48. auto else_state = context.PopState();
  49. // Propagate the location of `else`.
  50. auto if_state = context.PopState();
  51. if_state.token = else_state.token;
  52. if_state.has_error |= else_state.has_error;
  53. context.PushState(if_state);
  54. }
  55. auto HandleIfExprFinish(Context& context) -> void {
  56. auto state = context.PopState();
  57. context.AddNode(NodeKind::IfExprElse, state.token, state.has_error);
  58. }
  59. } // namespace Carbon::Parse