handle_paren_expr.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. auto HandleParenExpr(Context& context) -> void {
  7. auto state = context.PopState();
  8. // Advance past the open paren.
  9. context.AddLeafNode(NodeKind::ExprOpenParen,
  10. context.ConsumeChecked(Lex::TokenKind::OpenParen));
  11. if (context.PositionIs(Lex::TokenKind::CloseParen)) {
  12. context.PushState(state, State::TupleLiteralFinish);
  13. } else {
  14. context.PushState(state, State::ParenExprFinish);
  15. context.PushState(State::ExprAfterOpenParenFinish);
  16. context.PushState(State::Expr);
  17. }
  18. }
  19. auto HandleExprAfterOpenParenFinish(Context& context) -> void {
  20. auto state = context.PopState();
  21. auto list_token_kind = context.ConsumeListToken(
  22. NodeKind::TupleLiteralComma, Lex::TokenKind::CloseParen, state.has_error);
  23. if (list_token_kind == Context::ListTokenKind::Close) {
  24. return;
  25. }
  26. // We found a comma, so switch parent state to tuple handling.
  27. auto finish_state = context.PopState();
  28. CARBON_CHECK(finish_state.state == State::ParenExprFinish)
  29. << "Unexpected parent state, found: " << finish_state.state;
  30. context.PushState(finish_state, State::TupleLiteralFinish);
  31. // If the comma is not immediately followed by a close paren, push handlers
  32. // for the next tuple element.
  33. if (list_token_kind != Context::ListTokenKind::CommaClose) {
  34. context.PushState(state, State::TupleLiteralElementFinish);
  35. context.PushState(State::Expr);
  36. }
  37. }
  38. auto HandleTupleLiteralElementFinish(Context& context) -> void {
  39. auto state = context.PopState();
  40. if (context.ConsumeListToken(NodeKind::TupleLiteralComma,
  41. Lex::TokenKind::CloseParen, state.has_error) ==
  42. Context::ListTokenKind::Comma) {
  43. context.PushState(state);
  44. context.PushState(State::Expr);
  45. }
  46. }
  47. auto HandleParenExprFinish(Context& context) -> void {
  48. auto state = context.PopState();
  49. context.AddNode(NodeKind::ParenExpr, context.Consume(), state.subtree_start,
  50. state.has_error);
  51. }
  52. auto HandleTupleLiteralFinish(Context& context) -> void {
  53. auto state = context.PopState();
  54. context.AddNode(NodeKind::TupleLiteral, context.Consume(),
  55. state.subtree_start, state.has_error);
  56. }
  57. } // namespace Carbon::Parse