handle_code_block.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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 HandleCodeBlock(Context& context) -> void {
  7. context.PopAndDiscardState();
  8. context.PushState(State::CodeBlockFinish);
  9. if (context.ConsumeAndAddLeafNodeIf(Lex::TokenKind::OpenCurlyBrace,
  10. NodeKind::CodeBlockStart)) {
  11. context.PushState(State::StatementScopeLoop);
  12. } else {
  13. context.AddLeafNode(NodeKind::CodeBlockStart, *context.position(),
  14. /*has_error=*/true);
  15. // Recover by parsing a single statement.
  16. CARBON_DIAGNOSTIC(ExpectedCodeBlock, Error, "Expected braced code block.");
  17. context.emitter().Emit(*context.position(), ExpectedCodeBlock);
  18. context.PushState(State::Statement);
  19. }
  20. }
  21. auto HandleCodeBlockFinish(Context& context) -> void {
  22. auto state = context.PopState();
  23. // If the block started with an open curly, this is a close curly.
  24. if (context.tokens().GetKind(state.token) == Lex::TokenKind::OpenCurlyBrace) {
  25. context.AddNode(NodeKind::CodeBlock, context.Consume(), state.subtree_start,
  26. state.has_error);
  27. } else {
  28. context.AddNode(NodeKind::CodeBlock, state.token, state.subtree_start,
  29. /*has_error=*/true);
  30. }
  31. }
  32. } // namespace Carbon::Parse