expression.h 31 KB

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