handle_paren_condition.cpp 1.9 KB

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