expression.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  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_EXPRESSION_H_
  5. #define CARBON_EXPLORER_AST_EXPRESSION_H_
  6. #include <map>
  7. #include <optional>
  8. #include <string>
  9. #include <utility>
  10. #include <variant>
  11. #include <vector>
  12. #include "common/ostream.h"
  13. #include "explorer/ast/ast_node.h"
  14. #include "explorer/ast/bindings.h"
  15. #include "explorer/ast/element.h"
  16. #include "explorer/ast/paren_contents.h"
  17. #include "explorer/ast/value_category.h"
  18. #include "explorer/ast/value_node.h"
  19. #include "explorer/common/arena.h"
  20. #include "explorer/common/source_location.h"
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/Support/Compiler.h"
  23. namespace Carbon {
  24. class Value;
  25. class Witness;
  26. class MemberName;
  27. class VariableType;
  28. class InterfaceType;
  29. class ImplBinding;
  30. class GenericBinding;
  31. class Expression : public AstNode {
  32. public:
  33. ~Expression() override = 0;
  34. void Print(llvm::raw_ostream& out) const override;
  35. void PrintID(llvm::raw_ostream& out) const override;
  36. static auto classof(const AstNode* node) {
  37. return InheritsFromExpression(node->kind());
  38. }
  39. // Returns the enumerator corresponding to the most-derived type of this
  40. // object.
  41. auto kind() const -> ExpressionKind {
  42. return static_cast<ExpressionKind>(root_kind());
  43. }
  44. // The static type of this expression. Cannot be called before typechecking.
  45. auto static_type() const -> const Value& {
  46. CARBON_CHECK(static_type_.has_value());
  47. return **static_type_;
  48. }
  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 category of this expression. Cannot be called before
  56. // typechecking.
  57. auto value_category() const -> ValueCategory { return *value_category_; }
  58. // Sets the value category of this expression. Can be called multiple times,
  59. // but the argument must have the same value each time.
  60. void set_value_category(ValueCategory value_category) {
  61. CARBON_CHECK(!value_category_.has_value() ||
  62. value_category == *value_category_);
  63. value_category_ = value_category;
  64. }
  65. // Determines whether the expression has already been type-checked. Should
  66. // only be used by type-checking.
  67. auto is_type_checked() -> bool {
  68. return static_type_.has_value() && value_category_.has_value();
  69. }
  70. protected:
  71. // Constructs an Expression representing syntax at the given line number.
  72. // `kind` must be the enumerator corresponding to the most-derived type being
  73. // constructed.
  74. Expression(AstNodeKind kind, SourceLocation source_loc)
  75. : AstNode(kind, source_loc) {}
  76. private:
  77. std::optional<Nonnull<const Value*>> static_type_;
  78. std::optional<ValueCategory> value_category_;
  79. };
  80. // A mixin for expressions that can be rewritten to a different expression by
  81. // type-checking.
  82. template <typename Base>
  83. class RewritableMixin : public Base {
  84. public:
  85. using Base::Base;
  86. // Set the rewritten form of this expression. Can only be called during type
  87. // checking.
  88. auto set_rewritten_form(Nonnull<const Expression*> rewritten_form) -> void {
  89. CARBON_CHECK(!rewritten_form_.has_value()) << "rewritten form set twice";
  90. rewritten_form_ = rewritten_form;
  91. this->set_static_type(&rewritten_form->static_type());
  92. this->set_value_category(rewritten_form->value_category());
  93. }
  94. // Get the rewritten form of this expression. A rewritten form is used when
  95. // the expression is rewritten as a function call on an interface. A
  96. // rewritten form is not used when providing built-in operator semantics.
  97. auto rewritten_form() const -> std::optional<Nonnull<const Expression*>> {
  98. return rewritten_form_;
  99. }
  100. private:
  101. std::optional<Nonnull<const Expression*>> rewritten_form_;
  102. };
  103. // A FieldInitializer represents the initialization of a single struct field.
  104. class FieldInitializer {
  105. public:
  106. FieldInitializer(std::string name, Nonnull<Expression*> expression)
  107. : name_(std::move(name)), expression_(expression) {}
  108. auto name() const -> const std::string& { return name_; }
  109. auto expression() const -> const Expression& { return *expression_; }
  110. auto expression() -> Expression& { return *expression_; }
  111. private:
  112. // The field name. Cannot be empty.
  113. std::string name_;
  114. // The expression that initializes the field.
  115. Nonnull<Expression*> expression_;
  116. };
  117. enum class Operator {
  118. Add,
  119. AddressOf,
  120. And,
  121. As,
  122. BitwiseAnd,
  123. BitwiseOr,
  124. BitwiseXor,
  125. BitShiftLeft,
  126. BitShiftRight,
  127. Complement,
  128. Deref,
  129. Div,
  130. Eq,
  131. Less,
  132. LessEq,
  133. Greater,
  134. GreaterEq,
  135. Mul,
  136. Mod,
  137. Neg,
  138. Not,
  139. NotEq,
  140. Or,
  141. Sub,
  142. Ptr,
  143. };
  144. // Returns the lexical representation of `op`, such as "+" for `Add`.
  145. auto OperatorToString(Operator op) -> std::string_view;
  146. class IdentifierExpression : public Expression {
  147. public:
  148. explicit IdentifierExpression(SourceLocation source_loc, std::string name)
  149. : Expression(AstNodeKind::IdentifierExpression, source_loc),
  150. name_(std::move(name)) {}
  151. static auto classof(const AstNode* node) -> bool {
  152. return InheritsFromIdentifierExpression(node->kind());
  153. }
  154. auto name() const -> const std::string& { return name_; }
  155. // Returns the ValueNodeView this identifier refers to. Cannot be called
  156. // before name resolution.
  157. auto value_node() const -> const ValueNodeView& { return *value_node_; }
  158. // Sets the value returned by value_node. Can be called only during name
  159. // resolution.
  160. void set_value_node(ValueNodeView value_node) {
  161. CARBON_CHECK(!value_node_.has_value() || value_node_ == value_node);
  162. value_node_ = std::move(value_node);
  163. }
  164. private:
  165. std::string name_;
  166. std::optional<ValueNodeView> value_node_;
  167. };
  168. // A `.Self` expression within either a `:!` binding or a standalone `where`
  169. // expression.
  170. //
  171. // In a `:!` binding, the type of `.Self` is always `type`. For example, in
  172. // `A:! AddableWith(.Self)`, the expression `.Self` refers to the same type as
  173. // `A`, but with type `type`.
  174. //
  175. // In a `where` binding, the type of `.Self` is the constraint preceding the
  176. // `where` keyword. For example, in `Foo where .Result is Bar(.Self)`, the type
  177. // of `.Self` is `Foo`.
  178. class DotSelfExpression : public Expression {
  179. public:
  180. explicit DotSelfExpression(SourceLocation source_loc)
  181. : Expression(AstNodeKind::DotSelfExpression, source_loc) {}
  182. static auto classof(const AstNode* node) -> bool {
  183. return InheritsFromDotSelfExpression(node->kind());
  184. }
  185. // The self binding. Cannot be called before name resolution.
  186. auto self_binding() const -> const GenericBinding& { return **self_binding_; }
  187. auto self_binding() -> GenericBinding& { return **self_binding_; }
  188. // Sets the self binding. Called only during name resolution.
  189. void set_self_binding(Nonnull<GenericBinding*> self_binding) {
  190. CARBON_CHECK(!self_binding_.has_value() || self_binding_ == self_binding);
  191. self_binding_ = self_binding;
  192. }
  193. private:
  194. std::string name_;
  195. std::optional<Nonnull<GenericBinding*>> self_binding_;
  196. };
  197. class MemberAccessExpression : public Expression {
  198. public:
  199. explicit MemberAccessExpression(AstNodeKind kind, SourceLocation source_loc,
  200. Nonnull<Expression*> object)
  201. : Expression(kind, source_loc), object_(object) {}
  202. static auto classof(const AstNode* node) -> bool {
  203. return InheritsFromMemberAccessExpression(node->kind());
  204. }
  205. auto object() const -> const Expression& { return *object_; }
  206. auto object() -> Expression& { return *object_; }
  207. // Can only be called by type-checking, if a conversion was required.
  208. void set_object(Nonnull<Expression*> object) { object_ = object; }
  209. // Returns true if this is an access of a member of the type of the object,
  210. // rather than an access of a member of the object itself. In this case, the
  211. // value of the object expression is ignored, and the type is accessed
  212. // instead.
  213. //
  214. // For example, given `x: Class`, `x.StaticFunction` is a type access
  215. // equivalent to `T.StaticFunction`, and given `T:! Interface` and `y: T`,
  216. // `y.AssociatedConstant` is a type access equivalent to
  217. // `T.AssociatedConstant`.
  218. auto is_type_access() const -> bool { return is_type_access_; }
  219. // Can only be called once, during typechecking.
  220. void set_is_type_access(bool type_access) { is_type_access_ = type_access; }
  221. // Returns true if the member is a method that has a "self" declaration in an
  222. // AddrPattern.
  223. auto is_addr_me_method() const -> bool { return is_addr_me_method_; }
  224. // Can only be called once, during typechecking.
  225. void set_is_addr_me_method() { is_addr_me_method_ = true; }
  226. // If `object` has a generic type, returns the witness value, which might be
  227. // either concrete or symbolic. Otherwise, returns `std::nullopt`. Should not
  228. // be called before typechecking.
  229. auto impl() const -> std::optional<Nonnull<const Witness*>> { return impl_; }
  230. // Can only be called once, during typechecking.
  231. void set_impl(Nonnull<const Witness*> impl) {
  232. CARBON_CHECK(!impl_.has_value());
  233. impl_ = impl;
  234. }
  235. // Returns the constant value of this expression, if one has been set. This
  236. // value will be used instead of accessing a member. Even if this is present,
  237. // the operand of the member access expression must still be evaluated, in
  238. // case it has side effects.
  239. auto constant_value() const -> std::optional<Nonnull<const Value*>> {
  240. return constant_value_;
  241. }
  242. // Sets the value returned by constant_value(). Can only be called once,
  243. // during typechecking.
  244. void set_constant_value(Nonnull<const Value*> value) {
  245. CARBON_CHECK(!constant_value_.has_value());
  246. constant_value_ = value;
  247. }
  248. private:
  249. Nonnull<Expression*> object_;
  250. bool is_type_access_ = false;
  251. bool is_addr_me_method_ = false;
  252. std::optional<Nonnull<const Witness*>> impl_;
  253. std::optional<Nonnull<const Value*>> constant_value_;
  254. };
  255. class SimpleMemberAccessExpression
  256. : public RewritableMixin<MemberAccessExpression> {
  257. public:
  258. explicit SimpleMemberAccessExpression(SourceLocation source_loc,
  259. Nonnull<Expression*> object,
  260. std::string member_name)
  261. : RewritableMixin(AstNodeKind::SimpleMemberAccessExpression, source_loc,
  262. object),
  263. member_name_(std::move(member_name)) {}
  264. static auto classof(const AstNode* node) -> bool {
  265. return InheritsFromSimpleMemberAccessExpression(node->kind());
  266. }
  267. auto member_name() const -> const std::string& { return member_name_; }
  268. // Returns the `NamedElement` that the member name resolved to.
  269. // Should not be called before typechecking.
  270. auto member() const -> const NamedElement& {
  271. CARBON_CHECK(member_.has_value());
  272. return *member_.value();
  273. }
  274. // Can only be called once, during typechecking.
  275. void set_member(Nonnull<const NamedElement*> member) { member_ = member; }
  276. // If `object` is a constrained type parameter and `member` was found in an
  277. // interface, returns that interface. Should not be called before
  278. // typechecking.
  279. auto found_in_interface() const
  280. -> std::optional<Nonnull<const InterfaceType*>> {
  281. return found_in_interface_;
  282. }
  283. // Can only be called once, during typechecking.
  284. void set_found_in_interface(Nonnull<const InterfaceType*> interface) {
  285. CARBON_CHECK(!found_in_interface_.has_value());
  286. found_in_interface_ = interface;
  287. }
  288. // Returns the ValueNodeView this identifier refers to, if this was
  289. // determined by name resolution. Cannot be called before name resolution.
  290. auto value_node() const -> std::optional<ValueNodeView> {
  291. return value_node_;
  292. }
  293. // Sets the value returned by value_node. Can be called only during name
  294. // resolution.
  295. void set_value_node(ValueNodeView value_node) {
  296. CARBON_CHECK(!value_node_.has_value() || value_node_ == value_node);
  297. value_node_ = std::move(value_node);
  298. }
  299. private:
  300. std::string member_name_;
  301. std::optional<Nonnull<const NamedElement*>> member_;
  302. std::optional<Nonnull<const InterfaceType*>> found_in_interface_;
  303. std::optional<ValueNodeView> value_node_;
  304. };
  305. // A compound member access expression of the form `object.(path)`.
  306. //
  307. // `path` is required to have `TypeOfMemberName` type, and describes the member
  308. // being accessed, which is one of:
  309. //
  310. // - An instance member of a type: `object.(Type.member)`.
  311. // - A non-instance member of an interface: `Type.(Interface.member)` or
  312. // `object.(Interface.member)`.
  313. // - An instance member of an interface: `object.(Interface.member)` or
  314. // `object.(Type.(Interface.member))`.
  315. //
  316. // Note that the `path` is evaluated during type-checking, not at runtime, so
  317. // the corresponding `member` is determined statically.
  318. class CompoundMemberAccessExpression : public MemberAccessExpression {
  319. public:
  320. explicit CompoundMemberAccessExpression(SourceLocation source_loc,
  321. Nonnull<Expression*> object,
  322. Nonnull<Expression*> path)
  323. : MemberAccessExpression(AstNodeKind::CompoundMemberAccessExpression,
  324. source_loc, object),
  325. path_(path) {}
  326. static auto classof(const AstNode* node) -> bool {
  327. return InheritsFromCompoundMemberAccessExpression(node->kind());
  328. }
  329. auto path() const -> const Expression& { return *path_; }
  330. auto path() -> Expression& { return *path_; }
  331. // Returns the `MemberName` value that evaluation of the path produced.
  332. // Should not be called before typechecking.
  333. auto member() const -> const MemberName& {
  334. CARBON_CHECK(member_.has_value());
  335. return **member_;
  336. }
  337. // Can only be called once, during typechecking.
  338. void set_member(Nonnull<const MemberName*> member) {
  339. CARBON_CHECK(!member_.has_value());
  340. member_ = member;
  341. }
  342. private:
  343. Nonnull<Expression*> path_;
  344. std::optional<Nonnull<const MemberName*>> member_;
  345. };
  346. class IndexExpression : public Expression {
  347. public:
  348. explicit IndexExpression(SourceLocation source_loc,
  349. Nonnull<Expression*> object,
  350. Nonnull<Expression*> offset)
  351. : Expression(AstNodeKind::IndexExpression, source_loc),
  352. object_(object),
  353. offset_(offset) {}
  354. static auto classof(const AstNode* node) -> bool {
  355. return InheritsFromIndexExpression(node->kind());
  356. }
  357. auto object() const -> const Expression& { return *object_; }
  358. auto object() -> Expression& { return *object_; }
  359. auto offset() const -> const Expression& { return *offset_; }
  360. auto offset() -> Expression& { return *offset_; }
  361. private:
  362. Nonnull<Expression*> object_;
  363. Nonnull<Expression*> offset_;
  364. };
  365. class BaseAccessExpression : public MemberAccessExpression {
  366. public:
  367. explicit BaseAccessExpression(SourceLocation source_loc,
  368. Nonnull<Expression*> object,
  369. Nonnull<const BaseElement*> base)
  370. : MemberAccessExpression(AstNodeKind::BaseAccessExpression, source_loc,
  371. object),
  372. base_(base) {
  373. set_static_type(&base->type());
  374. set_value_category(ValueCategory::Let);
  375. }
  376. static auto classof(const AstNode* node) -> bool {
  377. return InheritsFromBaseAccessExpression(node->kind());
  378. }
  379. auto element() const -> const BaseElement& { return *base_; }
  380. private:
  381. const Nonnull<const BaseElement*> base_;
  382. };
  383. class IntLiteral : public Expression {
  384. public:
  385. explicit IntLiteral(SourceLocation source_loc, int value)
  386. : Expression(AstNodeKind::IntLiteral, source_loc), value_(value) {}
  387. static auto classof(const AstNode* node) -> bool {
  388. return InheritsFromIntLiteral(node->kind());
  389. }
  390. auto value() const -> int { return value_; }
  391. private:
  392. int value_;
  393. };
  394. class BoolLiteral : public Expression {
  395. public:
  396. explicit BoolLiteral(SourceLocation source_loc, bool value)
  397. : Expression(AstNodeKind::BoolLiteral, source_loc), value_(value) {}
  398. static auto classof(const AstNode* node) -> bool {
  399. return InheritsFromBoolLiteral(node->kind());
  400. }
  401. auto value() const -> bool { return value_; }
  402. private:
  403. bool value_;
  404. };
  405. class StringLiteral : public Expression {
  406. public:
  407. explicit StringLiteral(SourceLocation source_loc, std::string value)
  408. : Expression(AstNodeKind::StringLiteral, source_loc),
  409. value_(std::move(value)) {}
  410. static auto classof(const AstNode* node) -> bool {
  411. return InheritsFromStringLiteral(node->kind());
  412. }
  413. auto value() const -> const std::string& { return value_; }
  414. private:
  415. std::string value_;
  416. };
  417. class StringTypeLiteral : public Expression {
  418. public:
  419. explicit StringTypeLiteral(SourceLocation source_loc)
  420. : Expression(AstNodeKind::StringTypeLiteral, source_loc) {}
  421. static auto classof(const AstNode* node) -> bool {
  422. return InheritsFromStringTypeLiteral(node->kind());
  423. }
  424. };
  425. class TupleLiteral : public Expression {
  426. public:
  427. explicit TupleLiteral(SourceLocation source_loc)
  428. : TupleLiteral(source_loc, {}) {}
  429. explicit TupleLiteral(SourceLocation source_loc,
  430. std::vector<Nonnull<Expression*>> fields)
  431. : Expression(AstNodeKind::TupleLiteral, source_loc),
  432. fields_(std::move(fields)) {}
  433. static auto classof(const AstNode* node) -> bool {
  434. return InheritsFromTupleLiteral(node->kind());
  435. }
  436. auto fields() const -> llvm::ArrayRef<Nonnull<const Expression*>> {
  437. return fields_;
  438. }
  439. auto fields() -> llvm::ArrayRef<Nonnull<Expression*>> { return fields_; }
  440. private:
  441. std::vector<Nonnull<Expression*>> fields_;
  442. };
  443. // A literal value of a struct type.
  444. class StructLiteral : public Expression {
  445. public:
  446. explicit StructLiteral(SourceLocation loc) : StructLiteral(loc, {}) {}
  447. explicit StructLiteral(SourceLocation loc,
  448. std::vector<FieldInitializer> fields)
  449. : Expression(AstNodeKind::StructLiteral, loc),
  450. fields_(std::move(fields)) {}
  451. static auto classof(const AstNode* node) -> bool {
  452. return InheritsFromStructLiteral(node->kind());
  453. }
  454. auto fields() const -> llvm::ArrayRef<FieldInitializer> { return fields_; }
  455. auto fields() -> llvm::MutableArrayRef<FieldInitializer> { return fields_; }
  456. private:
  457. std::vector<FieldInitializer> fields_;
  458. };
  459. // A base class for literals with a constant value determined by type-checking.
  460. class ConstantValueLiteral : public Expression {
  461. public:
  462. explicit ConstantValueLiteral(
  463. AstNodeKind kind, SourceLocation source_loc,
  464. std::optional<Nonnull<const Value*>> constant_value = std::nullopt)
  465. : Expression(kind, source_loc), constant_value_(constant_value) {}
  466. static auto classof(const AstNode* node) -> bool {
  467. return InheritsFromConstantValueLiteral(node->kind());
  468. }
  469. // Returns the constant value of this expression.
  470. auto constant_value() const -> const Value& {
  471. CARBON_CHECK(constant_value_);
  472. return **constant_value_;
  473. }
  474. // Sets the value returned by constant_value(). Can only be called once,
  475. // during typechecking.
  476. void set_constant_value(Nonnull<const Value*> value) {
  477. CARBON_CHECK(!constant_value_.has_value());
  478. constant_value_ = value;
  479. }
  480. private:
  481. std::optional<Nonnull<const Value*>> constant_value_;
  482. };
  483. // A literal representing a struct type.
  484. //
  485. // Note that a struct type literal can't be empty because `{}` is a struct
  486. // value. However, that value implicitly converts to a type.
  487. class StructTypeLiteral : public ConstantValueLiteral {
  488. public:
  489. explicit StructTypeLiteral(SourceLocation loc,
  490. std::vector<FieldInitializer> fields)
  491. : ConstantValueLiteral(AstNodeKind::StructTypeLiteral, loc),
  492. fields_(std::move(fields)) {
  493. CARBON_CHECK(!fields_.empty())
  494. << "`{}` is represented as a StructLiteral, not a StructTypeLiteral.";
  495. }
  496. static auto classof(const AstNode* node) -> bool {
  497. return InheritsFromStructTypeLiteral(node->kind());
  498. }
  499. auto fields() const -> llvm::ArrayRef<FieldInitializer> { return fields_; }
  500. auto fields() -> llvm::MutableArrayRef<FieldInitializer> { return fields_; }
  501. private:
  502. std::vector<FieldInitializer> fields_;
  503. };
  504. class OperatorExpression : public RewritableMixin<Expression> {
  505. public:
  506. explicit OperatorExpression(SourceLocation source_loc, Operator op,
  507. std::vector<Nonnull<Expression*>> arguments)
  508. : RewritableMixin(AstNodeKind::OperatorExpression, source_loc),
  509. op_(op),
  510. arguments_(std::move(arguments)) {}
  511. static auto classof(const AstNode* node) -> bool {
  512. return InheritsFromOperatorExpression(node->kind());
  513. }
  514. auto op() const -> Operator { return op_; }
  515. auto arguments() const -> llvm::ArrayRef<Nonnull<Expression*>> {
  516. return arguments_;
  517. }
  518. auto arguments() -> llvm::MutableArrayRef<Nonnull<Expression*>> {
  519. return arguments_;
  520. }
  521. private:
  522. Operator op_;
  523. std::vector<Nonnull<Expression*>> arguments_;
  524. };
  525. class CallExpression : public Expression {
  526. public:
  527. explicit CallExpression(SourceLocation source_loc,
  528. Nonnull<Expression*> function,
  529. Nonnull<Expression*> argument)
  530. : Expression(AstNodeKind::CallExpression, source_loc),
  531. function_(function),
  532. argument_(argument),
  533. bindings_({}, {}) {}
  534. static auto classof(const AstNode* node) -> bool {
  535. return InheritsFromCallExpression(node->kind());
  536. }
  537. auto function() const -> const Expression& { return *function_; }
  538. auto function() -> Expression& { return *function_; }
  539. auto argument() const -> const Expression& { return *argument_; }
  540. auto argument() -> Expression& { return *argument_; }
  541. auto bindings() -> const Bindings& { return bindings_; }
  542. // Can only be called once, during typechecking.
  543. void set_bindings(Bindings bindings) {
  544. CARBON_CHECK(bindings_.args().empty() && bindings_.witnesses().empty());
  545. bindings_ = std::move(bindings);
  546. }
  547. auto deduced_args() const -> const BindingMap& { return bindings_.args(); }
  548. // Maps each of `function`'s impl bindings to a witness.
  549. // Should not be called before typechecking, or if `function` is not
  550. // a generic function.
  551. auto impls() const -> const ImplWitnessMap& { return bindings_.witnesses(); }
  552. // Can only be called by type-checking, if a conversion was required.
  553. void set_argument(Nonnull<Expression*> argument) { argument_ = argument; }
  554. private:
  555. Nonnull<Expression*> function_;
  556. Nonnull<Expression*> argument_;
  557. Bindings bindings_;
  558. };
  559. class FunctionTypeLiteral : public ConstantValueLiteral {
  560. public:
  561. explicit FunctionTypeLiteral(SourceLocation source_loc,
  562. Nonnull<TupleLiteral*> parameter,
  563. Nonnull<Expression*> return_type)
  564. : ConstantValueLiteral(AstNodeKind::FunctionTypeLiteral, source_loc),
  565. parameter_(parameter),
  566. return_type_(return_type) {}
  567. static auto classof(const AstNode* node) -> bool {
  568. return InheritsFromFunctionTypeLiteral(node->kind());
  569. }
  570. auto parameter() const -> const TupleLiteral& { return *parameter_; }
  571. auto parameter() -> TupleLiteral& { return *parameter_; }
  572. auto return_type() const -> const Expression& { return *return_type_; }
  573. auto return_type() -> Expression& { return *return_type_; }
  574. private:
  575. Nonnull<TupleLiteral*> parameter_;
  576. Nonnull<Expression*> return_type_;
  577. };
  578. class BoolTypeLiteral : public Expression {
  579. public:
  580. explicit BoolTypeLiteral(SourceLocation source_loc)
  581. : Expression(AstNodeKind::BoolTypeLiteral, source_loc) {}
  582. static auto classof(const AstNode* node) -> bool {
  583. return InheritsFromBoolTypeLiteral(node->kind());
  584. }
  585. };
  586. class IntTypeLiteral : public Expression {
  587. public:
  588. explicit IntTypeLiteral(SourceLocation source_loc)
  589. : Expression(AstNodeKind::IntTypeLiteral, source_loc) {}
  590. static auto classof(const AstNode* node) -> bool {
  591. return InheritsFromIntTypeLiteral(node->kind());
  592. }
  593. };
  594. class ContinuationTypeLiteral : public Expression {
  595. public:
  596. explicit ContinuationTypeLiteral(SourceLocation source_loc)
  597. : Expression(AstNodeKind::ContinuationTypeLiteral, source_loc) {}
  598. static auto classof(const AstNode* node) -> bool {
  599. return InheritsFromContinuationTypeLiteral(node->kind());
  600. }
  601. };
  602. class TypeTypeLiteral : public Expression {
  603. public:
  604. explicit TypeTypeLiteral(SourceLocation source_loc)
  605. : Expression(AstNodeKind::TypeTypeLiteral, source_loc) {}
  606. static auto classof(const AstNode* node) -> bool {
  607. return InheritsFromTypeTypeLiteral(node->kind());
  608. }
  609. };
  610. // A literal value. This is used in desugaring, and can't be expressed in
  611. // source syntax.
  612. class ValueLiteral : public ConstantValueLiteral {
  613. public:
  614. // Value literals are created by type-checking, and so are created with their
  615. // type and value category already known.
  616. ValueLiteral(SourceLocation source_loc, Nonnull<const Value*> value,
  617. Nonnull<const Value*> type, ValueCategory value_category)
  618. : ConstantValueLiteral(AstNodeKind::ValueLiteral, source_loc, value) {
  619. set_static_type(type);
  620. set_value_category(value_category);
  621. }
  622. static auto classof(const AstNode* node) -> bool {
  623. return InheritsFromValueLiteral(node->kind());
  624. }
  625. };
  626. class IntrinsicExpression : public Expression {
  627. public:
  628. enum class Intrinsic {
  629. Print,
  630. Alloc,
  631. Dealloc,
  632. Rand,
  633. ImplicitAs,
  634. ImplicitAsConvert,
  635. IntEq,
  636. StrEq,
  637. StrCompare,
  638. IntCompare,
  639. IntBitAnd,
  640. IntBitOr,
  641. IntBitXor,
  642. IntBitComplement,
  643. IntLeftShift,
  644. IntRightShift,
  645. Assert,
  646. };
  647. // Returns the enumerator corresponding to the intrinsic named `name`,
  648. // or raises a fatal compile error if there is no such enumerator.
  649. static auto FindIntrinsic(std::string_view name, SourceLocation source_loc)
  650. -> ErrorOr<Intrinsic>;
  651. explicit IntrinsicExpression(Intrinsic intrinsic, Nonnull<TupleLiteral*> args,
  652. SourceLocation source_loc)
  653. : Expression(AstNodeKind::IntrinsicExpression, source_loc),
  654. intrinsic_(intrinsic),
  655. args_(args) {}
  656. static auto classof(const AstNode* node) -> bool {
  657. return InheritsFromIntrinsicExpression(node->kind());
  658. }
  659. auto intrinsic() const -> Intrinsic { return intrinsic_; }
  660. auto name() const -> std::string_view;
  661. auto args() const -> const TupleLiteral& { return *args_; }
  662. auto args() -> TupleLiteral& { return *args_; }
  663. private:
  664. Intrinsic intrinsic_;
  665. Nonnull<TupleLiteral*> args_;
  666. };
  667. class IfExpression : public Expression {
  668. public:
  669. explicit IfExpression(SourceLocation source_loc,
  670. Nonnull<Expression*> condition,
  671. Nonnull<Expression*> then_expression,
  672. Nonnull<Expression*> else_expression)
  673. : Expression(AstNodeKind::IfExpression, source_loc),
  674. condition_(condition),
  675. then_expression_(then_expression),
  676. else_expression_(else_expression) {}
  677. static auto classof(const AstNode* node) -> bool {
  678. return InheritsFromIfExpression(node->kind());
  679. }
  680. auto condition() const -> const Expression& { return *condition_; }
  681. auto condition() -> Expression& { return *condition_; }
  682. auto then_expression() const -> const Expression& {
  683. return *then_expression_;
  684. }
  685. auto then_expression() -> Expression& { return *then_expression_; }
  686. auto else_expression() const -> const Expression& {
  687. return *else_expression_;
  688. }
  689. auto else_expression() -> Expression& { return *else_expression_; }
  690. // Can only be called by type-checking, if a conversion was required.
  691. void set_condition(Nonnull<Expression*> condition) { condition_ = condition; }
  692. private:
  693. Nonnull<Expression*> condition_;
  694. Nonnull<Expression*> then_expression_;
  695. Nonnull<Expression*> else_expression_;
  696. };
  697. // A clause appearing on the right-hand side of a `where` operator that forms a
  698. // more precise constraint from a more general one.
  699. class WhereClause : public AstNode {
  700. public:
  701. ~WhereClause() override = 0;
  702. void Print(llvm::raw_ostream& out) const override;
  703. void PrintID(llvm::raw_ostream& out) const override;
  704. static auto classof(const AstNode* node) {
  705. return InheritsFromWhereClause(node->kind());
  706. }
  707. auto kind() const -> WhereClauseKind {
  708. return static_cast<WhereClauseKind>(root_kind());
  709. }
  710. protected:
  711. WhereClause(WhereClauseKind kind, SourceLocation source_loc)
  712. : AstNode(static_cast<AstNodeKind>(kind), source_loc) {}
  713. };
  714. // An `is` where clause.
  715. //
  716. // For example, `ConstraintA where .Type is ConstraintB` requires that the
  717. // associated type `.Type` implements the constraint `ConstraintB`.
  718. class IsWhereClause : public WhereClause {
  719. public:
  720. explicit IsWhereClause(SourceLocation source_loc, Nonnull<Expression*> type,
  721. Nonnull<Expression*> constraint)
  722. : WhereClause(WhereClauseKind::IsWhereClause, source_loc),
  723. type_(type),
  724. constraint_(constraint) {}
  725. static auto classof(const AstNode* node) {
  726. return InheritsFromIsWhereClause(node->kind());
  727. }
  728. auto type() const -> const Expression& { return *type_; }
  729. auto type() -> Expression& { return *type_; }
  730. auto constraint() const -> const Expression& { return *constraint_; }
  731. auto constraint() -> Expression& { return *constraint_; }
  732. private:
  733. Nonnull<Expression*> type_;
  734. Nonnull<Expression*> constraint_;
  735. };
  736. // An `==` where clause.
  737. //
  738. // For example, `Constraint where .Type == i32` requires that the associated
  739. // type `.Type` is `i32`.
  740. class EqualsWhereClause : public WhereClause {
  741. public:
  742. explicit EqualsWhereClause(SourceLocation source_loc,
  743. Nonnull<Expression*> lhs, Nonnull<Expression*> rhs)
  744. : WhereClause(WhereClauseKind::EqualsWhereClause, source_loc),
  745. lhs_(lhs),
  746. rhs_(rhs) {}
  747. static auto classof(const AstNode* node) {
  748. return InheritsFromEqualsWhereClause(node->kind());
  749. }
  750. auto lhs() const -> const Expression& { return *lhs_; }
  751. auto lhs() -> Expression& { return *lhs_; }
  752. auto rhs() const -> const Expression& { return *rhs_; }
  753. auto rhs() -> Expression& { return *rhs_; }
  754. private:
  755. Nonnull<Expression*> lhs_;
  756. Nonnull<Expression*> rhs_;
  757. };
  758. // An `=` where clause.
  759. //
  760. // For example, `Constraint where .Type = i32` specifies that the associated
  761. // type `.Type` is rewritten to `i32` whenever used.
  762. class RewriteWhereClause : public WhereClause {
  763. public:
  764. explicit RewriteWhereClause(SourceLocation source_loc,
  765. std::string member_name,
  766. Nonnull<Expression*> replacement)
  767. : WhereClause(WhereClauseKind::RewriteWhereClause, source_loc),
  768. member_name_(std::move(member_name)),
  769. replacement_(replacement) {}
  770. static auto classof(const AstNode* node) {
  771. return InheritsFromRewriteWhereClause(node->kind());
  772. }
  773. auto member_name() const -> std::string_view { return member_name_; }
  774. auto replacement() const -> const Expression& { return *replacement_; }
  775. auto replacement() -> Expression& { return *replacement_; }
  776. private:
  777. std::string member_name_;
  778. Nonnull<Expression*> replacement_;
  779. };
  780. // A `where` expression: `AddableWith(i32) where .Result == i32`.
  781. //
  782. // The first operand is rewritten to a generic binding, for example
  783. // `.Self:! AddableWith(i32)`, which may be used in the clauses.
  784. class WhereExpression : public RewritableMixin<Expression> {
  785. public:
  786. explicit WhereExpression(SourceLocation source_loc,
  787. Nonnull<GenericBinding*> self_binding,
  788. std::vector<Nonnull<WhereClause*>> clauses)
  789. : RewritableMixin(AstNodeKind::WhereExpression, source_loc),
  790. self_binding_(self_binding),
  791. clauses_(std::move(clauses)) {}
  792. static auto classof(const AstNode* node) -> bool {
  793. return InheritsFromWhereExpression(node->kind());
  794. }
  795. auto self_binding() const -> const GenericBinding& { return *self_binding_; }
  796. auto self_binding() -> GenericBinding& { return *self_binding_; }
  797. auto enclosing_dot_self() const
  798. -> std::optional<Nonnull<const GenericBinding*>> {
  799. return enclosing_dot_self_;
  800. }
  801. // Sets the enclosing value of `.Self`. Can only be called during name
  802. // resolution.
  803. void set_enclosing_dot_self(Nonnull<const GenericBinding*> dot_self) {
  804. CARBON_CHECK(!enclosing_dot_self_ || enclosing_dot_self_ == dot_self);
  805. enclosing_dot_self_ = dot_self;
  806. }
  807. auto clauses() const -> llvm::ArrayRef<Nonnull<const WhereClause*>> {
  808. return clauses_;
  809. }
  810. auto clauses() -> llvm::ArrayRef<Nonnull<WhereClause*>> { return clauses_; }
  811. private:
  812. Nonnull<GenericBinding*> self_binding_;
  813. std::vector<Nonnull<WhereClause*>> clauses_;
  814. std::optional<Nonnull<const GenericBinding*>> enclosing_dot_self_;
  815. };
  816. // A builtin conversion to a type determined by type-checking. These are
  817. // created by type-checking when a type conversion is found to be necessary but
  818. // that conversion is implemented directly rather than by an `ImplicitAs`
  819. // implementation.
  820. class BuiltinConvertExpression : public Expression {
  821. public:
  822. BuiltinConvertExpression(Nonnull<Expression*> source_expression,
  823. Nonnull<const Value*> destination_type)
  824. : Expression(AstNodeKind::BuiltinConvertExpression,
  825. source_expression->source_loc()),
  826. source_expression_(source_expression) {
  827. set_static_type(destination_type);
  828. set_value_category(ValueCategory::Let);
  829. }
  830. static auto classof(const AstNode* node) -> bool {
  831. return InheritsFromBuiltinConvertExpression(node->kind());
  832. }
  833. auto source_expression() -> Nonnull<Expression*> {
  834. return source_expression_;
  835. }
  836. auto source_expression() const -> Nonnull<const Expression*> {
  837. return source_expression_;
  838. }
  839. // Set the rewritten form of this expression. Can only be called during type
  840. // checking.
  841. auto set_rewritten_form(Nonnull<const Expression*> rewritten_form) -> void {
  842. CARBON_CHECK(!rewritten_form_.has_value()) << "rewritten form set twice";
  843. rewritten_form_ = rewritten_form;
  844. }
  845. // Get the rewritten form of this expression. A rewritten form can be used to
  846. // prepare the conversion during type checking.
  847. auto rewritten_form() const -> std::optional<Nonnull<const Expression*>> {
  848. return rewritten_form_;
  849. }
  850. private:
  851. Nonnull<Expression*> source_expression_;
  852. std::optional<Nonnull<const Expression*>> rewritten_form_;
  853. };
  854. // An expression whose semantics have not been implemented. This can be used
  855. // as a placeholder during development, in order to implement and test parsing
  856. // of a new expression syntax without having to implement its semantics.
  857. class UnimplementedExpression : public Expression {
  858. public:
  859. // Constructs an UnimplementedExpression with the given label and the given
  860. // children, which must all be convertible to Nonnull<AstNode*>. The label
  861. // should correspond roughly to the name of the class that will eventually
  862. // replace this usage of UnimplementedExpression.
  863. template <typename... Children>
  864. UnimplementedExpression(SourceLocation source_loc, std::string label,
  865. Children... children)
  866. : Expression(AstNodeKind::UnimplementedExpression, source_loc),
  867. label_(std::move(label)) {
  868. AddChildren(children...);
  869. }
  870. static auto classof(const AstNode* node) -> bool {
  871. return InheritsFromUnimplementedExpression(node->kind());
  872. }
  873. auto label() const -> std::string_view { return label_; }
  874. auto children() const -> llvm::ArrayRef<Nonnull<const AstNode*>> {
  875. return children_;
  876. }
  877. private:
  878. void AddChildren() {}
  879. template <typename... Children>
  880. void AddChildren(Nonnull<AstNode*> child, Children... children) {
  881. children_.push_back(child);
  882. AddChildren(children...);
  883. }
  884. std::string label_;
  885. std::vector<Nonnull<AstNode*>> children_;
  886. };
  887. // A literal representing a statically-sized array type.
  888. class ArrayTypeLiteral : public ConstantValueLiteral {
  889. public:
  890. // Constructs an array type literal which uses the given expressions to
  891. // represent the element type and size.
  892. ArrayTypeLiteral(SourceLocation source_loc,
  893. Nonnull<Expression*> element_type_expression,
  894. Nonnull<Expression*> size_expression)
  895. : ConstantValueLiteral(AstNodeKind::ArrayTypeLiteral, source_loc),
  896. element_type_expression_(element_type_expression),
  897. size_expression_(size_expression) {}
  898. static auto classof(const AstNode* node) -> bool {
  899. return InheritsFromArrayTypeLiteral(node->kind());
  900. }
  901. auto element_type_expression() const -> const Expression& {
  902. return *element_type_expression_;
  903. }
  904. auto element_type_expression() -> Expression& {
  905. return *element_type_expression_;
  906. }
  907. auto size_expression() const -> const Expression& {
  908. return *size_expression_;
  909. }
  910. auto size_expression() -> Expression& { return *size_expression_; }
  911. private:
  912. Nonnull<Expression*> element_type_expression_;
  913. Nonnull<Expression*> size_expression_;
  914. };
  915. // Converts paren_contents to an Expression, interpreting the parentheses as
  916. // grouping if their contents permit that interpretation, or as forming a
  917. // tuple otherwise.
  918. auto ExpressionFromParenContents(
  919. Nonnull<Arena*> arena, SourceLocation source_loc,
  920. const ParenContents<Expression>& paren_contents) -> Nonnull<Expression*>;
  921. // Converts paren_contents to an Expression, interpreting the parentheses as
  922. // forming a tuple.
  923. auto TupleExpressionFromParenContents(
  924. Nonnull<Arena*> arena, SourceLocation source_loc,
  925. const ParenContents<Expression>& paren_contents) -> Nonnull<TupleLiteral*>;
  926. } // namespace Carbon
  927. #endif // CARBON_EXPLORER_AST_EXPRESSION_H_