handle_paren_condition.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. #include "toolchain/parse/handle.h"
  6. namespace Carbon::Parse {
  7. // Handles ParenConditionAs(If|While|Match).
  8. static auto HandleParenCondition(Context& context, NodeKind start_kind,
  9. State finish_state) -> void {
  10. auto state = context.PopState();
  11. std::optional<Lex::TokenIndex> open_paren =
  12. context.ConsumeAndAddOpenParen(state.token, start_kind);
  13. if (open_paren) {
  14. state.token = *open_paren;
  15. }
  16. context.PushState(state, finish_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.AddInvalidParse(*context.position());
  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 HandleParenConditionAsMatch(Context& context) -> void {
  35. HandleParenCondition(context, NodeKind::MatchConditionStart,
  36. State::ParenConditionFinishAsMatch);
  37. }
  38. auto HandleParenConditionFinishAsIf(Context& context) -> void {
  39. auto state = context.PopState();
  40. context.ConsumeAndAddCloseSymbol(state.token, state, NodeKind::IfCondition);
  41. }
  42. auto HandleParenConditionFinishAsWhile(Context& context) -> void {
  43. auto state = context.PopState();
  44. context.ConsumeAndAddCloseSymbol(state.token, state,
  45. NodeKind::WhileCondition);
  46. }
  47. auto HandleParenConditionFinishAsMatch(Context& context) -> void {
  48. auto state = context.PopState();
  49. context.ConsumeAndAddCloseSymbol(state.token, state,
  50. NodeKind::MatchCondition);
  51. }
  52. } // namespace Carbon::Parse