expression.h 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  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/static_scope.h"
  18. #include "explorer/ast/value_category.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 ToString(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 : public MemberAccessExpression {
  256. public:
  257. explicit SimpleMemberAccessExpression(SourceLocation source_loc,
  258. Nonnull<Expression*> object,
  259. std::string member_name)
  260. : MemberAccessExpression(AstNodeKind::SimpleMemberAccessExpression,
  261. source_loc, object),
  262. member_name_(std::move(member_name)) {}
  263. static auto classof(const AstNode* node) -> bool {
  264. return InheritsFromSimpleMemberAccessExpression(node->kind());
  265. }
  266. auto member_name() const -> const std::string& { return member_name_; }
  267. // Returns the `NamedElement` that the member name resolved to.
  268. // Should not be called before typechecking.
  269. auto member() const -> const NamedElement& {
  270. CARBON_CHECK(member_.has_value());
  271. return *member_.value();
  272. }
  273. // Can only be called once, during typechecking.
  274. void set_member(Nonnull<const NamedElement*> member) { member_ = member; }
  275. // If `object` is a constrained type parameter and `member` was found in an
  276. // interface, returns that interface. Should not be called before
  277. // typechecking.
  278. auto found_in_interface() const
  279. -> std::optional<Nonnull<const InterfaceType*>> {
  280. return found_in_interface_;
  281. }
  282. // Can only be called once, during typechecking.
  283. void set_found_in_interface(Nonnull<const InterfaceType*> interface) {
  284. CARBON_CHECK(!found_in_interface_.has_value());
  285. found_in_interface_ = interface;
  286. }
  287. private:
  288. std::string member_name_;
  289. std::optional<Nonnull<const NamedElement*>> member_;
  290. std::optional<Nonnull<const InterfaceType*>> found_in_interface_;
  291. };
  292. // A compound member access expression of the form `object.(path)`.
  293. //
  294. // `path` is required to have `TypeOfMemberName` type, and describes the member
  295. // being accessed, which is one of:
  296. //
  297. // - An instance member of a type: `object.(Type.member)`.
  298. // - A non-instance member of an interface: `Type.(Interface.member)` or
  299. // `object.(Interface.member)`.
  300. // - An instance member of an interface: `object.(Interface.member)` or
  301. // `object.(Type.(Interface.member))`.
  302. //
  303. // Note that the `path` is evaluated during type-checking, not at runtime, so
  304. // the corresponding `member` is determined statically.
  305. class CompoundMemberAccessExpression : public MemberAccessExpression {
  306. public:
  307. explicit CompoundMemberAccessExpression(SourceLocation source_loc,
  308. Nonnull<Expression*> object,
  309. Nonnull<Expression*> path)
  310. : MemberAccessExpression(AstNodeKind::CompoundMemberAccessExpression,
  311. source_loc, object),
  312. path_(path) {}
  313. static auto classof(const AstNode* node) -> bool {
  314. return InheritsFromCompoundMemberAccessExpression(node->kind());
  315. }
  316. auto path() const -> const Expression& { return *path_; }
  317. auto path() -> Expression& { return *path_; }
  318. // Returns the `MemberName` value that evaluation of the path produced.
  319. // Should not be called before typechecking.
  320. auto member() const -> const MemberName& {
  321. CARBON_CHECK(member_.has_value());
  322. return **member_;
  323. }
  324. // Can only be called once, during typechecking.
  325. void set_member(Nonnull<const MemberName*> member) {
  326. CARBON_CHECK(!member_.has_value());
  327. member_ = member;
  328. }
  329. private:
  330. Nonnull<Expression*> path_;
  331. std::optional<Nonnull<const MemberName*>> member_;
  332. };
  333. class IndexExpression : public Expression {
  334. public:
  335. explicit IndexExpression(SourceLocation source_loc,
  336. Nonnull<Expression*> object,
  337. Nonnull<Expression*> offset)
  338. : Expression(AstNodeKind::IndexExpression, source_loc),
  339. object_(object),
  340. offset_(offset) {}
  341. static auto classof(const AstNode* node) -> bool {
  342. return InheritsFromIndexExpression(node->kind());
  343. }
  344. auto object() const -> const Expression& { return *object_; }
  345. auto object() -> Expression& { return *object_; }
  346. auto offset() const -> const Expression& { return *offset_; }
  347. auto offset() -> Expression& { return *offset_; }
  348. private:
  349. Nonnull<Expression*> object_;
  350. Nonnull<Expression*> offset_;
  351. };
  352. class BaseAccessExpression : public MemberAccessExpression {
  353. public:
  354. explicit BaseAccessExpression(SourceLocation source_loc,
  355. Nonnull<Expression*> object,
  356. Nonnull<const BaseElement*> base)
  357. : MemberAccessExpression(AstNodeKind::BaseAccessExpression, source_loc,
  358. object),
  359. base_(base) {
  360. set_static_type(&base->type());
  361. set_value_category(ValueCategory::Let);
  362. }
  363. static auto classof(const AstNode* node) -> bool {
  364. return InheritsFromBaseAccessExpression(node->kind());
  365. }
  366. auto element() const -> const BaseElement& { return *base_; }
  367. private:
  368. const Nonnull<const BaseElement*> base_;
  369. };
  370. class IntLiteral : public Expression {
  371. public:
  372. explicit IntLiteral(SourceLocation source_loc, int value)
  373. : Expression(AstNodeKind::IntLiteral, source_loc), value_(value) {}
  374. static auto classof(const AstNode* node) -> bool {
  375. return InheritsFromIntLiteral(node->kind());
  376. }
  377. auto value() const -> int { return value_; }
  378. private:
  379. int value_;
  380. };
  381. class BoolLiteral : public Expression {
  382. public:
  383. explicit BoolLiteral(SourceLocation source_loc, bool value)
  384. : Expression(AstNodeKind::BoolLiteral, source_loc), value_(value) {}
  385. static auto classof(const AstNode* node) -> bool {
  386. return InheritsFromBoolLiteral(node->kind());
  387. }
  388. auto value() const -> bool { return value_; }
  389. private:
  390. bool value_;
  391. };
  392. class StringLiteral : public Expression {
  393. public:
  394. explicit StringLiteral(SourceLocation source_loc, std::string value)
  395. : Expression(AstNodeKind::StringLiteral, source_loc),
  396. value_(std::move(value)) {}
  397. static auto classof(const AstNode* node) -> bool {
  398. return InheritsFromStringLiteral(node->kind());
  399. }
  400. auto value() const -> const std::string& { return value_; }
  401. private:
  402. std::string value_;
  403. };
  404. class StringTypeLiteral : public Expression {
  405. public:
  406. explicit StringTypeLiteral(SourceLocation source_loc)
  407. : Expression(AstNodeKind::StringTypeLiteral, source_loc) {}
  408. static auto classof(const AstNode* node) -> bool {
  409. return InheritsFromStringTypeLiteral(node->kind());
  410. }
  411. };
  412. class TupleLiteral : public Expression {
  413. public:
  414. explicit TupleLiteral(SourceLocation source_loc)
  415. : TupleLiteral(source_loc, {}) {}
  416. explicit TupleLiteral(SourceLocation source_loc,
  417. std::vector<Nonnull<Expression*>> fields)
  418. : Expression(AstNodeKind::TupleLiteral, source_loc),
  419. fields_(std::move(fields)) {}
  420. static auto classof(const AstNode* node) -> bool {
  421. return InheritsFromTupleLiteral(node->kind());
  422. }
  423. auto fields() const -> llvm::ArrayRef<Nonnull<const Expression*>> {
  424. return fields_;
  425. }
  426. auto fields() -> llvm::ArrayRef<Nonnull<Expression*>> { return fields_; }
  427. private:
  428. std::vector<Nonnull<Expression*>> fields_;
  429. };
  430. // A literal value of a struct type.
  431. class StructLiteral : public Expression {
  432. public:
  433. explicit StructLiteral(SourceLocation loc) : StructLiteral(loc, {}) {}
  434. explicit StructLiteral(SourceLocation loc,
  435. std::vector<FieldInitializer> fields)
  436. : Expression(AstNodeKind::StructLiteral, loc),
  437. fields_(std::move(fields)) {}
  438. static auto classof(const AstNode* node) -> bool {
  439. return InheritsFromStructLiteral(node->kind());
  440. }
  441. auto fields() const -> llvm::ArrayRef<FieldInitializer> { return fields_; }
  442. auto fields() -> llvm::MutableArrayRef<FieldInitializer> { return fields_; }
  443. private:
  444. std::vector<FieldInitializer> fields_;
  445. };
  446. // A base class for literals with a constant value determined by type-checking.
  447. class ConstantValueLiteral : public Expression {
  448. public:
  449. explicit ConstantValueLiteral(
  450. AstNodeKind kind, SourceLocation source_loc,
  451. std::optional<Nonnull<const Value*>> constant_value = std::nullopt)
  452. : Expression(kind, source_loc), constant_value_(constant_value) {}
  453. static auto classof(const AstNode* node) -> bool {
  454. return InheritsFromConstantValueLiteral(node->kind());
  455. }
  456. // Returns the constant value of this expression.
  457. auto constant_value() const -> const Value& {
  458. CARBON_CHECK(constant_value_);
  459. return **constant_value_;
  460. }
  461. // Sets the value returned by constant_value(). Can only be called once,
  462. // during typechecking.
  463. void set_constant_value(Nonnull<const Value*> value) {
  464. CARBON_CHECK(!constant_value_.has_value());
  465. constant_value_ = value;
  466. }
  467. private:
  468. std::optional<Nonnull<const Value*>> constant_value_;
  469. };
  470. // A literal representing a struct type.
  471. //
  472. // Note that a struct type literal can't be empty because `{}` is a struct
  473. // value. However, that value implicitly converts to a type.
  474. class StructTypeLiteral : public ConstantValueLiteral {
  475. public:
  476. explicit StructTypeLiteral(SourceLocation loc,
  477. std::vector<FieldInitializer> fields)
  478. : ConstantValueLiteral(AstNodeKind::StructTypeLiteral, loc),
  479. fields_(std::move(fields)) {
  480. CARBON_CHECK(!fields_.empty())
  481. << "`{}` is represented as a StructLiteral, not a StructTypeLiteral.";
  482. }
  483. static auto classof(const AstNode* node) -> bool {
  484. return InheritsFromStructTypeLiteral(node->kind());
  485. }
  486. auto fields() const -> llvm::ArrayRef<FieldInitializer> { return fields_; }
  487. auto fields() -> llvm::MutableArrayRef<FieldInitializer> { return fields_; }
  488. private:
  489. std::vector<FieldInitializer> fields_;
  490. };
  491. class OperatorExpression : public RewritableMixin<Expression> {
  492. public:
  493. explicit OperatorExpression(SourceLocation source_loc, Operator op,
  494. std::vector<Nonnull<Expression*>> arguments)
  495. : RewritableMixin(AstNodeKind::OperatorExpression, source_loc),
  496. op_(op),
  497. arguments_(std::move(arguments)) {}
  498. static auto classof(const AstNode* node) -> bool {
  499. return InheritsFromOperatorExpression(node->kind());
  500. }
  501. auto op() const -> Operator { return op_; }
  502. auto arguments() const -> llvm::ArrayRef<Nonnull<Expression*>> {
  503. return arguments_;
  504. }
  505. auto arguments() -> llvm::MutableArrayRef<Nonnull<Expression*>> {
  506. return arguments_;
  507. }
  508. private:
  509. Operator op_;
  510. std::vector<Nonnull<Expression*>> arguments_;
  511. };
  512. class CallExpression : public Expression {
  513. public:
  514. explicit CallExpression(SourceLocation source_loc,
  515. Nonnull<Expression*> function,
  516. Nonnull<Expression*> argument)
  517. : Expression(AstNodeKind::CallExpression, source_loc),
  518. function_(function),
  519. argument_(argument),
  520. bindings_({}, {}) {}
  521. static auto classof(const AstNode* node) -> bool {
  522. return InheritsFromCallExpression(node->kind());
  523. }
  524. auto function() const -> const Expression& { return *function_; }
  525. auto function() -> Expression& { return *function_; }
  526. auto argument() const -> const Expression& { return *argument_; }
  527. auto argument() -> Expression& { return *argument_; }
  528. auto bindings() -> const Bindings& { return bindings_; }
  529. // Can only be called once, during typechecking.
  530. void set_bindings(Bindings bindings) {
  531. CARBON_CHECK(bindings_.args().empty() && bindings_.witnesses().empty());
  532. bindings_ = std::move(bindings);
  533. }
  534. auto deduced_args() const -> const BindingMap& { return bindings_.args(); }
  535. // Maps each of `function`'s impl bindings to a witness.
  536. // Should not be called before typechecking, or if `function` is not
  537. // a generic function.
  538. auto impls() const -> const ImplWitnessMap& { return bindings_.witnesses(); }
  539. // Can only be called by type-checking, if a conversion was required.
  540. void set_argument(Nonnull<Expression*> argument) { argument_ = argument; }
  541. private:
  542. Nonnull<Expression*> function_;
  543. Nonnull<Expression*> argument_;
  544. Bindings bindings_;
  545. };
  546. class FunctionTypeLiteral : public ConstantValueLiteral {
  547. public:
  548. explicit FunctionTypeLiteral(SourceLocation source_loc,
  549. Nonnull<TupleLiteral*> parameter,
  550. Nonnull<Expression*> return_type)
  551. : ConstantValueLiteral(AstNodeKind::FunctionTypeLiteral, source_loc),
  552. parameter_(parameter),
  553. return_type_(return_type) {}
  554. static auto classof(const AstNode* node) -> bool {
  555. return InheritsFromFunctionTypeLiteral(node->kind());
  556. }
  557. auto parameter() const -> const TupleLiteral& { return *parameter_; }
  558. auto parameter() -> TupleLiteral& { return *parameter_; }
  559. auto return_type() const -> const Expression& { return *return_type_; }
  560. auto return_type() -> Expression& { return *return_type_; }
  561. private:
  562. Nonnull<TupleLiteral*> parameter_;
  563. Nonnull<Expression*> return_type_;
  564. };
  565. class BoolTypeLiteral : public Expression {
  566. public:
  567. explicit BoolTypeLiteral(SourceLocation source_loc)
  568. : Expression(AstNodeKind::BoolTypeLiteral, source_loc) {}
  569. static auto classof(const AstNode* node) -> bool {
  570. return InheritsFromBoolTypeLiteral(node->kind());
  571. }
  572. };
  573. class IntTypeLiteral : public Expression {
  574. public:
  575. explicit IntTypeLiteral(SourceLocation source_loc)
  576. : Expression(AstNodeKind::IntTypeLiteral, source_loc) {}
  577. static auto classof(const AstNode* node) -> bool {
  578. return InheritsFromIntTypeLiteral(node->kind());
  579. }
  580. };
  581. class ContinuationTypeLiteral : public Expression {
  582. public:
  583. explicit ContinuationTypeLiteral(SourceLocation source_loc)
  584. : Expression(AstNodeKind::ContinuationTypeLiteral, source_loc) {}
  585. static auto classof(const AstNode* node) -> bool {
  586. return InheritsFromContinuationTypeLiteral(node->kind());
  587. }
  588. };
  589. class TypeTypeLiteral : public Expression {
  590. public:
  591. explicit TypeTypeLiteral(SourceLocation source_loc)
  592. : Expression(AstNodeKind::TypeTypeLiteral, source_loc) {}
  593. static auto classof(const AstNode* node) -> bool {
  594. return InheritsFromTypeTypeLiteral(node->kind());
  595. }
  596. };
  597. // A literal value. This is used in desugaring, and can't be expressed in
  598. // source syntax.
  599. class ValueLiteral : public ConstantValueLiteral {
  600. public:
  601. // Value literals are created by type-checking, and so are created with their
  602. // type and value category already known.
  603. ValueLiteral(SourceLocation source_loc, Nonnull<const Value*> value,
  604. Nonnull<const Value*> type, ValueCategory value_category)
  605. : ConstantValueLiteral(AstNodeKind::ValueLiteral, source_loc, value) {
  606. set_static_type(type);
  607. set_value_category(value_category);
  608. }
  609. static auto classof(const AstNode* node) -> bool {
  610. return InheritsFromValueLiteral(node->kind());
  611. }
  612. };
  613. class IntrinsicExpression : public Expression {
  614. public:
  615. enum class Intrinsic {
  616. Print,
  617. Alloc,
  618. Dealloc,
  619. Rand,
  620. IntEq,
  621. StrEq,
  622. StrCompare,
  623. IntCompare,
  624. IntBitAnd,
  625. IntBitOr,
  626. IntBitXor,
  627. IntBitComplement,
  628. IntLeftShift,
  629. IntRightShift,
  630. Assert,
  631. };
  632. // Returns the enumerator corresponding to the intrinsic named `name`,
  633. // or raises a fatal compile error if there is no such enumerator.
  634. static auto FindIntrinsic(std::string_view name, SourceLocation source_loc)
  635. -> ErrorOr<Intrinsic>;
  636. explicit IntrinsicExpression(Intrinsic intrinsic, Nonnull<TupleLiteral*> args,
  637. SourceLocation source_loc)
  638. : Expression(AstNodeKind::IntrinsicExpression, source_loc),
  639. intrinsic_(intrinsic),
  640. args_(args) {}
  641. static auto classof(const AstNode* node) -> bool {
  642. return InheritsFromIntrinsicExpression(node->kind());
  643. }
  644. auto intrinsic() const -> Intrinsic { return intrinsic_; }
  645. auto name() const -> std::string_view;
  646. auto args() const -> const TupleLiteral& { return *args_; }
  647. auto args() -> TupleLiteral& { return *args_; }
  648. private:
  649. Intrinsic intrinsic_;
  650. Nonnull<TupleLiteral*> args_;
  651. };
  652. class IfExpression : public Expression {
  653. public:
  654. explicit IfExpression(SourceLocation source_loc,
  655. Nonnull<Expression*> condition,
  656. Nonnull<Expression*> then_expression,
  657. Nonnull<Expression*> else_expression)
  658. : Expression(AstNodeKind::IfExpression, source_loc),
  659. condition_(condition),
  660. then_expression_(then_expression),
  661. else_expression_(else_expression) {}
  662. static auto classof(const AstNode* node) -> bool {
  663. return InheritsFromIfExpression(node->kind());
  664. }
  665. auto condition() const -> const Expression& { return *condition_; }
  666. auto condition() -> Expression& { return *condition_; }
  667. auto then_expression() const -> const Expression& {
  668. return *then_expression_;
  669. }
  670. auto then_expression() -> Expression& { return *then_expression_; }
  671. auto else_expression() const -> const Expression& {
  672. return *else_expression_;
  673. }
  674. auto else_expression() -> Expression& { return *else_expression_; }
  675. // Can only be called by type-checking, if a conversion was required.
  676. void set_condition(Nonnull<Expression*> condition) { condition_ = condition; }
  677. private:
  678. Nonnull<Expression*> condition_;
  679. Nonnull<Expression*> then_expression_;
  680. Nonnull<Expression*> else_expression_;
  681. };
  682. // A clause appearing on the right-hand side of a `where` operator that forms a
  683. // more precise constraint from a more general one.
  684. class WhereClause : public AstNode {
  685. public:
  686. ~WhereClause() override = 0;
  687. void Print(llvm::raw_ostream& out) const override;
  688. void PrintID(llvm::raw_ostream& out) const override;
  689. static auto classof(const AstNode* node) {
  690. return InheritsFromWhereClause(node->kind());
  691. }
  692. auto kind() const -> WhereClauseKind {
  693. return static_cast<WhereClauseKind>(root_kind());
  694. }
  695. protected:
  696. WhereClause(WhereClauseKind kind, SourceLocation source_loc)
  697. : AstNode(static_cast<AstNodeKind>(kind), source_loc) {}
  698. };
  699. // An `is` where clause.
  700. //
  701. // For example, `ConstraintA where .Type is ConstraintB` requires that the
  702. // associated type `.Type` implements the constraint `ConstraintB`.
  703. class IsWhereClause : public WhereClause {
  704. public:
  705. explicit IsWhereClause(SourceLocation source_loc, Nonnull<Expression*> type,
  706. Nonnull<Expression*> constraint)
  707. : WhereClause(WhereClauseKind::IsWhereClause, source_loc),
  708. type_(type),
  709. constraint_(constraint) {}
  710. static auto classof(const AstNode* node) {
  711. return InheritsFromIsWhereClause(node->kind());
  712. }
  713. auto type() const -> const Expression& { return *type_; }
  714. auto type() -> Expression& { return *type_; }
  715. auto constraint() const -> const Expression& { return *constraint_; }
  716. auto constraint() -> Expression& { return *constraint_; }
  717. private:
  718. Nonnull<Expression*> type_;
  719. Nonnull<Expression*> constraint_;
  720. };
  721. // An `==` where clause.
  722. //
  723. // For example, `Constraint where .Type == i32` requires that the associated
  724. // type `.Type` is `i32`.
  725. class EqualsWhereClause : public WhereClause {
  726. public:
  727. explicit EqualsWhereClause(SourceLocation source_loc,
  728. Nonnull<Expression*> lhs, Nonnull<Expression*> rhs)
  729. : WhereClause(WhereClauseKind::EqualsWhereClause, source_loc),
  730. lhs_(lhs),
  731. rhs_(rhs) {}
  732. static auto classof(const AstNode* node) {
  733. return InheritsFromEqualsWhereClause(node->kind());
  734. }
  735. auto lhs() const -> const Expression& { return *lhs_; }
  736. auto lhs() -> Expression& { return *lhs_; }
  737. auto rhs() const -> const Expression& { return *rhs_; }
  738. auto rhs() -> Expression& { return *rhs_; }
  739. private:
  740. Nonnull<Expression*> lhs_;
  741. Nonnull<Expression*> rhs_;
  742. };
  743. // An `=` where clause.
  744. //
  745. // For example, `Constraint where .Type = i32` specifies that the associated
  746. // type `.Type` is rewritten to `i32` whenever used.
  747. class RewriteWhereClause : public WhereClause {
  748. public:
  749. explicit RewriteWhereClause(SourceLocation source_loc,
  750. std::string member_name,
  751. Nonnull<Expression*> replacement)
  752. : WhereClause(WhereClauseKind::RewriteWhereClause, source_loc),
  753. member_name_(std::move(member_name)),
  754. replacement_(replacement) {}
  755. static auto classof(const AstNode* node) {
  756. return InheritsFromRewriteWhereClause(node->kind());
  757. }
  758. auto member_name() const -> std::string_view { return member_name_; }
  759. auto replacement() const -> const Expression& { return *replacement_; }
  760. auto replacement() -> Expression& { return *replacement_; }
  761. private:
  762. std::string member_name_;
  763. Nonnull<Expression*> replacement_;
  764. };
  765. // A `where` expression: `AddableWith(i32) where .Result == i32`.
  766. //
  767. // The first operand is rewritten to a generic binding, for example
  768. // `.Self:! AddableWith(i32)`, which may be used in the clauses.
  769. class WhereExpression : public RewritableMixin<Expression> {
  770. public:
  771. explicit WhereExpression(SourceLocation source_loc,
  772. Nonnull<GenericBinding*> self_binding,
  773. std::vector<Nonnull<WhereClause*>> clauses)
  774. : RewritableMixin(AstNodeKind::WhereExpression, source_loc),
  775. self_binding_(self_binding),
  776. clauses_(std::move(clauses)) {}
  777. static auto classof(const AstNode* node) -> bool {
  778. return InheritsFromWhereExpression(node->kind());
  779. }
  780. auto self_binding() const -> const GenericBinding& { return *self_binding_; }
  781. auto self_binding() -> GenericBinding& { return *self_binding_; }
  782. auto enclosing_dot_self() const
  783. -> std::optional<Nonnull<const GenericBinding*>> {
  784. return enclosing_dot_self_;
  785. }
  786. // Sets the enclosing value of `.Self`. Can only be called during name
  787. // resolution.
  788. void set_enclosing_dot_self(Nonnull<const GenericBinding*> dot_self) {
  789. CARBON_CHECK(!enclosing_dot_self_ || enclosing_dot_self_ == dot_self);
  790. enclosing_dot_self_ = dot_self;
  791. }
  792. auto clauses() const -> llvm::ArrayRef<Nonnull<const WhereClause*>> {
  793. return clauses_;
  794. }
  795. auto clauses() -> llvm::ArrayRef<Nonnull<WhereClause*>> { return clauses_; }
  796. private:
  797. Nonnull<GenericBinding*> self_binding_;
  798. std::vector<Nonnull<WhereClause*>> clauses_;
  799. std::optional<Nonnull<const GenericBinding*>> enclosing_dot_self_;
  800. };
  801. // A builtin conversion to a type determined by type-checking. These are
  802. // created by type-checking when a type conversion is found to be necessary but
  803. // that conversion is implemented directly rather than by an `ImplicitAs`
  804. // implementation.
  805. class BuiltinConvertExpression : public Expression {
  806. public:
  807. BuiltinConvertExpression(Nonnull<Expression*> source_expression,
  808. Nonnull<const Value*> destination_type)
  809. : Expression(AstNodeKind::BuiltinConvertExpression,
  810. source_expression->source_loc()),
  811. source_expression_(source_expression) {
  812. set_static_type(destination_type);
  813. set_value_category(ValueCategory::Let);
  814. }
  815. static auto classof(const AstNode* node) -> bool {
  816. return InheritsFromBuiltinConvertExpression(node->kind());
  817. }
  818. auto source_expression() -> Nonnull<Expression*> {
  819. return source_expression_;
  820. }
  821. auto source_expression() const -> Nonnull<const Expression*> {
  822. return source_expression_;
  823. }
  824. // Set the rewritten form of this expression. Can only be called during type
  825. // checking.
  826. auto set_rewritten_form(Nonnull<const Expression*> rewritten_form) -> void {
  827. CARBON_CHECK(!rewritten_form_.has_value()) << "rewritten form set twice";
  828. rewritten_form_ = rewritten_form;
  829. }
  830. // Get the rewritten form of this expression. A rewritten form can be used to
  831. // prepare the conversion during type checking.
  832. auto rewritten_form() const -> std::optional<Nonnull<const Expression*>> {
  833. return rewritten_form_;
  834. }
  835. private:
  836. Nonnull<Expression*> source_expression_;
  837. std::optional<Nonnull<const Expression*>> rewritten_form_;
  838. };
  839. // An expression whose semantics have not been implemented. This can be used
  840. // as a placeholder during development, in order to implement and test parsing
  841. // of a new expression syntax without having to implement its semantics.
  842. class UnimplementedExpression : public Expression {
  843. public:
  844. // Constructs an UnimplementedExpression with the given label and the given
  845. // children, which must all be convertible to Nonnull<AstNode*>. The label
  846. // should correspond roughly to the name of the class that will eventually
  847. // replace this usage of UnimplementedExpression.
  848. template <typename... Children>
  849. UnimplementedExpression(SourceLocation source_loc, std::string label,
  850. Children... children)
  851. : Expression(AstNodeKind::UnimplementedExpression, source_loc),
  852. label_(std::move(label)) {
  853. AddChildren(children...);
  854. }
  855. static auto classof(const AstNode* node) -> bool {
  856. return InheritsFromUnimplementedExpression(node->kind());
  857. }
  858. auto label() const -> std::string_view { return label_; }
  859. auto children() const -> llvm::ArrayRef<Nonnull<const AstNode*>> {
  860. return children_;
  861. }
  862. private:
  863. void AddChildren() {}
  864. template <typename... Children>
  865. void AddChildren(Nonnull<AstNode*> child, Children... children) {
  866. children_.push_back(child);
  867. AddChildren(children...);
  868. }
  869. std::string label_;
  870. std::vector<Nonnull<AstNode*>> children_;
  871. };
  872. // A literal representing a statically-sized array type.
  873. class ArrayTypeLiteral : public ConstantValueLiteral {
  874. public:
  875. // Constructs an array type literal which uses the given expressions to
  876. // represent the element type and size.
  877. ArrayTypeLiteral(SourceLocation source_loc,
  878. Nonnull<Expression*> element_type_expression,
  879. Nonnull<Expression*> size_expression)
  880. : ConstantValueLiteral(AstNodeKind::ArrayTypeLiteral, source_loc),
  881. element_type_expression_(element_type_expression),
  882. size_expression_(size_expression) {}
  883. static auto classof(const AstNode* node) -> bool {
  884. return InheritsFromArrayTypeLiteral(node->kind());
  885. }
  886. auto element_type_expression() const -> const Expression& {
  887. return *element_type_expression_;
  888. }
  889. auto element_type_expression() -> Expression& {
  890. return *element_type_expression_;
  891. }
  892. auto size_expression() const -> const Expression& {
  893. return *size_expression_;
  894. }
  895. auto size_expression() -> Expression& { return *size_expression_; }
  896. private:
  897. Nonnull<Expression*> element_type_expression_;
  898. Nonnull<Expression*> size_expression_;
  899. };
  900. // Converts paren_contents to an Expression, interpreting the parentheses as
  901. // grouping if their contents permit that interpretation, or as forming a
  902. // tuple otherwise.
  903. auto ExpressionFromParenContents(
  904. Nonnull<Arena*> arena, SourceLocation source_loc,
  905. const ParenContents<Expression>& paren_contents) -> Nonnull<Expression*>;
  906. // Converts paren_contents to an Expression, interpreting the parentheses as
  907. // forming a tuple.
  908. auto TupleExpressionFromParenContents(
  909. Nonnull<Arena*> arena, SourceLocation source_loc,
  910. const ParenContents<Expression>& paren_contents) -> Nonnull<TupleLiteral*>;
  911. } // namespace Carbon
  912. #endif // CARBON_EXPLORER_AST_EXPRESSION_H_