declaration.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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_DECLARATION_H_
  5. #define CARBON_EXPLORER_AST_DECLARATION_H_
  6. #include <string>
  7. #include <string_view>
  8. #include <utility>
  9. #include <vector>
  10. #include "common/check.h"
  11. #include "common/ostream.h"
  12. #include "explorer/ast/ast_node.h"
  13. #include "explorer/ast/impl_binding.h"
  14. #include "explorer/ast/pattern.h"
  15. #include "explorer/ast/return_term.h"
  16. #include "explorer/ast/statement.h"
  17. #include "explorer/ast/value_category.h"
  18. #include "explorer/ast/value_node.h"
  19. #include "explorer/common/nonnull.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 MixinPseudoType;
  25. class ConstraintType;
  26. class NominalClassType;
  27. class MatchFirstDeclaration;
  28. // Abstract base class of all AST nodes representing patterns.
  29. //
  30. // Declaration and its derived classes support LLVM-style RTTI, including
  31. // llvm::isa, llvm::cast, and llvm::dyn_cast. To support this, every
  32. // class derived from Declaration must provide a `classof` operation, and
  33. // every concrete derived class must have a corresponding enumerator
  34. // in `Kind`; see https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html for
  35. // details.
  36. class Declaration : public AstNode {
  37. public:
  38. ~Declaration() override = 0;
  39. Declaration(const Declaration&) = delete;
  40. auto operator=(const Declaration&) -> Declaration& = delete;
  41. void Print(llvm::raw_ostream& out) const override;
  42. void PrintID(llvm::raw_ostream& out) const override;
  43. static auto classof(const AstNode* node) -> bool {
  44. return InheritsFromDeclaration(node->kind());
  45. }
  46. // Returns the enumerator corresponding to the most-derived type of this
  47. // object.
  48. auto kind() const -> DeclarationKind {
  49. return static_cast<DeclarationKind>(root_kind());
  50. }
  51. // The static type of the declared entity. Cannot be called before
  52. // typechecking.
  53. auto static_type() const -> const Value& { return **static_type_; }
  54. // Sets the static type of the declared entity. Can only be called once,
  55. // during typechecking.
  56. void set_static_type(Nonnull<const Value*> type) {
  57. CARBON_CHECK(!static_type_.has_value());
  58. static_type_ = type;
  59. }
  60. // Returns whether the static type has been set. Should only be called
  61. // during typechecking: before typechecking it's guaranteed to be false,
  62. // and after typechecking it's guaranteed to be true.
  63. auto has_static_type() const -> bool { return static_type_.has_value(); }
  64. // Sets the value returned by constant_value(). Can only be called once,
  65. // during typechecking.
  66. void set_constant_value(Nonnull<const Value*> value) {
  67. CARBON_CHECK(!constant_value_.has_value());
  68. constant_value_ = value;
  69. }
  70. // See value_node.h for API.
  71. auto constant_value() const -> std::optional<Nonnull<const Value*>> {
  72. return constant_value_;
  73. }
  74. // See value_node.h for API.
  75. auto symbolic_identity() const -> std::optional<Nonnull<const Value*>> {
  76. return constant_value_;
  77. }
  78. // Returns whether this node has been declared.
  79. auto is_declared() const -> bool { return is_declared_; }
  80. // Set that this node is declared. Should only be called once, by the
  81. // type-checker, once the node is ready to be named and used.
  82. void set_is_declared() {
  83. CARBON_CHECK(!is_declared_) << "should not be declared twice";
  84. is_declared_ = true;
  85. }
  86. // Returns whether this node has been fully type-checked.
  87. auto is_type_checked() const -> bool { return is_type_checked_; }
  88. // Set that this node is type-checked. Should only be called once, by the
  89. // type-checker, once full type-checking is complete.
  90. void set_is_type_checked() {
  91. CARBON_CHECK(!is_type_checked_) << "should not be type-checked twice";
  92. is_type_checked_ = true;
  93. }
  94. protected:
  95. // Constructs a Declaration representing syntax at the given line number.
  96. // `kind` must be the enumerator corresponding to the most-derived type being
  97. // constructed.
  98. Declaration(AstNodeKind kind, SourceLocation source_loc)
  99. : AstNode(kind, source_loc) {}
  100. private:
  101. std::optional<Nonnull<const Value*>> static_type_;
  102. std::optional<Nonnull<const Value*>> constant_value_;
  103. bool is_declared_ = false;
  104. bool is_type_checked_ = false;
  105. };
  106. // Determine whether two declarations declare the same entity.
  107. inline auto DeclaresSameEntity(const Declaration& first,
  108. const Declaration& second) -> bool {
  109. return &first == &second;
  110. }
  111. // A name being declared in a named declaration.
  112. class DeclaredName {
  113. public:
  114. struct NameComponent {
  115. SourceLocation source_loc;
  116. std::string name;
  117. };
  118. explicit DeclaredName(SourceLocation loc, std::string name)
  119. : components_{{loc, std::move(name)}} {}
  120. void Print(llvm::raw_ostream& out) const;
  121. void Append(SourceLocation loc, std::string name) {
  122. components_.push_back({loc, std::move(name)});
  123. }
  124. // Returns the location of the first name component.
  125. auto source_loc() const -> SourceLocation {
  126. return components_.front().source_loc;
  127. }
  128. // Returns whether this is a qualified name, as opposed to a simple
  129. // single-identifier name.
  130. auto is_qualified() const { return components_.size() > 1; }
  131. // Returns a range containing the components of the name other than the final
  132. // component.
  133. auto qualifiers() const -> llvm::ArrayRef<NameComponent> {
  134. return llvm::ArrayRef(components_).drop_back();
  135. }
  136. // Returns the innermost name, which is the unqualified name of the entity
  137. // being declared. For example in `fn Namespace.Func();`, returns `"Func"`.
  138. auto inner_name() const -> std::string_view {
  139. return components_.back().name;
  140. }
  141. private:
  142. std::vector<NameComponent> components_;
  143. };
  144. // A declaration of a namespace.
  145. class NamespaceDeclaration : public Declaration {
  146. public:
  147. using ImplementsCarbonValueNode = void;
  148. explicit NamespaceDeclaration(SourceLocation source_loc, DeclaredName name)
  149. : Declaration(AstNodeKind::NamespaceDeclaration, source_loc),
  150. name_(std::move(name)) {}
  151. static auto classof(const AstNode* node) -> bool {
  152. return InheritsFromNamespaceDeclaration(node->kind());
  153. }
  154. auto name() const -> const DeclaredName& { return name_; }
  155. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  156. private:
  157. DeclaredName name_;
  158. };
  159. // A function's virtual override keyword.
  160. enum class VirtualOverride { None, Abstract, Virtual, Impl };
  161. class CallableDeclaration : public Declaration {
  162. public:
  163. CallableDeclaration(AstNodeKind kind, SourceLocation loc,
  164. std::vector<Nonnull<GenericBinding*>> deduced_params,
  165. std::optional<Nonnull<Pattern*>> self_pattern,
  166. Nonnull<TuplePattern*> param_pattern,
  167. ReturnTerm return_term,
  168. std::optional<Nonnull<Block*>> body,
  169. VirtualOverride virt_override)
  170. : Declaration(kind, loc),
  171. deduced_parameters_(std::move(deduced_params)),
  172. self_pattern_(self_pattern),
  173. param_pattern_(param_pattern),
  174. return_term_(return_term),
  175. body_(body),
  176. virt_override_(virt_override) {}
  177. void PrintDepth(int depth, llvm::raw_ostream& out) const;
  178. auto deduced_parameters() const
  179. -> llvm::ArrayRef<Nonnull<const GenericBinding*>> {
  180. return deduced_parameters_;
  181. }
  182. auto deduced_parameters() -> llvm::ArrayRef<Nonnull<GenericBinding*>> {
  183. return deduced_parameters_;
  184. }
  185. auto self_pattern() const -> const Pattern& { return **self_pattern_; }
  186. auto self_pattern() -> Pattern& { return **self_pattern_; }
  187. auto param_pattern() const -> const TuplePattern& { return *param_pattern_; }
  188. auto param_pattern() -> TuplePattern& { return *param_pattern_; }
  189. auto return_term() const -> const ReturnTerm& { return return_term_; }
  190. auto return_term() -> ReturnTerm& { return return_term_; }
  191. auto body() const -> std::optional<Nonnull<const Block*>> { return body_; }
  192. auto body() -> std::optional<Nonnull<Block*>> { return body_; }
  193. auto virt_override() const -> VirtualOverride { return virt_override_; }
  194. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  195. auto is_method() const -> bool { return self_pattern_.has_value(); }
  196. private:
  197. std::vector<Nonnull<GenericBinding*>> deduced_parameters_;
  198. std::optional<Nonnull<Pattern*>> self_pattern_;
  199. Nonnull<TuplePattern*> param_pattern_;
  200. ReturnTerm return_term_;
  201. std::optional<Nonnull<Block*>> body_;
  202. VirtualOverride virt_override_;
  203. };
  204. class FunctionDeclaration : public CallableDeclaration {
  205. public:
  206. using ImplementsCarbonValueNode = void;
  207. static auto Create(Nonnull<Arena*> arena, SourceLocation source_loc,
  208. DeclaredName name,
  209. std::vector<Nonnull<AstNode*>> deduced_params,
  210. Nonnull<TuplePattern*> param_pattern,
  211. ReturnTerm return_term,
  212. std::optional<Nonnull<Block*>> body,
  213. VirtualOverride virt_override)
  214. -> ErrorOr<Nonnull<FunctionDeclaration*>>;
  215. // Use `Create()` instead. This is public only so Arena::New() can call it.
  216. FunctionDeclaration(SourceLocation source_loc, DeclaredName name,
  217. std::vector<Nonnull<GenericBinding*>> deduced_params,
  218. std::optional<Nonnull<Pattern*>> self_pattern,
  219. Nonnull<TuplePattern*> param_pattern,
  220. ReturnTerm return_term,
  221. std::optional<Nonnull<Block*>> body,
  222. VirtualOverride virt_override)
  223. : CallableDeclaration(AstNodeKind::FunctionDeclaration, source_loc,
  224. std::move(deduced_params), self_pattern,
  225. param_pattern, return_term, body, virt_override),
  226. name_(std::move(name)) {}
  227. static auto classof(const AstNode* node) -> bool {
  228. return InheritsFromFunctionDeclaration(node->kind());
  229. }
  230. auto name() const -> const DeclaredName& { return name_; }
  231. private:
  232. DeclaredName name_;
  233. };
  234. class DestructorDeclaration : public CallableDeclaration {
  235. public:
  236. using ImplementsCarbonValueNode = void;
  237. static auto CreateDestructor(Nonnull<Arena*> arena, SourceLocation source_loc,
  238. std::vector<Nonnull<AstNode*>> deduced_params,
  239. Nonnull<TuplePattern*> param_pattern,
  240. ReturnTerm return_term,
  241. std::optional<Nonnull<Block*>> body)
  242. -> ErrorOr<Nonnull<DestructorDeclaration*>>;
  243. // Use `Create()` instead. This is public only so Arena::New() can call it.
  244. DestructorDeclaration(SourceLocation source_loc,
  245. std::vector<Nonnull<GenericBinding*>> deduced_params,
  246. std::optional<Nonnull<Pattern*>> self_pattern,
  247. Nonnull<TuplePattern*> param_pattern,
  248. ReturnTerm return_term,
  249. std::optional<Nonnull<Block*>> body)
  250. : CallableDeclaration(AstNodeKind::DestructorDeclaration, source_loc,
  251. std::move(deduced_params), self_pattern,
  252. param_pattern, return_term, body,
  253. // TODO: Add virtual destructors
  254. VirtualOverride::None) {}
  255. static auto classof(const AstNode* node) -> bool {
  256. return InheritsFromDestructorDeclaration(node->kind());
  257. }
  258. };
  259. class SelfDeclaration : public Declaration {
  260. public:
  261. using ImplementsCarbonValueNode = void;
  262. explicit SelfDeclaration(SourceLocation source_loc)
  263. : Declaration(AstNodeKind::SelfDeclaration, source_loc) {}
  264. static auto classof(const AstNode* node) -> bool {
  265. return InheritsFromSelfDeclaration(node->kind());
  266. }
  267. static auto name() -> std::string_view { return "Self"; }
  268. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  269. };
  270. enum class ClassExtensibility { None, Base, Abstract };
  271. class ClassDeclaration : public Declaration {
  272. public:
  273. using ImplementsCarbonValueNode = void;
  274. ClassDeclaration(SourceLocation source_loc, DeclaredName name,
  275. Nonnull<SelfDeclaration*> self_decl,
  276. ClassExtensibility extensibility,
  277. std::optional<Nonnull<TuplePattern*>> type_params,
  278. std::optional<Nonnull<Expression*>> base,
  279. std::vector<Nonnull<Declaration*>> members)
  280. : Declaration(AstNodeKind::ClassDeclaration, source_loc),
  281. name_(std::move(name)),
  282. extensibility_(extensibility),
  283. self_decl_(self_decl),
  284. type_params_(type_params),
  285. base_expr_(base),
  286. members_(std::move(members)) {}
  287. static auto classof(const AstNode* node) -> bool {
  288. return InheritsFromClassDeclaration(node->kind());
  289. }
  290. auto name() const -> const DeclaredName& { return name_; }
  291. auto extensibility() const -> ClassExtensibility { return extensibility_; }
  292. auto type_params() const -> std::optional<Nonnull<const TuplePattern*>> {
  293. return type_params_;
  294. }
  295. auto type_params() -> std::optional<Nonnull<TuplePattern*>> {
  296. return type_params_;
  297. }
  298. auto self() const -> Nonnull<const SelfDeclaration*> { return self_decl_; }
  299. auto self() -> Nonnull<SelfDeclaration*> { return self_decl_; }
  300. auto members() const -> llvm::ArrayRef<Nonnull<Declaration*>> {
  301. return members_;
  302. }
  303. auto destructor() const -> std::optional<Nonnull<DestructorDeclaration*>> {
  304. for (const auto& x : members_) {
  305. if (x->kind() == DeclarationKind::DestructorDeclaration) {
  306. return llvm::cast<DestructorDeclaration>(x);
  307. }
  308. }
  309. return std::nullopt;
  310. }
  311. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  312. auto base_expr() const -> std::optional<Nonnull<Expression*>> {
  313. return base_expr_;
  314. }
  315. // Returns the original base type, before instantiation & substitutions
  316. // Use `NominalClassType::base()` to get the instantiated type.
  317. auto base_type() const -> std::optional<Nonnull<const NominalClassType*>> {
  318. return base_type_;
  319. }
  320. void set_base_type(
  321. std::optional<Nonnull<const NominalClassType*>> base_type) {
  322. base_type_ = base_type;
  323. }
  324. private:
  325. DeclaredName name_;
  326. ClassExtensibility extensibility_;
  327. Nonnull<SelfDeclaration*> self_decl_;
  328. std::optional<Nonnull<TuplePattern*>> type_params_;
  329. std::optional<Nonnull<Expression*>> base_expr_;
  330. std::vector<Nonnull<Declaration*>> members_;
  331. std::optional<Nonnull<FunctionDeclaration*>> destructor_;
  332. std::optional<Nonnull<const ClassDeclaration*>> base_;
  333. std::optional<Nonnull<const NominalClassType*>> base_type_;
  334. };
  335. // EXPERIMENTAL MIXIN FEATURE
  336. class MixinDeclaration : public Declaration {
  337. public:
  338. using ImplementsCarbonValueNode = void;
  339. MixinDeclaration(SourceLocation source_loc, DeclaredName name,
  340. std::optional<Nonnull<TuplePattern*>> params,
  341. Nonnull<GenericBinding*> self,
  342. std::vector<Nonnull<Declaration*>> members)
  343. : Declaration(AstNodeKind::MixinDeclaration, source_loc),
  344. name_(std::move(name)),
  345. params_(params),
  346. self_(self),
  347. members_(std::move(members)) {}
  348. static auto classof(const AstNode* node) -> bool {
  349. return InheritsFromMixinDeclaration(node->kind());
  350. }
  351. auto name() const -> const DeclaredName& { return name_; }
  352. auto params() const -> std::optional<Nonnull<const TuplePattern*>> {
  353. return params_;
  354. }
  355. auto params() -> std::optional<Nonnull<TuplePattern*>> { return params_; }
  356. auto self() const -> Nonnull<const GenericBinding*> { return self_; }
  357. auto self() -> Nonnull<GenericBinding*> { return self_; }
  358. auto members() const -> llvm::ArrayRef<Nonnull<Declaration*>> {
  359. return members_;
  360. }
  361. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  362. private:
  363. DeclaredName name_;
  364. std::optional<Nonnull<TuplePattern*>> params_;
  365. Nonnull<GenericBinding*> self_;
  366. std::vector<Nonnull<Declaration*>> members_;
  367. };
  368. // EXPERIMENTAL MIXIN FEATURE
  369. class MixDeclaration : public Declaration {
  370. public:
  371. MixDeclaration(SourceLocation source_loc,
  372. std::optional<Nonnull<Expression*>> mixin_type)
  373. : Declaration(AstNodeKind::MixDeclaration, source_loc),
  374. mixin_(mixin_type) {}
  375. static auto classof(const AstNode* node) -> bool {
  376. return InheritsFromMixDeclaration(node->kind());
  377. }
  378. auto mixin() const -> const Expression& { return **mixin_; }
  379. auto mixin() -> Expression& { return **mixin_; }
  380. auto mixin_value() const -> const MixinPseudoType& { return *mixin_value_; }
  381. void set_mixin_value(Nonnull<const MixinPseudoType*> mixin_value) {
  382. mixin_value_ = mixin_value;
  383. }
  384. private:
  385. std::optional<Nonnull<Expression*>> mixin_;
  386. Nonnull<const MixinPseudoType*> mixin_value_;
  387. };
  388. class AlternativeSignature : public AstNode {
  389. public:
  390. AlternativeSignature(SourceLocation source_loc, std::string name,
  391. std::optional<Nonnull<TupleLiteral*>> parameters)
  392. : AstNode(AstNodeKind::AlternativeSignature, source_loc),
  393. name_(std::move(name)),
  394. parameters_(parameters) {}
  395. void Print(llvm::raw_ostream& out) const override;
  396. void PrintID(llvm::raw_ostream& out) const override;
  397. static auto classof(const AstNode* node) -> bool {
  398. return InheritsFromAlternativeSignature(node->kind());
  399. }
  400. auto name() const -> const std::string& { return name_; }
  401. auto parameters() const -> std::optional<Nonnull<const TupleLiteral*>> {
  402. return parameters_;
  403. }
  404. auto parameters() -> std::optional<Nonnull<TupleLiteral*>> {
  405. return parameters_;
  406. }
  407. // The static type described by the parameters expression, if any. Cannot be
  408. // called before type checking. This will be nullopt after type checking if
  409. // this alternative does not have a parameter list.
  410. auto parameters_static_type() const -> std::optional<Nonnull<const Value*>> {
  411. return parameters_static_type_;
  412. }
  413. // Sets the static type of the declared entity. Can only be called once,
  414. // during typechecking.
  415. void set_parameters_static_type(Nonnull<const Value*> type) {
  416. CARBON_CHECK(!parameters_static_type_.has_value());
  417. parameters_static_type_ = type;
  418. }
  419. private:
  420. std::string name_;
  421. std::optional<Nonnull<TupleLiteral*>> parameters_;
  422. std::optional<Nonnull<const Value*>> parameters_static_type_;
  423. };
  424. class ChoiceDeclaration : public Declaration {
  425. public:
  426. using ImplementsCarbonValueNode = void;
  427. ChoiceDeclaration(SourceLocation source_loc, DeclaredName name,
  428. std::optional<Nonnull<TuplePattern*>> type_params,
  429. std::vector<Nonnull<AlternativeSignature*>> alternatives)
  430. : Declaration(AstNodeKind::ChoiceDeclaration, source_loc),
  431. name_(std::move(name)),
  432. type_params_(type_params),
  433. alternatives_(std::move(alternatives)) {}
  434. static auto classof(const AstNode* node) -> bool {
  435. return InheritsFromChoiceDeclaration(node->kind());
  436. }
  437. auto name() const -> const DeclaredName& { return name_; }
  438. auto type_params() const -> std::optional<Nonnull<const TuplePattern*>> {
  439. return type_params_;
  440. }
  441. auto type_params() -> std::optional<Nonnull<TuplePattern*>> {
  442. return type_params_;
  443. }
  444. auto alternatives() const
  445. -> llvm::ArrayRef<Nonnull<const AlternativeSignature*>> {
  446. return alternatives_;
  447. }
  448. auto alternatives() -> llvm::ArrayRef<Nonnull<AlternativeSignature*>> {
  449. return alternatives_;
  450. }
  451. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  452. auto FindAlternative(std::string_view name) const
  453. -> std::optional<const AlternativeSignature*>;
  454. private:
  455. DeclaredName name_;
  456. std::optional<Nonnull<TuplePattern*>> type_params_;
  457. std::vector<Nonnull<AlternativeSignature*>> alternatives_;
  458. };
  459. // Global variable definition implements the Declaration concept.
  460. class VariableDeclaration : public Declaration {
  461. public:
  462. VariableDeclaration(SourceLocation source_loc,
  463. Nonnull<BindingPattern*> binding,
  464. std::optional<Nonnull<Expression*>> initializer,
  465. ValueCategory value_category)
  466. : Declaration(AstNodeKind::VariableDeclaration, source_loc),
  467. binding_(binding),
  468. initializer_(initializer),
  469. value_category_(value_category) {}
  470. static auto classof(const AstNode* node) -> bool {
  471. return InheritsFromVariableDeclaration(node->kind());
  472. }
  473. auto binding() const -> const BindingPattern& { return *binding_; }
  474. auto binding() -> BindingPattern& { return *binding_; }
  475. auto initializer() const -> const Expression& { return **initializer_; }
  476. auto initializer() -> Expression& { return **initializer_; }
  477. auto value_category() const -> ValueCategory { return value_category_; }
  478. auto has_initializer() const -> bool { return initializer_.has_value(); }
  479. // Can only be called by type-checking, if a conversion was required.
  480. void set_initializer(Nonnull<Expression*> initializer) {
  481. CARBON_CHECK(has_initializer()) << "should not add a new initializer";
  482. initializer_ = initializer;
  483. }
  484. private:
  485. Nonnull<BindingPattern*> binding_;
  486. std::optional<Nonnull<Expression*>> initializer_;
  487. ValueCategory value_category_;
  488. };
  489. // Base class for constraint and interface declarations. Interfaces and named
  490. // constraints behave the same in most respects, but only interfaces can
  491. // introduce new associated functions and constants.
  492. class ConstraintTypeDeclaration : public Declaration {
  493. public:
  494. using ImplementsCarbonValueNode = void;
  495. ConstraintTypeDeclaration(AstNodeKind kind, Nonnull<Arena*> arena,
  496. SourceLocation source_loc, DeclaredName name,
  497. std::optional<Nonnull<TuplePattern*>> params,
  498. std::vector<Nonnull<Declaration*>> members)
  499. : Declaration(kind, source_loc),
  500. name_(std::move(name)),
  501. params_(params),
  502. self_type_(arena->New<SelfDeclaration>(source_loc)),
  503. members_(std::move(members)) {
  504. // `interface X` has `Self:! X`.
  505. auto* self_type_ref = arena->New<IdentifierExpression>(
  506. source_loc, std::string(name_.inner_name()));
  507. self_type_ref->set_value_node(self_type_);
  508. self_ = arena->New<GenericBinding>(source_loc, "Self", self_type_ref);
  509. }
  510. static auto classof(const AstNode* node) -> bool {
  511. return InheritsFromConstraintTypeDeclaration(node->kind());
  512. }
  513. auto name() const -> const DeclaredName& { return name_; }
  514. auto params() const -> std::optional<Nonnull<const TuplePattern*>> {
  515. return params_;
  516. }
  517. auto params() -> std::optional<Nonnull<TuplePattern*>> { return params_; }
  518. // Get the type of `Self`, which is a reference to the interface itself, with
  519. // parameters mapped to their values. For example, in `interface X(T:!
  520. // type)`, the self type is `X(T)`.
  521. auto self_type() const -> Nonnull<const SelfDeclaration*> {
  522. return self_type_;
  523. }
  524. auto self_type() -> Nonnull<SelfDeclaration*> { return self_type_; }
  525. auto self() const -> Nonnull<const GenericBinding*> { return self_; }
  526. auto self() -> Nonnull<GenericBinding*> { return self_; }
  527. auto members() const -> llvm::ArrayRef<Nonnull<Declaration*>> {
  528. return members_;
  529. }
  530. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  531. // Get the constraint type corresponding to this interface, or nullopt if
  532. // this interface is incomplete.
  533. auto constraint_type() const
  534. -> std::optional<Nonnull<const ConstraintType*>> {
  535. return constraint_type_;
  536. }
  537. // Set the constraint type corresponding to this interface. Can only be set
  538. // once, by type-checking.
  539. void set_constraint_type(Nonnull<const ConstraintType*> constraint_type) {
  540. CARBON_CHECK(!constraint_type_);
  541. constraint_type_ = constraint_type;
  542. }
  543. private:
  544. DeclaredName name_;
  545. std::optional<Nonnull<TuplePattern*>> params_;
  546. Nonnull<SelfDeclaration*> self_type_;
  547. Nonnull<GenericBinding*> self_;
  548. std::vector<Nonnull<Declaration*>> members_;
  549. std::optional<Nonnull<const ConstraintType*>> constraint_type_;
  550. };
  551. // A `interface` declaration.
  552. class InterfaceDeclaration : public ConstraintTypeDeclaration {
  553. public:
  554. using ImplementsCarbonValueNode = void;
  555. InterfaceDeclaration(Nonnull<Arena*> arena, SourceLocation source_loc,
  556. DeclaredName name,
  557. std::optional<Nonnull<TuplePattern*>> params,
  558. std::vector<Nonnull<Declaration*>> members)
  559. : ConstraintTypeDeclaration(AstNodeKind::InterfaceDeclaration, arena,
  560. source_loc, std::move(name), params,
  561. std::move(members)) {}
  562. static auto classof(const AstNode* node) -> bool {
  563. return InheritsFromInterfaceDeclaration(node->kind());
  564. }
  565. };
  566. // A `constraint` declaration, such as `constraint X { impl as Y; }`.
  567. class ConstraintDeclaration : public ConstraintTypeDeclaration {
  568. public:
  569. using ImplementsCarbonValueNode = void;
  570. ConstraintDeclaration(Nonnull<Arena*> arena, SourceLocation source_loc,
  571. DeclaredName name,
  572. std::optional<Nonnull<TuplePattern*>> params,
  573. std::vector<Nonnull<Declaration*>> members)
  574. : ConstraintTypeDeclaration(AstNodeKind::ConstraintDeclaration, arena,
  575. source_loc, std::move(name), params,
  576. std::move(members)) {}
  577. static auto classof(const AstNode* node) -> bool {
  578. return InheritsFromConstraintDeclaration(node->kind());
  579. }
  580. };
  581. // An `extends` declaration in an interface.
  582. class InterfaceExtendsDeclaration : public Declaration {
  583. public:
  584. InterfaceExtendsDeclaration(SourceLocation source_loc,
  585. Nonnull<Expression*> base)
  586. : Declaration(AstNodeKind::InterfaceExtendsDeclaration, source_loc),
  587. base_(base) {}
  588. static auto classof(const AstNode* node) -> bool {
  589. return InheritsFromInterfaceExtendsDeclaration(node->kind());
  590. }
  591. auto base() const -> const Expression* { return base_; }
  592. auto base() -> Expression* { return base_; }
  593. private:
  594. Nonnull<Expression*> base_;
  595. };
  596. // An `impl ... as` declaration in an interface.
  597. class InterfaceImplDeclaration : public Declaration {
  598. public:
  599. InterfaceImplDeclaration(SourceLocation source_loc,
  600. Nonnull<Expression*> impl_type,
  601. Nonnull<Expression*> constraint)
  602. : Declaration(AstNodeKind::InterfaceImplDeclaration, source_loc),
  603. impl_type_(impl_type),
  604. constraint_(constraint) {}
  605. static auto classof(const AstNode* node) -> bool {
  606. return InheritsFromInterfaceImplDeclaration(node->kind());
  607. }
  608. auto impl_type() const -> const Expression* { return impl_type_; }
  609. auto impl_type() -> Expression* { return impl_type_; }
  610. auto constraint() const -> const Expression* { return constraint_; }
  611. auto constraint() -> Expression* { return constraint_; }
  612. private:
  613. Nonnull<Expression*> impl_type_;
  614. Nonnull<Expression*> constraint_;
  615. };
  616. class AssociatedConstantDeclaration : public Declaration {
  617. public:
  618. using ImplementsCarbonValueNode = void;
  619. AssociatedConstantDeclaration(SourceLocation source_loc,
  620. Nonnull<GenericBinding*> binding)
  621. : Declaration(AstNodeKind::AssociatedConstantDeclaration, source_loc),
  622. binding_(binding) {}
  623. static auto classof(const AstNode* node) -> bool {
  624. return InheritsFromAssociatedConstantDeclaration(node->kind());
  625. }
  626. auto binding() const -> const GenericBinding& { return *binding_; }
  627. auto binding() -> GenericBinding& { return *binding_; }
  628. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  629. private:
  630. Nonnull<GenericBinding*> binding_;
  631. };
  632. enum class ImplKind { InternalImpl, ExternalImpl };
  633. class ImplDeclaration : public Declaration {
  634. public:
  635. static auto Create(Nonnull<Arena*> arena, SourceLocation source_loc,
  636. ImplKind kind, Nonnull<Expression*> impl_type,
  637. Nonnull<Expression*> interface,
  638. std::vector<Nonnull<AstNode*>> deduced_params,
  639. std::vector<Nonnull<Declaration*>> members)
  640. -> ErrorOr<Nonnull<ImplDeclaration*>>;
  641. // Use `Create` instead.
  642. ImplDeclaration(SourceLocation source_loc, ImplKind kind,
  643. Nonnull<Expression*> impl_type,
  644. Nonnull<SelfDeclaration*> self_decl,
  645. Nonnull<Expression*> interface,
  646. std::vector<Nonnull<GenericBinding*>> deduced_params,
  647. std::vector<Nonnull<Declaration*>> members)
  648. : Declaration(AstNodeKind::ImplDeclaration, source_loc),
  649. kind_(kind),
  650. impl_type_(impl_type),
  651. self_decl_(self_decl),
  652. interface_(interface),
  653. deduced_parameters_(std::move(deduced_params)),
  654. members_(std::move(members)) {}
  655. static auto classof(const AstNode* node) -> bool {
  656. return InheritsFromImplDeclaration(node->kind());
  657. }
  658. // Return whether this is an external or internal impl.
  659. auto kind() const -> ImplKind { return kind_; }
  660. // Return the type that is doing the implementing.
  661. auto impl_type() const -> Nonnull<Expression*> { return impl_type_; }
  662. // Return the interface that is being implemented.
  663. auto interface() const -> const Expression& { return *interface_; }
  664. auto interface() -> Expression& { return *interface_; }
  665. void set_constraint_type(Nonnull<const ConstraintType*> constraint_type) {
  666. constraint_type_ = constraint_type;
  667. }
  668. auto constraint_type() const -> Nonnull<const ConstraintType*> {
  669. return *constraint_type_;
  670. }
  671. // Returns the deduced parameters specified on the impl declaration. This
  672. // does not include any generic parameters from enclosing scopes.
  673. auto deduced_parameters() const
  674. -> llvm::ArrayRef<Nonnull<const GenericBinding*>> {
  675. return deduced_parameters_;
  676. }
  677. auto deduced_parameters() -> llvm::ArrayRef<Nonnull<GenericBinding*>> {
  678. return deduced_parameters_;
  679. }
  680. auto members() const -> llvm::ArrayRef<Nonnull<Declaration*>> {
  681. return members_;
  682. }
  683. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  684. void set_impl_bindings(llvm::ArrayRef<Nonnull<const ImplBinding*>> imps) {
  685. impl_bindings_ = imps;
  686. }
  687. auto impl_bindings() const -> llvm::ArrayRef<Nonnull<const ImplBinding*>> {
  688. return impl_bindings_;
  689. }
  690. auto self() const -> Nonnull<const SelfDeclaration*> { return self_decl_; }
  691. auto self() -> Nonnull<SelfDeclaration*> { return self_decl_; }
  692. // Set the enclosing match_first declaration. Should only be called once,
  693. // during type-checking.
  694. void set_match_first(Nonnull<const MatchFirstDeclaration*> match_first) {
  695. match_first_ = match_first;
  696. }
  697. // Get the enclosing match_first declaration, if any exists.
  698. auto match_first() const
  699. -> std::optional<Nonnull<const MatchFirstDeclaration*>> {
  700. return match_first_;
  701. }
  702. private:
  703. ImplKind kind_;
  704. Nonnull<Expression*> impl_type_;
  705. Nonnull<SelfDeclaration*> self_decl_;
  706. Nonnull<Expression*> interface_;
  707. std::optional<Nonnull<const ConstraintType*>> constraint_type_;
  708. std::vector<Nonnull<GenericBinding*>> deduced_parameters_;
  709. std::vector<Nonnull<Declaration*>> members_;
  710. std::vector<Nonnull<const ImplBinding*>> impl_bindings_;
  711. std::optional<Nonnull<const MatchFirstDeclaration*>> match_first_;
  712. };
  713. class MatchFirstDeclaration : public Declaration {
  714. public:
  715. MatchFirstDeclaration(SourceLocation source_loc,
  716. std::vector<Nonnull<ImplDeclaration*>> impls)
  717. : Declaration(AstNodeKind::MatchFirstDeclaration, source_loc),
  718. impls_(std::move(impls)) {}
  719. static auto classof(const AstNode* node) -> bool {
  720. return InheritsFromMatchFirstDeclaration(node->kind());
  721. }
  722. auto impls() const -> llvm::ArrayRef<Nonnull<const ImplDeclaration*>> {
  723. return impls_;
  724. }
  725. auto impls() -> llvm::ArrayRef<Nonnull<ImplDeclaration*>> { return impls_; }
  726. private:
  727. std::vector<Nonnull<ImplDeclaration*>> impls_;
  728. };
  729. class AliasDeclaration : public Declaration {
  730. public:
  731. using ImplementsCarbonValueNode = void;
  732. explicit AliasDeclaration(SourceLocation source_loc, DeclaredName name,
  733. Nonnull<Expression*> target)
  734. : Declaration(AstNodeKind::AliasDeclaration, source_loc),
  735. name_(std::move(name)),
  736. target_(target) {}
  737. static auto classof(const AstNode* node) -> bool {
  738. return InheritsFromAliasDeclaration(node->kind());
  739. }
  740. auto name() const -> const DeclaredName& { return name_; }
  741. auto target() const -> const Expression& { return *target_; }
  742. auto target() -> Expression& { return *target_; }
  743. auto value_category() const -> ValueCategory { return ValueCategory::Let; }
  744. private:
  745. DeclaredName name_;
  746. Nonnull<Expression*> target_;
  747. };
  748. // Return the unqualified name of a declaration, if it has one.
  749. auto GetName(const Declaration&) -> std::optional<std::string_view>;
  750. } // namespace Carbon
  751. #endif // CARBON_EXPLORER_AST_DECLARATION_H_