declaration.h 38 KB

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