declaration.h 32 KB

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