handle_period.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // Handles PeriodAs variants and ArrowExpr.
  7. // TODO: This currently only supports identifiers on the rhs, but will in the
  8. // future need to handle things like `object.(Interface.member)` for qualifiers.
  9. static auto HandlePeriodOrArrow(Context& context, NodeKind node_kind,
  10. bool is_arrow) -> void {
  11. auto state = context.PopState();
  12. // `.` identifier
  13. auto dot = context.ConsumeChecked(is_arrow ? Lex::TokenKind::MinusGreater
  14. : Lex::TokenKind::Period);
  15. if (!context.ConsumeAndAddLeafNodeIf(Lex::TokenKind::Identifier,
  16. NodeKind::Name)) {
  17. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterDotOrArrow, Error,
  18. "Expected identifier after `{0}`.", llvm::StringRef);
  19. context.emitter().Emit(*context.position(),
  20. ExpectedIdentifierAfterDotOrArrow,
  21. is_arrow ? "->" : ".");
  22. // If we see a keyword, assume it was intended to be a name.
  23. // TODO: Should keywords be valid here?
  24. if (context.PositionKind().is_keyword()) {
  25. context.AddLeafNode(NodeKind::Name, context.Consume(),
  26. /*has_error=*/true);
  27. } else {
  28. context.AddLeafNode(NodeKind::Name, *context.position(),
  29. /*has_error=*/true);
  30. // Indicate the error to the parent state so that it can avoid producing
  31. // more errors.
  32. context.ReturnErrorOnState();
  33. }
  34. }
  35. context.AddNode(node_kind, dot, state.subtree_start, state.has_error);
  36. }
  37. auto HandlePeriodAsDecl(Context& context) -> void {
  38. HandlePeriodOrArrow(context, NodeKind::QualifiedDecl,
  39. /*is_arrow=*/false);
  40. }
  41. auto HandlePeriodAsExpr(Context& context) -> void {
  42. HandlePeriodOrArrow(context, NodeKind::MemberAccessExpr,
  43. /*is_arrow=*/false);
  44. }
  45. auto HandlePeriodAsStruct(Context& context) -> void {
  46. HandlePeriodOrArrow(context, NodeKind::StructFieldDesignator,
  47. /*is_arrow=*/false);
  48. }
  49. auto HandleArrowExpr(Context& context) -> void {
  50. HandlePeriodOrArrow(context, NodeKind::PointerMemberAccessExpr,
  51. /*is_arrow=*/true);
  52. }
  53. } // namespace Carbon::Parse