refactor: comments/annotations for Java

Removes duplicate code to generate comments/annotations.

When generating comments, newlines are appended only if necessary, which
removes unnecessary newlines in the output.

Bug: none
Test: aidl_unittests
Change-Id: I1df1302300e07045bab4d02b0f61b21b1152b5ae
diff --git a/ast_java.cpp b/ast_java.cpp
index 8604bc2..066624e 100644
--- a/ast_java.cpp
+++ b/ast_java.cpp
@@ -37,6 +37,11 @@
   return str;
 }
 
+void WriteComment(CodeWriter* to, const std::string& comment) {
+  to->Write("%s", comment.c_str());
+  if (!comment.empty() && comment.back() != '\n') to->Write("\n");
+}
+
 void WriteModifiers(CodeWriter* to, int mod, int mask) {
   int m = mod & mask;
 
@@ -78,9 +83,7 @@
 Field::Field(int m, std::shared_ptr<Variable> v) : ClassElement(), modifiers(m), variable(v) {}
 
 void Field::Write(CodeWriter* to) const {
-  if (this->comment.length() != 0) {
-    to->Write("%s\n", this->comment.c_str());
-  }
+  WriteComment(to, comment);
   for (const auto& a : this->annotations) {
     to->Write("%s\n", a.c_str());
   }
@@ -329,9 +332,7 @@
 void Method::Write(CodeWriter* to) const {
   size_t N, i;
 
-  if (this->comment.length() != 0) {
-    to->Write("%s\n", this->comment.c_str());
-  }
+  WriteComment(to, comment);
 
   for (const auto& a : this->annotations) {
     to->Write("%s\n", a.c_str());
@@ -381,9 +382,7 @@
 void Class::Write(CodeWriter* to) const {
   size_t N, i;
 
-  if (this->comment.length() != 0) {
-    to->Write("%s\n", this->comment.c_str());
-  }
+  WriteComment(to, comment);
   for (const auto& a : this->annotations) {
     to->Write("%s\n", a.c_str());
   }