handle_let.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 {
  26. if (!state.has_error) {
  27. CARBON_DIAGNOSTIC(
  28. ExpectedInitializerAfterLet, Error,
  29. "Expected `=`; `let` declaration must have an initializer.");
  30. context.emitter().Emit(*context.position(), ExpectedInitializerAfterLet);
  31. }
  32. context.ReturnErrorOnState();
  33. }
  34. }
  35. auto HandleLetFinish(Context& context) -> void {
  36. auto state = context.PopState();
  37. auto end_token = state.token;
  38. if (context.PositionIs(Lex::TokenKind::Semi)) {
  39. end_token = context.Consume();
  40. } else {
  41. context.EmitExpectedDeclSemi(Lex::TokenKind::Let);
  42. state.has_error = true;
  43. end_token = context.SkipPastLikelyEnd(state.token);
  44. }
  45. context.AddNode(NodeKind::LetDecl, end_token, state.subtree_start,
  46. state.has_error);
  47. }
  48. } // namespace Carbon::Parse