pattern.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. auto has_static_type() const -> bool { return static_type_.has_value(); }
  49. // Sets the static type of this expression. Can only be called once, during
  50. // typechecking.
  51. void set_static_type(Nonnull<const Value*> type) {
  52. CARBON_CHECK(!static_type_.has_value());
  53. static_type_ = type;
  54. }
  55. // The value of this pattern. Cannot be called before typechecking.
  56. // TODO: Rename to avoid confusion with BindingPattern::constant_value
  57. auto value() const -> const Value& { return **value_; }
  58. // Sets the value of this pattern. Can only be called once, during
  59. // typechecking.
  60. void set_value(Nonnull<const Value*> value) { value_ = value; }
  61. // Returns whether the value has been set. Should only be called
  62. // during typechecking: before typechecking it's guaranteed to be false,
  63. // and after typechecking it's guaranteed to be true.
  64. auto has_value() const -> bool { return value_.has_value(); }
  65. // Determines whether the pattern has already been type-checked. Should
  66. // only be used by type-checking.
  67. auto is_type_checked() const -> bool {
  68. return static_type_.has_value() && value_.has_value();
  69. }
  70. protected:
  71. // Constructs a Pattern representing syntax at the given line number.
  72. // `kind` must be the enumerator corresponding to the most-derived type being
  73. // constructed.
  74. Pattern(AstNodeKind kind, SourceLocation source_loc)
  75. : AstNode(kind, source_loc) {}
  76. private:
  77. std::optional<Nonnull<const Value*>> static_type_;
  78. std::optional<Nonnull<const Value*>> value_;
  79. };
  80. // Call the given `visitor` on all patterns nested within the given pattern,
  81. // including `pattern` itself. Aborts and returns `false` if `visitor` returns
  82. // `false`, otherwise returns `true`.
  83. auto VisitNestedPatterns(const Pattern& pattern,
  84. llvm::function_ref<bool(const Pattern&)> visitor)
  85. -> bool;
  86. // A pattern consisting of the `auto` keyword.
  87. class AutoPattern : public Pattern {
  88. public:
  89. explicit AutoPattern(SourceLocation source_loc)
  90. : Pattern(AstNodeKind::AutoPattern, source_loc) {}
  91. static auto classof(const AstNode* node) -> bool {
  92. return InheritsFromAutoPattern(node->kind());
  93. }
  94. };
  95. class VarPattern : public Pattern {
  96. public:
  97. explicit VarPattern(SourceLocation source_loc, Nonnull<Pattern*> pattern)
  98. : Pattern(AstNodeKind::VarPattern, source_loc), pattern_(pattern) {}
  99. static auto classof(const AstNode* node) -> bool {
  100. return InheritsFromVarPattern(node->kind());
  101. }
  102. auto pattern() const -> const Pattern& { return *pattern_; }
  103. auto pattern() -> Pattern& { return *pattern_; }
  104. auto value_category() const -> ValueCategory { return ValueCategory::Var; }
  105. private:
  106. Nonnull<Pattern*> pattern_;
  107. };
  108. // A pattern that matches a value of a specified type, and optionally binds
  109. // a name to it.
  110. class BindingPattern : public Pattern {
  111. public:
  112. using ImplementsCarbonValueNode = void;
  113. BindingPattern(SourceLocation source_loc, std::string name,
  114. Nonnull<Pattern*> type,
  115. std::optional<ValueCategory> value_category)
  116. : Pattern(AstNodeKind::BindingPattern, source_loc),
  117. name_(std::move(name)),
  118. type_(type),
  119. value_category_(value_category) {}
  120. static auto classof(const AstNode* node) -> bool {
  121. return InheritsFromBindingPattern(node->kind());
  122. }
  123. // The name this pattern binds, if any. If equal to AnonymousName, indicates
  124. // that this BindingPattern does not bind a name, which in turn means it
  125. // should not be used as a ValueNode.
  126. auto name() const -> const std::string& { return name_; }
  127. // The pattern specifying the type of values that this pattern matches.
  128. auto type() const -> const Pattern& { return *type_; }
  129. auto type() -> Pattern& { return *type_; }
  130. // Returns the value category of this pattern. Can only be called after
  131. // typechecking.
  132. auto value_category() const -> ValueCategory {
  133. return value_category_.value();
  134. }
  135. // Returns whether the value category has been set. Should only be called
  136. // during typechecking.
  137. auto has_value_category() const -> bool {
  138. return value_category_.has_value();
  139. }
  140. // Sets the value category of the variable being bound. Can only be called
  141. // once during typechecking
  142. void set_value_category(ValueCategory vc) {
  143. CARBON_CHECK(!value_category_.has_value());
  144. value_category_ = vc;
  145. }
  146. auto constant_value() const -> std::optional<Nonnull<const Value*>> {
  147. return std::nullopt;
  148. }
  149. auto symbolic_identity() const -> std::optional<Nonnull<const Value*>> {
  150. return std::nullopt;
  151. }
  152. private:
  153. std::string name_;
  154. Nonnull<Pattern*> type_;
  155. std::optional<ValueCategory> value_category_;
  156. };
  157. class AddrPattern : public Pattern {
  158. public:
  159. explicit AddrPattern(SourceLocation source_loc,
  160. Nonnull<BindingPattern*> binding)
  161. : Pattern(AstNodeKind::AddrPattern, source_loc), binding_(binding) {}
  162. static auto classof(const AstNode* node) -> bool {
  163. return InheritsFromAddrPattern(node->kind());
  164. }
  165. auto binding() const -> const BindingPattern& { return *binding_; }
  166. auto binding() -> BindingPattern& { return *binding_; }
  167. private:
  168. Nonnull<BindingPattern*> binding_;
  169. };
  170. // A pattern that matches a tuple value field-wise.
  171. class TuplePattern : public Pattern {
  172. public:
  173. TuplePattern(SourceLocation source_loc, std::vector<Nonnull<Pattern*>> fields)
  174. : Pattern(AstNodeKind::TuplePattern, source_loc),
  175. fields_(std::move(fields)) {}
  176. static auto classof(const AstNode* node) -> bool {
  177. return InheritsFromTuplePattern(node->kind());
  178. }
  179. auto fields() const -> llvm::ArrayRef<Nonnull<const Pattern*>> {
  180. return fields_;
  181. }
  182. auto fields() -> llvm::ArrayRef<Nonnull<Pattern*>> { return fields_; }
  183. private:
  184. std::vector<Nonnull<Pattern*>> fields_;
  185. };
  186. class GenericBinding : public Pattern {
  187. public:
  188. using ImplementsCarbonValueNode = void;
  189. GenericBinding(SourceLocation source_loc, std::string name,
  190. Nonnull<Expression*> type)
  191. : Pattern(AstNodeKind::GenericBinding, source_loc),
  192. name_(std::move(name)),
  193. type_(type) {}
  194. void Print(llvm::raw_ostream& out) const override;
  195. void PrintID(llvm::raw_ostream& out) const override;
  196. static auto classof(const AstNode* node) -> bool {
  197. return InheritsFromGenericBinding(node->kind());
  198. }
  199. auto name() const -> const std::string& { return name_; }
  200. auto type() const -> const Expression& { return *type_; }
  201. auto type() -> Expression& { return *type_; }
  202. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  203. auto constant_value() const -> std::optional<Nonnull<const Value*>> {
  204. return std::nullopt;
  205. }
  206. auto symbolic_identity() const -> std::optional<Nonnull<const Value*>> {
  207. return symbolic_identity_;
  208. }
  209. void set_symbolic_identity(Nonnull<const Value*> value) {
  210. CARBON_CHECK(!symbolic_identity_.has_value());
  211. symbolic_identity_ = value;
  212. }
  213. // The impl binding associated with this type variable.
  214. auto impl_binding() const -> std::optional<Nonnull<const ImplBinding*>> {
  215. return impl_binding_;
  216. }
  217. // Set the impl binding.
  218. void set_impl_binding(Nonnull<const ImplBinding*> binding) {
  219. CARBON_CHECK(!impl_binding_.has_value());
  220. impl_binding_ = binding;
  221. }
  222. // Return the original generic binding.
  223. auto original() const -> Nonnull<const GenericBinding*> {
  224. if (original_.has_value()) {
  225. return *original_;
  226. } else {
  227. return this;
  228. }
  229. }
  230. // Set the original generic binding.
  231. void set_original(Nonnull<const GenericBinding*> orig) { original_ = orig; }
  232. // Returns whether this binding has been named as a type within its own type
  233. // expression via `.Self`. Set by type-checking.
  234. auto named_as_type_via_dot_self() const -> bool {
  235. return named_as_type_via_dot_self_;
  236. }
  237. // Set that this binding was named as a type within its own type expression
  238. // via `.Self`. May only be called during type-checking.
  239. void set_named_as_type_via_dot_self() { named_as_type_via_dot_self_ = true; }
  240. private:
  241. std::string name_;
  242. Nonnull<Expression*> type_;
  243. std::optional<Nonnull<const Value*>> symbolic_identity_;
  244. std::optional<Nonnull<const ImplBinding*>> impl_binding_;
  245. std::optional<Nonnull<const GenericBinding*>> original_;
  246. bool named_as_type_via_dot_self_ = false;
  247. };
  248. // Converts paren_contents to a Pattern, interpreting the parentheses as
  249. // grouping if their contents permit that interpretation, or as forming a
  250. // tuple otherwise.
  251. auto PatternFromParenContents(Nonnull<Arena*> arena, SourceLocation source_loc,
  252. const ParenContents<Pattern>& paren_contents)
  253. -> Nonnull<Pattern*>;
  254. // Converts paren_contents to a TuplePattern, interpreting the parentheses as
  255. // forming a tuple.
  256. auto TuplePatternFromParenContents(Nonnull<Arena*> arena,
  257. SourceLocation source_loc,
  258. const ParenContents<Pattern>& paren_contents)
  259. -> Nonnull<TuplePattern*>;
  260. // Converts `contents` to ParenContents<Pattern> by replacing each Expression
  261. // with an ExpressionPattern.
  262. auto ParenExpressionToParenPattern(Nonnull<Arena*> arena,
  263. const ParenContents<Expression>& contents)
  264. -> ParenContents<Pattern>;
  265. // A pattern that matches an alternative of a choice type.
  266. class AlternativePattern : public Pattern {
  267. public:
  268. // Constructs an AlternativePattern that matches the alternative specified
  269. // by `alternative`, if its arguments match `arguments`.
  270. static auto Create(Nonnull<Arena*> arena, SourceLocation source_loc,
  271. Nonnull<Expression*> alternative,
  272. Nonnull<TuplePattern*> arguments)
  273. -> ErrorOr<Nonnull<AlternativePattern*>> {
  274. CARBON_ASSIGN_OR_RETURN(
  275. Nonnull<SimpleMemberAccessExpression*> member_access,
  276. RequireSimpleMemberAccess(alternative));
  277. return arena->New<AlternativePattern>(source_loc, &member_access->object(),
  278. member_access->member_name(),
  279. arguments);
  280. }
  281. // Constructs an AlternativePattern that matches a value of the type
  282. // specified by choice_type if it represents an alternative named
  283. // alternative_name, and its arguments match `arguments`.
  284. AlternativePattern(SourceLocation source_loc,
  285. Nonnull<Expression*> choice_type,
  286. std::string alternative_name,
  287. Nonnull<TuplePattern*> arguments)
  288. : Pattern(AstNodeKind::AlternativePattern, source_loc),
  289. choice_type_(choice_type),
  290. alternative_name_(std::move(alternative_name)),
  291. arguments_(arguments) {}
  292. static auto classof(const AstNode* node) -> bool {
  293. return InheritsFromAlternativePattern(node->kind());
  294. }
  295. auto choice_type() const -> const Expression& { return *choice_type_; }
  296. auto choice_type() -> Expression& { return *choice_type_; }
  297. auto alternative_name() const -> const std::string& {
  298. return alternative_name_;
  299. }
  300. auto arguments() const -> const TuplePattern& { return *arguments_; }
  301. auto arguments() -> TuplePattern& { return *arguments_; }
  302. private:
  303. static auto RequireSimpleMemberAccess(Nonnull<Expression*> alternative)
  304. -> ErrorOr<Nonnull<SimpleMemberAccessExpression*>>;
  305. Nonnull<Expression*> choice_type_;
  306. std::string alternative_name_;
  307. Nonnull<TuplePattern*> arguments_;
  308. };
  309. // A pattern that matches a value if it is equal to the value of a given
  310. // expression.
  311. class ExpressionPattern : public Pattern {
  312. public:
  313. explicit ExpressionPattern(Nonnull<Expression*> expression)
  314. : Pattern(AstNodeKind::ExpressionPattern, expression->source_loc()),
  315. expression_(expression) {}
  316. static auto classof(const AstNode* node) -> bool {
  317. return InheritsFromExpressionPattern(node->kind());
  318. }
  319. auto expression() const -> const Expression& { return *expression_; }
  320. auto expression() -> Expression& { return *expression_; }
  321. private:
  322. Nonnull<Expression*> expression_;
  323. };
  324. } // namespace Carbon
  325. #endif // CARBON_EXPLORER_AST_PATTERN_H_