pattern.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 CARBON_EXPLORER_AST_PATTERN_H_
  5. #define CARBON_EXPLORER_AST_PATTERN_H_
  6. #include <optional>
  7. #include <string>
  8. #include <vector>
  9. #include "common/ostream.h"
  10. #include "explorer/ast/ast_node.h"
  11. #include "explorer/ast/ast_rtti.h"
  12. #include "explorer/ast/expression.h"
  13. #include "explorer/ast/static_scope.h"
  14. #include "explorer/ast/value_category.h"
  15. #include "explorer/common/source_location.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/STLFunctionalExtras.h"
  18. namespace Carbon {
  19. class Value;
  20. // Abstract base class of all AST nodes representing patterns.
  21. //
  22. // Pattern and its derived classes support LLVM-style RTTI, including
  23. // llvm::isa, llvm::cast, and llvm::dyn_cast. To support this, every
  24. // class derived from Pattern must provide a `classof` operation, and
  25. // every concrete derived class must have a corresponding enumerator
  26. // in `Kind`; see https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html for
  27. // details.
  28. class Pattern : public AstNode {
  29. public:
  30. Pattern(const Pattern&) = delete;
  31. auto operator=(const Pattern&) -> Pattern& = delete;
  32. ~Pattern() override = 0;
  33. void Print(llvm::raw_ostream& out) const override;
  34. void PrintID(llvm::raw_ostream& out) const override;
  35. static auto classof(const AstNode* node) -> bool {
  36. return InheritsFromPattern(node->kind());
  37. }
  38. // Returns the enumerator corresponding to the most-derived type of this
  39. // object.
  40. auto kind() const -> PatternKind {
  41. return static_cast<PatternKind>(root_kind());
  42. }
  43. // The static type of this pattern. Cannot be called before typechecking.
  44. auto static_type() const -> const Value& {
  45. CARBON_CHECK(static_type_.has_value());
  46. return **static_type_;
  47. }
  48. // Sets the static type of this expression. Can only be called once, during
  49. // typechecking.
  50. void set_static_type(Nonnull<const Value*> type) {
  51. CARBON_CHECK(!static_type_.has_value());
  52. static_type_ = type;
  53. }
  54. // The value of this pattern. Cannot be called before typechecking.
  55. // TODO rename to avoid confusion with BindingPattern::constant_value
  56. auto value() const -> const Value& { return **value_; }
  57. // Sets the value of this pattern. Can only be called once, during
  58. // typechecking.
  59. void set_value(Nonnull<const Value*> value) { value_ = value; }
  60. // Returns whether the value has been set. Should only be called
  61. // during typechecking: before typechecking it's guaranteed to be false,
  62. // and after typechecking it's guaranteed to be true.
  63. auto has_value() const -> bool { return value_.has_value(); }
  64. protected:
  65. // Constructs a Pattern representing syntax at the given line number.
  66. // `kind` must be the enumerator corresponding to the most-derived type being
  67. // constructed.
  68. Pattern(AstNodeKind kind, SourceLocation source_loc)
  69. : AstNode(kind, source_loc) {}
  70. private:
  71. std::optional<Nonnull<const Value*>> static_type_;
  72. std::optional<Nonnull<const Value*>> value_;
  73. };
  74. // Call the given `visitor` on all patterns nested within the given pattern,
  75. // including `pattern` itself. Aborts and returns `false` if `visitor` returns
  76. // `false`, otherwise returns `true`.
  77. auto VisitNestedPatterns(const Pattern& pattern,
  78. llvm::function_ref<bool(const Pattern&)> visitor)
  79. -> bool;
  80. // A pattern consisting of the `auto` keyword.
  81. class AutoPattern : public Pattern {
  82. public:
  83. explicit AutoPattern(SourceLocation source_loc)
  84. : Pattern(AstNodeKind::AutoPattern, source_loc) {}
  85. static auto classof(const AstNode* node) -> bool {
  86. return InheritsFromAutoPattern(node->kind());
  87. }
  88. };
  89. class VarPattern : public Pattern {
  90. public:
  91. explicit VarPattern(SourceLocation source_loc, Nonnull<Pattern*> pattern)
  92. : Pattern(AstNodeKind::VarPattern, source_loc), pattern_(pattern) {}
  93. static auto classof(const AstNode* node) -> bool {
  94. return InheritsFromVarPattern(node->kind());
  95. }
  96. auto pattern() const -> const Pattern& { return *pattern_; }
  97. auto pattern() -> Pattern& { return *pattern_; }
  98. auto value_category() const -> ValueCategory { return ValueCategory::Var; }
  99. private:
  100. Nonnull<Pattern*> pattern_;
  101. };
  102. // A pattern that matches a value of a specified type, and optionally binds
  103. // a name to it.
  104. class BindingPattern : public Pattern {
  105. public:
  106. using ImplementsCarbonValueNode = void;
  107. BindingPattern(SourceLocation source_loc, std::string name,
  108. Nonnull<Pattern*> type,
  109. std::optional<ValueCategory> value_category)
  110. : Pattern(AstNodeKind::BindingPattern, source_loc),
  111. name_(std::move(name)),
  112. type_(type),
  113. value_category_(value_category) {}
  114. static auto classof(const AstNode* node) -> bool {
  115. return InheritsFromBindingPattern(node->kind());
  116. }
  117. // The name this pattern binds, if any. If equal to AnonymousName, indicates
  118. // that this BindingPattern does not bind a name, which in turn means it
  119. // should not be used as a ValueNode.
  120. auto name() const -> const std::string& { return name_; }
  121. // The pattern specifying the type of values that this pattern matches.
  122. auto type() const -> const Pattern& { return *type_; }
  123. auto type() -> Pattern& { return *type_; }
  124. // Returns the value category of this pattern. Can only be called after
  125. // typechecking.
  126. auto value_category() const -> ValueCategory {
  127. return value_category_.value();
  128. }
  129. // Returns whether the value category has been set. Should only be called
  130. // during typechecking.
  131. auto has_value_category() const -> bool {
  132. return value_category_.has_value();
  133. }
  134. // Sets the value category of the variable being bound. Can only be called
  135. // once during typechecking
  136. void set_value_category(ValueCategory vc) {
  137. CARBON_CHECK(!value_category_.has_value());
  138. value_category_ = vc;
  139. }
  140. auto constant_value() const -> std::optional<Nonnull<const Value*>> {
  141. return std::nullopt;
  142. }
  143. auto symbolic_identity() const -> std::optional<Nonnull<const Value*>> {
  144. return std::nullopt;
  145. }
  146. private:
  147. std::string name_;
  148. Nonnull<Pattern*> type_;
  149. std::optional<ValueCategory> value_category_;
  150. };
  151. // A pattern that matches a tuple value field-wise.
  152. class TuplePattern : public Pattern {
  153. public:
  154. TuplePattern(SourceLocation source_loc, std::vector<Nonnull<Pattern*>> fields)
  155. : Pattern(AstNodeKind::TuplePattern, source_loc),
  156. fields_(std::move(fields)) {}
  157. static auto classof(const AstNode* node) -> bool {
  158. return InheritsFromTuplePattern(node->kind());
  159. }
  160. auto fields() const -> llvm::ArrayRef<Nonnull<const Pattern*>> {
  161. return fields_;
  162. }
  163. auto fields() -> llvm::ArrayRef<Nonnull<Pattern*>> { return fields_; }
  164. private:
  165. std::vector<Nonnull<Pattern*>> fields_;
  166. };
  167. class GenericBinding : public Pattern {
  168. public:
  169. using ImplementsCarbonValueNode = void;
  170. GenericBinding(SourceLocation source_loc, std::string name,
  171. Nonnull<Expression*> type)
  172. : Pattern(AstNodeKind::GenericBinding, source_loc),
  173. name_(std::move(name)),
  174. type_(type) {}
  175. void Print(llvm::raw_ostream& out) const override;
  176. void PrintID(llvm::raw_ostream& out) const override;
  177. static auto classof(const AstNode* node) -> bool {
  178. return InheritsFromGenericBinding(node->kind());
  179. }
  180. auto name() const -> const std::string& { return name_; }
  181. auto type() const -> const Expression& { return *type_; }
  182. auto type() -> Expression& { return *type_; }
  183. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  184. auto constant_value() const -> std::optional<Nonnull<const Value*>> {
  185. return std::nullopt;
  186. }
  187. auto symbolic_identity() const -> std::optional<Nonnull<const Value*>> {
  188. return symbolic_identity_;
  189. }
  190. void set_symbolic_identity(Nonnull<const Value*> value) {
  191. CARBON_CHECK(!symbolic_identity_.has_value());
  192. symbolic_identity_ = value;
  193. }
  194. // The impl binding associated with this type variable.
  195. auto impl_binding() const -> std::optional<Nonnull<const ImplBinding*>> {
  196. return impl_binding_;
  197. }
  198. // Set the impl binding.
  199. void set_impl_binding(Nonnull<const ImplBinding*> binding) {
  200. CARBON_CHECK(!impl_binding_.has_value());
  201. impl_binding_ = binding;
  202. }
  203. private:
  204. std::string name_;
  205. Nonnull<Expression*> type_;
  206. std::optional<Nonnull<const Value*>> symbolic_identity_;
  207. std::optional<Nonnull<const ImplBinding*>> impl_binding_;
  208. };
  209. // Converts paren_contents to a Pattern, interpreting the parentheses as
  210. // grouping if their contents permit that interpretation, or as forming a
  211. // tuple otherwise.
  212. auto PatternFromParenContents(Nonnull<Arena*> arena, SourceLocation source_loc,
  213. const ParenContents<Pattern>& paren_contents)
  214. -> Nonnull<Pattern*>;
  215. // Converts paren_contents to a TuplePattern, interpreting the parentheses as
  216. // forming a tuple.
  217. auto TuplePatternFromParenContents(Nonnull<Arena*> arena,
  218. SourceLocation source_loc,
  219. const ParenContents<Pattern>& paren_contents)
  220. -> Nonnull<TuplePattern*>;
  221. // Converts `contents` to ParenContents<Pattern> by replacing each Expression
  222. // with an ExpressionPattern.
  223. auto ParenExpressionToParenPattern(Nonnull<Arena*> arena,
  224. const ParenContents<Expression>& contents)
  225. -> ParenContents<Pattern>;
  226. // A pattern that matches an alternative of a choice type.
  227. class AlternativePattern : public Pattern {
  228. public:
  229. // Constructs an AlternativePattern that matches the alternative specified
  230. // by `alternative`, if its arguments match `arguments`.
  231. static auto Create(Nonnull<Arena*> arena, SourceLocation source_loc,
  232. Nonnull<Expression*> alternative,
  233. Nonnull<TuplePattern*> arguments)
  234. -> ErrorOr<Nonnull<AlternativePattern*>> {
  235. CARBON_ASSIGN_OR_RETURN(Nonnull<FieldAccessExpression*> field_access,
  236. RequireFieldAccess(alternative));
  237. return arena->New<AlternativePattern>(source_loc,
  238. &field_access->aggregate(),
  239. field_access->field(), arguments);
  240. }
  241. // Constructs an AlternativePattern that matches a value of the type
  242. // specified by choice_type if it represents an alternative named
  243. // alternative_name, and its arguments match `arguments`.
  244. AlternativePattern(SourceLocation source_loc,
  245. Nonnull<Expression*> choice_type,
  246. std::string alternative_name,
  247. Nonnull<TuplePattern*> arguments)
  248. : Pattern(AstNodeKind::AlternativePattern, source_loc),
  249. choice_type_(choice_type),
  250. alternative_name_(std::move(alternative_name)),
  251. arguments_(arguments) {}
  252. static auto classof(const AstNode* node) -> bool {
  253. return InheritsFromAlternativePattern(node->kind());
  254. }
  255. auto choice_type() const -> const Expression& { return *choice_type_; }
  256. auto choice_type() -> Expression& { return *choice_type_; }
  257. auto alternative_name() const -> const std::string& {
  258. return alternative_name_;
  259. }
  260. auto arguments() const -> const TuplePattern& { return *arguments_; }
  261. auto arguments() -> TuplePattern& { return *arguments_; }
  262. private:
  263. static auto RequireFieldAccess(Nonnull<Expression*> alternative)
  264. -> ErrorOr<Nonnull<FieldAccessExpression*>>;
  265. Nonnull<Expression*> choice_type_;
  266. std::string alternative_name_;
  267. Nonnull<TuplePattern*> arguments_;
  268. };
  269. // A pattern that matches a value if it is equal to the value of a given
  270. // expression.
  271. class ExpressionPattern : public Pattern {
  272. public:
  273. explicit ExpressionPattern(Nonnull<Expression*> expression)
  274. : Pattern(AstNodeKind::ExpressionPattern, expression->source_loc()),
  275. expression_(expression) {}
  276. static auto classof(const AstNode* node) -> bool {
  277. return InheritsFromExpressionPattern(node->kind());
  278. }
  279. auto expression() const -> const Expression& { return *expression_; }
  280. auto expression() -> Expression& { return *expression_; }
  281. private:
  282. Nonnull<Expression*> expression_;
  283. };
  284. } // namespace Carbon
  285. #endif // CARBON_EXPLORER_AST_PATTERN_H_