declaration.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 "executable_semantics/ast/declaration.h"
  5. #include "llvm/ADT/StringExtras.h"
  6. #include "llvm/Support/Casting.h"
  7. namespace Carbon {
  8. using llvm::cast;
  9. Declaration::~Declaration() = default;
  10. void Declaration::Print(llvm::raw_ostream& out) const {
  11. switch (kind()) {
  12. case DeclarationKind::FunctionDeclaration:
  13. cast<FunctionDeclaration>(*this).PrintDepth(-1, out);
  14. break;
  15. case DeclarationKind::ClassDeclaration: {
  16. const auto& class_decl = cast<ClassDeclaration>(*this);
  17. out << "class " << class_decl.name() << " {\n";
  18. for (Nonnull<Member*> m : class_decl.members()) {
  19. out << *m;
  20. }
  21. out << "}\n";
  22. break;
  23. }
  24. case DeclarationKind::ChoiceDeclaration: {
  25. const auto& choice = cast<ChoiceDeclaration>(*this);
  26. out << "choice " << choice.name() << " {\n";
  27. for (Nonnull<const AlternativeSignature*> alt : choice.alternatives()) {
  28. out << *alt << ";\n";
  29. }
  30. out << "}\n";
  31. break;
  32. }
  33. case DeclarationKind::VariableDeclaration: {
  34. const auto& var = cast<VariableDeclaration>(*this);
  35. out << "var " << var.binding() << " = " << var.initializer() << "\n";
  36. break;
  37. }
  38. }
  39. }
  40. void GenericBinding::Print(llvm::raw_ostream& out) const {
  41. out << name() << ":! " << type();
  42. }
  43. void ReturnTerm::Print(llvm::raw_ostream& out) const {
  44. switch (kind_) {
  45. case ReturnKind::Omitted:
  46. return;
  47. case ReturnKind::Auto:
  48. out << "-> auto";
  49. return;
  50. case ReturnKind::Expression:
  51. out << "-> " << **type_expression_;
  52. return;
  53. }
  54. }
  55. void FunctionDeclaration::PrintDepth(int depth, llvm::raw_ostream& out) const {
  56. out << "fn " << name_ << " ";
  57. if (!deduced_parameters_.empty()) {
  58. out << "[";
  59. llvm::ListSeparator sep;
  60. for (Nonnull<const GenericBinding*> deduced : deduced_parameters_) {
  61. out << sep << *deduced;
  62. }
  63. out << "]";
  64. }
  65. out << *param_pattern_ << return_term_;
  66. if (body_) {
  67. out << " {\n";
  68. (*body_)->PrintDepth(depth, out);
  69. out << "\n}\n";
  70. } else {
  71. out << ";\n";
  72. }
  73. }
  74. void AlternativeSignature::Print(llvm::raw_ostream& out) const {
  75. out << "alt " << name() << " " << signature();
  76. }
  77. } // namespace Carbon