declaration.cpp 2.2 KB

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