Extract DumpVisitor

Moving Dump*() methods from AIDL AST to its own visitor.

Bug: n/a
Test: m aidl_unittests
Change-Id: I61c1a978b5a50582daec930b92cc9be49c31c991
diff --git a/Android.bp b/Android.bp
index e52c5f1..f96608a 100644
--- a/Android.bp
+++ b/Android.bp
@@ -59,6 +59,7 @@
     srcs: [
         "aidl_checkapi.cpp",
         "aidl_const_expressions.cpp",
+        "aidl_dumpapi.cpp",
         "aidl_language_l.ll",
         "aidl_language_y.yy",
         "aidl_language.cpp",
diff --git a/aidl.cpp b/aidl.cpp
index 612a376..77c5f31 100644
--- a/aidl.cpp
+++ b/aidl.cpp
@@ -37,6 +37,7 @@
 #include <android-base/strings.h>
 
 #include "aidl_checkapi.h"
+#include "aidl_dumpapi.h"
 #include "aidl_language.h"
 #include "aidl_typenames.h"
 #include "generate_aidl_mappings.h"
@@ -890,40 +891,6 @@
   return writer->Close();
 }
 
-static string GetApiDumpPathFor(const AidlDefinedType& defined_type, const Options& options) {
-  string package_as_path = Join(Split(defined_type.GetPackage(), "."), OS_PATH_SEPARATOR);
-  AIDL_FATAL_IF(options.OutputDir().empty() || options.OutputDir().back() != '/', defined_type);
-  return options.OutputDir() + package_as_path + OS_PATH_SEPARATOR + defined_type.GetName() +
-         ".aidl";
-}
-
-bool dump_api(const Options& options, const IoDelegate& io_delegate) {
-  for (const auto& file : options.InputFiles()) {
-    AidlTypenames typenames;
-    if (internals::load_and_validate_aidl(file, options, io_delegate, &typenames, nullptr) ==
-        AidlError::OK) {
-      const auto& doc = typenames.MainDocument();
-
-      for (const auto& type : doc.DefinedTypes()) {
-        unique_ptr<CodeWriter> writer =
-            io_delegate.GetCodeWriter(GetApiDumpPathFor(*type, options));
-        // dump doc comments (license) as well for each type
-        for (const auto& c : doc.GetComments()) {
-          (*writer) << c.body;
-        }
-        (*writer) << kPreamble;
-        if (!type->GetPackage().empty()) {
-          (*writer) << "package " << type->GetPackage() << ";\n";
-        }
-        type->Dump(writer.get());
-      }
-    } else {
-      return false;
-    }
-  }
-  return true;
-}
-
 int aidl_entry(const Options& options, const IoDelegate& io_delegate) {
   AidlErrorLog::clearError();
 
diff --git a/aidl.h b/aidl.h
index 22bd2f7..1ff8d46 100644
--- a/aidl.h
+++ b/aidl.h
@@ -47,7 +47,6 @@
 
 int compile_aidl(const Options& options, const IoDelegate& io_delegate);
 bool preprocess_aidl(const Options& options, const IoDelegate& io_delegate);
-bool dump_api(const Options& options, const IoDelegate& io_delegate);
 bool dump_mappings(const Options& options, const IoDelegate& io_delegate);
 
 // main entry point to AIDL
diff --git a/aidl_checkapi.cpp b/aidl_checkapi.cpp
index 6337f8e..f07e7e6 100644
--- a/aidl_checkapi.cpp
+++ b/aidl_checkapi.cpp
@@ -15,10 +15,6 @@
  */
 
 #include "aidl.h"
-#include "aidl_language.h"
-#include "import_resolver.h"
-#include "logging.h"
-#include "options.h"
 
 #include <map>
 #include <string>
@@ -28,6 +24,12 @@
 #include <android-base/strings.h>
 #include <gtest/gtest.h>
 
+#include "aidl_dumpapi.h"
+#include "aidl_language.h"
+#include "import_resolver.h"
+#include "logging.h"
+#include "options.h"
+
 namespace android {
 namespace aidl {
 
@@ -40,9 +42,12 @@
 using std::vector;
 
 static std::string Dump(const AidlDefinedType& type) {
-  std::string dump;
-  type.Dump(CodeWriter::ForString(&dump).get());
-  return dump;
+  string code;
+  CodeWriterPtr out = CodeWriter::ForString(&code);
+  DumpVisitor visitor(*out);
+  type.DispatchVisit(visitor);
+  out->Close();
+  return code;
 }
 
 // Uses each type's Dump() and GTest utility(EqHelper).
diff --git a/aidl_dumpapi.cpp b/aidl_dumpapi.cpp
new file mode 100644
index 0000000..ae970ea
--- /dev/null
+++ b/aidl_dumpapi.cpp
@@ -0,0 +1,180 @@
+/*
+ * Copyright (C) 2021, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "aidl_dumpapi.h"
+
+#include <android-base/strings.h>
+
+#include "aidl.h"
+#include "logging.h"
+#include "os.h"
+
+using android::base::Join;
+using android::base::Split;
+using std::string;
+using std::unique_ptr;
+
+namespace android {
+namespace aidl {
+
+void DumpVisitor::DumpType(const AidlDefinedType& dt, const string& type) {
+  DumpComments(dt);
+  DumpAnnotations(dt);
+  out << type << " " << dt.GetName() << " {\n";
+  out.Indent();
+  DumpMembers(dt);
+  out.Dedent();
+  out << "}\n";
+}
+
+void DumpVisitor::DumpMembers(const AidlDefinedType& dt) {
+  for (const auto& method : dt.GetMethods()) {
+    if (!method->IsUserDefined()) continue;
+    method->DispatchVisit(*this);
+  }
+  for (const auto& field : dt.GetFields()) {
+    field->DispatchVisit(*this);
+  }
+  for (const auto& constdecl : dt.GetConstantDeclarations()) {
+    constdecl->DispatchVisit(*this);
+  }
+}
+
+// Dumps comment only if its has meaningful tags.
+void DumpVisitor::DumpComments(const AidlCommentable& c) {
+  const auto hidden = c.IsHidden();
+  const auto deprecated = FindDeprecated(c.GetComments());
+  if (hidden || deprecated) {
+    out << "/**\n";
+    if (hidden) {
+      out << " * @hide\n";
+    }
+    if (deprecated) {
+      out << " * @deprecated " << deprecated->note << "\n";
+    }
+    out << " */\n";
+  }
+}
+
+void DumpVisitor::DumpAnnotations(const AidlAnnotatable& a) {
+  auto annotations = a.ToString();
+  if (!annotations.empty()) {
+    out << annotations << "\n";
+  }
+}
+
+void DumpVisitor::DumpConstantValue(const AidlTypeSpecifier& type, const AidlConstantValue& c) {
+  out << c.ValueString(type, AidlConstantValueDecorator);
+}
+
+void DumpVisitor::Visit(const AidlInterface& t) {
+  DumpType(t, "interface");
+}
+void DumpVisitor::Visit(const AidlParcelable& t) {
+  DumpType(t, "parcelable");
+}
+void DumpVisitor::Visit(const AidlStructuredParcelable& t) {
+  DumpType(t, "parcelable");
+}
+void DumpVisitor::Visit(const AidlUnionDecl& t) {
+  DumpType(t, "union");
+}
+void DumpVisitor::Visit(const AidlEnumDeclaration& t) {
+  DumpComments(t);
+  DumpAnnotations(t);
+  out << "enum " << t.GetName() << " {\n";
+  out.Indent();
+  for (const auto& e : t.GetEnumerators()) {
+    out << e->GetName() << " = ";
+    DumpConstantValue(t.GetBackingType(), *e->GetValue());
+    out << ",\n";
+  }
+  out.Dedent();
+  out << "}\n";
+}
+
+void DumpVisitor::Visit(const AidlMethod& m) {
+  DumpComments(m);
+  out << m.ToString() << ";\n";
+}
+void DumpVisitor::Visit(const AidlVariableDeclaration& v) {
+  DumpComments(v);
+  Visit(v.GetType());
+  if (v.IsDefaultUserSpecified()) {
+    out << " " << v.GetName() << " = ";
+    DumpConstantValue(v.GetType(), *v.GetDefaultValue());
+    out << ";\n";
+  } else {
+    out << " " << v.GetName() << ";\n";
+  }
+}
+void DumpVisitor::Visit(const AidlConstantDeclaration& c) {
+  DumpComments(c);
+  out << "const ";
+  Visit(c.GetType());
+  out << " " << c.GetName() << " = ";
+  DumpConstantValue(c.GetType(), c.GetValue());
+  out << ";\n";
+}
+
+void DumpVisitor::Visit(const AidlEnumerator& e) {
+  out << e.GetName() << " = ";
+
+  e.GetValue()->DispatchVisit(*this);
+  out << ",\n";
+}
+
+void DumpVisitor::Visit(const AidlTypeSpecifier& t) {
+  out << t.ToString();
+}
+
+static string GetApiDumpPathFor(const AidlDefinedType& defined_type, const Options& options) {
+  string package_as_path = Join(Split(defined_type.GetPackage(), "."), OS_PATH_SEPARATOR);
+  AIDL_FATAL_IF(options.OutputDir().empty() || options.OutputDir().back() != '/', defined_type);
+  return options.OutputDir() + package_as_path + OS_PATH_SEPARATOR + defined_type.GetName() +
+         ".aidl";
+}
+
+bool dump_api(const Options& options, const IoDelegate& io_delegate) {
+  for (const auto& file : options.InputFiles()) {
+    AidlTypenames typenames;
+    if (internals::load_and_validate_aidl(file, options, io_delegate, &typenames, nullptr) ==
+        AidlError::OK) {
+      const auto& doc = typenames.MainDocument();
+
+      for (const auto& type : doc.DefinedTypes()) {
+        unique_ptr<CodeWriter> writer =
+            io_delegate.GetCodeWriter(GetApiDumpPathFor(*type, options));
+        // dump doc comments (license) as well for each type
+        for (const auto& c : doc.GetComments()) {
+          (*writer) << c.body;
+        }
+        (*writer) << kPreamble;
+        if (!type->GetPackage().empty()) {
+          (*writer) << "package " << type->GetPackage() << ";\n";
+        }
+        DumpVisitor visitor(*writer);
+        type->DispatchVisit(visitor);
+      }
+    } else {
+      return false;
+    }
+  }
+  return true;
+}
+
+}  // namespace aidl
+}  // namespace android
\ No newline at end of file
diff --git a/aidl_dumpapi.h b/aidl_dumpapi.h
new file mode 100644
index 0000000..f30c54a
--- /dev/null
+++ b/aidl_dumpapi.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2021, The Android Open Source Project *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include "aidl_language.h"
+#include "code_writer.h"
+
+namespace android {
+namespace aidl {
+
+struct DumpVisitor : AidlVisitor {
+  CodeWriter& out;
+  DumpVisitor(CodeWriter& out) : out(out) {}
+
+  void DumpType(const AidlDefinedType& dt, const string& type);
+  void DumpMembers(const AidlDefinedType& dt);
+  void DumpComments(const AidlCommentable& c);
+  void DumpAnnotations(const AidlAnnotatable& a);
+  void DumpConstantValue(const AidlTypeSpecifier& type, const AidlConstantValue& c);
+
+  void Visit(const AidlInterface& t) override;
+  void Visit(const AidlParcelable& t) override;
+  void Visit(const AidlStructuredParcelable& t) override;
+  void Visit(const AidlUnionDecl& t) override;
+  void Visit(const AidlEnumDeclaration& t) override;
+  void Visit(const AidlMethod& m) override;
+  void Visit(const AidlVariableDeclaration& v) override;
+  void Visit(const AidlConstantDeclaration& c) override;
+  void Visit(const AidlEnumerator& e) override;
+  void Visit(const AidlTypeSpecifier& t) override;
+};
+
+bool dump_api(const Options& options, const IoDelegate& io_delegate);
+
+}  // namespace aidl
+}  // namespace android
diff --git a/aidl_language.cpp b/aidl_language.cpp
index f06b8a4..1616f22 100644
--- a/aidl_language.cpp
+++ b/aidl_language.cpp
@@ -411,12 +411,6 @@
   return "";
 }
 
-void AidlAnnotatable::DumpAnnotations(CodeWriter* writer) const {
-  if (annotations_.empty()) return;
-
-  writer->Write("%s\n", AidlAnnotatable::ToString().c_str());
-}
-
 bool AidlAnnotatable::CheckValid(const AidlTypenames&) const {
   for (const auto& annotation : GetAnnotations()) {
     if (!annotation.CheckValid()) {
@@ -766,23 +760,6 @@
   return android::aidl::FindDeprecated(GetComments()).has_value();
 }
 
-// Dumps comment only if its has meaningful tags.
-void AidlCommentable::DumpComments(CodeWriter& out) const {
-  using namespace android::aidl;
-  const auto hidden = IsHidden();
-  const auto deprecated = FindDeprecated(GetComments());
-  if (hidden || deprecated) {
-    out << "/**\n";
-    if (hidden) {
-      out << " * @hide\n";
-    }
-    if (deprecated) {
-      out << " * @deprecated " << deprecated->note << "\n";
-    }
-    out << " */\n";
-  }
-}
-
 AidlMember::AidlMember(const AidlLocation& location, const Comments& comments)
     : AidlCommentable(location, comments) {}
 
@@ -903,26 +880,6 @@
   return GetPackage() + "." + GetName();
 }
 
-void AidlDefinedType::DumpHeader(CodeWriter* writer) const {
-  DumpComments(*writer);
-  DumpAnnotations(writer);
-}
-
-void AidlDefinedType::DumpMembers(CodeWriter& out) const {
-  for (const auto& method : GetMethods()) {
-    method->DumpComments(out);
-    out << method->ToString() << ";\n";
-  }
-  for (const auto& field : GetFields()) {
-    field->DumpComments(out);
-    out << field->ToString() << ";\n";
-  }
-  for (const auto& constdecl : GetConstantDeclarations()) {
-    constdecl->DumpComments(out);
-    out << constdecl->ToString() << ";\n";
-  }
-}
-
 bool AidlDefinedType::CheckValidWithMembers(const AidlTypenames& typenames) const {
   bool success = true;
 
@@ -1028,26 +985,12 @@
   return true;
 }
 
-void AidlParcelable::Dump(CodeWriter* writer) const {
-  DumpHeader(writer);
-  writer->Write("parcelable %s ;\n", GetName().c_str());
-}
-
 AidlStructuredParcelable::AidlStructuredParcelable(
     const AidlLocation& location, const std::string& name, const std::string& package,
     const Comments& comments, std::vector<std::string>* type_params,
     std::vector<std::unique_ptr<AidlMember>>* members)
     : AidlParcelable(location, name, package, comments, "" /*cpp_header*/, type_params, members) {}
 
-void AidlStructuredParcelable::Dump(CodeWriter* writer) const {
-  DumpHeader(writer);
-  writer->Write("parcelable %s {\n", GetName().c_str());
-  writer->Indent();
-  DumpMembers(*writer);
-  writer->Dedent();
-  writer->Write("}\n");
-}
-
 bool AidlStructuredParcelable::CheckValid(const AidlTypenames& typenames) const {
   if (!AidlParcelable::CheckValid(typenames)) {
     return false;
@@ -1275,33 +1218,12 @@
   return success;
 }
 
-void AidlEnumDeclaration::Dump(CodeWriter* writer) const {
-  DumpHeader(writer);
-  writer->Write("enum %s {\n", GetName().c_str());
-  writer->Indent();
-  for (const auto& enumerator : GetEnumerators()) {
-    writer->Write("%s = %s,\n", enumerator->GetName().c_str(),
-                  enumerator->ValueString(GetBackingType(), AidlConstantValueDecorator).c_str());
-  }
-  writer->Dedent();
-  writer->Write("}\n");
-}
-
 AidlUnionDecl::AidlUnionDecl(const AidlLocation& location, const std::string& name,
                              const std::string& package, const Comments& comments,
                              std::vector<std::string>* type_params,
                              std::vector<std::unique_ptr<AidlMember>>* members)
     : AidlParcelable(location, name, package, comments, "" /*cpp_header*/, type_params, members) {}
 
-void AidlUnionDecl::Dump(CodeWriter* writer) const {
-  DumpHeader(writer);
-  writer->Write("union %s {\n", GetName().c_str());
-  writer->Indent();
-  DumpMembers(*writer);
-  writer->Dedent();
-  writer->Write("}\n");
-}
-
 bool AidlUnionDecl::CheckValid(const AidlTypenames& typenames) const {
   // visit parents
   if (!AidlParcelable::CheckValid(typenames)) {
@@ -1394,15 +1316,6 @@
   }
 }
 
-void AidlInterface::Dump(CodeWriter* writer) const {
-  DumpHeader(writer);
-  writer->Write("interface %s {\n", GetName().c_str());
-  writer->Indent();
-  DumpMembers(*writer);
-  writer->Dedent();
-  writer->Write("}\n");
-}
-
 bool AidlInterface::CheckValid(const AidlTypenames& typenames) const {
   if (!AidlDefinedType::CheckValid(typenames)) {
     return false;
diff --git a/aidl_language.h b/aidl_language.h
index ca45103..d223740 100644
--- a/aidl_language.h
+++ b/aidl_language.h
@@ -189,7 +189,6 @@
 
   bool IsHidden() const;
   bool IsDeprecated() const;
-  void DumpComments(CodeWriter& out) const;
 };
 
 // Transforms a value string into a language specific form. Raw value as produced by
@@ -328,8 +327,6 @@
   bool JavaDerive(const std::string& method) const;
   std::string GetDescriptor() const;
 
-  void DumpAnnotations(CodeWriter* writer) const;
-
   const AidlAnnotation* UnsupportedAppUsage() const;
   const AidlAnnotation* RustDerive() const;
   const AidlAnnotation* BackingType() const;
@@ -950,10 +947,6 @@
         const_cast<const AidlDefinedType*>(this)->AsUnstructuredParcelable());
   }
 
-  virtual void Dump(CodeWriter* writer) const = 0;
-  void DumpHeader(CodeWriter* writer) const;
-  void DumpMembers(CodeWriter& out) const;
-
   const std::vector<std::unique_ptr<AidlVariableDeclaration>>& GetFields() const {
     return variables_;
   }
@@ -1010,8 +1003,6 @@
   const AidlNode& AsAidlNode() const override { return *this; }
   std::string GetPreprocessDeclarationName() const override { return "parcelable"; }
 
-  void Dump(CodeWriter* writer) const override;
-
   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
 
  private:
@@ -1035,8 +1026,6 @@
   const AidlStructuredParcelable* AsStructuredParcelable() const override { return this; }
   std::string GetPreprocessDeclarationName() const override { return "structured_parcelable"; }
 
-  void Dump(CodeWriter* writer) const override;
-
   bool CheckValid(const AidlTypenames& typenames) const override;
   bool LanguageSpecificCheckValid(const AidlTypenames& typenames,
                                   Options::Language lang) const override;
@@ -1101,7 +1090,6 @@
     return true;
   }
   std::string GetPreprocessDeclarationName() const override { return "enum"; }
-  void Dump(CodeWriter* writer) const override;
 
   const AidlEnumDeclaration* AsEnumDeclaration() const override { return this; }
 
@@ -1140,7 +1128,6 @@
                                   Options::Language lang) const override;
   std::string GetPreprocessDeclarationName() const override { return "union"; }
 
-  void Dump(CodeWriter* writer) const override;
   const AidlUnionDecl* AsUnionDeclaration() const override { return this; }
   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
 };
@@ -1161,8 +1148,6 @@
   const AidlInterface* AsInterface() const override { return this; }
   std::string GetPreprocessDeclarationName() const override { return "interface"; }
 
-  void Dump(CodeWriter* writer) const override;
-
   bool CheckValid(const AidlTypenames& typenames) const override;
   bool LanguageSpecificCheckValid(const AidlTypenames& typenames,
                                   Options::Language lang) const override;
diff --git a/aidl_unittest.cpp b/aidl_unittest.cpp
index 6d67b7d..05008c9 100644
--- a/aidl_unittest.cpp
+++ b/aidl_unittest.cpp
@@ -28,6 +28,7 @@
 #include <vector>
 
 #include "aidl_checkapi.h"
+#include "aidl_dumpapi.h"
 #include "aidl_language.h"
 #include "aidl_to_cpp.h"
 #include "aidl_to_java.h"
@@ -3517,7 +3518,10 @@
   EXPECT_TRUE(type);
   const auto& enum_type = type->AsEnumDeclaration();
   string code;
-  enum_type->Dump(CodeWriter::ForString(&code).get());
+  auto writer = CodeWriter::ForString(&code);
+  DumpVisitor visitor(*writer);
+  visitor.Visit(*enum_type);
+  writer->Close();
   EXPECT_EQ(R"--(@Backing(type="int")
 enum Foo {
   STANDARD_SHIFT = 16,