handle_code_block.cpp 1.4 KB

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