declaration.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. #include "explorer/ast/declaration.h"
  5. #include "explorer/ast/value.h"
  6. #include "explorer/base/print_as_id.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. #include "llvm/Support/Casting.h"
  9. namespace Carbon {
  10. using llvm::cast;
  11. Declaration::~Declaration() = default;
  12. void Declaration::Print(llvm::raw_ostream& out) const { PrintIndent(0, out); }
  13. void Declaration::PrintIndent(int indent_num_spaces,
  14. llvm::raw_ostream& out) const {
  15. if (kind() != DeclarationKind::FunctionDeclaration &&
  16. kind() != DeclarationKind::DestructorDeclaration) {
  17. out.indent(indent_num_spaces);
  18. }
  19. switch (kind()) {
  20. case DeclarationKind::NamespaceDeclaration:
  21. out << PrintAsID(*this) << ";";
  22. break;
  23. case DeclarationKind::InterfaceDeclaration:
  24. case DeclarationKind::ConstraintDeclaration: {
  25. const auto& iface_decl = cast<ConstraintTypeDeclaration>(*this);
  26. out << PrintAsID(*this);
  27. out << " {\n";
  28. for (Nonnull<Declaration*> m : iface_decl.members()) {
  29. out.indent(indent_num_spaces + 2) << *m << "\n";
  30. }
  31. out.indent(indent_num_spaces) << "}";
  32. break;
  33. }
  34. case DeclarationKind::ImplDeclaration: {
  35. const auto& impl_decl = cast<ImplDeclaration>(*this);
  36. out << PrintAsID(impl_decl) << " {\n";
  37. for (Nonnull<Declaration*> m : impl_decl.members()) {
  38. m->PrintIndent(indent_num_spaces + 2, out);
  39. out << "\n";
  40. }
  41. out.indent(indent_num_spaces) << "}";
  42. break;
  43. }
  44. case DeclarationKind::MatchFirstDeclaration: {
  45. const auto& match_first_decl = cast<MatchFirstDeclaration>(*this);
  46. out << PrintAsID(match_first_decl) << " {\n";
  47. for (Nonnull<const ImplDeclaration*> m :
  48. match_first_decl.impl_declarations()) {
  49. m->PrintIndent(indent_num_spaces + 2, out);
  50. out << "\n";
  51. }
  52. out.indent(indent_num_spaces) << "}";
  53. break;
  54. }
  55. case DeclarationKind::FunctionDeclaration:
  56. cast<FunctionDeclaration>(*this).PrintIndent(indent_num_spaces, out);
  57. break;
  58. case DeclarationKind::DestructorDeclaration:
  59. cast<DestructorDeclaration>(*this).PrintIndent(indent_num_spaces, out);
  60. break;
  61. case DeclarationKind::ClassDeclaration: {
  62. const auto& class_decl = cast<ClassDeclaration>(*this);
  63. out << PrintAsID(class_decl);
  64. if (class_decl.type_params().has_value()) {
  65. out << **class_decl.type_params();
  66. }
  67. out << " {\n";
  68. for (Nonnull<Declaration*> m : class_decl.members()) {
  69. m->PrintIndent(indent_num_spaces + 2, out);
  70. out << "\n";
  71. }
  72. out.indent(indent_num_spaces) << "}";
  73. break;
  74. }
  75. case DeclarationKind::MixinDeclaration: {
  76. const auto& mixin_decl = cast<MixinDeclaration>(*this);
  77. out << PrintAsID(mixin_decl) << "{\n";
  78. for (Nonnull<Declaration*> m : mixin_decl.members()) {
  79. m->PrintIndent(indent_num_spaces + 2, out);
  80. out << "\n";
  81. }
  82. out.indent(indent_num_spaces) << "}";
  83. break;
  84. }
  85. case DeclarationKind::MixDeclaration: {
  86. const auto& mix_decl = cast<MixDeclaration>(*this);
  87. out << PrintAsID(mix_decl);
  88. out << mix_decl.mixin() << ";";
  89. break;
  90. }
  91. case DeclarationKind::ChoiceDeclaration: {
  92. const auto& choice = cast<ChoiceDeclaration>(*this);
  93. out << PrintAsID(choice) << " {\n";
  94. for (Nonnull<const AlternativeSignature*> alt : choice.alternatives()) {
  95. out.indent(indent_num_spaces + 2) << *alt << ";\n";
  96. }
  97. out.indent(indent_num_spaces) << "}";
  98. break;
  99. }
  100. case DeclarationKind::VariableDeclaration: {
  101. const auto& var = cast<VariableDeclaration>(*this);
  102. out << PrintAsID(var);
  103. if (var.has_initializer()) {
  104. out << " = " << var.initializer();
  105. }
  106. out << ";";
  107. break;
  108. }
  109. case DeclarationKind::InterfaceExtendDeclaration:
  110. case DeclarationKind::InterfaceRequireDeclaration:
  111. case DeclarationKind::AssociatedConstantDeclaration: {
  112. out << PrintAsID(*this) << ";";
  113. break;
  114. }
  115. case DeclarationKind::SelfDeclaration: {
  116. out << "Self";
  117. break;
  118. }
  119. case DeclarationKind::AliasDeclaration: {
  120. const auto& alias = cast<AliasDeclaration>(*this);
  121. out << PrintAsID(alias) << " = " << alias.target() << ";";
  122. break;
  123. }
  124. case DeclarationKind::ExtendBaseDeclaration: {
  125. out << PrintAsID(*this) << ";";
  126. break;
  127. }
  128. }
  129. }
  130. void Declaration::PrintID(llvm::raw_ostream& out) const {
  131. switch (kind()) {
  132. case DeclarationKind::NamespaceDeclaration:
  133. out << "namespace " << cast<NamespaceDeclaration>(*this).name();
  134. break;
  135. case DeclarationKind::InterfaceDeclaration: {
  136. const auto& iface_decl = cast<InterfaceDeclaration>(*this);
  137. out << "interface " << iface_decl.name();
  138. break;
  139. }
  140. case DeclarationKind::ConstraintDeclaration: {
  141. const auto& constraint_decl = cast<ConstraintDeclaration>(*this);
  142. out << "constraint " << constraint_decl.name();
  143. break;
  144. }
  145. case DeclarationKind::ImplDeclaration: {
  146. const auto& impl_decl = cast<ImplDeclaration>(*this);
  147. switch (impl_decl.kind()) {
  148. case ImplKind::InternalImpl:
  149. out << "extend ";
  150. break;
  151. case ImplKind::ExternalImpl:
  152. break;
  153. }
  154. out << "impl ";
  155. if (!impl_decl.deduced_parameters().empty()) {
  156. out << "forall [";
  157. llvm::ListSeparator sep;
  158. for (const auto* param : impl_decl.deduced_parameters()) {
  159. out << sep << *param;
  160. }
  161. out << "] ";
  162. }
  163. if (impl_decl.kind() != ImplKind::InternalImpl) {
  164. out << *impl_decl.impl_type() << " ";
  165. }
  166. out << "as " << impl_decl.interface();
  167. break;
  168. }
  169. case DeclarationKind::MatchFirstDeclaration:
  170. out << "match_first";
  171. break;
  172. case DeclarationKind::FunctionDeclaration:
  173. out << "fn " << cast<FunctionDeclaration>(*this).name();
  174. break;
  175. case DeclarationKind::DestructorDeclaration:
  176. out << *GetName(*this);
  177. break;
  178. case DeclarationKind::ClassDeclaration: {
  179. const auto& class_decl = cast<ClassDeclaration>(*this);
  180. out << "class " << class_decl.name();
  181. break;
  182. }
  183. case DeclarationKind::MixinDeclaration: {
  184. const auto& mixin_decl = cast<MixinDeclaration>(*this);
  185. out << "__mixin " << mixin_decl.name();
  186. if (mixin_decl.self()->type().kind() != ExpressionKind::TypeTypeLiteral) {
  187. out << " for " << mixin_decl.self()->type();
  188. }
  189. break;
  190. }
  191. case DeclarationKind::MixDeclaration: {
  192. out << "__mix ";
  193. break;
  194. }
  195. case DeclarationKind::ChoiceDeclaration: {
  196. const auto& choice = cast<ChoiceDeclaration>(*this);
  197. out << "choice " << choice.name();
  198. break;
  199. }
  200. case DeclarationKind::VariableDeclaration: {
  201. const auto& var = cast<VariableDeclaration>(*this);
  202. out << "var " << var.binding();
  203. break;
  204. }
  205. case DeclarationKind::InterfaceExtendDeclaration: {
  206. const auto& extend = cast<InterfaceExtendDeclaration>(*this);
  207. out << "extend " << *extend.base();
  208. break;
  209. }
  210. case DeclarationKind::InterfaceRequireDeclaration: {
  211. const auto& impl = cast<InterfaceRequireDeclaration>(*this);
  212. out << "require " << *impl.impl_type() << " impls " << *impl.constraint();
  213. break;
  214. }
  215. case DeclarationKind::AssociatedConstantDeclaration: {
  216. const auto& let = cast<AssociatedConstantDeclaration>(*this);
  217. out << "let " << let.binding();
  218. break;
  219. }
  220. case DeclarationKind::SelfDeclaration: {
  221. out << "Self";
  222. break;
  223. }
  224. case DeclarationKind::AliasDeclaration: {
  225. const auto& alias = cast<AliasDeclaration>(*this);
  226. out << "alias " << alias.name();
  227. break;
  228. }
  229. case DeclarationKind::ExtendBaseDeclaration: {
  230. const auto& extend = cast<ExtendBaseDeclaration>(*this);
  231. out << "extend base: " << *extend.base_class();
  232. break;
  233. }
  234. }
  235. }
  236. void DeclaredName::Print(llvm::raw_ostream& out) const {
  237. for (const auto& [loc, name] : qualifiers()) {
  238. out << name << ".";
  239. }
  240. out << inner_name();
  241. }
  242. auto GetName(const Declaration& declaration)
  243. -> std::optional<std::string_view> {
  244. switch (declaration.kind()) {
  245. case DeclarationKind::NamespaceDeclaration:
  246. return cast<NamespaceDeclaration>(declaration).name().inner_name();
  247. case DeclarationKind::FunctionDeclaration:
  248. return cast<FunctionDeclaration>(declaration).name().inner_name();
  249. case DeclarationKind::DestructorDeclaration:
  250. return "destructor";
  251. case DeclarationKind::ClassDeclaration:
  252. return cast<ClassDeclaration>(declaration).name().inner_name();
  253. case DeclarationKind::MixinDeclaration: {
  254. return cast<MixinDeclaration>(declaration).name().inner_name();
  255. }
  256. case DeclarationKind::MixDeclaration: {
  257. return std::nullopt;
  258. }
  259. case DeclarationKind::ChoiceDeclaration:
  260. return cast<ChoiceDeclaration>(declaration).name().inner_name();
  261. case DeclarationKind::InterfaceDeclaration:
  262. case DeclarationKind::ConstraintDeclaration:
  263. return cast<ConstraintTypeDeclaration>(declaration).name().inner_name();
  264. case DeclarationKind::VariableDeclaration:
  265. return cast<VariableDeclaration>(declaration).binding().name();
  266. case DeclarationKind::AssociatedConstantDeclaration:
  267. return cast<AssociatedConstantDeclaration>(declaration).binding().name();
  268. case DeclarationKind::InterfaceExtendDeclaration:
  269. case DeclarationKind::InterfaceRequireDeclaration:
  270. case DeclarationKind::ImplDeclaration:
  271. case DeclarationKind::MatchFirstDeclaration:
  272. return std::nullopt;
  273. case DeclarationKind::SelfDeclaration:
  274. return SelfDeclaration::name();
  275. case DeclarationKind::AliasDeclaration: {
  276. return cast<AliasDeclaration>(declaration).name().inner_name();
  277. }
  278. case DeclarationKind::ExtendBaseDeclaration: {
  279. return "extend base";
  280. }
  281. }
  282. }
  283. void ReturnTerm::Print(llvm::raw_ostream& out) const {
  284. switch (kind_) {
  285. case ReturnKind::Omitted:
  286. return;
  287. case ReturnKind::Auto:
  288. out << "-> auto";
  289. return;
  290. case ReturnKind::Expression:
  291. CARBON_CHECK(type_expression_.has_value());
  292. out << "-> " << **type_expression_;
  293. return;
  294. }
  295. }
  296. namespace {
  297. // The deduced parameters of a function declaration.
  298. struct DeducedParameters {
  299. // The `self` parameter, if any.
  300. std::optional<Nonnull<Pattern*>> self_pattern;
  301. // All other deduced parameters.
  302. std::vector<Nonnull<GenericBinding*>> resolved_params;
  303. };
  304. // Split the `self` pattern (if any) out of `deduced_params`.
  305. auto SplitDeducedParameters(
  306. SourceLocation source_loc,
  307. const std::vector<Nonnull<AstNode*>>& deduced_params)
  308. -> ErrorOr<DeducedParameters> {
  309. DeducedParameters result;
  310. for (Nonnull<AstNode*> param : deduced_params) {
  311. switch (param->kind()) {
  312. case AstNodeKind::GenericBinding:
  313. result.resolved_params.push_back(&cast<GenericBinding>(*param));
  314. break;
  315. case AstNodeKind::BindingPattern: {
  316. Nonnull<BindingPattern*> binding = &cast<BindingPattern>(*param);
  317. if (binding->name() != "self") {
  318. return ProgramError(source_loc)
  319. << "illegal binding pattern in implicit parameter list";
  320. }
  321. if (result.self_pattern.has_value()) {
  322. return ProgramError(source_loc)
  323. << "parameter list cannot contain more than one `self` "
  324. "parameter";
  325. }
  326. result.self_pattern = binding;
  327. break;
  328. }
  329. case AstNodeKind::AddrPattern: {
  330. Nonnull<AddrPattern*> addr_pattern = &cast<AddrPattern>(*param);
  331. Nonnull<BindingPattern*> binding =
  332. &cast<BindingPattern>(addr_pattern->binding());
  333. if (binding->name() != "self") {
  334. return ProgramError(source_loc)
  335. << "illegal binding pattern in implicit parameter list";
  336. }
  337. if (result.self_pattern.has_value()) {
  338. return ProgramError(source_loc)
  339. << "parameter list cannot contain more than one `self` "
  340. "parameter";
  341. }
  342. result.self_pattern = addr_pattern;
  343. break;
  344. }
  345. default:
  346. return ProgramError(source_loc)
  347. << "illegal AST node in implicit parameter list";
  348. }
  349. }
  350. return result;
  351. }
  352. } // namespace
  353. auto DestructorDeclaration::CreateDestructor(
  354. Nonnull<Arena*> arena, SourceLocation source_loc,
  355. std::vector<Nonnull<AstNode*>> deduced_params,
  356. Nonnull<TuplePattern*> param_pattern, ReturnTerm return_term,
  357. std::optional<Nonnull<Block*>> body, VirtualOverride virt_override)
  358. -> ErrorOr<Nonnull<DestructorDeclaration*>> {
  359. DeducedParameters split_params;
  360. CARBON_ASSIGN_OR_RETURN(split_params,
  361. SplitDeducedParameters(source_loc, deduced_params));
  362. return arena->New<DestructorDeclaration>(
  363. source_loc, std::move(split_params.resolved_params),
  364. split_params.self_pattern, param_pattern, return_term, body,
  365. virt_override);
  366. }
  367. auto FunctionDeclaration::Create(Nonnull<Arena*> arena,
  368. SourceLocation source_loc, DeclaredName name,
  369. std::vector<Nonnull<AstNode*>> deduced_params,
  370. Nonnull<TuplePattern*> param_pattern,
  371. ReturnTerm return_term,
  372. std::optional<Nonnull<Block*>> body,
  373. VirtualOverride virt_override)
  374. -> ErrorOr<Nonnull<FunctionDeclaration*>> {
  375. DeducedParameters split_params;
  376. CARBON_ASSIGN_OR_RETURN(split_params,
  377. SplitDeducedParameters(source_loc, deduced_params));
  378. return arena->New<FunctionDeclaration>(
  379. source_loc, std::move(name), std::move(split_params.resolved_params),
  380. split_params.self_pattern, param_pattern, return_term, body,
  381. virt_override);
  382. }
  383. void CallableDeclaration::PrintIndent(int indent_num_spaces,
  384. llvm::raw_ostream& out) const {
  385. auto name = GetName(*this);
  386. CARBON_CHECK(name, "Unexpected missing name for `{0}`.", *this);
  387. out.indent(indent_num_spaces) << "fn " << *name << " ";
  388. if (!deduced_parameters_.empty() || self_pattern_) {
  389. out << "[";
  390. llvm::ListSeparator sep;
  391. for (Nonnull<const GenericBinding*> deduced : deduced_parameters_) {
  392. out << sep << *deduced;
  393. }
  394. if (self_pattern_) {
  395. out << sep << **self_pattern_;
  396. }
  397. out << "]";
  398. }
  399. out << *param_pattern_;
  400. if (!return_term_.is_omitted()) {
  401. out << " " << return_term_;
  402. }
  403. if (body_) {
  404. out << "\n";
  405. (*body_)->PrintIndent(indent_num_spaces, out);
  406. } else {
  407. out << ";";
  408. }
  409. }
  410. ClassDeclaration::ClassDeclaration(CloneContext& context,
  411. const ClassDeclaration& other)
  412. : Declaration(context, other),
  413. name_(other.name_),
  414. extensibility_(other.extensibility_),
  415. self_decl_(context.Clone(other.self_decl_)),
  416. type_params_(context.Clone(other.type_params_)),
  417. members_(context.Clone(other.members_)),
  418. base_type_(context.Clone(other.base_type_)) {}
  419. ExtendBaseDeclaration::ExtendBaseDeclaration(CloneContext& context,
  420. const ExtendBaseDeclaration& other)
  421. : Declaration(context, other),
  422. base_class_(context.Clone(other.base_class_)) {}
  423. ConstraintTypeDeclaration::ConstraintTypeDeclaration(
  424. CloneContext& context, const ConstraintTypeDeclaration& other)
  425. : Declaration(context, other),
  426. name_(other.name_),
  427. params_(context.Clone(other.params_)),
  428. self_type_(context.Clone(other.self_type_)),
  429. self_(context.Clone(other.self_)),
  430. members_(context.Clone(other.members_)),
  431. constraint_type_(context.Clone(other.constraint_type_)) {}
  432. auto ImplDeclaration::Create(Nonnull<Arena*> arena, SourceLocation source_loc,
  433. ImplKind kind, Nonnull<Expression*> impl_type,
  434. Nonnull<Expression*> interface,
  435. std::vector<Nonnull<AstNode*>> deduced_params,
  436. std::vector<Nonnull<Declaration*>> members)
  437. -> ErrorOr<Nonnull<ImplDeclaration*>> {
  438. std::vector<Nonnull<GenericBinding*>> resolved_params;
  439. for (Nonnull<AstNode*> param : deduced_params) {
  440. switch (param->kind()) {
  441. case AstNodeKind::GenericBinding:
  442. resolved_params.push_back(&cast<GenericBinding>(*param));
  443. break;
  444. default:
  445. return ProgramError(source_loc)
  446. << "illegal AST node in implicit parameter list of impl";
  447. }
  448. }
  449. Nonnull<SelfDeclaration*> self_decl =
  450. arena->New<SelfDeclaration>(impl_type->source_loc());
  451. return arena->New<ImplDeclaration>(source_loc, kind, impl_type, self_decl,
  452. interface, resolved_params, members);
  453. }
  454. ImplDeclaration::ImplDeclaration(CloneContext& context,
  455. const ImplDeclaration& other)
  456. : Declaration(context, other),
  457. kind_(other.kind_),
  458. deduced_parameters_(context.Clone(other.deduced_parameters_)),
  459. impl_type_(context.Clone(other.impl_type_)),
  460. self_decl_(context.Clone(other.self_decl_)),
  461. interface_(context.Clone(other.interface_)),
  462. constraint_type_(context.Clone(other.constraint_type_)),
  463. members_(context.Clone(other.members_)),
  464. impl_bindings_(context.Remap(other.impl_bindings_)),
  465. match_first_(context.Remap(other.match_first_)) {}
  466. void AlternativeSignature::Print(llvm::raw_ostream& out) const {
  467. out << "alt " << name();
  468. if (auto params = parameters()) {
  469. out << **params;
  470. }
  471. }
  472. void AlternativeSignature::PrintID(llvm::raw_ostream& out) const {
  473. out << name();
  474. }
  475. auto ChoiceDeclaration::FindAlternative(std::string_view name) const
  476. -> std::optional<const AlternativeSignature*> {
  477. for (const auto* alt : alternatives()) {
  478. if (alt->name() == name) {
  479. return alt;
  480. }
  481. }
  482. return std::nullopt;
  483. }
  484. MixDeclaration::MixDeclaration(CloneContext& context,
  485. const MixDeclaration& other)
  486. : Declaration(context, other),
  487. mixin_(context.Clone(other.mixin_)),
  488. mixin_value_(context.Clone(other.mixin_value_)) {}
  489. } // namespace Carbon