handle_let.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 HandleLet(Context& context) -> void {
  7. auto state = context.PopState();
  8. // These will start at the `let`.
  9. context.PushState(state, State::LetFinish);
  10. context.PushState(state, State::LetAfterPattern);
  11. // This will start at the pattern.
  12. context.PushState(State::Pattern);
  13. }
  14. auto HandleLetAfterPattern(Context& context) -> void {
  15. auto state = context.PopState();
  16. if (state.has_error) {
  17. if (auto after_pattern =
  18. context.FindNextOf({Lex::TokenKind::Equal, Lex::TokenKind::Semi})) {
  19. context.SkipTo(*after_pattern);
  20. }
  21. }
  22. if (auto equals = context.ConsumeIf(Lex::TokenKind::Equal)) {
  23. context.AddLeafNode(NodeKind::LetInitializer, *equals);
  24. context.PushState(State::Expr);
  25. } else if (!state.has_error) {
  26. CARBON_DIAGNOSTIC(
  27. ExpectedInitializerAfterLet, Error,
  28. "Expected `=`; `let` declaration must have an initializer.");
  29. context.emitter().Emit(*context.position(), ExpectedInitializerAfterLet);
  30. context.ReturnErrorOnState();
  31. }
  32. }
  33. auto HandleLetFinish(Context& context) -> void {
  34. auto state = context.PopState();
  35. auto end_token = state.token;
  36. if (context.PositionIs(Lex::TokenKind::Semi)) {
  37. end_token = context.Consume();
  38. } else {
  39. context.EmitExpectedDeclSemi(Lex::TokenKind::Let);
  40. state.has_error = true;
  41. end_token = context.SkipPastLikelyEnd(state.token);
  42. }
  43. context.AddNode(NodeKind::LetDecl, end_token, state.subtree_start,
  44. state.has_error);
  45. }
  46. } // namespace Carbon::Parse