handle_paren_condition.cpp 1.9 KB

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