parser_handle_paren_condition.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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/parser/parser_context.h"
  5. namespace Carbon {
  6. // Handles ParenConditionAs(If|While).
  7. static auto ParserHandleParenCondition(ParserContext& context,
  8. ParseNodeKind start_kind,
  9. ParserState finish_state) -> void {
  10. auto state = context.PopState();
  11. std::optional<TokenizedBuffer::Token> open_paren =
  12. context.ConsumeAndAddOpenParen(state.token, start_kind);
  13. if (open_paren) {
  14. state.token = *open_paren;
  15. }
  16. state.state = finish_state;
  17. context.PushState(state);
  18. if (!open_paren && context.PositionIs(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.AddLeafNode(ParseNodeKind::InvalidParse, *context.position(),
  23. /*has_error=*/true);
  24. } else {
  25. context.PushState(ParserState::Expression);
  26. }
  27. }
  28. auto ParserHandleParenConditionAsIf(ParserContext& context) -> void {
  29. ParserHandleParenCondition(context, ParseNodeKind::IfConditionStart,
  30. ParserState::ParenConditionFinishAsIf);
  31. }
  32. auto ParserHandleParenConditionAsWhile(ParserContext& context) -> void {
  33. ParserHandleParenCondition(context, ParseNodeKind::WhileConditionStart,
  34. ParserState::ParenConditionFinishAsWhile);
  35. }
  36. auto ParserHandleParenConditionFinishAsIf(ParserContext& context) -> void {
  37. auto state = context.PopState();
  38. context.ConsumeAndAddCloseSymbol(state.token, state,
  39. ParseNodeKind::IfCondition);
  40. }
  41. auto ParserHandleParenConditionFinishAsWhile(ParserContext& context) -> void {
  42. auto state = context.PopState();
  43. context.ConsumeAndAddCloseSymbol(state.token, state,
  44. ParseNodeKind::WhileCondition);
  45. }
  46. } // namespace Carbon