declaration.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 ClassDefinition& class_def =
  15. cast<ClassDeclaration>(*this).definition();
  16. out << "class " << class_def.name() << " {\n";
  17. for (Nonnull<Member*> m : class_def.members()) {
  18. out << *m;
  19. }
  20. out << "}\n";
  21. break;
  22. }
  23. case Kind::ChoiceDeclaration: {
  24. const auto& choice = cast<ChoiceDeclaration>(*this);
  25. out << "choice " << choice.name() << " {\n";
  26. for (const auto& alt : 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 FunctionDeclaration::PrintDepth(int depth, llvm::raw_ostream& out) const {
  40. out << "fn " << name_ << " ";
  41. if (!deduced_parameters_.empty()) {
  42. out << "[";
  43. unsigned int i = 0;
  44. for (const auto& deduced : deduced_parameters_) {
  45. if (i != 0) {
  46. out << ", ";
  47. }
  48. out << deduced.name << ":! ";
  49. deduced.type->Print(out);
  50. ++i;
  51. }
  52. out << "]";
  53. }
  54. out << *param_pattern_;
  55. if (!is_omitted_return_type_) {
  56. out << " -> " << *return_type_;
  57. }
  58. if (body_) {
  59. out << " {\n";
  60. (*body_)->PrintDepth(depth, out);
  61. out << "\n}\n";
  62. } else {
  63. out << ";\n";
  64. }
  65. }
  66. } // namespace Carbon