handle_form_literal.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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/lex/token_kind.h"
  5. #include "toolchain/lex/tokenized_buffer.h"
  6. #include "toolchain/parse/context.h"
  7. #include "toolchain/parse/handle.h"
  8. #include "toolchain/parse/node_kind.h"
  9. #include "toolchain/parse/state.h"
  10. namespace Carbon::Parse {
  11. auto HandleFormLiteral(Context& context) -> void {
  12. auto state = context.PopState();
  13. auto keyword = context.ConsumeChecked(Lex::TokenKind::Form);
  14. context.AddLeafNode(NodeKind::FormLiteralKeyword, keyword);
  15. if (auto paren = context.ConsumeAndAddOpenParen(
  16. keyword, NodeKind::FormLiteralOpenParen)) {
  17. // Stash the open paren token for use by ConsumeAndAddCloseSymbol.
  18. state.token = *paren;
  19. } else {
  20. state.has_error = true;
  21. }
  22. context.PushState(state, StateKind::FormLiteralFinish);
  23. if (state.has_error) {
  24. context.AddInvalidParse(keyword);
  25. } else {
  26. context.PushState(StateKind::PrimitiveForm, keyword);
  27. }
  28. }
  29. auto HandlePrimitiveForm(Context& context) -> void {
  30. auto state = context.PopState();
  31. if (context.PositionIs(Lex::TokenKind::Ref) ||
  32. context.PositionIs(Lex::TokenKind::Var) ||
  33. context.PositionIs(Lex::TokenKind::Val)) {
  34. state.token = context.Consume();
  35. } else {
  36. CARBON_DIAGNOSTIC(ExpectedCategoryModifier, Error,
  37. "expected `ref`, `var`, or `val` after `form(`");
  38. context.emitter().Emit(*context.position(), ExpectedCategoryModifier);
  39. state.has_error = true;
  40. }
  41. context.PushState(state, StateKind::PrimitiveFormFinish);
  42. context.PushState(StateKind::Expr);
  43. }
  44. auto HandlePrimitiveFormFinish(Context& context) -> void {
  45. auto state = context.PopState();
  46. // Arbitrary default, only used in error recovery.
  47. auto node_kind = NodeKind::ValPrimitiveForm;
  48. switch (context.tokens().GetKind(state.token)) {
  49. case Lex::TokenKind::Ref:
  50. node_kind = NodeKind::RefPrimitiveForm;
  51. break;
  52. case Lex::TokenKind::Var:
  53. node_kind = NodeKind::VarPrimitiveForm;
  54. break;
  55. case Lex::TokenKind::Val:
  56. node_kind = NodeKind::ValPrimitiveForm;
  57. break;
  58. default:
  59. CARBON_CHECK(state.has_error);
  60. // Use the default node_kind set earlier for error recovery.
  61. break;
  62. }
  63. context.AddNode(node_kind, state.token, state.has_error);
  64. }
  65. auto HandleFormLiteralFinish(Context& context) -> void {
  66. auto state = context.PopState();
  67. context.ConsumeAndAddCloseSymbol(state, NodeKind::FormLiteral);
  68. }
  69. } // namespace Carbon::Parse