declaration.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 (const auto& alt : choice.alternatives()) {
  26. out << "alt " << alt.name() << " " << alt.signature() << ";\n";
  27. }
  28. out << "}\n";
  29. break;
  30. }
  31. case Kind::VariableDeclaration: {
  32. const auto& var = cast<VariableDeclaration>(*this);
  33. out << "var " << var.binding() << " = " << var.initializer() << "\n";
  34. break;
  35. }
  36. }
  37. }
  38. void FunctionDeclaration::PrintDepth(int depth, llvm::raw_ostream& out) const {
  39. out << "fn " << name_ << " ";
  40. if (!deduced_parameters_.empty()) {
  41. out << "[";
  42. unsigned int i = 0;
  43. for (const auto& deduced : deduced_parameters_) {
  44. if (i != 0) {
  45. out << ", ";
  46. }
  47. out << deduced.name() << ":! ";
  48. deduced.type().Print(out);
  49. ++i;
  50. }
  51. out << "]";
  52. }
  53. out << *param_pattern_;
  54. if (!is_omitted_return_type_) {
  55. out << " -> " << *return_type_;
  56. }
  57. if (body_) {
  58. out << " {\n";
  59. (*body_)->PrintDepth(depth, out);
  60. out << "\n}\n";
  61. } else {
  62. out << ";\n";
  63. }
  64. }
  65. } // namespace Carbon