handle_code_block.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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(State::CodeBlockFinish);
  10. if (context.ConsumeAndAddLeafNodeIf(Lex::TokenKind::OpenCurlyBrace,
  11. NodeKind::CodeBlockStart)) {
  12. context.PushState(State::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(State::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.subtree_start,
  27. state.has_error);
  28. } else {
  29. context.AddNode(NodeKind::CodeBlock, state.token, state.subtree_start,
  30. /*has_error=*/true);
  31. }
  32. }
  33. } // namespace Carbon::Parse