paren_contents.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. #ifndef EXECUTABLE_SEMANTICS_AST_PAREN_CONTENTS_H_
  5. #define EXECUTABLE_SEMANTICS_AST_PAREN_CONTENTS_H_
  6. #include <optional>
  7. #include <string>
  8. #include <vector>
  9. #include "executable_semantics/ast/source_location.h"
  10. #include "executable_semantics/common/error.h"
  11. namespace Carbon {
  12. // Represents the syntactic contents of an expression or pattern delimited by
  13. // parentheses. In those syntaxes, parentheses can be used either for grouping
  14. // or for forming a tuple, depending on their context and the syntax of their
  15. // contents; this class helps calling code resolve that ambiguity. Since that
  16. // ambiguity is purely syntactic, this class should only be needed during
  17. // parsing.
  18. //
  19. // `Term` is the type of the syntactic grouping being built, and the type of
  20. // the individual syntactic units it's built from; typically it should be
  21. // either `Expression` or `Pattern`.
  22. template <typename Term>
  23. struct ParenContents {
  24. // If this object represents a single term with no trailing comma, this
  25. // method returns that term. This typically means the parentheses can be
  26. // interpreted as grouping.
  27. auto SingleTerm() const -> std::optional<Nonnull<Term*>>;
  28. std::vector<Nonnull<Term*>> elements;
  29. bool has_trailing_comma;
  30. };
  31. // Implementation details only below here.
  32. template <typename Term>
  33. auto ParenContents<Term>::SingleTerm() const -> std::optional<Nonnull<Term*>> {
  34. if (elements.size() == 1 && !has_trailing_comma) {
  35. return elements.front();
  36. } else {
  37. return std::nullopt;
  38. }
  39. }
  40. } // namespace Carbon
  41. #endif // EXECUTABLE_SEMANTICS_AST_PAREN_CONTENTS_H_