handle_let.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. context.PopAndDiscardState();
  8. // These will start at the `let`.
  9. context.PushState(State::LetFinish);
  10. context.PushState(State::LetAfterPattern);
  11. context.AddLeafNode(NodeKind::LetIntroducer, context.Consume());
  12. // This will start at the pattern.
  13. context.PushState(State::PatternAsLet);
  14. }
  15. auto HandleLetAfterPattern(Context& context) -> void {
  16. auto state = context.PopState();
  17. if (state.has_error) {
  18. if (auto after_pattern =
  19. context.FindNextOf({Lex::TokenKind::Equal, Lex::TokenKind::Semi})) {
  20. context.SkipTo(*after_pattern);
  21. }
  22. }
  23. if (auto equals = context.ConsumeIf(Lex::TokenKind::Equal)) {
  24. context.AddLeafNode(NodeKind::LetInitializer, *equals);
  25. context.PushState(State::Expr);
  26. } else 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. context.ReturnErrorOnState();
  32. }
  33. }
  34. auto HandleLetFinish(Context& context) -> void {
  35. auto state = context.PopState();
  36. auto end_token = state.token;
  37. if (context.PositionIs(Lex::TokenKind::Semi)) {
  38. end_token = context.Consume();
  39. } else {
  40. context.EmitExpectedDeclSemi(Lex::TokenKind::Let);
  41. state.has_error = true;
  42. if (auto semi_token = context.SkipPastLikelyEnd(state.token)) {
  43. end_token = *semi_token;
  44. }
  45. }
  46. context.AddNode(NodeKind::LetDecl, end_token, state.subtree_start,
  47. state.has_error);
  48. }
  49. } // namespace Carbon::Parse