handle_paren_condition.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 <optional>
  5. #include "toolchain/parse/context.h"
  6. #include "toolchain/parse/handle.h"
  7. namespace Carbon::Parse {
  8. // Handles ParenConditionAs(If|While|Match).
  9. static auto HandleParenCondition(Context& context, NodeKind start_kind,
  10. StateKind finish_state_kind) -> void {
  11. auto state = context.PopState();
  12. std::optional<Lex::TokenIndex> open_paren =
  13. context.ConsumeAndAddOpenParen(state.token, start_kind);
  14. if (open_paren) {
  15. state.token = *open_paren;
  16. }
  17. context.PushState(state, finish_state_kind);
  18. if (!open_paren && context.PositionIs(Lex::TokenKind::OpenCurlyBrace)) {
  19. // For an open curly, assume the condition was completely omitted.
  20. // Expression parsing would treat the { as a struct, but instead assume it's
  21. // a code block and just emit an invalid parse.
  22. context.AddInvalidParse(*context.position());
  23. } else {
  24. context.PushState(StateKind::Expr);
  25. }
  26. }
  27. auto HandleParenConditionAsIf(Context& context) -> void {
  28. HandleParenCondition(context, NodeKind::IfConditionStart,
  29. StateKind::ParenConditionFinishAsIf);
  30. }
  31. auto HandleParenConditionAsWhile(Context& context) -> void {
  32. HandleParenCondition(context, NodeKind::WhileConditionStart,
  33. StateKind::ParenConditionFinishAsWhile);
  34. }
  35. auto HandleParenConditionAsMatch(Context& context) -> void {
  36. HandleParenCondition(context, NodeKind::MatchConditionStart,
  37. StateKind::ParenConditionFinishAsMatch);
  38. }
  39. auto HandleParenConditionFinishAsIf(Context& context) -> void {
  40. auto state = context.PopState();
  41. context.ConsumeAndAddCloseSymbol(state.token, state, NodeKind::IfCondition);
  42. }
  43. auto HandleParenConditionFinishAsWhile(Context& context) -> void {
  44. auto state = context.PopState();
  45. context.ConsumeAndAddCloseSymbol(state.token, state,
  46. NodeKind::WhileCondition);
  47. }
  48. auto HandleParenConditionFinishAsMatch(Context& context) -> void {
  49. auto state = context.PopState();
  50. context.ConsumeAndAddCloseSymbol(state.token, state,
  51. NodeKind::MatchCondition);
  52. }
  53. } // namespace Carbon::Parse