declaration.h 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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::optional<Nonnull<Expression*>> base,
  312. std::vector<Nonnull<Declaration*>> members)
  313. : Declaration(AstNodeKind::ClassDeclaration, source_loc),
  314. name_(std::move(name)),
  315. extensibility_(extensibility),
  316. self_decl_(self_decl),
  317. type_params_(type_params),
  318. base_expr_(base),
  319. members_(std::move(members)) {}
  320. explicit ClassDeclaration(CloneContext& context,
  321. const ClassDeclaration& other);
  322. static auto classof(const AstNode* node) -> bool {
  323. return InheritsFromClassDeclaration(node->kind());
  324. }
  325. auto name() const -> const DeclaredName& { return name_; }
  326. auto extensibility() const -> ClassExtensibility { return extensibility_; }
  327. auto type_params() const -> std::optional<Nonnull<const TuplePattern*>> {
  328. return type_params_;
  329. }
  330. auto type_params() -> std::optional<Nonnull<TuplePattern*>> {
  331. return type_params_;
  332. }
  333. auto self() const -> Nonnull<const SelfDeclaration*> { return self_decl_; }
  334. auto self() -> Nonnull<SelfDeclaration*> { return self_decl_; }
  335. auto members() const -> llvm::ArrayRef<Nonnull<Declaration*>> {
  336. return members_;
  337. }
  338. auto destructor() const
  339. -> std::optional<Nonnull<const DestructorDeclaration*>> {
  340. for (const auto& x : members_) {
  341. if (x->kind() == DeclarationKind::DestructorDeclaration) {
  342. return llvm::cast<DestructorDeclaration>(x);
  343. }
  344. }
  345. return std::nullopt;
  346. }
  347. auto expression_category() const -> ExpressionCategory {
  348. return ExpressionCategory::Value;
  349. }
  350. auto base_expr() const -> std::optional<Nonnull<Expression*>> {
  351. return base_expr_;
  352. }
  353. // Returns the original base type, before instantiation & substitutions
  354. // Use `NominalClassType::base()` to get the instantiated type.
  355. auto base_type() const -> std::optional<Nonnull<const NominalClassType*>> {
  356. return base_type_;
  357. }
  358. void set_base_type(
  359. std::optional<Nonnull<const NominalClassType*>> base_type) {
  360. base_type_ = base_type;
  361. }
  362. private:
  363. DeclaredName name_;
  364. ClassExtensibility extensibility_;
  365. Nonnull<SelfDeclaration*> self_decl_;
  366. std::optional<Nonnull<TuplePattern*>> type_params_;
  367. std::optional<Nonnull<Expression*>> base_expr_;
  368. std::vector<Nonnull<Declaration*>> members_;
  369. std::optional<Nonnull<const NominalClassType*>> base_type_;
  370. };
  371. // EXPERIMENTAL MIXIN FEATURE
  372. class MixinDeclaration : public Declaration {
  373. public:
  374. using ImplementsCarbonValueNode = void;
  375. MixinDeclaration(SourceLocation source_loc, DeclaredName name,
  376. std::optional<Nonnull<TuplePattern*>> params,
  377. Nonnull<GenericBinding*> self,
  378. std::vector<Nonnull<Declaration*>> members)
  379. : Declaration(AstNodeKind::MixinDeclaration, source_loc),
  380. name_(std::move(name)),
  381. params_(params),
  382. self_(self),
  383. members_(std::move(members)) {}
  384. explicit MixinDeclaration(CloneContext& context,
  385. const MixinDeclaration& other)
  386. : Declaration(context, other),
  387. name_(other.name_),
  388. params_(context.Clone(other.params_)),
  389. self_(context.Clone(other.self_)),
  390. members_(context.Clone(other.members_)) {}
  391. static auto classof(const AstNode* node) -> bool {
  392. return InheritsFromMixinDeclaration(node->kind());
  393. }
  394. auto name() const -> const DeclaredName& { return name_; }
  395. auto params() const -> std::optional<Nonnull<const TuplePattern*>> {
  396. return params_;
  397. }
  398. auto params() -> std::optional<Nonnull<TuplePattern*>> { return params_; }
  399. auto self() const -> Nonnull<const GenericBinding*> { return self_; }
  400. auto self() -> Nonnull<GenericBinding*> { return self_; }
  401. auto members() const -> llvm::ArrayRef<Nonnull<Declaration*>> {
  402. return members_;
  403. }
  404. auto expression_category() const -> ExpressionCategory {
  405. return ExpressionCategory::Value;
  406. }
  407. private:
  408. DeclaredName name_;
  409. std::optional<Nonnull<TuplePattern*>> params_;
  410. Nonnull<GenericBinding*> self_;
  411. std::vector<Nonnull<Declaration*>> members_;
  412. };
  413. // EXPERIMENTAL MIXIN FEATURE
  414. class MixDeclaration : public Declaration {
  415. public:
  416. MixDeclaration(SourceLocation source_loc,
  417. std::optional<Nonnull<Expression*>> mixin_type)
  418. : Declaration(AstNodeKind::MixDeclaration, source_loc),
  419. mixin_(mixin_type) {}
  420. explicit MixDeclaration(CloneContext& context, const MixDeclaration& other);
  421. static auto classof(const AstNode* node) -> bool {
  422. return InheritsFromMixDeclaration(node->kind());
  423. }
  424. auto mixin() const -> const Expression& { return **mixin_; }
  425. auto mixin() -> Expression& { return **mixin_; }
  426. auto mixin_value() const -> const MixinPseudoType& { return **mixin_value_; }
  427. void set_mixin_value(Nonnull<const MixinPseudoType*> mixin_value) {
  428. mixin_value_ = mixin_value;
  429. }
  430. private:
  431. std::optional<Nonnull<Expression*>> mixin_;
  432. std::optional<Nonnull<const MixinPseudoType*>> mixin_value_;
  433. };
  434. class AlternativeSignature : public AstNode {
  435. public:
  436. AlternativeSignature(SourceLocation source_loc, std::string name,
  437. std::optional<Nonnull<TupleLiteral*>> parameters)
  438. : AstNode(AstNodeKind::AlternativeSignature, source_loc),
  439. name_(std::move(name)),
  440. parameters_(parameters) {}
  441. explicit AlternativeSignature(CloneContext& context,
  442. const AlternativeSignature& other)
  443. : AstNode(context, other),
  444. name_(other.name_),
  445. parameters_(context.Clone(other.parameters_)),
  446. parameters_static_type_(context.Clone(other.parameters_static_type_)) {}
  447. void Print(llvm::raw_ostream& out) const override;
  448. void PrintID(llvm::raw_ostream& out) const override;
  449. static auto classof(const AstNode* node) -> bool {
  450. return InheritsFromAlternativeSignature(node->kind());
  451. }
  452. auto name() const -> const std::string& { return name_; }
  453. auto parameters() const -> std::optional<Nonnull<const TupleLiteral*>> {
  454. return parameters_;
  455. }
  456. auto parameters() -> std::optional<Nonnull<TupleLiteral*>> {
  457. return parameters_;
  458. }
  459. // The static type described by the parameters expression, if any. Cannot be
  460. // called before type checking. This will be nullopt after type checking if
  461. // this alternative does not have a parameter list.
  462. auto parameters_static_type() const -> std::optional<Nonnull<const Value*>> {
  463. return parameters_static_type_;
  464. }
  465. // Sets the static type of the declared entity. Can only be called once,
  466. // during typechecking.
  467. void set_parameters_static_type(Nonnull<const Value*> type) {
  468. CARBON_CHECK(!parameters_static_type_.has_value());
  469. parameters_static_type_ = type;
  470. }
  471. private:
  472. std::string name_;
  473. std::optional<Nonnull<TupleLiteral*>> parameters_;
  474. std::optional<Nonnull<const Value*>> parameters_static_type_;
  475. };
  476. class ChoiceDeclaration : public Declaration {
  477. public:
  478. using ImplementsCarbonValueNode = void;
  479. ChoiceDeclaration(SourceLocation source_loc, DeclaredName name,
  480. std::optional<Nonnull<TuplePattern*>> type_params,
  481. std::vector<Nonnull<AlternativeSignature*>> alternatives)
  482. : Declaration(AstNodeKind::ChoiceDeclaration, source_loc),
  483. name_(std::move(name)),
  484. type_params_(type_params),
  485. alternatives_(std::move(alternatives)) {}
  486. explicit ChoiceDeclaration(CloneContext& context,
  487. const ChoiceDeclaration& other)
  488. : Declaration(context, other),
  489. name_(other.name_),
  490. type_params_(context.Clone(other.type_params_)),
  491. alternatives_(context.Clone(other.alternatives_)) {}
  492. static auto classof(const AstNode* node) -> bool {
  493. return InheritsFromChoiceDeclaration(node->kind());
  494. }
  495. auto name() const -> const DeclaredName& { return name_; }
  496. auto type_params() const -> std::optional<Nonnull<const TuplePattern*>> {
  497. return type_params_;
  498. }
  499. auto type_params() -> std::optional<Nonnull<TuplePattern*>> {
  500. return type_params_;
  501. }
  502. auto alternatives() const
  503. -> llvm::ArrayRef<Nonnull<const AlternativeSignature*>> {
  504. return alternatives_;
  505. }
  506. auto alternatives() -> llvm::ArrayRef<Nonnull<AlternativeSignature*>> {
  507. return alternatives_;
  508. }
  509. auto expression_category() const -> ExpressionCategory {
  510. return ExpressionCategory::Value;
  511. }
  512. auto FindAlternative(std::string_view name) const
  513. -> std::optional<const AlternativeSignature*>;
  514. private:
  515. DeclaredName name_;
  516. std::optional<Nonnull<TuplePattern*>> type_params_;
  517. std::vector<Nonnull<AlternativeSignature*>> alternatives_;
  518. };
  519. // Global variable definition implements the Declaration concept.
  520. class VariableDeclaration : public Declaration {
  521. public:
  522. VariableDeclaration(SourceLocation source_loc,
  523. Nonnull<BindingPattern*> binding,
  524. std::optional<Nonnull<Expression*>> initializer,
  525. ExpressionCategory expression_category)
  526. : Declaration(AstNodeKind::VariableDeclaration, source_loc),
  527. binding_(binding),
  528. initializer_(initializer),
  529. expression_category_(expression_category) {}
  530. explicit VariableDeclaration(CloneContext& context,
  531. const VariableDeclaration& other)
  532. : Declaration(context, other),
  533. binding_(context.Clone(other.binding_)),
  534. initializer_(context.Clone(other.initializer_)),
  535. expression_category_(other.expression_category_) {}
  536. static auto classof(const AstNode* node) -> bool {
  537. return InheritsFromVariableDeclaration(node->kind());
  538. }
  539. auto binding() const -> const BindingPattern& { return *binding_; }
  540. auto binding() -> BindingPattern& { return *binding_; }
  541. auto initializer() const -> const Expression& { return **initializer_; }
  542. auto initializer() -> Expression& { return **initializer_; }
  543. auto expression_category() const -> ExpressionCategory {
  544. return expression_category_;
  545. }
  546. auto has_initializer() const -> bool { return initializer_.has_value(); }
  547. // Can only be called by type-checking, if a conversion was required.
  548. void set_initializer(Nonnull<Expression*> initializer) {
  549. CARBON_CHECK(has_initializer()) << "should not add a new initializer";
  550. initializer_ = initializer;
  551. }
  552. private:
  553. Nonnull<BindingPattern*> binding_;
  554. std::optional<Nonnull<Expression*>> initializer_;
  555. ExpressionCategory expression_category_;
  556. };
  557. // Base class for constraint and interface declarations. Interfaces and named
  558. // constraints behave the same in most respects, but only interfaces can
  559. // introduce new associated functions and constants.
  560. class ConstraintTypeDeclaration : public Declaration {
  561. public:
  562. using ImplementsCarbonValueNode = void;
  563. ConstraintTypeDeclaration(AstNodeKind kind, Nonnull<Arena*> arena,
  564. SourceLocation source_loc, DeclaredName name,
  565. std::optional<Nonnull<TuplePattern*>> params,
  566. std::vector<Nonnull<Declaration*>> members)
  567. : Declaration(kind, source_loc),
  568. name_(std::move(name)),
  569. params_(params),
  570. self_type_(arena->New<SelfDeclaration>(source_loc)),
  571. members_(std::move(members)) {
  572. // `interface X` has `Self:! X`.
  573. auto* self_type_ref = arena->New<IdentifierExpression>(
  574. source_loc, std::string(name_.inner_name()));
  575. self_type_ref->set_value_node(self_type_);
  576. self_ = arena->New<GenericBinding>(source_loc, "Self", self_type_ref,
  577. GenericBinding::BindingKind::Checked);
  578. }
  579. explicit ConstraintTypeDeclaration(CloneContext& context,
  580. const ConstraintTypeDeclaration& other);
  581. static auto classof(const AstNode* node) -> bool {
  582. return InheritsFromConstraintTypeDeclaration(node->kind());
  583. }
  584. auto name() const -> const DeclaredName& { return name_; }
  585. auto params() const -> std::optional<Nonnull<const TuplePattern*>> {
  586. return params_;
  587. }
  588. auto params() -> std::optional<Nonnull<TuplePattern*>> { return params_; }
  589. // Get the type of `Self`, which is a reference to the interface itself, with
  590. // parameters mapped to their values. For example, in `interface X(T:!
  591. // type)`, the self type is `X(T)`.
  592. auto self_type() const -> Nonnull<const SelfDeclaration*> {
  593. return self_type_;
  594. }
  595. auto self_type() -> Nonnull<SelfDeclaration*> { return self_type_; }
  596. auto self() const -> Nonnull<const GenericBinding*> { return self_; }
  597. auto self() -> Nonnull<GenericBinding*> { return self_; }
  598. auto members() const -> llvm::ArrayRef<Nonnull<Declaration*>> {
  599. return members_;
  600. }
  601. auto expression_category() const -> ExpressionCategory {
  602. return ExpressionCategory::Value;
  603. }
  604. // Get the constraint type corresponding to this interface, or nullopt if
  605. // this interface is incomplete.
  606. auto constraint_type() const
  607. -> std::optional<Nonnull<const ConstraintType*>> {
  608. return constraint_type_;
  609. }
  610. // Set the constraint type corresponding to this interface. Can only be set
  611. // once, by type-checking.
  612. void set_constraint_type(Nonnull<const ConstraintType*> constraint_type) {
  613. CARBON_CHECK(!constraint_type_);
  614. constraint_type_ = constraint_type;
  615. }
  616. private:
  617. DeclaredName name_;
  618. std::optional<Nonnull<TuplePattern*>> params_;
  619. Nonnull<SelfDeclaration*> self_type_;
  620. Nonnull<GenericBinding*> self_;
  621. std::vector<Nonnull<Declaration*>> members_;
  622. std::optional<Nonnull<const ConstraintType*>> constraint_type_;
  623. };
  624. // A `interface` declaration.
  625. class InterfaceDeclaration : public ConstraintTypeDeclaration {
  626. public:
  627. using ImplementsCarbonValueNode = void;
  628. InterfaceDeclaration(Nonnull<Arena*> arena, SourceLocation source_loc,
  629. DeclaredName name,
  630. std::optional<Nonnull<TuplePattern*>> params,
  631. std::vector<Nonnull<Declaration*>> members)
  632. : ConstraintTypeDeclaration(AstNodeKind::InterfaceDeclaration, arena,
  633. source_loc, std::move(name), params,
  634. std::move(members)) {}
  635. explicit InterfaceDeclaration(CloneContext& context,
  636. const InterfaceDeclaration& other)
  637. : ConstraintTypeDeclaration(context, other) {}
  638. static auto classof(const AstNode* node) -> bool {
  639. return InheritsFromInterfaceDeclaration(node->kind());
  640. }
  641. };
  642. // A `constraint` declaration, such as `constraint X { impl as Y; }`.
  643. class ConstraintDeclaration : public ConstraintTypeDeclaration {
  644. public:
  645. using ImplementsCarbonValueNode = void;
  646. ConstraintDeclaration(Nonnull<Arena*> arena, SourceLocation source_loc,
  647. DeclaredName name,
  648. std::optional<Nonnull<TuplePattern*>> params,
  649. std::vector<Nonnull<Declaration*>> members)
  650. : ConstraintTypeDeclaration(AstNodeKind::ConstraintDeclaration, arena,
  651. source_loc, std::move(name), params,
  652. std::move(members)) {}
  653. explicit ConstraintDeclaration(CloneContext& context,
  654. const ConstraintDeclaration& other)
  655. : ConstraintTypeDeclaration(context, other) {}
  656. static auto classof(const AstNode* node) -> bool {
  657. return InheritsFromConstraintDeclaration(node->kind());
  658. }
  659. };
  660. // An `extends` declaration in an interface.
  661. class InterfaceExtendsDeclaration : public Declaration {
  662. public:
  663. InterfaceExtendsDeclaration(SourceLocation source_loc,
  664. Nonnull<Expression*> base)
  665. : Declaration(AstNodeKind::InterfaceExtendsDeclaration, source_loc),
  666. base_(base) {}
  667. explicit InterfaceExtendsDeclaration(CloneContext& context,
  668. const InterfaceExtendsDeclaration& other)
  669. : Declaration(context, other), base_(context.Clone(other.base_)) {}
  670. static auto classof(const AstNode* node) -> bool {
  671. return InheritsFromInterfaceExtendsDeclaration(node->kind());
  672. }
  673. auto base() const -> const Expression* { return base_; }
  674. auto base() -> Expression* { return base_; }
  675. private:
  676. Nonnull<Expression*> base_;
  677. };
  678. // An `impl ... as` declaration in an interface.
  679. class InterfaceImplDeclaration : public Declaration {
  680. public:
  681. InterfaceImplDeclaration(SourceLocation source_loc,
  682. Nonnull<Expression*> impl_type,
  683. Nonnull<Expression*> constraint)
  684. : Declaration(AstNodeKind::InterfaceImplDeclaration, source_loc),
  685. impl_type_(impl_type),
  686. constraint_(constraint) {}
  687. explicit InterfaceImplDeclaration(CloneContext& context,
  688. const InterfaceImplDeclaration& other)
  689. : Declaration(context, other),
  690. impl_type_(context.Clone(other.impl_type_)),
  691. constraint_(context.Clone(other.constraint_)) {}
  692. static auto classof(const AstNode* node) -> bool {
  693. return InheritsFromInterfaceImplDeclaration(node->kind());
  694. }
  695. auto impl_type() const -> const Expression* { return impl_type_; }
  696. auto impl_type() -> Expression* { return impl_type_; }
  697. auto constraint() const -> const Expression* { return constraint_; }
  698. auto constraint() -> Expression* { return constraint_; }
  699. private:
  700. Nonnull<Expression*> impl_type_;
  701. Nonnull<Expression*> constraint_;
  702. };
  703. class AssociatedConstantDeclaration : public Declaration {
  704. public:
  705. using ImplementsCarbonValueNode = void;
  706. AssociatedConstantDeclaration(SourceLocation source_loc,
  707. Nonnull<GenericBinding*> binding)
  708. : Declaration(AstNodeKind::AssociatedConstantDeclaration, source_loc),
  709. binding_(binding) {}
  710. explicit AssociatedConstantDeclaration(
  711. CloneContext& context, const AssociatedConstantDeclaration& other)
  712. : Declaration(context, other), binding_(context.Clone(other.binding_)) {}
  713. static auto classof(const AstNode* node) -> bool {
  714. return InheritsFromAssociatedConstantDeclaration(node->kind());
  715. }
  716. auto binding() const -> const GenericBinding& { return *binding_; }
  717. auto binding() -> GenericBinding& { return *binding_; }
  718. auto expression_category() const -> ExpressionCategory {
  719. return ExpressionCategory::Value;
  720. }
  721. private:
  722. Nonnull<GenericBinding*> binding_;
  723. };
  724. enum class ImplKind { InternalImpl, ExternalImpl };
  725. class ImplDeclaration : public Declaration {
  726. public:
  727. static auto Create(Nonnull<Arena*> arena, SourceLocation source_loc,
  728. ImplKind kind, Nonnull<Expression*> impl_type,
  729. Nonnull<Expression*> interface,
  730. std::vector<Nonnull<AstNode*>> deduced_params,
  731. std::vector<Nonnull<Declaration*>> members)
  732. -> ErrorOr<Nonnull<ImplDeclaration*>>;
  733. // Use `Create` instead.
  734. ImplDeclaration(SourceLocation source_loc, ImplKind kind,
  735. Nonnull<Expression*> impl_type,
  736. Nonnull<SelfDeclaration*> self_decl,
  737. Nonnull<Expression*> interface,
  738. std::vector<Nonnull<GenericBinding*>> deduced_params,
  739. std::vector<Nonnull<Declaration*>> members)
  740. : Declaration(AstNodeKind::ImplDeclaration, source_loc),
  741. kind_(kind),
  742. deduced_parameters_(std::move(deduced_params)),
  743. impl_type_(impl_type),
  744. self_decl_(self_decl),
  745. interface_(interface),
  746. members_(std::move(members)) {}
  747. explicit ImplDeclaration(CloneContext& context, const ImplDeclaration& other);
  748. static auto classof(const AstNode* node) -> bool {
  749. return InheritsFromImplDeclaration(node->kind());
  750. }
  751. // Return whether this is an external or internal impl.
  752. auto kind() const -> ImplKind { return kind_; }
  753. // Return the type that is doing the implementing.
  754. auto impl_type() const -> Nonnull<Expression*> { return impl_type_; }
  755. // Return the interface that is being implemented.
  756. auto interface() const -> const Expression& { return *interface_; }
  757. auto interface() -> Expression& { return *interface_; }
  758. void set_constraint_type(Nonnull<const ConstraintType*> constraint_type) {
  759. constraint_type_ = constraint_type;
  760. }
  761. auto constraint_type() const -> Nonnull<const ConstraintType*> {
  762. return *constraint_type_;
  763. }
  764. // Returns the deduced parameters specified on the impl declaration. This
  765. // does not include any generic parameters from enclosing scopes.
  766. auto deduced_parameters() const
  767. -> llvm::ArrayRef<Nonnull<const GenericBinding*>> {
  768. return deduced_parameters_;
  769. }
  770. auto deduced_parameters() -> llvm::ArrayRef<Nonnull<GenericBinding*>> {
  771. return deduced_parameters_;
  772. }
  773. auto members() const -> llvm::ArrayRef<Nonnull<Declaration*>> {
  774. return members_;
  775. }
  776. auto expression_category() const -> ExpressionCategory {
  777. return ExpressionCategory::Value;
  778. }
  779. void set_impl_bindings(llvm::ArrayRef<Nonnull<const ImplBinding*>> imps) {
  780. impl_bindings_ = imps;
  781. }
  782. auto impl_bindings() const -> llvm::ArrayRef<Nonnull<const ImplBinding*>> {
  783. return impl_bindings_;
  784. }
  785. auto self() const -> Nonnull<const SelfDeclaration*> { return self_decl_; }
  786. auto self() -> Nonnull<SelfDeclaration*> { return self_decl_; }
  787. // Set the enclosing match_first declaration. Should only be called once,
  788. // during type-checking.
  789. void set_match_first(Nonnull<const MatchFirstDeclaration*> match_first) {
  790. match_first_ = match_first;
  791. }
  792. // Get the enclosing match_first declaration, if any exists.
  793. auto match_first() const
  794. -> std::optional<Nonnull<const MatchFirstDeclaration*>> {
  795. return match_first_;
  796. }
  797. private:
  798. ImplKind kind_;
  799. std::vector<Nonnull<GenericBinding*>> deduced_parameters_;
  800. Nonnull<Expression*> impl_type_;
  801. Nonnull<SelfDeclaration*> self_decl_;
  802. Nonnull<Expression*> interface_;
  803. std::optional<Nonnull<const ConstraintType*>> constraint_type_;
  804. std::vector<Nonnull<Declaration*>> members_;
  805. std::vector<Nonnull<const ImplBinding*>> impl_bindings_;
  806. std::optional<Nonnull<const MatchFirstDeclaration*>> match_first_;
  807. };
  808. class MatchFirstDeclaration : public Declaration {
  809. public:
  810. MatchFirstDeclaration(
  811. SourceLocation source_loc,
  812. std::vector<Nonnull<ImplDeclaration*>> impl_declarations)
  813. : Declaration(AstNodeKind::MatchFirstDeclaration, source_loc),
  814. impl_declarations_(std::move(impl_declarations)) {}
  815. explicit MatchFirstDeclaration(CloneContext& context,
  816. const MatchFirstDeclaration& other)
  817. : Declaration(context, other),
  818. impl_declarations_(context.Clone(other.impl_declarations_)) {}
  819. static auto classof(const AstNode* node) -> bool {
  820. return InheritsFromMatchFirstDeclaration(node->kind());
  821. }
  822. auto impl_declarations() const
  823. -> llvm::ArrayRef<Nonnull<const ImplDeclaration*>> {
  824. return impl_declarations_;
  825. }
  826. auto impl_declarations() -> llvm::ArrayRef<Nonnull<ImplDeclaration*>> {
  827. return impl_declarations_;
  828. }
  829. private:
  830. std::vector<Nonnull<ImplDeclaration*>> impl_declarations_;
  831. };
  832. class AliasDeclaration : public Declaration {
  833. public:
  834. using ImplementsCarbonValueNode = void;
  835. explicit AliasDeclaration(SourceLocation source_loc, DeclaredName name,
  836. Nonnull<Expression*> target)
  837. : Declaration(AstNodeKind::AliasDeclaration, source_loc),
  838. name_(std::move(name)),
  839. target_(target) {}
  840. explicit AliasDeclaration(CloneContext& context,
  841. const AliasDeclaration& other)
  842. : Declaration(context, other),
  843. name_(other.name_),
  844. target_(context.Clone(other.target_)) {}
  845. static auto classof(const AstNode* node) -> bool {
  846. return InheritsFromAliasDeclaration(node->kind());
  847. }
  848. auto name() const -> const DeclaredName& { return name_; }
  849. auto target() const -> const Expression& { return *target_; }
  850. auto target() -> Expression& { return *target_; }
  851. auto expression_category() const -> ExpressionCategory {
  852. return ExpressionCategory::Value;
  853. }
  854. // Sets the resolved declaration of alias target. Should only be called once,
  855. // during name resolution.
  856. void set_resolved_declaration(Nonnull<const Declaration*> decl) {
  857. CARBON_CHECK(!resolved_declaration_.has_value());
  858. resolved_declaration_ = decl;
  859. }
  860. // Get the resolved declaration of alias target, if any exists.
  861. auto resolved_declaration() const
  862. -> std::optional<Nonnull<const Declaration*>> {
  863. return resolved_declaration_;
  864. }
  865. private:
  866. DeclaredName name_;
  867. Nonnull<Expression*> target_;
  868. std::optional<Nonnull<const Declaration*>> resolved_declaration_;
  869. };
  870. // Return the unqualified name of a declaration, if it has one.
  871. auto GetName(const Declaration&) -> std::optional<std::string_view>;
  872. } // namespace Carbon
  873. #endif // CARBON_EXPLORER_AST_DECLARATION_H_