parser_handle_designator.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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/parser/parser_context.h"
  5. namespace Carbon {
  6. // Handles DesignatorAs.
  7. auto ParserHandleDesignator(ParserContext& context, bool as_struct) -> void {
  8. auto state = context.PopState();
  9. // `.` identifier
  10. auto dot = context.ConsumeChecked(TokenKind::Period);
  11. if (!context.ConsumeAndAddLeafNodeIf(TokenKind::Identifier,
  12. ParseNodeKind::DesignatedName)) {
  13. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterDot, Error,
  14. "Expected identifier after `.`.");
  15. context.emitter().Emit(*context.position(), ExpectedIdentifierAfterDot);
  16. // If we see a keyword, assume it was intended to be the designated name.
  17. // TODO: Should keywords be valid in designators?
  18. if (context.PositionKind().is_keyword()) {
  19. context.AddLeafNode(ParseNodeKind::DesignatedName, context.Consume(),
  20. /*has_error=*/true);
  21. } else {
  22. context.AddLeafNode(ParseNodeKind::DesignatedName, *context.position(),
  23. /*has_error=*/true);
  24. // Indicate the error to the parent state so that it can avoid producing
  25. // more errors.
  26. context.ReturnErrorOnState();
  27. }
  28. }
  29. context.AddNode(as_struct ? ParseNodeKind::StructFieldDesignator
  30. : ParseNodeKind::DesignatorExpression,
  31. dot, state.subtree_start, state.has_error);
  32. }
  33. auto ParserHandleDesignatorAsExpression(ParserContext& context) -> void {
  34. ParserHandleDesignator(context, /*as_struct=*/false);
  35. }
  36. auto ParserHandleDesignatorAsStruct(ParserContext& context) -> void {
  37. ParserHandleDesignator(context, /*as_struct=*/true);
  38. }
  39. } // namespace Carbon