Files
carbon-lang/toolchain/parse/handle_paren_expr.cpp
T
Geoff Romer 5897e57c21 Clarify naming around paren expressions (#3444)
(Split out of #3410)

Consistently use `ParenExpr` solely for parenthesized single
expressions, and use more syntax-oriented terminology for states and
nodes that might represent either a `ParenExpr` or a tuple literal.
2023-12-08 21:46:28 +00:00

78 lines
2.5 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "toolchain/parse/context.h"
namespace Carbon::Parse {
auto HandleParenExpr(Context& context) -> void {
auto state = context.PopState();
// Advance past the open paren.
context.AddLeafNode(NodeKind::ExprOpenParen,
context.ConsumeChecked(Lex::TokenKind::OpenParen));
if (context.PositionIs(Lex::TokenKind::CloseParen)) {
state.state = State::TupleLiteralFinish;
context.PushState(state);
} else {
state.state = State::ParenExprFinish;
context.PushState(state);
context.PushState(State::ExprAfterOpenParenFinish);
context.PushState(State::Expr);
}
}
auto HandleExprAfterOpenParenFinish(Context& context) -> void {
auto state = context.PopState();
auto list_token_kind = context.ConsumeListToken(
NodeKind::TupleLiteralComma, Lex::TokenKind::CloseParen, state.has_error);
if (list_token_kind == Context::ListTokenKind::Close) {
return;
}
// We found a comma, so switch parent state to tuple handling.
auto finish_state = context.PopState();
CARBON_CHECK(finish_state.state == State::ParenExprFinish)
<< "Unexpected parent state, found: " << finish_state.state;
finish_state.state = State::TupleLiteralFinish;
context.PushState(finish_state);
// If the comma is not immediately followed by a close paren, push handlers
// for the next tuple element.
if (list_token_kind != Context::ListTokenKind::CommaClose) {
state.state = State::TupleLiteralElementFinish;
context.PushState(state);
context.PushState(State::Expr);
}
}
auto HandleTupleLiteralElementFinish(Context& context) -> void {
auto state = context.PopState();
if (context.ConsumeListToken(NodeKind::TupleLiteralComma,
Lex::TokenKind::CloseParen, state.has_error) ==
Context::ListTokenKind::Comma) {
context.PushState(state);
context.PushState(State::Expr);
}
}
auto HandleParenExprFinish(Context& context) -> void {
auto state = context.PopState();
context.AddNode(NodeKind::ParenExpr, context.Consume(), state.subtree_start,
state.has_error);
}
auto HandleTupleLiteralFinish(Context& context) -> void {
auto state = context.PopState();
context.AddNode(NodeKind::TupleLiteral, context.Consume(),
state.subtree_start, state.has_error);
}
} // namespace Carbon::Parse