declaration.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. void Declaration::Print(llvm::raw_ostream& out) const {
  9. switch (kind()) {
  10. case Kind::FunctionDeclaration:
  11. cast<FunctionDeclaration>(*this).PrintDepth(-1, out);
  12. break;
  13. case Kind::ClassDeclaration: {
  14. const auto& class_decl = cast<ClassDeclaration>(*this);
  15. out << "class " << class_decl.name() << " {\n";
  16. for (Nonnull<Member*> m : class_decl.members()) {
  17. out << *m;
  18. }
  19. out << "}\n";
  20. break;
  21. }
  22. case Kind::ChoiceDeclaration: {
  23. const auto& choice = cast<ChoiceDeclaration>(*this);
  24. out << "choice " << choice.name() << " {\n";
  25. for (Nonnull<const ChoiceDeclaration::Alternative*> alt :
  26. choice.alternatives()) {
  27. out << "alt " << alt->name() << " " << alt->signature() << ";\n";
  28. }
  29. out << "}\n";
  30. break;
  31. }
  32. case Kind::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