declaration.h 39 KB

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