pattern.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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/clone_context.h"
  13. #include "explorer/ast/expression.h"
  14. #include "explorer/ast/expression_category.h"
  15. #include "explorer/ast/value_node.h"
  16. #include "explorer/common/source_location.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/STLFunctionalExtras.h"
  19. namespace Carbon {
  20. class Value;
  21. // Abstract base class of all AST nodes representing patterns.
  22. //
  23. // Pattern and its derived classes support LLVM-style RTTI, including
  24. // llvm::isa, llvm::cast, and llvm::dyn_cast. To support this, every
  25. // class derived from Pattern must provide a `classof` operation, and
  26. // every concrete derived class must have a corresponding enumerator
  27. // in `Kind`; see https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html for
  28. // details.
  29. class Pattern : public AstNode {
  30. public:
  31. explicit Pattern(CloneContext& context, const Pattern& other)
  32. : AstNode(context, other),
  33. static_type_(context.Clone(other.static_type_)),
  34. value_(context.Clone(other.value_)) {}
  35. Pattern(const Pattern&) = delete;
  36. auto operator=(const Pattern&) -> Pattern& = delete;
  37. ~Pattern() override = 0;
  38. void Print(llvm::raw_ostream& out) const override;
  39. void PrintID(llvm::raw_ostream& out) const override;
  40. static auto classof(const AstNode* node) -> bool {
  41. return InheritsFromPattern(node->kind());
  42. }
  43. // Returns the enumerator corresponding to the most-derived type of this
  44. // object.
  45. auto kind() const -> PatternKind {
  46. return static_cast<PatternKind>(root_kind());
  47. }
  48. // The static type of this pattern. Cannot be called before typechecking.
  49. auto static_type() const -> const Value& {
  50. CARBON_CHECK(static_type_.has_value());
  51. return **static_type_;
  52. }
  53. auto has_static_type() const -> bool { return static_type_.has_value(); }
  54. // Sets the static type of this expression. Can only be called once, during
  55. // typechecking.
  56. void set_static_type(Nonnull<const Value*> type) {
  57. CARBON_CHECK(!static_type_.has_value());
  58. static_type_ = type;
  59. }
  60. // The value of this pattern. Cannot be called before typechecking.
  61. // TODO: Rename to avoid confusion with BindingPattern::constant_value
  62. auto value() const -> const Value& { return **value_; }
  63. // Sets the value of this pattern. Can only be called once, during
  64. // typechecking.
  65. void set_value(Nonnull<const Value*> value) {
  66. CARBON_CHECK(!value_) << "set_value called more than once";
  67. value_ = value;
  68. }
  69. // Returns whether the value has been set. Should only be called
  70. // during typechecking: before typechecking it's guaranteed to be false,
  71. // and after typechecking it's guaranteed to be true.
  72. auto has_value() const -> bool { return value_.has_value(); }
  73. // Determines whether the pattern has already been type-checked. Should
  74. // only be used by type-checking.
  75. auto is_type_checked() const -> bool {
  76. return static_type_.has_value() && value_.has_value();
  77. }
  78. protected:
  79. // Constructs a Pattern representing syntax at the given line number.
  80. // `kind` must be the enumerator corresponding to the most-derived type being
  81. // constructed.
  82. Pattern(AstNodeKind kind, SourceLocation source_loc)
  83. : AstNode(kind, source_loc) {}
  84. private:
  85. std::optional<Nonnull<const Value*>> static_type_;
  86. std::optional<Nonnull<const Value*>> value_;
  87. };
  88. // Call the given `visitor` on all patterns nested within the given pattern,
  89. // including `pattern` itself. Aborts and returns `false` if `visitor` returns
  90. // `false`, otherwise returns `true`.
  91. auto VisitNestedPatterns(const Pattern& pattern,
  92. llvm::function_ref<bool(const Pattern&)> visitor)
  93. -> bool;
  94. inline auto VisitNestedPatterns(Pattern& pattern,
  95. llvm::function_ref<bool(Pattern&)> visitor)
  96. -> bool {
  97. // The non-const version is is implemented in terms of the const version. The
  98. // const_cast is safe because every pattern reachable through a non-const
  99. // pattern is also non-const.
  100. const Pattern& const_pattern = pattern;
  101. return VisitNestedPatterns(const_pattern, [&](const Pattern& inner) {
  102. return visitor(const_cast<Pattern&>(inner));
  103. });
  104. }
  105. // A pattern consisting of the `auto` keyword.
  106. class AutoPattern : public Pattern {
  107. public:
  108. explicit AutoPattern(SourceLocation source_loc)
  109. : Pattern(AstNodeKind::AutoPattern, source_loc) {}
  110. explicit AutoPattern(CloneContext& context, const AutoPattern& other)
  111. : Pattern(context, other) {}
  112. static auto classof(const AstNode* node) -> bool {
  113. return InheritsFromAutoPattern(node->kind());
  114. }
  115. };
  116. class VarPattern : public Pattern {
  117. public:
  118. explicit VarPattern(SourceLocation source_loc, Nonnull<Pattern*> pattern)
  119. : Pattern(AstNodeKind::VarPattern, source_loc), pattern_(pattern) {}
  120. explicit VarPattern(CloneContext& context, const VarPattern& other)
  121. : Pattern(context, other), pattern_(context.Clone(other.pattern_)) {}
  122. static auto classof(const AstNode* node) -> bool {
  123. return InheritsFromVarPattern(node->kind());
  124. }
  125. auto pattern() const -> const Pattern& { return *pattern_; }
  126. auto pattern() -> Pattern& { return *pattern_; }
  127. auto expression_category() const -> ExpressionCategory {
  128. return ExpressionCategory::Reference;
  129. }
  130. private:
  131. Nonnull<Pattern*> pattern_;
  132. };
  133. // A pattern that matches a value of a specified type, and optionally binds
  134. // a name to it.
  135. class BindingPattern : public Pattern {
  136. public:
  137. using ImplementsCarbonValueNode = void;
  138. BindingPattern(SourceLocation source_loc, std::string name,
  139. Nonnull<Pattern*> type,
  140. std::optional<ExpressionCategory> expression_category)
  141. : Pattern(AstNodeKind::BindingPattern, source_loc),
  142. name_(std::move(name)),
  143. type_(type),
  144. expression_category_(expression_category) {}
  145. explicit BindingPattern(CloneContext& context, const BindingPattern& other)
  146. : Pattern(context, other),
  147. name_(other.name_),
  148. type_(context.Clone(other.type_)),
  149. expression_category_(other.expression_category_) {}
  150. static auto classof(const AstNode* node) -> bool {
  151. return InheritsFromBindingPattern(node->kind());
  152. }
  153. // The name this pattern binds, if any. If equal to AnonymousName, indicates
  154. // that this BindingPattern does not bind a name, which in turn means it
  155. // should not be used as a ValueNode.
  156. auto name() const -> const std::string& { return name_; }
  157. // The pattern specifying the type of values that this pattern matches.
  158. auto type() const -> const Pattern& { return *type_; }
  159. auto type() -> Pattern& { return *type_; }
  160. // Returns the value category of this pattern. Can only be called after
  161. // typechecking.
  162. auto expression_category() const -> ExpressionCategory {
  163. return expression_category_.value();
  164. }
  165. // Returns whether the value category has been set. Should only be called
  166. // during typechecking.
  167. auto has_expression_category() const -> bool {
  168. return expression_category_.has_value();
  169. }
  170. // Sets the value category of the variable being bound. Can only be called
  171. // once during typechecking
  172. void set_expression_category(ExpressionCategory vc) {
  173. CARBON_CHECK(!expression_category_.has_value());
  174. expression_category_ = vc;
  175. }
  176. auto constant_value() const -> std::optional<Nonnull<const Value*>> {
  177. return std::nullopt;
  178. }
  179. auto symbolic_identity() const -> std::optional<Nonnull<const Value*>> {
  180. return std::nullopt;
  181. }
  182. private:
  183. std::string name_;
  184. Nonnull<Pattern*> type_;
  185. std::optional<ExpressionCategory> expression_category_;
  186. };
  187. class AddrPattern : public Pattern {
  188. public:
  189. explicit AddrPattern(SourceLocation source_loc,
  190. Nonnull<BindingPattern*> binding)
  191. : Pattern(AstNodeKind::AddrPattern, source_loc), binding_(binding) {}
  192. explicit AddrPattern(CloneContext& context, const AddrPattern& other)
  193. : Pattern(context, other), binding_(context.Clone(other.binding_)) {}
  194. static auto classof(const AstNode* node) -> bool {
  195. return InheritsFromAddrPattern(node->kind());
  196. }
  197. auto binding() const -> const BindingPattern& { return *binding_; }
  198. auto binding() -> BindingPattern& { return *binding_; }
  199. private:
  200. Nonnull<BindingPattern*> binding_;
  201. };
  202. // A pattern that matches a tuple value field-wise.
  203. class TuplePattern : public Pattern {
  204. public:
  205. TuplePattern(SourceLocation source_loc, std::vector<Nonnull<Pattern*>> fields)
  206. : Pattern(AstNodeKind::TuplePattern, source_loc),
  207. fields_(std::move(fields)) {}
  208. explicit TuplePattern(CloneContext& context, const TuplePattern& other)
  209. : Pattern(context, other), fields_(context.Clone(other.fields_)) {}
  210. static auto classof(const AstNode* node) -> bool {
  211. return InheritsFromTuplePattern(node->kind());
  212. }
  213. auto fields() const -> llvm::ArrayRef<Nonnull<const Pattern*>> {
  214. return fields_;
  215. }
  216. auto fields() -> llvm::ArrayRef<Nonnull<Pattern*>> { return fields_; }
  217. private:
  218. std::vector<Nonnull<Pattern*>> fields_;
  219. };
  220. class GenericBinding : public Pattern {
  221. public:
  222. using ImplementsCarbonValueNode = void;
  223. enum class BindingKind {
  224. // A checked generic binding, `T:! type`.
  225. Checked,
  226. // A template generic binding, `template T:! type`.
  227. Template,
  228. };
  229. explicit GenericBinding(SourceLocation source_loc, std::string name,
  230. Nonnull<Expression*> type, BindingKind binding_kind)
  231. : Pattern(AstNodeKind::GenericBinding, source_loc),
  232. name_(std::move(name)),
  233. type_(type),
  234. binding_kind_(binding_kind) {}
  235. explicit GenericBinding(CloneContext& context, const GenericBinding& other);
  236. static auto classof(const AstNode* node) -> bool {
  237. return InheritsFromGenericBinding(node->kind());
  238. }
  239. auto name() const -> const std::string& { return name_; }
  240. auto type() const -> const Expression& { return *type_; }
  241. auto type() -> Expression& { return *type_; }
  242. auto binding_kind() const -> BindingKind { return binding_kind_; }
  243. // The index of this binding, which is the number of bindings that are in
  244. // scope at the point where this binding is declared.
  245. auto index() const -> int { return *index_; }
  246. // Set the index of this binding. Should be called only during type-checking.
  247. void set_index(int index) {
  248. CARBON_CHECK(!index_) << "should only set depth and index once";
  249. index_ = index;
  250. }
  251. auto expression_category() const -> ExpressionCategory {
  252. return ExpressionCategory::Value;
  253. }
  254. auto constant_value() const -> std::optional<Nonnull<const Value*>> {
  255. return template_value_;
  256. }
  257. auto symbolic_identity() const -> std::optional<Nonnull<const Value*>> {
  258. return symbolic_identity_;
  259. }
  260. void set_symbolic_identity(Nonnull<const Value*> value) {
  261. CARBON_CHECK(!symbolic_identity_.has_value());
  262. symbolic_identity_ = value;
  263. }
  264. void set_template_value(Nonnull<const Value*> template_value) {
  265. CARBON_CHECK(binding_kind_ == BindingKind::Template);
  266. template_value_ = template_value;
  267. }
  268. auto has_template_value() const -> bool {
  269. CARBON_CHECK(binding_kind_ == BindingKind::Template);
  270. return template_value_.has_value();
  271. }
  272. // The impl binding associated with this type variable.
  273. auto impl_binding() const -> std::optional<Nonnull<const ImplBinding*>> {
  274. return impl_binding_;
  275. }
  276. // Set the impl binding.
  277. void set_impl_binding(Nonnull<const ImplBinding*> binding) {
  278. CARBON_CHECK(!impl_binding_.has_value());
  279. impl_binding_ = binding;
  280. }
  281. // Return the original generic binding.
  282. auto original() const -> Nonnull<const GenericBinding*> {
  283. if (original_.has_value()) {
  284. return *original_;
  285. } else {
  286. return this;
  287. }
  288. }
  289. // Set the original generic binding.
  290. void set_original(Nonnull<const GenericBinding*> orig) { original_ = orig; }
  291. // Returns whether this binding has been named as a type within its own type
  292. // expression via `.Self`. Set by type-checking.
  293. auto named_as_type_via_dot_self() const -> bool {
  294. return named_as_type_via_dot_self_;
  295. }
  296. // Set that this binding was named as a type within its own type expression
  297. // via `.Self`. May only be called during type-checking.
  298. void set_named_as_type_via_dot_self() { named_as_type_via_dot_self_ = true; }
  299. private:
  300. std::string name_;
  301. Nonnull<Expression*> type_;
  302. BindingKind binding_kind_;
  303. std::optional<int> index_;
  304. std::optional<Nonnull<const Value*>> template_value_;
  305. std::optional<Nonnull<const Value*>> symbolic_identity_;
  306. std::optional<Nonnull<const ImplBinding*>> impl_binding_;
  307. std::optional<Nonnull<const GenericBinding*>> original_;
  308. bool named_as_type_via_dot_self_ = false;
  309. };
  310. // Converts paren_contents to a Pattern, interpreting the parentheses as
  311. // grouping if their contents permit that interpretation, or as forming a
  312. // tuple otherwise.
  313. auto PatternFromParenContents(Nonnull<Arena*> arena, SourceLocation source_loc,
  314. const ParenContents<Pattern>& paren_contents)
  315. -> Nonnull<Pattern*>;
  316. // Converts paren_contents to a TuplePattern, interpreting the parentheses as
  317. // forming a tuple.
  318. auto TuplePatternFromParenContents(Nonnull<Arena*> arena,
  319. SourceLocation source_loc,
  320. const ParenContents<Pattern>& paren_contents)
  321. -> Nonnull<TuplePattern*>;
  322. // Converts `contents` to ParenContents<Pattern> by replacing each Expression
  323. // with an ExpressionPattern.
  324. auto ParenExpressionToParenPattern(Nonnull<Arena*> arena,
  325. const ParenContents<Expression>& contents)
  326. -> ParenContents<Pattern>;
  327. // A pattern that matches an alternative of a choice type.
  328. class AlternativePattern : public Pattern {
  329. public:
  330. // Constructs an AlternativePattern that matches the alternative specified
  331. // by `alternative`, if its arguments match `arguments`.
  332. static auto Create(Nonnull<Arena*> arena, SourceLocation source_loc,
  333. Nonnull<Expression*> alternative,
  334. Nonnull<TuplePattern*> arguments)
  335. -> ErrorOr<Nonnull<AlternativePattern*>> {
  336. CARBON_ASSIGN_OR_RETURN(
  337. Nonnull<SimpleMemberAccessExpression*> member_access,
  338. RequireSimpleMemberAccess(alternative));
  339. return arena->New<AlternativePattern>(source_loc, &member_access->object(),
  340. member_access->member_name(),
  341. arguments);
  342. }
  343. // Constructs an AlternativePattern that matches a value of the type
  344. // specified by choice_type if it represents an alternative named
  345. // alternative_name, and its arguments match `arguments`.
  346. AlternativePattern(SourceLocation source_loc,
  347. Nonnull<Expression*> choice_type,
  348. std::string alternative_name,
  349. Nonnull<TuplePattern*> arguments)
  350. : Pattern(AstNodeKind::AlternativePattern, source_loc),
  351. choice_type_(choice_type),
  352. alternative_name_(std::move(alternative_name)),
  353. arguments_(arguments) {}
  354. explicit AlternativePattern(CloneContext& context,
  355. const AlternativePattern& other)
  356. : Pattern(context, other),
  357. choice_type_(context.Clone(other.choice_type_)),
  358. alternative_name_(other.alternative_name_),
  359. arguments_(context.Clone(other.arguments_)) {}
  360. static auto classof(const AstNode* node) -> bool {
  361. return InheritsFromAlternativePattern(node->kind());
  362. }
  363. auto choice_type() const -> const Expression& { return *choice_type_; }
  364. auto choice_type() -> Expression& { return *choice_type_; }
  365. auto alternative_name() const -> const std::string& {
  366. return alternative_name_;
  367. }
  368. auto arguments() const -> const TuplePattern& { return *arguments_; }
  369. auto arguments() -> TuplePattern& { return *arguments_; }
  370. private:
  371. static auto RequireSimpleMemberAccess(Nonnull<Expression*> alternative)
  372. -> ErrorOr<Nonnull<SimpleMemberAccessExpression*>>;
  373. Nonnull<Expression*> choice_type_;
  374. std::string alternative_name_;
  375. Nonnull<TuplePattern*> arguments_;
  376. };
  377. // A pattern that matches a value if it is equal to the value of a given
  378. // expression.
  379. class ExpressionPattern : public Pattern {
  380. public:
  381. explicit ExpressionPattern(Nonnull<Expression*> expression)
  382. : Pattern(AstNodeKind::ExpressionPattern, expression->source_loc()),
  383. expression_(expression) {}
  384. explicit ExpressionPattern(CloneContext& context,
  385. const ExpressionPattern& other)
  386. : Pattern(context, other),
  387. expression_(context.Clone(other.expression_)) {}
  388. static auto classof(const AstNode* node) -> bool {
  389. return InheritsFromExpressionPattern(node->kind());
  390. }
  391. auto expression() const -> const Expression& { return *expression_; }
  392. auto expression() -> Expression& { return *expression_; }
  393. private:
  394. Nonnull<Expression*> expression_;
  395. };
  396. } // namespace Carbon
  397. #endif // CARBON_EXPLORER_AST_PATTERN_H_