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