Adjust handling of cases where conditions are missing. (#3119)

In #3064, code was changed to look at a future token. This is an issue
because the parser is set up to enforce that tokens aren't used without
being consumed. That's part of #3118; related validation fails. Also,
since it's not necessarily the open paren that was consumed, it could be
a different opening symbol, which the closing symbol handling doesn't
check.

Under this approach, it's tracked whether an open paren was consumed,
and the open paren is associated with the state. That's more aligned
with how the parser expects to be fed information.

In paren condition handling for if and while, I'm also adding some
special casing for `if {` in particular to not assume the `{` is a
struct. I just think that this will come up somewhat often and the
resulting output is better this way (an error either way). I'm not doing
similar with `for` because there's already some `var` handling there,
and I'd need a little more time to think about structure -- whereas
right now I'm just trying to fix the crashes (`if {}`, `if []`, etc).

Fixes #3118
This commit is contained in:
Jon Ross-Perkins
2023-08-18 23:04:30 +00:00
committed by GitHub
parent fe93c0225f
commit 4ae0fa6f86
9 changed files with 184 additions and 18 deletions
@@ -12,11 +12,23 @@ static auto ParserHandleParenCondition(ParserContext& context,
ParserState finish_state) -> void {
auto state = context.PopState();
context.ConsumeAndAddOpenParen(state.token, start_kind);
std::optional<TokenizedBuffer::Token> open_paren =
context.ConsumeAndAddOpenParen(state.token, start_kind);
if (open_paren) {
state.token = *open_paren;
}
state.state = finish_state;
context.PushState(state);
context.PushState(ParserState::Expression);
if (!open_paren && context.PositionIs(TokenKind::OpenCurlyBrace)) {
// For an open curly, assume the condition was completely omitted.
// Expression parsing would treat the { as a struct, but instead assume it's
// a code block and just emit an invalid parse.
context.AddLeafNode(ParseNodeKind::InvalidParse, *context.position(),
/*has_error=*/true);
} else {
context.PushState(ParserState::Expression);
}
}
auto ParserHandleParenConditionAsIf(ParserContext& context) -> void {
@@ -32,17 +44,15 @@ auto ParserHandleParenConditionAsWhile(ParserContext& context) -> void {
auto ParserHandleParenConditionFinishAsIf(ParserContext& context) -> void {
auto state = context.PopState();
context.ConsumeAndAddCloseSymbol(
*(TokenizedBuffer::TokenIterator(state.token) + 1), state,
ParseNodeKind::IfCondition);
context.ConsumeAndAddCloseSymbol(state.token, state,
ParseNodeKind::IfCondition);
}
auto ParserHandleParenConditionFinishAsWhile(ParserContext& context) -> void {
auto state = context.PopState();
context.ConsumeAndAddCloseSymbol(
*(TokenizedBuffer::TokenIterator(state.token) + 1), state,
ParseNodeKind::WhileCondition);
context.ConsumeAndAddCloseSymbol(state.token, state,
ParseNodeKind::WhileCondition);
}
} // namespace Carbon