pattern.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. // Set the original generic binding.
  230. void set_original(Nonnull<const GenericBinding*> orig) { original_ = orig; }
  231. // Returns whether this binding has been named as a type within its own type
  232. // expression via `.Self`. Set by type-checking.
  233. auto named_as_type_via_dot_self() const -> bool {
  234. return named_as_type_via_dot_self_;
  235. }
  236. // Set that this binding was named as a type within its own type expression
  237. // via `.Self`. May only be called during type-checking.
  238. void set_named_as_type_via_dot_self() { named_as_type_via_dot_self_ = true; }
  239. private:
  240. std::string name_;
  241. Nonnull<Expression*> type_;
  242. std::optional<Nonnull<const Value*>> symbolic_identity_;
  243. std::optional<Nonnull<const ImplBinding*>> impl_binding_;
  244. std::optional<Nonnull<const GenericBinding*>> original_;
  245. bool named_as_type_via_dot_self_ = false;
  246. };
  247. // Converts paren_contents to a Pattern, interpreting the parentheses as
  248. // grouping if their contents permit that interpretation, or as forming a
  249. // tuple otherwise.
  250. auto PatternFromParenContents(Nonnull<Arena*> arena, SourceLocation source_loc,
  251. const ParenContents<Pattern>& paren_contents)
  252. -> Nonnull<Pattern*>;
  253. // Converts paren_contents to a TuplePattern, interpreting the parentheses as
  254. // forming a tuple.
  255. auto TuplePatternFromParenContents(Nonnull<Arena*> arena,
  256. SourceLocation source_loc,
  257. const ParenContents<Pattern>& paren_contents)
  258. -> Nonnull<TuplePattern*>;
  259. // Converts `contents` to ParenContents<Pattern> by replacing each Expression
  260. // with an ExpressionPattern.
  261. auto ParenExpressionToParenPattern(Nonnull<Arena*> arena,
  262. const ParenContents<Expression>& contents)
  263. -> ParenContents<Pattern>;
  264. // A pattern that matches an alternative of a choice type.
  265. class AlternativePattern : public Pattern {
  266. public:
  267. // Constructs an AlternativePattern that matches the alternative specified
  268. // by `alternative`, if its arguments match `arguments`.
  269. static auto Create(Nonnull<Arena*> arena, SourceLocation source_loc,
  270. Nonnull<Expression*> alternative,
  271. Nonnull<TuplePattern*> arguments)
  272. -> ErrorOr<Nonnull<AlternativePattern*>> {
  273. CARBON_ASSIGN_OR_RETURN(
  274. Nonnull<SimpleMemberAccessExpression*> member_access,
  275. RequireSimpleMemberAccess(alternative));
  276. return arena->New<AlternativePattern>(source_loc, &member_access->object(),
  277. member_access->member_name(),
  278. arguments);
  279. }
  280. // Constructs an AlternativePattern that matches a value of the type
  281. // specified by choice_type if it represents an alternative named
  282. // alternative_name, and its arguments match `arguments`.
  283. AlternativePattern(SourceLocation source_loc,
  284. Nonnull<Expression*> choice_type,
  285. std::string alternative_name,
  286. Nonnull<TuplePattern*> arguments)
  287. : Pattern(AstNodeKind::AlternativePattern, source_loc),
  288. choice_type_(choice_type),
  289. alternative_name_(std::move(alternative_name)),
  290. arguments_(arguments) {}
  291. static auto classof(const AstNode* node) -> bool {
  292. return InheritsFromAlternativePattern(node->kind());
  293. }
  294. auto choice_type() const -> const Expression& { return *choice_type_; }
  295. auto choice_type() -> Expression& { return *choice_type_; }
  296. auto alternative_name() const -> const std::string& {
  297. return alternative_name_;
  298. }
  299. auto arguments() const -> const TuplePattern& { return *arguments_; }
  300. auto arguments() -> TuplePattern& { return *arguments_; }
  301. private:
  302. static auto RequireSimpleMemberAccess(Nonnull<Expression*> alternative)
  303. -> ErrorOr<Nonnull<SimpleMemberAccessExpression*>>;
  304. Nonnull<Expression*> choice_type_;
  305. std::string alternative_name_;
  306. Nonnull<TuplePattern*> arguments_;
  307. };
  308. // A pattern that matches a value if it is equal to the value of a given
  309. // expression.
  310. class ExpressionPattern : public Pattern {
  311. public:
  312. explicit ExpressionPattern(Nonnull<Expression*> expression)
  313. : Pattern(AstNodeKind::ExpressionPattern, expression->source_loc()),
  314. expression_(expression) {}
  315. static auto classof(const AstNode* node) -> bool {
  316. return InheritsFromExpressionPattern(node->kind());
  317. }
  318. auto expression() const -> const Expression& { return *expression_; }
  319. auto expression() -> Expression& { return *expression_; }
  320. private:
  321. Nonnull<Expression*> expression_;
  322. };
  323. } // namespace Carbon
  324. #endif // CARBON_EXPLORER_AST_PATTERN_H_