AAPT2: Rename to match new style
Use Google3 naming style to match new
projects' and open source google projects' style.
Preferred to do this in a massive CL so as to avoid
style inconsistencies that plague legacy code bases.
This is a relatively NEW code base, may as well keep
it up to date.
Test: name/style refactor - existing tests pass
Change-Id: Ie80ecb78d46ec53efdfca2336bb57d96cbb7fb87
diff --git a/tools/aapt2/java/AnnotationProcessor.cpp b/tools/aapt2/java/AnnotationProcessor.cpp
index 23ff8ab..2951e5c 100644
--- a/tools/aapt2/java/AnnotationProcessor.cpp
+++ b/tools/aapt2/java/AnnotationProcessor.cpp
@@ -15,69 +15,71 @@
*/
#include "java/AnnotationProcessor.h"
-#include "util/Util.h"
#include <algorithm>
+#include "util/Util.h"
+
namespace aapt {
-void AnnotationProcessor::appendCommentLine(std::string& comment) {
- static const std::string sDeprecated = "@deprecated";
- static const std::string sSystemApi = "@SystemApi";
+void AnnotationProcessor::AppendCommentLine(std::string& comment) {
+ static const std::string sDeprecated = "@deprecated";
+ static const std::string sSystemApi = "@SystemApi";
- if (comment.find(sDeprecated) != std::string::npos) {
- mAnnotationBitMask |= kDeprecated;
- }
+ if (comment.find(sDeprecated) != std::string::npos) {
+ annotation_bit_mask_ |= kDeprecated;
+ }
- std::string::size_type idx = comment.find(sSystemApi);
- if (idx != std::string::npos) {
- mAnnotationBitMask |= kSystemApi;
- comment.erase(comment.begin() + idx, comment.begin() + idx + sSystemApi.size());
- }
+ std::string::size_type idx = comment.find(sSystemApi);
+ if (idx != std::string::npos) {
+ annotation_bit_mask_ |= kSystemApi;
+ comment.erase(comment.begin() + idx,
+ comment.begin() + idx + sSystemApi.size());
+ }
- if (util::trimWhitespace(comment).empty()) {
- return;
- }
+ if (util::TrimWhitespace(comment).empty()) {
+ return;
+ }
- if (!mHasComments) {
- mHasComments = true;
- mComment << "/**";
- }
+ if (!has_comments_) {
+ has_comments_ = true;
+ comment_ << "/**";
+ }
- mComment << "\n * " << std::move(comment);
+ comment_ << "\n * " << std::move(comment);
}
-void AnnotationProcessor::appendComment(const StringPiece& comment) {
- // We need to process line by line to clean-up whitespace and append prefixes.
- for (StringPiece line : util::tokenize(comment, '\n')) {
- line = util::trimWhitespace(line);
- if (!line.empty()) {
- std::string lineCopy = line.toString();
- appendCommentLine(lineCopy);
- }
+void AnnotationProcessor::AppendComment(const StringPiece& comment) {
+ // We need to process line by line to clean-up whitespace and append prefixes.
+ for (StringPiece line : util::Tokenize(comment, '\n')) {
+ line = util::TrimWhitespace(line);
+ if (!line.empty()) {
+ std::string lineCopy = line.ToString();
+ AppendCommentLine(lineCopy);
}
+ }
}
-void AnnotationProcessor::appendNewLine() {
- mComment << "\n *";
+void AnnotationProcessor::AppendNewLine() { comment_ << "\n *"; }
+
+void AnnotationProcessor::WriteToStream(std::ostream* out,
+ const StringPiece& prefix) const {
+ if (has_comments_) {
+ std::string result = comment_.str();
+ for (StringPiece line : util::Tokenize(result, '\n')) {
+ *out << prefix << line << "\n";
+ }
+ *out << prefix << " */"
+ << "\n";
+ }
+
+ if (annotation_bit_mask_ & kDeprecated) {
+ *out << prefix << "@Deprecated\n";
+ }
+
+ if (annotation_bit_mask_ & kSystemApi) {
+ *out << prefix << "@android.annotation.SystemApi\n";
+ }
}
-void AnnotationProcessor::writeToStream(std::ostream* out, const StringPiece& prefix) const {
- if (mHasComments) {
- std::string result = mComment.str();
- for (StringPiece line : util::tokenize(result, '\n')) {
- *out << prefix << line << "\n";
- }
- *out << prefix << " */" << "\n";
- }
-
- if (mAnnotationBitMask & kDeprecated) {
- *out << prefix << "@Deprecated\n";
- }
-
- if (mAnnotationBitMask & kSystemApi) {
- *out << prefix << "@android.annotation.SystemApi\n";
- }
-}
-
-} // namespace aapt
+} // namespace aapt
diff --git a/tools/aapt2/java/AnnotationProcessor.h b/tools/aapt2/java/AnnotationProcessor.h
index 5419608..666a7f3 100644
--- a/tools/aapt2/java/AnnotationProcessor.h
+++ b/tools/aapt2/java/AnnotationProcessor.h
@@ -17,11 +17,11 @@
#ifndef AAPT_JAVA_ANNOTATIONPROCESSOR_H
#define AAPT_JAVA_ANNOTATIONPROCESSOR_H
-#include "util/StringPiece.h"
-
#include <sstream>
#include <string>
+#include "util/StringPiece.h"
+
namespace aapt {
/**
@@ -58,15 +58,15 @@
* configurations,
* we need to collect all the comments.
*/
- void appendComment(const StringPiece& comment);
+ void AppendComment(const StringPiece& comment);
- void appendNewLine();
+ void AppendNewLine();
/**
* Writes the comments and annotations to the stream, with the given prefix
* before each line.
*/
- void writeToStream(std::ostream* out, const StringPiece& prefix) const;
+ void WriteToStream(std::ostream* out, const StringPiece& prefix) const;
private:
enum : uint32_t {
@@ -74,12 +74,12 @@
kSystemApi = 0x02,
};
- std::stringstream mComment;
+ std::stringstream comment_;
std::stringstream mAnnotations;
- bool mHasComments = false;
- uint32_t mAnnotationBitMask = 0;
+ bool has_comments_ = false;
+ uint32_t annotation_bit_mask_ = 0;
- void appendCommentLine(std::string& line);
+ void AppendCommentLine(std::string& line);
};
} // namespace aapt
diff --git a/tools/aapt2/java/AnnotationProcessor_test.cpp b/tools/aapt2/java/AnnotationProcessor_test.cpp
index 5a39add..3e43c42 100644
--- a/tools/aapt2/java/AnnotationProcessor_test.cpp
+++ b/tools/aapt2/java/AnnotationProcessor_test.cpp
@@ -15,38 +15,39 @@
*/
#include "java/AnnotationProcessor.h"
+
#include "test/Test.h"
namespace aapt {
TEST(AnnotationProcessorTest, EmitsDeprecated) {
- const char* comment = "Some comment, and it should contain a marker word, "
- "something that marks this resource as nor needed. "
- "{@deprecated That's the marker! }";
+ const char* comment =
+ "Some comment, and it should contain a marker word, "
+ "something that marks this resource as nor needed. "
+ "{@deprecated That's the marker! }";
- AnnotationProcessor processor;
- processor.appendComment(comment);
+ AnnotationProcessor processor;
+ processor.AppendComment(comment);
- std::stringstream result;
- processor.writeToStream(&result, "");
- std::string annotations = result.str();
+ std::stringstream result;
+ processor.WriteToStream(&result, "");
+ std::string annotations = result.str();
- EXPECT_NE(std::string::npos, annotations.find("@Deprecated"));
+ EXPECT_NE(std::string::npos, annotations.find("@Deprecated"));
}
TEST(AnnotationProcessorTest, EmitsSystemApiAnnotationAndRemovesFromComment) {
- AnnotationProcessor processor;
- processor.appendComment("@SystemApi This is a system API");
+ AnnotationProcessor processor;
+ processor.AppendComment("@SystemApi This is a system API");
- std::stringstream result;
- processor.writeToStream(&result, "");
- std::string annotations = result.str();
+ std::stringstream result;
+ processor.WriteToStream(&result, "");
+ std::string annotations = result.str();
- EXPECT_NE(std::string::npos, annotations.find("@android.annotation.SystemApi"));
- EXPECT_EQ(std::string::npos, annotations.find("@SystemApi"));
- EXPECT_NE(std::string::npos, annotations.find("This is a system API"));
+ EXPECT_NE(std::string::npos,
+ annotations.find("@android.annotation.SystemApi"));
+ EXPECT_EQ(std::string::npos, annotations.find("@SystemApi"));
+ EXPECT_NE(std::string::npos, annotations.find("This is a system API"));
}
-} // namespace aapt
-
-
+} // namespace aapt
diff --git a/tools/aapt2/java/ClassDefinition.cpp b/tools/aapt2/java/ClassDefinition.cpp
index 08f2c8b..f1f1f92 100644
--- a/tools/aapt2/java/ClassDefinition.cpp
+++ b/tools/aapt2/java/ClassDefinition.cpp
@@ -15,61 +15,59 @@
*/
#include "java/ClassDefinition.h"
-#include "util/StringPiece.h"
-#include <ostream>
+#include "util/StringPiece.h"
namespace aapt {
bool ClassDefinition::empty() const {
- for (const std::unique_ptr<ClassMember>& member : mMembers) {
- if (!member->empty()) {
- return false;
- }
+ for (const std::unique_ptr<ClassMember>& member : members_) {
+ if (!member->empty()) {
+ return false;
}
- return true;
+ }
+ return true;
}
-void ClassDefinition::writeToStream(const StringPiece& prefix, bool final,
+void ClassDefinition::WriteToStream(const StringPiece& prefix, bool final,
std::ostream* out) const {
- if (mMembers.empty() && !mCreateIfEmpty) {
- return;
- }
+ if (members_.empty() && !create_if_empty_) {
+ return;
+ }
- ClassMember::writeToStream(prefix, final, out);
+ ClassMember::WriteToStream(prefix, final, out);
- *out << prefix << "public ";
- if (mQualifier == ClassQualifier::Static) {
- *out << "static ";
- }
- *out << "final class " << mName << " {\n";
+ *out << prefix << "public ";
+ if (qualifier_ == ClassQualifier::Static) {
+ *out << "static ";
+ }
+ *out << "final class " << name_ << " {\n";
- std::string newPrefix = prefix.toString();
- newPrefix.append(kIndent);
+ std::string new_prefix = prefix.ToString();
+ new_prefix.append(kIndent);
- for (const std::unique_ptr<ClassMember>& member : mMembers) {
- member->writeToStream(newPrefix, final, out);
- *out << "\n";
- }
+ for (const std::unique_ptr<ClassMember>& member : members_) {
+ member->WriteToStream(new_prefix, final, out);
+ *out << "\n";
+ }
- *out << prefix << "}";
+ *out << prefix << "}";
}
constexpr static const char* sWarningHeader =
- "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
- " *\n"
- " * This class was automatically generated by the\n"
- " * aapt tool from the resource data it found. It\n"
- " * should not be modified by hand.\n"
- " */\n\n";
+ "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
+ " *\n"
+ " * This class was automatically generated by the\n"
+ " * aapt tool from the resource data it found. It\n"
+ " * should not be modified by hand.\n"
+ " */\n\n";
-bool ClassDefinition::writeJavaFile(const ClassDefinition* def,
- const StringPiece& package,
- bool final,
+bool ClassDefinition::WriteJavaFile(const ClassDefinition* def,
+ const StringPiece& package, bool final,
std::ostream* out) {
- *out << sWarningHeader << "package " << package << ";\n\n";
- def->writeToStream("", final, out);
- return bool(*out);
+ *out << sWarningHeader << "package " << package << ";\n\n";
+ def->WriteToStream("", final, out);
+ return bool(*out);
}
-} // namespace aapt
+} // namespace aapt
diff --git a/tools/aapt2/java/ClassDefinition.h b/tools/aapt2/java/ClassDefinition.h
index bd7e7b2..d8b61d9 100644
--- a/tools/aapt2/java/ClassDefinition.h
+++ b/tools/aapt2/java/ClassDefinition.h
@@ -17,15 +17,16 @@
#ifndef AAPT_JAVA_CLASSDEFINITION_H
#define AAPT_JAVA_CLASSDEFINITION_H
+#include <ostream>
+#include <string>
+
+#include "android-base/macros.h"
+
#include "Resource.h"
#include "java/AnnotationProcessor.h"
#include "util/StringPiece.h"
#include "util/Util.h"
-#include <android-base/macros.h>
-#include <sstream>
-#include <string>
-
namespace aapt {
// The number of attributes to emit per line in a Styleable array.
@@ -36,38 +37,38 @@
public:
virtual ~ClassMember() = default;
- AnnotationProcessor* getCommentBuilder() { return &mProcessor; }
+ AnnotationProcessor* GetCommentBuilder() { return &processor_; }
virtual bool empty() const = 0;
- virtual void writeToStream(const StringPiece& prefix, bool final,
+ virtual void WriteToStream(const StringPiece& prefix, bool final,
std::ostream* out) const {
- mProcessor.writeToStream(out, prefix);
+ processor_.WriteToStream(out, prefix);
}
private:
- AnnotationProcessor mProcessor;
+ AnnotationProcessor processor_;
};
template <typename T>
class PrimitiveMember : public ClassMember {
public:
PrimitiveMember(const StringPiece& name, const T& val)
- : mName(name.toString()), mVal(val) {}
+ : name_(name.ToString()), val_(val) {}
bool empty() const override { return false; }
- void writeToStream(const StringPiece& prefix, bool final,
+ void WriteToStream(const StringPiece& prefix, bool final,
std::ostream* out) const override {
- ClassMember::writeToStream(prefix, final, out);
+ ClassMember::WriteToStream(prefix, final, out);
*out << prefix << "public static " << (final ? "final " : "") << "int "
- << mName << "=" << mVal << ";";
+ << name_ << "=" << val_ << ";";
}
private:
- std::string mName;
- T mVal;
+ std::string name_;
+ T val_;
DISALLOW_COPY_AND_ASSIGN(PrimitiveMember);
};
@@ -79,21 +80,21 @@
class PrimitiveMember<std::string> : public ClassMember {
public:
PrimitiveMember(const StringPiece& name, const std::string& val)
- : mName(name.toString()), mVal(val) {}
+ : name_(name.ToString()), val_(val) {}
bool empty() const override { return false; }
- void writeToStream(const StringPiece& prefix, bool final,
+ void WriteToStream(const StringPiece& prefix, bool final,
std::ostream* out) const override {
- ClassMember::writeToStream(prefix, final, out);
+ ClassMember::WriteToStream(prefix, final, out);
*out << prefix << "public static " << (final ? "final " : "") << "String "
- << mName << "=\"" << mVal << "\";";
+ << name_ << "=\"" << val_ << "\";";
}
private:
- std::string mName;
- std::string mVal;
+ std::string name_;
+ std::string val_;
DISALLOW_COPY_AND_ASSIGN(PrimitiveMember);
};
@@ -106,20 +107,20 @@
class PrimitiveArrayMember : public ClassMember {
public:
explicit PrimitiveArrayMember(const StringPiece& name)
- : mName(name.toString()) {}
+ : name_(name.ToString()) {}
- void addElement(const T& val) { mElements.push_back(val); }
+ void AddElement(const T& val) { elements_.push_back(val); }
bool empty() const override { return false; }
- void writeToStream(const StringPiece& prefix, bool final,
+ void WriteToStream(const StringPiece& prefix, bool final,
std::ostream* out) const override {
- ClassMember::writeToStream(prefix, final, out);
+ ClassMember::WriteToStream(prefix, final, out);
- *out << prefix << "public static final int[] " << mName << "={";
+ *out << prefix << "public static final int[] " << name_ << "={";
- const auto begin = mElements.begin();
- const auto end = mElements.end();
+ const auto begin = elements_.begin();
+ const auto end = elements_.end();
for (auto current = begin; current != end; ++current) {
if (std::distance(begin, current) % kAttribsPerLine == 0) {
*out << "\n" << prefix << kIndent << kIndent;
@@ -134,8 +135,8 @@
}
private:
- std::string mName;
- std::vector<T> mElements;
+ std::string name_;
+ std::vector<T> elements_;
DISALLOW_COPY_AND_ASSIGN(PrimitiveArrayMember);
};
@@ -146,29 +147,29 @@
class ClassDefinition : public ClassMember {
public:
- static bool writeJavaFile(const ClassDefinition* def,
+ static bool WriteJavaFile(const ClassDefinition* def,
const StringPiece& package, bool final,
std::ostream* out);
ClassDefinition(const StringPiece& name, ClassQualifier qualifier,
bool createIfEmpty)
- : mName(name.toString()),
- mQualifier(qualifier),
- mCreateIfEmpty(createIfEmpty) {}
+ : name_(name.ToString()),
+ qualifier_(qualifier),
+ create_if_empty_(createIfEmpty) {}
- void addMember(std::unique_ptr<ClassMember> member) {
- mMembers.push_back(std::move(member));
+ void AddMember(std::unique_ptr<ClassMember> member) {
+ members_.push_back(std::move(member));
}
bool empty() const override;
- void writeToStream(const StringPiece& prefix, bool final,
+ void WriteToStream(const StringPiece& prefix, bool final,
std::ostream* out) const override;
private:
- std::string mName;
- ClassQualifier mQualifier;
- bool mCreateIfEmpty;
- std::vector<std::unique_ptr<ClassMember>> mMembers;
+ std::string name_;
+ ClassQualifier qualifier_;
+ bool create_if_empty_;
+ std::vector<std::unique_ptr<ClassMember>> members_;
DISALLOW_COPY_AND_ASSIGN(ClassDefinition);
};
diff --git a/tools/aapt2/java/JavaClassGenerator.cpp b/tools/aapt2/java/JavaClassGenerator.cpp
index fbaefb1..6e7c7078 100644
--- a/tools/aapt2/java/JavaClassGenerator.cpp
+++ b/tools/aapt2/java/JavaClassGenerator.cpp
@@ -14,16 +14,7 @@
* limitations under the License.
*/
-#include "NameMangler.h"
-#include "Resource.h"
-#include "ResourceTable.h"
-#include "ResourceValues.h"
-#include "ValueVisitor.h"
-#include "java/AnnotationProcessor.h"
-#include "java/ClassDefinition.h"
#include "java/JavaClassGenerator.h"
-#include "process/SymbolTable.h"
-#include "util/StringPiece.h"
#include <algorithm>
#include <ostream>
@@ -31,42 +22,49 @@
#include <sstream>
#include <tuple>
+#include "android-base/logging.h"
+
+#include "NameMangler.h"
+#include "Resource.h"
+#include "ResourceTable.h"
+#include "ResourceValues.h"
+#include "ValueVisitor.h"
+#include "java/AnnotationProcessor.h"
+#include "java/ClassDefinition.h"
+#include "process/SymbolTable.h"
+#include "util/StringPiece.h"
+
namespace aapt {
-JavaClassGenerator::JavaClassGenerator(IAaptContext* context, ResourceTable* table,
- const JavaClassGeneratorOptions& options) :
- mContext(context), mTable(table), mOptions(options) {
-}
-
static const std::set<StringPiece> sJavaIdentifiers = {
- "abstract", "assert", "boolean", "break", "byte",
- "case", "catch", "char", "class", "const", "continue",
- "default", "do", "double", "else", "enum", "extends",
- "final", "finally", "float", "for", "goto", "if",
- "implements", "import", "instanceof", "int", "interface",
- "long", "native", "new", "package", "private", "protected",
- "public", "return", "short", "static", "strictfp", "super",
- "switch", "synchronized", "this", "throw", "throws",
- "transient", "try", "void", "volatile", "while", "true",
- "false", "null"
-};
+ "abstract", "assert", "boolean", "break", "byte",
+ "case", "catch", "char", "class", "const",
+ "continue", "default", "do", "double", "else",
+ "enum", "extends", "final", "finally", "float",
+ "for", "goto", "if", "implements", "import",
+ "instanceof", "int", "interface", "long", "native",
+ "new", "package", "private", "protected", "public",
+ "return", "short", "static", "strictfp", "super",
+ "switch", "synchronized", "this", "throw", "throws",
+ "transient", "try", "void", "volatile", "while",
+ "true", "false", "null"};
-static bool isValidSymbol(const StringPiece& symbol) {
- return sJavaIdentifiers.find(symbol) == sJavaIdentifiers.end();
+static bool IsValidSymbol(const StringPiece& symbol) {
+ return sJavaIdentifiers.find(symbol) == sJavaIdentifiers.end();
}
/*
* Java symbols can not contain . or -, but those are valid in a resource name.
* Replace those with '_'.
*/
-static std::string transform(const StringPiece& symbol) {
- std::string output = symbol.toString();
- for (char& c : output) {
- if (c == '.' || c == '-') {
- c = '_';
- }
+static std::string Transform(const StringPiece& symbol) {
+ std::string output = symbol.ToString();
+ for (char& c : output) {
+ if (c == '.' || c == '-') {
+ c = '_';
}
- return output;
+ }
+ return output;
}
/**
@@ -80,475 +78,519 @@
* Foo_android_bar
* Foo_bar
*/
-static std::string transformNestedAttr(const ResourceNameRef& attrName,
- const std::string& styleableClassName,
- const StringPiece& packageNameToGenerate) {
- std::string output = styleableClassName;
+static std::string TransformNestedAttr(
+ const ResourceNameRef& attr_name, const std::string& styleable_class_name,
+ const StringPiece& package_name_to_generate) {
+ std::string output = styleable_class_name;
- // We may reference IDs from other packages, so prefix the entry name with
- // the package.
- if (!attrName.package.empty() && packageNameToGenerate != attrName.package) {
- output += "_" + transform(attrName.package);
- }
- output += "_" + transform(attrName.entry);
- return output;
+ // We may reference IDs from other packages, so prefix the entry name with
+ // the package.
+ if (!attr_name.package.empty() &&
+ package_name_to_generate != attr_name.package) {
+ output += "_" + Transform(attr_name.package);
+ }
+ output += "_" + Transform(attr_name.entry);
+ return output;
}
-static void addAttributeFormatDoc(AnnotationProcessor* processor, Attribute* attr) {
- const uint32_t typeMask = attr->typeMask;
- if (typeMask & android::ResTable_map::TYPE_REFERENCE) {
- processor->appendComment(
- "<p>May be a reference to another resource, in the form\n"
- "\"<code>@[+][<i>package</i>:]<i>type</i>/<i>name</i></code>\" or a theme\n"
- "attribute in the form\n"
- "\"<code>?[<i>package</i>:]<i>type</i>/<i>name</i></code>\".");
+static void AddAttributeFormatDoc(AnnotationProcessor* processor,
+ Attribute* attr) {
+ const uint32_t type_mask = attr->type_mask;
+ if (type_mask & android::ResTable_map::TYPE_REFERENCE) {
+ processor->AppendComment(
+ "<p>May be a reference to another resource, in the form\n"
+ "\"<code>@[+][<i>package</i>:]<i>type</i>/<i>name</i></code>\" or a "
+ "theme\n"
+ "attribute in the form\n"
+ "\"<code>?[<i>package</i>:]<i>type</i>/<i>name</i></code>\".");
+ }
+
+ if (type_mask & android::ResTable_map::TYPE_STRING) {
+ processor->AppendComment(
+ "<p>May be a string value, using '\\\\;' to escape characters such as\n"
+ "'\\\\n' or '\\\\uxxxx' for a unicode character;");
+ }
+
+ if (type_mask & android::ResTable_map::TYPE_INTEGER) {
+ processor->AppendComment(
+ "<p>May be an integer value, such as \"<code>100</code>\".");
+ }
+
+ if (type_mask & android::ResTable_map::TYPE_BOOLEAN) {
+ processor->AppendComment(
+ "<p>May be a boolean value, such as \"<code>true</code>\" or\n"
+ "\"<code>false</code>\".");
+ }
+
+ if (type_mask & android::ResTable_map::TYPE_COLOR) {
+ processor->AppendComment(
+ "<p>May be a color value, in the form of "
+ "\"<code>#<i>rgb</i></code>\",\n"
+ "\"<code>#<i>argb</i></code>\", \"<code>#<i>rrggbb</i></code\", or \n"
+ "\"<code>#<i>aarrggbb</i></code>\".");
+ }
+
+ if (type_mask & android::ResTable_map::TYPE_FLOAT) {
+ processor->AppendComment(
+ "<p>May be a floating point value, such as \"<code>1.2</code>\".");
+ }
+
+ if (type_mask & android::ResTable_map::TYPE_DIMENSION) {
+ processor->AppendComment(
+ "<p>May be a dimension value, which is a floating point number "
+ "appended with a\n"
+ "unit such as \"<code>14.5sp</code>\".\n"
+ "Available units are: px (pixels), dp (density-independent pixels),\n"
+ "sp (scaled pixels based on preferred font size), in (inches), and\n"
+ "mm (millimeters).");
+ }
+
+ if (type_mask & android::ResTable_map::TYPE_FRACTION) {
+ processor->AppendComment(
+ "<p>May be a fractional value, which is a floating point number "
+ "appended with\n"
+ "either % or %p, such as \"<code>14.5%</code>\".\n"
+ "The % suffix always means a percentage of the base size;\n"
+ "the optional %p suffix provides a size relative to some parent "
+ "container.");
+ }
+
+ if (type_mask &
+ (android::ResTable_map::TYPE_FLAGS | android::ResTable_map::TYPE_ENUM)) {
+ if (type_mask & android::ResTable_map::TYPE_FLAGS) {
+ processor->AppendComment(
+ "<p>Must be one or more (separated by '|') of the following "
+ "constant values.</p>");
+ } else {
+ processor->AppendComment(
+ "<p>Must be one of the following constant values.</p>");
}
- if (typeMask & android::ResTable_map::TYPE_STRING) {
- processor->appendComment(
- "<p>May be a string value, using '\\\\;' to escape characters such as\n"
- "'\\\\n' or '\\\\uxxxx' for a unicode character;");
+ processor->AppendComment(
+ "<table>\n<colgroup align=\"left\" />\n"
+ "<colgroup align=\"left\" />\n"
+ "<colgroup align=\"left\" />\n"
+ "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n");
+ for (const Attribute::Symbol& symbol : attr->symbols) {
+ std::stringstream line;
+ line << "<tr><td>" << symbol.symbol.name.value().entry << "</td>"
+ << "<td>" << std::hex << symbol.value << std::dec << "</td>"
+ << "<td>" << util::TrimWhitespace(symbol.symbol.GetComment())
+ << "</td></tr>";
+ processor->AppendComment(line.str());
}
-
- if (typeMask & android::ResTable_map::TYPE_INTEGER) {
- processor->appendComment("<p>May be an integer value, such as \"<code>100</code>\".");
- }
-
- if (typeMask & android::ResTable_map::TYPE_BOOLEAN) {
- processor->appendComment(
- "<p>May be a boolean value, such as \"<code>true</code>\" or\n"
- "\"<code>false</code>\".");
- }
-
- if (typeMask & android::ResTable_map::TYPE_COLOR) {
- processor->appendComment(
- "<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\",\n"
- "\"<code>#<i>argb</i></code>\", \"<code>#<i>rrggbb</i></code\", or \n"
- "\"<code>#<i>aarrggbb</i></code>\".");
- }
-
- if (typeMask & android::ResTable_map::TYPE_FLOAT) {
- processor->appendComment(
- "<p>May be a floating point value, such as \"<code>1.2</code>\".");
- }
-
- if (typeMask & android::ResTable_map::TYPE_DIMENSION) {
- processor->appendComment(
- "<p>May be a dimension value, which is a floating point number appended with a\n"
- "unit such as \"<code>14.5sp</code>\".\n"
- "Available units are: px (pixels), dp (density-independent pixels),\n"
- "sp (scaled pixels based on preferred font size), in (inches), and\n"
- "mm (millimeters).");
- }
-
- if (typeMask & android::ResTable_map::TYPE_FRACTION) {
- processor->appendComment(
- "<p>May be a fractional value, which is a floating point number appended with\n"
- "either % or %p, such as \"<code>14.5%</code>\".\n"
- "The % suffix always means a percentage of the base size;\n"
- "the optional %p suffix provides a size relative to some parent container.");
- }
-
- if (typeMask & (android::ResTable_map::TYPE_FLAGS | android::ResTable_map::TYPE_ENUM)) {
- if (typeMask & android::ResTable_map::TYPE_FLAGS) {
- processor->appendComment(
- "<p>Must be one or more (separated by '|') of the following "
- "constant values.</p>");
- } else {
- processor->appendComment("<p>Must be one of the following constant values.</p>");
- }
-
- processor->appendComment("<table>\n<colgroup align=\"left\" />\n"
- "<colgroup align=\"left\" />\n"
- "<colgroup align=\"left\" />\n"
- "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n");
- for (const Attribute::Symbol& symbol : attr->symbols) {
- std::stringstream line;
- line << "<tr><td>" << symbol.symbol.name.value().entry << "</td>"
- << "<td>" << std::hex << symbol.value << std::dec << "</td>"
- << "<td>" << util::trimWhitespace(symbol.symbol.getComment()) << "</td></tr>";
- processor->appendComment(line.str());
- }
- processor->appendComment("</table>");
- }
+ processor->AppendComment("</table>");
+ }
}
-bool JavaClassGenerator::skipSymbol(SymbolState state) {
- switch (mOptions.types) {
+JavaClassGenerator::JavaClassGenerator(IAaptContext* context,
+ ResourceTable* table,
+ const JavaClassGeneratorOptions& options)
+ : context_(context), table_(table), options_(options) {}
+
+bool JavaClassGenerator::SkipSymbol(SymbolState state) {
+ switch (options_.types) {
case JavaClassGeneratorOptions::SymbolTypes::kAll:
- return false;
+ return false;
case JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate:
- return state == SymbolState::kUndefined;
+ return state == SymbolState::kUndefined;
case JavaClassGeneratorOptions::SymbolTypes::kPublic:
- return state != SymbolState::kPublic;
- }
- return true;
+ return state != SymbolState::kPublic;
+ }
+ return true;
}
struct StyleableAttr {
- const Reference* attrRef;
- std::string fieldName;
- std::unique_ptr<SymbolTable::Symbol> symbol;
+ const Reference* attr_ref;
+ std::string field_name;
+ std::unique_ptr<SymbolTable::Symbol> symbol;
};
-static bool lessStyleableAttr(const StyleableAttr& lhs, const StyleableAttr& rhs) {
- const ResourceId lhsId = lhs.attrRef->id ? lhs.attrRef->id.value() : ResourceId(0);
- const ResourceId rhsId = rhs.attrRef->id ? rhs.attrRef->id.value() : ResourceId(0);
- if (lhsId < rhsId) {
- return true;
- } else if (lhsId > rhsId) {
- return false;
+static bool less_styleable_attr(const StyleableAttr& lhs,
+ const StyleableAttr& rhs) {
+ const ResourceId lhs_id =
+ lhs.attr_ref->id ? lhs.attr_ref->id.value() : ResourceId(0);
+ const ResourceId rhs_id =
+ rhs.attr_ref->id ? rhs.attr_ref->id.value() : ResourceId(0);
+ if (lhs_id < rhs_id) {
+ return true;
+ } else if (lhs_id > rhs_id) {
+ return false;
+ } else {
+ return lhs.attr_ref->name.value() < rhs.attr_ref->name.value();
+ }
+}
+
+void JavaClassGenerator::AddMembersToStyleableClass(
+ const StringPiece& package_name_to_generate, const std::string& entry_name,
+ const Styleable* styleable, ClassDefinition* out_styleable_class_def) {
+ const std::string class_name = Transform(entry_name);
+
+ std::unique_ptr<ResourceArrayMember> styleable_array_def =
+ util::make_unique<ResourceArrayMember>(class_name);
+
+ // This must be sorted by resource ID.
+ std::vector<StyleableAttr> sorted_attributes;
+ sorted_attributes.reserve(styleable->entries.size());
+ for (const auto& attr : styleable->entries) {
+ // If we are not encoding final attributes, the styleable entry may have no
+ // ID if we are building a static library.
+ CHECK(!options_.use_final || attr.id) << "no ID set for Styleable entry";
+ CHECK(bool(attr.name)) << "no name set for Styleable entry";
+
+ // We will need the unmangled, transformed name in the comments and the
+ // field,
+ // so create it once and cache it in this StyleableAttr data structure.
+ StyleableAttr styleable_attr = {};
+ styleable_attr.attr_ref = &attr;
+ styleable_attr.field_name = TransformNestedAttr(
+ attr.name.value(), class_name, package_name_to_generate);
+
+ Reference mangled_reference;
+ mangled_reference.id = attr.id;
+ mangled_reference.name = attr.name;
+ if (mangled_reference.name.value().package.empty()) {
+ mangled_reference.name.value().package =
+ context_->GetCompilationPackage();
+ }
+
+ if (Maybe<ResourceName> mangled_name =
+ context_->GetNameMangler()->MangleName(
+ mangled_reference.name.value())) {
+ mangled_reference.name = mangled_name;
+ }
+
+ // Look up the symbol so that we can write out in the comments what are
+ // possible
+ // legal values for this attribute.
+ const SymbolTable::Symbol* symbol =
+ context_->GetExternalSymbols()->FindByReference(mangled_reference);
+ if (symbol && symbol->attribute) {
+ // Copy the symbol data structure because the returned instance can be
+ // destroyed.
+ styleable_attr.symbol = util::make_unique<SymbolTable::Symbol>(*symbol);
+ }
+ sorted_attributes.push_back(std::move(styleable_attr));
+ }
+
+ // Sort the attributes by ID.
+ std::sort(sorted_attributes.begin(), sorted_attributes.end(),
+ less_styleable_attr);
+
+ const size_t attr_count = sorted_attributes.size();
+ if (attr_count > 0) {
+ // Build the comment string for the Styleable. It includes details about the
+ // child attributes.
+ std::stringstream styleable_comment;
+ if (!styleable->GetComment().empty()) {
+ styleable_comment << styleable->GetComment() << "\n";
} else {
- return lhs.attrRef->name.value() < rhs.attrRef->name.value();
+ styleable_comment << "Attributes that can be used with a " << class_name
+ << ".\n";
}
+
+ styleable_comment << "<p>Includes the following attributes:</p>\n"
+ "<table>\n"
+ "<colgroup align=\"left\" />\n"
+ "<colgroup align=\"left\" />\n"
+ "<tr><th>Attribute</th><th>Description</th></tr>\n";
+
+ for (const StyleableAttr& entry : sorted_attributes) {
+ if (!entry.symbol) {
+ continue;
+ }
+
+ if (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic &&
+ !entry.symbol->is_public) {
+ // Don't write entries for non-public attributes.
+ continue;
+ }
+
+ StringPiece attr_comment_line = entry.symbol->attribute->GetComment();
+ if (attr_comment_line.contains("@removed")) {
+ // Removed attributes are public but hidden from the documentation, so
+ // don't emit
+ // them as part of the class documentation.
+ continue;
+ }
+
+ const ResourceName& attr_name = entry.attr_ref->name.value();
+ styleable_comment << "<tr><td>";
+ styleable_comment << "<code>{@link #" << entry.field_name << " "
+ << (!attr_name.package.empty()
+ ? attr_name.package
+ : context_->GetCompilationPackage())
+ << ":" << attr_name.entry << "}</code>";
+ styleable_comment << "</td>";
+
+ styleable_comment << "<td>";
+
+ // Only use the comment up until the first '.'. This is to stay compatible
+ // with
+ // the way old AAPT did it (presumably to keep it short and to avoid
+ // including
+ // annotations like @hide which would affect this Styleable).
+ auto iter =
+ std::find(attr_comment_line.begin(), attr_comment_line.end(), u'.');
+ if (iter != attr_comment_line.end()) {
+ attr_comment_line =
+ attr_comment_line.substr(0, (iter - attr_comment_line.begin()) + 1);
+ }
+ styleable_comment << attr_comment_line << "</td></tr>\n";
+ }
+ styleable_comment << "</table>\n";
+
+ for (const StyleableAttr& entry : sorted_attributes) {
+ if (!entry.symbol) {
+ continue;
+ }
+
+ if (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic &&
+ !entry.symbol->is_public) {
+ // Don't write entries for non-public attributes.
+ continue;
+ }
+ styleable_comment << "@see #" << entry.field_name << "\n";
+ }
+
+ styleable_array_def->GetCommentBuilder()->AppendComment(
+ styleable_comment.str());
+ }
+
+ // Add the ResourceIds to the array member.
+ for (const StyleableAttr& styleable_attr : sorted_attributes) {
+ styleable_array_def->AddElement(styleable_attr.attr_ref->id
+ ? styleable_attr.attr_ref->id.value()
+ : ResourceId(0));
+ }
+
+ // Add the Styleable array to the Styleable class.
+ out_styleable_class_def->AddMember(std::move(styleable_array_def));
+
+ // Now we emit the indices into the array.
+ for (size_t i = 0; i < attr_count; i++) {
+ const StyleableAttr& styleable_attr = sorted_attributes[i];
+
+ if (!styleable_attr.symbol) {
+ continue;
+ }
+
+ if (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic &&
+ !styleable_attr.symbol->is_public) {
+ // Don't write entries for non-public attributes.
+ continue;
+ }
+
+ StringPiece comment = styleable_attr.attr_ref->GetComment();
+ if (styleable_attr.symbol->attribute && comment.empty()) {
+ comment = styleable_attr.symbol->attribute->GetComment();
+ }
+
+ if (comment.contains("@removed")) {
+ // Removed attributes are public but hidden from the documentation, so
+ // don't emit them
+ // as part of the class documentation.
+ continue;
+ }
+
+ const ResourceName& attr_name = styleable_attr.attr_ref->name.value();
+
+ StringPiece package_name = attr_name.package;
+ if (package_name.empty()) {
+ package_name = context_->GetCompilationPackage();
+ }
+
+ std::unique_ptr<IntMember> index_member = util::make_unique<IntMember>(
+ sorted_attributes[i].field_name, static_cast<uint32_t>(i));
+
+ AnnotationProcessor* attr_processor = index_member->GetCommentBuilder();
+
+ if (!comment.empty()) {
+ attr_processor->AppendComment("<p>\n@attr description");
+ attr_processor->AppendComment(comment);
+ } else {
+ std::stringstream default_comment;
+ default_comment << "<p>This symbol is the offset where the "
+ << "{@link " << package_name << ".R.attr#"
+ << Transform(attr_name.entry) << "}\n"
+ << "attribute's value can be found in the "
+ << "{@link #" << class_name << "} array.";
+ attr_processor->AppendComment(default_comment.str());
+ }
+
+ attr_processor->AppendNewLine();
+
+ AddAttributeFormatDoc(attr_processor,
+ styleable_attr.symbol->attribute.get());
+ attr_processor->AppendNewLine();
+
+ std::stringstream doclava_name;
+ doclava_name << "@attr name " << package_name << ":" << attr_name.entry;
+
+ attr_processor->AppendComment(doclava_name.str());
+
+ out_styleable_class_def->AddMember(std::move(index_member));
+ }
}
-void JavaClassGenerator::addMembersToStyleableClass(const StringPiece& packageNameToGenerate,
- const std::string& entryName,
- const Styleable* styleable,
- ClassDefinition* outStyleableClassDef) {
- const std::string className = transform(entryName);
-
- std::unique_ptr<ResourceArrayMember> styleableArrayDef =
- util::make_unique<ResourceArrayMember>(className);
-
- // This must be sorted by resource ID.
- std::vector<StyleableAttr> sortedAttributes;
- sortedAttributes.reserve(styleable->entries.size());
- for (const auto& attr : styleable->entries) {
- // If we are not encoding final attributes, the styleable entry may have no ID
- // if we are building a static library.
- assert((!mOptions.useFinal || attr.id) && "no ID set for Styleable entry");
- assert(attr.name && "no name set for Styleable entry");
-
- // We will need the unmangled, transformed name in the comments and the field,
- // so create it once and cache it in this StyleableAttr data structure.
- StyleableAttr styleableAttr = {};
- styleableAttr.attrRef = &attr;
- styleableAttr.fieldName = transformNestedAttr(attr.name.value(), className,
- packageNameToGenerate);
-
- Reference mangledReference;
- mangledReference.id = attr.id;
- mangledReference.name = attr.name;
- if (mangledReference.name.value().package.empty()) {
- mangledReference.name.value().package = mContext->getCompilationPackage();
- }
-
- if (Maybe<ResourceName> mangledName =
- mContext->getNameMangler()->mangleName(mangledReference.name.value())) {
- mangledReference.name = mangledName;
- }
-
- // Look up the symbol so that we can write out in the comments what are possible
- // legal values for this attribute.
- const SymbolTable::Symbol* symbol = mContext->getExternalSymbols()->findByReference(
- mangledReference);
- if (symbol && symbol->attribute) {
- // Copy the symbol data structure because the returned instance can be destroyed.
- styleableAttr.symbol = util::make_unique<SymbolTable::Symbol>(*symbol);
- }
- sortedAttributes.push_back(std::move(styleableAttr));
+bool JavaClassGenerator::AddMembersToTypeClass(
+ const StringPiece& package_name_to_generate,
+ const ResourceTablePackage* package, const ResourceTableType* type,
+ ClassDefinition* out_type_class_def) {
+ for (const auto& entry : type->entries) {
+ if (SkipSymbol(entry->symbol_status.state)) {
+ continue;
}
- // Sort the attributes by ID.
- std::sort(sortedAttributes.begin(), sortedAttributes.end(), lessStyleableAttr);
-
- const size_t attrCount = sortedAttributes.size();
- if (attrCount > 0) {
- // Build the comment string for the Styleable. It includes details about the
- // child attributes.
- std::stringstream styleableComment;
- if (!styleable->getComment().empty()) {
- styleableComment << styleable->getComment() << "\n";
- } else {
- styleableComment << "Attributes that can be used with a " << className << ".\n";
- }
-
- styleableComment <<
- "<p>Includes the following attributes:</p>\n"
- "<table>\n"
- "<colgroup align=\"left\" />\n"
- "<colgroup align=\"left\" />\n"
- "<tr><th>Attribute</th><th>Description</th></tr>\n";
-
- for (const StyleableAttr& entry : sortedAttributes) {
- if (!entry.symbol) {
- continue;
- }
-
- if (mOptions.types == JavaClassGeneratorOptions::SymbolTypes::kPublic &&
- !entry.symbol->isPublic) {
- // Don't write entries for non-public attributes.
- continue;
- }
-
- StringPiece attrCommentLine = entry.symbol->attribute->getComment();
- if (attrCommentLine.contains("@removed")) {
- // Removed attributes are public but hidden from the documentation, so don't emit
- // them as part of the class documentation.
- continue;
- }
-
- const ResourceName& attrName = entry.attrRef->name.value();
- styleableComment << "<tr><td>";
- styleableComment << "<code>{@link #"
- << entry.fieldName << " "
- << (!attrName.package.empty()
- ? attrName.package : mContext->getCompilationPackage())
- << ":" << attrName.entry
- << "}</code>";
- styleableComment << "</td>";
-
- styleableComment << "<td>";
-
- // Only use the comment up until the first '.'. This is to stay compatible with
- // the way old AAPT did it (presumably to keep it short and to avoid including
- // annotations like @hide which would affect this Styleable).
- auto iter = std::find(attrCommentLine.begin(), attrCommentLine.end(), u'.');
- if (iter != attrCommentLine.end()) {
- attrCommentLine = attrCommentLine.substr(
- 0, (iter - attrCommentLine.begin()) + 1);
- }
- styleableComment << attrCommentLine << "</td></tr>\n";
- }
- styleableComment << "</table>\n";
-
- for (const StyleableAttr& entry : sortedAttributes) {
- if (!entry.symbol) {
- continue;
- }
-
- if (mOptions.types == JavaClassGeneratorOptions::SymbolTypes::kPublic &&
- !entry.symbol->isPublic) {
- // Don't write entries for non-public attributes.
- continue;
- }
- styleableComment << "@see #" << entry.fieldName << "\n";
- }
-
- styleableArrayDef->getCommentBuilder()->appendComment(styleableComment.str());
+ ResourceId id;
+ if (package->id && type->id && entry->id) {
+ id = ResourceId(package->id.value(), type->id.value(), entry->id.value());
}
- // Add the ResourceIds to the array member.
- for (const StyleableAttr& styleableAttr : sortedAttributes) {
- styleableArrayDef->addElement(
- styleableAttr.attrRef->id ? styleableAttr.attrRef->id.value() : ResourceId(0));
+ std::string unmangled_package;
+ std::string unmangled_name = entry->name;
+ if (NameMangler::Unmangle(&unmangled_name, &unmangled_package)) {
+ // The entry name was mangled, and we successfully unmangled it.
+ // Check that we want to emit this symbol.
+ if (package->name != unmangled_package) {
+ // Skip the entry if it doesn't belong to the package we're writing.
+ continue;
+ }
+ } else if (package_name_to_generate != package->name) {
+ // We are processing a mangled package name,
+ // but this is a non-mangled resource.
+ continue;
}
- // Add the Styleable array to the Styleable class.
- outStyleableClassDef->addMember(std::move(styleableArrayDef));
-
- // Now we emit the indices into the array.
- for (size_t i = 0; i < attrCount; i++) {
- const StyleableAttr& styleableAttr = sortedAttributes[i];
-
- if (!styleableAttr.symbol) {
- continue;
- }
-
- if (mOptions.types == JavaClassGeneratorOptions::SymbolTypes::kPublic &&
- !styleableAttr.symbol->isPublic) {
- // Don't write entries for non-public attributes.
- continue;
- }
-
- StringPiece comment = styleableAttr.attrRef->getComment();
- if (styleableAttr.symbol->attribute && comment.empty()) {
- comment = styleableAttr.symbol->attribute->getComment();
- }
-
- if (comment.contains("@removed")) {
- // Removed attributes are public but hidden from the documentation, so don't emit them
- // as part of the class documentation.
- continue;
- }
-
- const ResourceName& attrName = styleableAttr.attrRef->name.value();
-
- StringPiece packageName = attrName.package;
- if (packageName.empty()) {
- packageName = mContext->getCompilationPackage();
- }
-
- std::unique_ptr<IntMember> indexMember = util::make_unique<IntMember>(
- sortedAttributes[i].fieldName, static_cast<uint32_t>(i));
-
- AnnotationProcessor* attrProcessor = indexMember->getCommentBuilder();
-
- if (!comment.empty()) {
- attrProcessor->appendComment("<p>\n@attr description");
- attrProcessor->appendComment(comment);
- } else {
- std::stringstream defaultComment;
- defaultComment
- << "<p>This symbol is the offset where the "
- << "{@link " << packageName << ".R.attr#" << transform(attrName.entry) << "}\n"
- << "attribute's value can be found in the "
- << "{@link #" << className << "} array.";
- attrProcessor->appendComment(defaultComment.str());
- }
-
- attrProcessor->appendNewLine();
-
- addAttributeFormatDoc(attrProcessor, styleableAttr.symbol->attribute.get());
- attrProcessor->appendNewLine();
-
- std::stringstream doclavaName;
- doclavaName << "@attr name " << packageName << ":" << attrName.entry;;
- attrProcessor->appendComment(doclavaName.str());
-
- outStyleableClassDef->addMember(std::move(indexMember));
+ if (!IsValidSymbol(unmangled_name)) {
+ ResourceNameRef resource_name(package_name_to_generate, type->type,
+ unmangled_name);
+ std::stringstream err;
+ err << "invalid symbol name '" << resource_name << "'";
+ error_ = err.str();
+ return false;
}
+
+ if (type->type == ResourceType::kStyleable) {
+ CHECK(!entry->values.empty());
+
+ const Styleable* styleable =
+ static_cast<const Styleable*>(entry->values.front()->value.get());
+
+ // Comments are handled within this method.
+ AddMembersToStyleableClass(package_name_to_generate, unmangled_name,
+ styleable, out_type_class_def);
+ } else {
+ std::unique_ptr<ResourceMember> resource_member =
+ util::make_unique<ResourceMember>(Transform(unmangled_name), id);
+
+ // Build the comments and annotations for this entry.
+ AnnotationProcessor* processor = resource_member->GetCommentBuilder();
+
+ // Add the comments from any <public> tags.
+ if (entry->symbol_status.state != SymbolState::kUndefined) {
+ processor->AppendComment(entry->symbol_status.comment);
+ }
+
+ // Add the comments from all configurations of this entry.
+ for (const auto& config_value : entry->values) {
+ processor->AppendComment(config_value->value->GetComment());
+ }
+
+ // If this is an Attribute, append the format Javadoc.
+ if (!entry->values.empty()) {
+ if (Attribute* attr =
+ ValueCast<Attribute>(entry->values.front()->value.get())) {
+ // We list out the available values for the given attribute.
+ AddAttributeFormatDoc(processor, attr);
+ }
+ }
+
+ out_type_class_def->AddMember(std::move(resource_member));
+ }
+ }
+ return true;
}
-bool JavaClassGenerator::addMembersToTypeClass(const StringPiece& packageNameToGenerate,
- const ResourceTablePackage* package,
- const ResourceTableType* type,
- ClassDefinition* outTypeClassDef) {
-
- for (const auto& entry : type->entries) {
- if (skipSymbol(entry->symbolStatus.state)) {
- continue;
- }
-
- ResourceId id;
- if (package->id && type->id && entry->id) {
- id = ResourceId(package->id.value(), type->id.value(), entry->id.value());
- }
-
- std::string unmangledPackage;
- std::string unmangledName = entry->name;
- if (NameMangler::unmangle(&unmangledName, &unmangledPackage)) {
- // The entry name was mangled, and we successfully unmangled it.
- // Check that we want to emit this symbol.
- if (package->name != unmangledPackage) {
- // Skip the entry if it doesn't belong to the package we're writing.
- continue;
- }
- } else if (packageNameToGenerate != package->name) {
- // We are processing a mangled package name,
- // but this is a non-mangled resource.
- continue;
- }
-
- if (!isValidSymbol(unmangledName)) {
- ResourceNameRef resourceName(packageNameToGenerate, type->type, unmangledName);
- std::stringstream err;
- err << "invalid symbol name '" << resourceName << "'";
- mError = err.str();
- return false;
- }
-
- if (type->type == ResourceType::kStyleable) {
- assert(!entry->values.empty());
-
- const Styleable* styleable = static_cast<const Styleable*>(
- entry->values.front()->value.get());
-
- // Comments are handled within this method.
- addMembersToStyleableClass(packageNameToGenerate, unmangledName, styleable,
- outTypeClassDef);
- } else {
- std::unique_ptr<ResourceMember> resourceMember =
- util::make_unique<ResourceMember>(transform(unmangledName), id);
-
- // Build the comments and annotations for this entry.
- AnnotationProcessor* processor = resourceMember->getCommentBuilder();
-
- // Add the comments from any <public> tags.
- if (entry->symbolStatus.state != SymbolState::kUndefined) {
- processor->appendComment(entry->symbolStatus.comment);
- }
-
- // Add the comments from all configurations of this entry.
- for (const auto& configValue : entry->values) {
- processor->appendComment(configValue->value->getComment());
- }
-
- // If this is an Attribute, append the format Javadoc.
- if (!entry->values.empty()) {
- if (Attribute* attr = valueCast<Attribute>(entry->values.front()->value.get())) {
- // We list out the available values for the given attribute.
- addAttributeFormatDoc(processor, attr);
- }
- }
-
- outTypeClassDef->addMember(std::move(resourceMember));
- }
- }
- return true;
+bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate,
+ std::ostream* out) {
+ return Generate(package_name_to_generate, package_name_to_generate, out);
}
-bool JavaClassGenerator::generate(const StringPiece& packageNameToGenerate, std::ostream* out) {
- return generate(packageNameToGenerate, packageNameToGenerate, out);
+static void AppendJavaDocAnnotations(
+ const std::vector<std::string>& annotations,
+ AnnotationProcessor* processor) {
+ for (const std::string& annotation : annotations) {
+ std::string proper_annotation = "@";
+ proper_annotation += annotation;
+ processor->AppendComment(proper_annotation);
+ }
}
-static void appendJavaDocAnnotations(const std::vector<std::string>& annotations,
- AnnotationProcessor* processor) {
- for (const std::string& annotation : annotations) {
- std::string properAnnotation = "@";
- properAnnotation += annotation;
- processor->appendComment(properAnnotation);
- }
-}
+bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate,
+ const StringPiece& out_package_name,
+ std::ostream* out) {
+ ClassDefinition r_class("R", ClassQualifier::None, true);
-bool JavaClassGenerator::generate(const StringPiece& packageNameToGenerate,
- const StringPiece& outPackageName, std::ostream* out) {
+ for (const auto& package : table_->packages) {
+ for (const auto& type : package->types) {
+ if (type->type == ResourceType::kAttrPrivate) {
+ continue;
+ }
- ClassDefinition rClass("R", ClassQualifier::None, true);
+ const bool force_creation_if_empty =
+ (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic);
- for (const auto& package : mTable->packages) {
- for (const auto& type : package->types) {
- if (type->type == ResourceType::kAttrPrivate) {
- continue;
- }
+ std::unique_ptr<ClassDefinition> class_def =
+ util::make_unique<ClassDefinition>(ToString(type->type),
+ ClassQualifier::Static,
+ force_creation_if_empty);
- const bool forceCreationIfEmpty =
- (mOptions.types == JavaClassGeneratorOptions::SymbolTypes::kPublic);
-
- std::unique_ptr<ClassDefinition> classDef = util::make_unique<ClassDefinition>(
- toString(type->type), ClassQualifier::Static, forceCreationIfEmpty);
-
- bool result = addMembersToTypeClass(packageNameToGenerate, package.get(), type.get(),
- classDef.get());
- if (!result) {
- return false;
- }
-
- if (type->type == ResourceType::kAttr) {
- // Also include private attributes in this same class.
- ResourceTableType* privType = package->findType(ResourceType::kAttrPrivate);
- if (privType) {
- result = addMembersToTypeClass(packageNameToGenerate, package.get(), privType,
- classDef.get());
- if (!result) {
- return false;
- }
- }
- }
-
- if (type->type == ResourceType::kStyleable &&
- mOptions.types == JavaClassGeneratorOptions::SymbolTypes::kPublic) {
- // When generating a public R class, we don't want Styleable to be part of the API.
- // It is only emitted for documentation purposes.
- classDef->getCommentBuilder()->appendComment("@doconly");
- }
-
- appendJavaDocAnnotations(mOptions.javadocAnnotations, classDef->getCommentBuilder());
-
- rClass.addMember(std::move(classDef));
- }
- }
-
- appendJavaDocAnnotations(mOptions.javadocAnnotations, rClass.getCommentBuilder());
-
- if (!ClassDefinition::writeJavaFile(&rClass, outPackageName, mOptions.useFinal, out)) {
+ bool result = AddMembersToTypeClass(
+ package_name_to_generate, package.get(), type.get(), class_def.get());
+ if (!result) {
return false;
- }
+ }
- out->flush();
- return true;
+ if (type->type == ResourceType::kAttr) {
+ // Also include private attributes in this same class.
+ ResourceTableType* priv_type =
+ package->FindType(ResourceType::kAttrPrivate);
+ if (priv_type) {
+ result =
+ AddMembersToTypeClass(package_name_to_generate, package.get(),
+ priv_type, class_def.get());
+ if (!result) {
+ return false;
+ }
+ }
+ }
+
+ if (type->type == ResourceType::kStyleable &&
+ options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic) {
+ // When generating a public R class, we don't want Styleable to be part
+ // of the API.
+ // It is only emitted for documentation purposes.
+ class_def->GetCommentBuilder()->AppendComment("@doconly");
+ }
+
+ AppendJavaDocAnnotations(options_.javadoc_annotations,
+ class_def->GetCommentBuilder());
+
+ r_class.AddMember(std::move(class_def));
+ }
+ }
+
+ AppendJavaDocAnnotations(options_.javadoc_annotations,
+ r_class.GetCommentBuilder());
+
+ if (!ClassDefinition::WriteJavaFile(&r_class, out_package_name,
+ options_.use_final, out)) {
+ return false;
+ }
+
+ out->flush();
+ return true;
}
-} // namespace aapt
+} // namespace aapt
diff --git a/tools/aapt2/java/JavaClassGenerator.h b/tools/aapt2/java/JavaClassGenerator.h
index 2fdf268..190e73b 100644
--- a/tools/aapt2/java/JavaClassGenerator.h
+++ b/tools/aapt2/java/JavaClassGenerator.h
@@ -17,14 +17,14 @@
#ifndef AAPT_JAVA_CLASS_GENERATOR_H
#define AAPT_JAVA_CLASS_GENERATOR_H
+#include <ostream>
+#include <string>
+
#include "ResourceTable.h"
#include "ResourceValues.h"
#include "process/IResourceTableConsumer.h"
#include "util/StringPiece.h"
-#include <ostream>
-#include <string>
-
namespace aapt {
class AnnotationProcessor;
@@ -35,7 +35,7 @@
* Specifies whether to use the 'final' modifier
* on resource entries. Default is true.
*/
- bool useFinal = true;
+ bool use_final = true;
enum class SymbolTypes {
kAll,
@@ -49,7 +49,7 @@
* A list of JavaDoc annotations to add to the comments of all generated
* classes.
*/
- std::vector<std::string> javadocAnnotations;
+ std::vector<std::string> javadoc_annotations;
};
/*
@@ -69,34 +69,34 @@
* We need to generate these symbols in a separate file.
* Returns true on success.
*/
- bool generate(const StringPiece& packageNameToGenerate, std::ostream* out);
+ bool Generate(const StringPiece& packageNameToGenerate, std::ostream* out);
- bool generate(const StringPiece& packageNameToGenerate,
+ bool Generate(const StringPiece& packageNameToGenerate,
const StringPiece& outputPackageName, std::ostream* out);
const std::string& getError() const;
private:
- bool addMembersToTypeClass(const StringPiece& packageNameToGenerate,
+ bool AddMembersToTypeClass(const StringPiece& packageNameToGenerate,
const ResourceTablePackage* package,
const ResourceTableType* type,
ClassDefinition* outTypeClassDef);
- void addMembersToStyleableClass(const StringPiece& packageNameToGenerate,
+ void AddMembersToStyleableClass(const StringPiece& packageNameToGenerate,
const std::string& entryName,
const Styleable* styleable,
ClassDefinition* outStyleableClassDef);
- bool skipSymbol(SymbolState state);
+ bool SkipSymbol(SymbolState state);
- IAaptContext* mContext;
- ResourceTable* mTable;
- JavaClassGeneratorOptions mOptions;
- std::string mError;
+ IAaptContext* context_;
+ ResourceTable* table_;
+ JavaClassGeneratorOptions options_;
+ std::string error_;
};
inline const std::string& JavaClassGenerator::getError() const {
- return mError;
+ return error_;
}
} // namespace aapt
diff --git a/tools/aapt2/java/JavaClassGenerator_test.cpp b/tools/aapt2/java/JavaClassGenerator_test.cpp
index ed7c6bd..3d3d24e 100644
--- a/tools/aapt2/java/JavaClassGenerator_test.cpp
+++ b/tools/aapt2/java/JavaClassGenerator_test.cpp
@@ -15,154 +15,181 @@
*/
#include "java/JavaClassGenerator.h"
-#include "test/Test.h"
-#include "util/Util.h"
#include <sstream>
#include <string>
+#include "test/Test.h"
+#include "util/Util.h"
+
namespace aapt {
TEST(JavaClassGeneratorTest, FailWhenEntryIsJavaKeyword) {
- std::unique_ptr<ResourceTable> table = test::ResourceTableBuilder()
- .setPackageId("android", 0x01)
- .addSimple("android:id/class", ResourceId(0x01020000))
- .build();
+ std::unique_ptr<ResourceTable> table =
+ test::ResourceTableBuilder()
+ .SetPackageId("android", 0x01)
+ .AddSimple("android:id/class", ResourceId(0x01020000))
+ .Build();
- std::unique_ptr<IAaptContext> context = test::ContextBuilder()
- .addSymbolSource(util::make_unique<ResourceTableSymbolSource>(table.get()))
- .setNameManglerPolicy(NameManglerPolicy{ "android" })
- .build();
- JavaClassGenerator generator(context.get(), table.get(), {});
+ std::unique_ptr<IAaptContext> context =
+ test::ContextBuilder()
+ .AddSymbolSource(
+ util::make_unique<ResourceTableSymbolSource>(table.get()))
+ .SetNameManglerPolicy(NameManglerPolicy{"android"})
+ .Build();
+ JavaClassGenerator generator(context.get(), table.get(), {});
- std::stringstream out;
- EXPECT_FALSE(generator.generate("android", &out));
+ std::stringstream out;
+ EXPECT_FALSE(generator.Generate("android", &out));
}
TEST(JavaClassGeneratorTest, TransformInvalidJavaIdentifierCharacter) {
- std::unique_ptr<ResourceTable> table = test::ResourceTableBuilder()
- .setPackageId("android", 0x01)
- .addSimple("android:id/hey-man", ResourceId(0x01020000))
- .addValue("android:attr/cool.attr", ResourceId(0x01010000),
- test::AttributeBuilder(false).build())
- .addValue("android:styleable/hey.dude", ResourceId(0x01030000),
- test::StyleableBuilder()
- .addItem("android:attr/cool.attr", ResourceId(0x01010000))
- .build())
- .build();
+ std::unique_ptr<ResourceTable> table =
+ test::ResourceTableBuilder()
+ .SetPackageId("android", 0x01)
+ .AddSimple("android:id/hey-man", ResourceId(0x01020000))
+ .AddValue("android:attr/cool.attr", ResourceId(0x01010000),
+ test::AttributeBuilder(false).Build())
+ .AddValue(
+ "android:styleable/hey.dude", ResourceId(0x01030000),
+ test::StyleableBuilder()
+ .AddItem("android:attr/cool.attr", ResourceId(0x01010000))
+ .Build())
+ .Build();
- std::unique_ptr<IAaptContext> context = test::ContextBuilder()
- .addSymbolSource(util::make_unique<ResourceTableSymbolSource>(table.get()))
- .setNameManglerPolicy(NameManglerPolicy{ "android" })
- .build();
- JavaClassGenerator generator(context.get(), table.get(), {});
+ std::unique_ptr<IAaptContext> context =
+ test::ContextBuilder()
+ .AddSymbolSource(
+ util::make_unique<ResourceTableSymbolSource>(table.get()))
+ .SetNameManglerPolicy(NameManglerPolicy{"android"})
+ .Build();
+ JavaClassGenerator generator(context.get(), table.get(), {});
- std::stringstream out;
- EXPECT_TRUE(generator.generate("android", &out));
+ std::stringstream out;
+ EXPECT_TRUE(generator.Generate("android", &out));
- std::string output = out.str();
+ std::string output = out.str();
- EXPECT_NE(std::string::npos,
- output.find("public static final int hey_man=0x01020000;"));
+ EXPECT_NE(std::string::npos,
+ output.find("public static final int hey_man=0x01020000;"));
- EXPECT_NE(std::string::npos,
- output.find("public static final int[] hey_dude={"));
+ EXPECT_NE(std::string::npos,
+ output.find("public static final int[] hey_dude={"));
- EXPECT_NE(std::string::npos,
- output.find("public static final int hey_dude_cool_attr=0;"));
+ EXPECT_NE(std::string::npos,
+ output.find("public static final int hey_dude_cool_attr=0;"));
}
TEST(JavaClassGeneratorTest, CorrectPackageNameIsUsed) {
- std::unique_ptr<ResourceTable> table = test::ResourceTableBuilder()
- .setPackageId("android", 0x01)
- .addSimple("android:id/one", ResourceId(0x01020000))
- .addSimple("android:id/com.foo$two", ResourceId(0x01020001))
- .build();
+ std::unique_ptr<ResourceTable> table =
+ test::ResourceTableBuilder()
+ .SetPackageId("android", 0x01)
+ .AddSimple("android:id/one", ResourceId(0x01020000))
+ .AddSimple("android:id/com.foo$two", ResourceId(0x01020001))
+ .Build();
- std::unique_ptr<IAaptContext> context = test::ContextBuilder()
- .addSymbolSource(util::make_unique<ResourceTableSymbolSource>(table.get()))
- .setNameManglerPolicy(NameManglerPolicy{ "android" })
- .build();
- JavaClassGenerator generator(context.get(), table.get(), {});
- std::stringstream out;
- ASSERT_TRUE(generator.generate("android", "com.android.internal", &out));
+ std::unique_ptr<IAaptContext> context =
+ test::ContextBuilder()
+ .AddSymbolSource(
+ util::make_unique<ResourceTableSymbolSource>(table.get()))
+ .SetNameManglerPolicy(NameManglerPolicy{"android"})
+ .Build();
+ JavaClassGenerator generator(context.get(), table.get(), {});
+ std::stringstream out;
+ ASSERT_TRUE(generator.Generate("android", "com.android.internal", &out));
- std::string output = out.str();
- EXPECT_NE(std::string::npos, output.find("package com.android.internal;"));
- EXPECT_NE(std::string::npos, output.find("public static final int one=0x01020000;"));
- EXPECT_EQ(std::string::npos, output.find("two"));
- EXPECT_EQ(std::string::npos, output.find("com_foo$two"));
+ std::string output = out.str();
+ EXPECT_NE(std::string::npos, output.find("package com.android.internal;"));
+ EXPECT_NE(std::string::npos,
+ output.find("public static final int one=0x01020000;"));
+ EXPECT_EQ(std::string::npos, output.find("two"));
+ EXPECT_EQ(std::string::npos, output.find("com_foo$two"));
}
TEST(JavaClassGeneratorTest, AttrPrivateIsWrittenAsAttr) {
- std::unique_ptr<ResourceTable> table = test::ResourceTableBuilder()
- .setPackageId("android", 0x01)
- .addSimple("android:attr/two", ResourceId(0x01010001))
- .addSimple("android:^attr-private/one", ResourceId(0x01010000))
- .build();
+ std::unique_ptr<ResourceTable> table =
+ test::ResourceTableBuilder()
+ .SetPackageId("android", 0x01)
+ .AddSimple("android:attr/two", ResourceId(0x01010001))
+ .AddSimple("android:^attr-private/one", ResourceId(0x01010000))
+ .Build();
- std::unique_ptr<IAaptContext> context = test::ContextBuilder()
- .addSymbolSource(util::make_unique<ResourceTableSymbolSource>(table.get()))
- .setNameManglerPolicy(NameManglerPolicy{ "android" })
- .build();
- JavaClassGenerator generator(context.get(), table.get(), {});
- std::stringstream out;
- ASSERT_TRUE(generator.generate("android", &out));
+ std::unique_ptr<IAaptContext> context =
+ test::ContextBuilder()
+ .AddSymbolSource(
+ util::make_unique<ResourceTableSymbolSource>(table.get()))
+ .SetNameManglerPolicy(NameManglerPolicy{"android"})
+ .Build();
+ JavaClassGenerator generator(context.get(), table.get(), {});
+ std::stringstream out;
+ ASSERT_TRUE(generator.Generate("android", &out));
- std::string output = out.str();
- EXPECT_NE(std::string::npos, output.find("public static final class attr"));
- EXPECT_EQ(std::string::npos, output.find("public static final class ^attr-private"));
+ std::string output = out.str();
+ EXPECT_NE(std::string::npos, output.find("public static final class attr"));
+ EXPECT_EQ(std::string::npos,
+ output.find("public static final class ^attr-private"));
}
TEST(JavaClassGeneratorTest, OnlyWritePublicResources) {
- StdErrDiagnostics diag;
- std::unique_ptr<ResourceTable> table = test::ResourceTableBuilder()
- .setPackageId("android", 0x01)
- .addSimple("android:id/one", ResourceId(0x01020000))
- .addSimple("android:id/two", ResourceId(0x01020001))
- .addSimple("android:id/three", ResourceId(0x01020002))
- .setSymbolState("android:id/one", ResourceId(0x01020000), SymbolState::kPublic)
- .setSymbolState("android:id/two", ResourceId(0x01020001), SymbolState::kPrivate)
- .build();
+ StdErrDiagnostics diag;
+ std::unique_ptr<ResourceTable> table =
+ test::ResourceTableBuilder()
+ .SetPackageId("android", 0x01)
+ .AddSimple("android:id/one", ResourceId(0x01020000))
+ .AddSimple("android:id/two", ResourceId(0x01020001))
+ .AddSimple("android:id/three", ResourceId(0x01020002))
+ .SetSymbolState("android:id/one", ResourceId(0x01020000),
+ SymbolState::kPublic)
+ .SetSymbolState("android:id/two", ResourceId(0x01020001),
+ SymbolState::kPrivate)
+ .Build();
- std::unique_ptr<IAaptContext> context = test::ContextBuilder()
- .addSymbolSource(util::make_unique<ResourceTableSymbolSource>(table.get()))
- .setNameManglerPolicy(NameManglerPolicy{ "android" })
- .build();
+ std::unique_ptr<IAaptContext> context =
+ test::ContextBuilder()
+ .AddSymbolSource(
+ util::make_unique<ResourceTableSymbolSource>(table.get()))
+ .SetNameManglerPolicy(NameManglerPolicy{"android"})
+ .Build();
- JavaClassGeneratorOptions options;
- options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
- {
- JavaClassGenerator generator(context.get(), table.get(), options);
- std::stringstream out;
- ASSERT_TRUE(generator.generate("android", &out));
- std::string output = out.str();
- EXPECT_NE(std::string::npos, output.find("public static final int one=0x01020000;"));
- EXPECT_EQ(std::string::npos, output.find("two"));
- EXPECT_EQ(std::string::npos, output.find("three"));
- }
+ JavaClassGeneratorOptions options;
+ options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
+ {
+ JavaClassGenerator generator(context.get(), table.get(), options);
+ std::stringstream out;
+ ASSERT_TRUE(generator.Generate("android", &out));
+ std::string output = out.str();
+ EXPECT_NE(std::string::npos,
+ output.find("public static final int one=0x01020000;"));
+ EXPECT_EQ(std::string::npos, output.find("two"));
+ EXPECT_EQ(std::string::npos, output.find("three"));
+ }
- options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
- {
- JavaClassGenerator generator(context.get(), table.get(), options);
- std::stringstream out;
- ASSERT_TRUE(generator.generate("android", &out));
- std::string output = out.str();
- EXPECT_NE(std::string::npos, output.find("public static final int one=0x01020000;"));
- EXPECT_NE(std::string::npos, output.find("public static final int two=0x01020001;"));
- EXPECT_EQ(std::string::npos, output.find("three"));
- }
+ options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
+ {
+ JavaClassGenerator generator(context.get(), table.get(), options);
+ std::stringstream out;
+ ASSERT_TRUE(generator.Generate("android", &out));
+ std::string output = out.str();
+ EXPECT_NE(std::string::npos,
+ output.find("public static final int one=0x01020000;"));
+ EXPECT_NE(std::string::npos,
+ output.find("public static final int two=0x01020001;"));
+ EXPECT_EQ(std::string::npos, output.find("three"));
+ }
- options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
- {
- JavaClassGenerator generator(context.get(), table.get(), options);
- std::stringstream out;
- ASSERT_TRUE(generator.generate("android", &out));
- std::string output = out.str();
- EXPECT_NE(std::string::npos, output.find("public static final int one=0x01020000;"));
- EXPECT_NE(std::string::npos, output.find("public static final int two=0x01020001;"));
- EXPECT_NE(std::string::npos, output.find("public static final int three=0x01020002;"));
- }
+ options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
+ {
+ JavaClassGenerator generator(context.get(), table.get(), options);
+ std::stringstream out;
+ ASSERT_TRUE(generator.Generate("android", &out));
+ std::string output = out.str();
+ EXPECT_NE(std::string::npos,
+ output.find("public static final int one=0x01020000;"));
+ EXPECT_NE(std::string::npos,
+ output.find("public static final int two=0x01020001;"));
+ EXPECT_NE(std::string::npos,
+ output.find("public static final int three=0x01020002;"));
+ }
}
/*
@@ -172,12 +199,15 @@
ResourceId{ 0x01, 0x02, 0x0000 }));
ResourceTable table;
table.setPackage(u"com.lib");
- ASSERT_TRUE(table.addResource(ResourceName{ {}, ResourceType::kId, u"test" }, {},
- Source{ "lib.xml", 33 }, util::make_unique<Id>()));
+ ASSERT_TRUE(table.addResource(ResourceName{ {}, ResourceType::kId, u"test"
+}, {},
+ Source{ "lib.xml", 33 },
+util::make_unique<Id>()));
ASSERT_TRUE(mTable->merge(std::move(table)));
Linker linker(mTable,
- std::make_shared<MockResolver>(mTable, std::map<ResourceName, ResourceId>()),
+ std::make_shared<MockResolver>(mTable, std::map<ResourceName,
+ResourceId>()),
{});
ASSERT_TRUE(linker.linkAndValidate());
@@ -197,126 +227,139 @@
}*/
TEST(JavaClassGeneratorTest, EmitOtherPackagesAttributesInStyleable) {
- std::unique_ptr<ResourceTable> table = test::ResourceTableBuilder()
- .setPackageId("android", 0x01)
- .setPackageId("com.lib", 0x02)
- .addValue("android:attr/bar", ResourceId(0x01010000),
- test::AttributeBuilder(false).build())
- .addValue("com.lib:attr/bar", ResourceId(0x02010000),
- test::AttributeBuilder(false).build())
- .addValue("android:styleable/foo", ResourceId(0x01030000),
- test::StyleableBuilder()
- .addItem("android:attr/bar", ResourceId(0x01010000))
- .addItem("com.lib:attr/bar", ResourceId(0x02010000))
- .build())
- .build();
+ std::unique_ptr<ResourceTable> table =
+ test::ResourceTableBuilder()
+ .SetPackageId("android", 0x01)
+ .SetPackageId("com.lib", 0x02)
+ .AddValue("android:attr/bar", ResourceId(0x01010000),
+ test::AttributeBuilder(false).Build())
+ .AddValue("com.lib:attr/bar", ResourceId(0x02010000),
+ test::AttributeBuilder(false).Build())
+ .AddValue("android:styleable/foo", ResourceId(0x01030000),
+ test::StyleableBuilder()
+ .AddItem("android:attr/bar", ResourceId(0x01010000))
+ .AddItem("com.lib:attr/bar", ResourceId(0x02010000))
+ .Build())
+ .Build();
- std::unique_ptr<IAaptContext> context = test::ContextBuilder()
- .addSymbolSource(util::make_unique<ResourceTableSymbolSource>(table.get()))
- .setNameManglerPolicy(NameManglerPolicy{ "android" })
- .build();
- JavaClassGenerator generator(context.get(), table.get(), {});
+ std::unique_ptr<IAaptContext> context =
+ test::ContextBuilder()
+ .AddSymbolSource(
+ util::make_unique<ResourceTableSymbolSource>(table.get()))
+ .SetNameManglerPolicy(NameManglerPolicy{"android"})
+ .Build();
+ JavaClassGenerator generator(context.get(), table.get(), {});
- std::stringstream out;
- EXPECT_TRUE(generator.generate("android", &out));
+ std::stringstream out;
+ EXPECT_TRUE(generator.Generate("android", &out));
- std::string output = out.str();
- EXPECT_NE(std::string::npos, output.find("int foo_bar="));
- EXPECT_NE(std::string::npos, output.find("int foo_com_lib_bar="));
+ std::string output = out.str();
+ EXPECT_NE(std::string::npos, output.find("int foo_bar="));
+ EXPECT_NE(std::string::npos, output.find("int foo_com_lib_bar="));
}
TEST(JavaClassGeneratorTest, CommentsForSimpleResourcesArePresent) {
- std::unique_ptr<ResourceTable> table = test::ResourceTableBuilder()
- .setPackageId("android", 0x01)
- .addSimple("android:id/foo", ResourceId(0x01010000))
- .build();
- test::getValue<Id>(table.get(), "android:id/foo")
- ->setComment(std::string("This is a comment\n@deprecated"));
+ std::unique_ptr<ResourceTable> table =
+ test::ResourceTableBuilder()
+ .SetPackageId("android", 0x01)
+ .AddSimple("android:id/foo", ResourceId(0x01010000))
+ .Build();
+ test::GetValue<Id>(table.get(), "android:id/foo")
+ ->SetComment(std::string("This is a comment\n@deprecated"));
- std::unique_ptr<IAaptContext> context = test::ContextBuilder()
- .addSymbolSource(util::make_unique<ResourceTableSymbolSource>(table.get()))
- .setNameManglerPolicy(NameManglerPolicy{ "android" })
- .build();
- JavaClassGenerator generator(context.get(), table.get(), {});
- std::stringstream out;
- ASSERT_TRUE(generator.generate("android", &out));
- std::string actual = out.str();
+ std::unique_ptr<IAaptContext> context =
+ test::ContextBuilder()
+ .AddSymbolSource(
+ util::make_unique<ResourceTableSymbolSource>(table.get()))
+ .SetNameManglerPolicy(NameManglerPolicy{"android"})
+ .Build();
+ JavaClassGenerator generator(context.get(), table.get(), {});
+ std::stringstream out;
+ ASSERT_TRUE(generator.Generate("android", &out));
+ std::string actual = out.str();
- const char* expectedText =
-R"EOF(/**
+ const char* expectedText =
+ R"EOF(/**
* This is a comment
* @deprecated
*/
@Deprecated
public static final int foo=0x01010000;)EOF";
- EXPECT_NE(std::string::npos, actual.find(expectedText));
+ EXPECT_NE(std::string::npos, actual.find(expectedText));
}
-TEST(JavaClassGeneratorTest, CommentsForEnumAndFlagAttributesArePresent) {
+TEST(JavaClassGeneratorTest, CommentsForEnumAndFlagAttributesArePresent) {}
-}
+TEST(JavaClassGeneratorTest,
+ CommentsForStyleablesAndNestedAttributesArePresent) {
+ Attribute attr(false);
+ attr.SetComment(StringPiece("This is an attribute"));
-TEST(JavaClassGeneratorTest, CommentsForStyleablesAndNestedAttributesArePresent) {
- Attribute attr(false);
- attr.setComment(StringPiece("This is an attribute"));
+ Styleable styleable;
+ styleable.entries.push_back(
+ Reference(test::ParseNameOrDie("android:attr/one")));
+ styleable.SetComment(StringPiece("This is a styleable"));
- Styleable styleable;
- styleable.entries.push_back(Reference(test::parseNameOrDie("android:attr/one")));
- styleable.setComment(StringPiece("This is a styleable"));
+ std::unique_ptr<ResourceTable> table =
+ test::ResourceTableBuilder()
+ .SetPackageId("android", 0x01)
+ .AddValue("android:attr/one", util::make_unique<Attribute>(attr))
+ .AddValue("android:styleable/Container",
+ std::unique_ptr<Styleable>(styleable.Clone(nullptr)))
+ .Build();
- std::unique_ptr<ResourceTable> table = test::ResourceTableBuilder()
- .setPackageId("android", 0x01)
- .addValue("android:attr/one", util::make_unique<Attribute>(attr))
- .addValue("android:styleable/Container",
- std::unique_ptr<Styleable>(styleable.clone(nullptr)))
- .build();
+ std::unique_ptr<IAaptContext> context =
+ test::ContextBuilder()
+ .AddSymbolSource(
+ util::make_unique<ResourceTableSymbolSource>(table.get()))
+ .SetNameManglerPolicy(NameManglerPolicy{"android"})
+ .Build();
+ JavaClassGeneratorOptions options;
+ options.use_final = false;
+ JavaClassGenerator generator(context.get(), table.get(), options);
+ std::stringstream out;
+ ASSERT_TRUE(generator.Generate("android", &out));
+ std::string actual = out.str();
- std::unique_ptr<IAaptContext> context = test::ContextBuilder()
- .addSymbolSource(util::make_unique<ResourceTableSymbolSource>(table.get()))
- .setNameManglerPolicy(NameManglerPolicy{ "android" })
- .build();
- JavaClassGeneratorOptions options;
- options.useFinal = false;
- JavaClassGenerator generator(context.get(), table.get(), options);
- std::stringstream out;
- ASSERT_TRUE(generator.generate("android", &out));
- std::string actual = out.str();
-
- EXPECT_NE(std::string::npos, actual.find("attr name android:one"));
- EXPECT_NE(std::string::npos, actual.find("attr description"));
- EXPECT_NE(std::string::npos, actual.find(attr.getComment().data()));
- EXPECT_NE(std::string::npos, actual.find(styleable.getComment().data()));
+ EXPECT_NE(std::string::npos, actual.find("attr name android:one"));
+ EXPECT_NE(std::string::npos, actual.find("attr description"));
+ EXPECT_NE(std::string::npos, actual.find(attr.GetComment().data()));
+ EXPECT_NE(std::string::npos, actual.find(styleable.GetComment().data()));
}
TEST(JavaClassGeneratorTest, CommentsForRemovedAttributesAreNotPresentInClass) {
- Attribute attr(false);
- attr.setComment(StringPiece("removed"));
+ Attribute attr(false);
+ attr.SetComment(StringPiece("removed"));
- std::unique_ptr<ResourceTable> table = test::ResourceTableBuilder()
- .setPackageId("android", 0x01)
- .addValue("android:attr/one", util::make_unique<Attribute>(attr))
- .build();
+ std::unique_ptr<ResourceTable> table =
+ test::ResourceTableBuilder()
+ .SetPackageId("android", 0x01)
+ .AddValue("android:attr/one", util::make_unique<Attribute>(attr))
+ .Build();
- std::unique_ptr<IAaptContext> context = test::ContextBuilder()
- .addSymbolSource(util::make_unique<ResourceTableSymbolSource>(table.get()))
- .setNameManglerPolicy(NameManglerPolicy{ "android" })
- .build();
- JavaClassGeneratorOptions options;
- options.useFinal = false;
- JavaClassGenerator generator(context.get(), table.get(), options);
- std::stringstream out;
- ASSERT_TRUE(generator.generate("android", &out));
- std::string actual = out.str();
+ std::unique_ptr<IAaptContext> context =
+ test::ContextBuilder()
+ .AddSymbolSource(
+ util::make_unique<ResourceTableSymbolSource>(table.get()))
+ .SetNameManglerPolicy(NameManglerPolicy{"android"})
+ .Build();
+ JavaClassGeneratorOptions options;
+ options.use_final = false;
+ JavaClassGenerator generator(context.get(), table.get(), options);
+ std::stringstream out;
+ ASSERT_TRUE(generator.Generate("android", &out));
+ std::string actual = out.str();
- EXPECT_EQ(std::string::npos, actual.find("@attr name android:one"));
- EXPECT_EQ(std::string::npos, actual.find("@attr description"));
+ EXPECT_EQ(std::string::npos, actual.find("@attr name android:one"));
+ EXPECT_EQ(std::string::npos, actual.find("@attr description"));
- // We should find @removed only in the attribute javadoc and not anywhere else (i.e. the class
- // javadoc).
- const size_t pos = actual.find("removed");
- EXPECT_NE(std::string::npos, pos);
- EXPECT_EQ(std::string::npos, actual.find("removed", pos + 1));
+ // We should find @removed only in the attribute javadoc and not anywhere else
+ // (i.e. the class
+ // javadoc).
+ const size_t pos = actual.find("removed");
+ EXPECT_NE(std::string::npos, pos);
+ EXPECT_EQ(std::string::npos, actual.find("removed", pos + 1));
}
-} // namespace aapt
+} // namespace aapt
diff --git a/tools/aapt2/java/ManifestClassGenerator.cpp b/tools/aapt2/java/ManifestClassGenerator.cpp
index 5ff11b1..db84f29 100644
--- a/tools/aapt2/java/ManifestClassGenerator.cpp
+++ b/tools/aapt2/java/ManifestClassGenerator.cpp
@@ -14,111 +14,120 @@
* limitations under the License.
*/
-#include "Source.h"
-#include "java/AnnotationProcessor.h"
-#include "java/ClassDefinition.h"
#include "java/ManifestClassGenerator.h"
-#include "util/Maybe.h"
-#include "xml/XmlDom.h"
#include <algorithm>
+#include "Source.h"
+#include "java/AnnotationProcessor.h"
+#include "java/ClassDefinition.h"
+#include "util/Maybe.h"
+#include "xml/XmlDom.h"
+
namespace aapt {
-static Maybe<StringPiece> extractJavaIdentifier(IDiagnostics* diag, const Source& source,
+static Maybe<StringPiece> ExtractJavaIdentifier(IDiagnostics* diag,
+ const Source& source,
const StringPiece& value) {
- const StringPiece sep = ".";
- auto iter = std::find_end(value.begin(), value.end(), sep.begin(), sep.end());
+ const StringPiece sep = ".";
+ auto iter = std::find_end(value.begin(), value.end(), sep.begin(), sep.end());
- StringPiece result;
- if (iter != value.end()) {
- result.assign(iter + sep.size(), value.end() - (iter + sep.size()));
- } else {
- result = value;
- }
+ StringPiece result;
+ if (iter != value.end()) {
+ result.assign(iter + sep.size(), value.end() - (iter + sep.size()));
+ } else {
+ result = value;
+ }
- if (result.empty()) {
- diag->error(DiagMessage(source) << "empty symbol");
- return {};
- }
+ if (result.empty()) {
+ diag->Error(DiagMessage(source) << "empty symbol");
+ return {};
+ }
- iter = util::findNonAlphaNumericAndNotInSet(result, "_");
- if (iter != result.end()) {
- diag->error(DiagMessage(source)
- << "invalid character '" << StringPiece(iter, 1)
- << "' in '" << result << "'");
- return {};
- }
+ iter = util::FindNonAlphaNumericAndNotInSet(result, "_");
+ if (iter != result.end()) {
+ diag->Error(DiagMessage(source) << "invalid character '"
+ << StringPiece(iter, 1) << "' in '"
+ << result << "'");
+ return {};
+ }
- if (*result.begin() >= '0' && *result.begin() <= '9') {
- diag->error(DiagMessage(source) << "symbol can not start with a digit");
- return {};
- }
+ if (*result.begin() >= '0' && *result.begin() <= '9') {
+ diag->Error(DiagMessage(source) << "symbol can not start with a digit");
+ return {};
+ }
- return result;
+ return result;
}
-static bool writeSymbol(const Source& source, IDiagnostics* diag, xml::Element* el,
- ClassDefinition* classDef) {
- xml::Attribute* attr = el->findAttribute(xml::kSchemaAndroid, "name");
- if (!attr) {
- diag->error(DiagMessage(source) << "<" << el->name << "> must define 'android:name'");
- return false;
- }
+static bool WriteSymbol(const Source& source, IDiagnostics* diag,
+ xml::Element* el, ClassDefinition* class_def) {
+ xml::Attribute* attr = el->FindAttribute(xml::kSchemaAndroid, "name");
+ if (!attr) {
+ diag->Error(DiagMessage(source) << "<" << el->name
+ << "> must define 'android:name'");
+ return false;
+ }
- Maybe<StringPiece> result = extractJavaIdentifier(diag, source.withLine(el->lineNumber),
- attr->value);
- if (!result) {
- return false;
- }
+ Maybe<StringPiece> result = ExtractJavaIdentifier(
+ diag, source.WithLine(el->line_number), attr->value);
+ if (!result) {
+ return false;
+ }
- std::unique_ptr<StringMember> stringMember = util::make_unique<StringMember>(
- result.value(), attr->value);
- stringMember->getCommentBuilder()->appendComment(el->comment);
+ std::unique_ptr<StringMember> string_member =
+ util::make_unique<StringMember>(result.value(), attr->value);
+ string_member->GetCommentBuilder()->AppendComment(el->comment);
- classDef->addMember(std::move(stringMember));
- return true;
+ class_def->AddMember(std::move(string_member));
+ return true;
}
-std::unique_ptr<ClassDefinition> generateManifestClass(IDiagnostics* diag, xml::XmlResource* res) {
- xml::Element* el = xml::findRootElement(res->root.get());
- if (!el) {
- diag->error(DiagMessage(res->file.source) << "no root tag defined");
- return {};
+std::unique_ptr<ClassDefinition> GenerateManifestClass(IDiagnostics* diag,
+ xml::XmlResource* res) {
+ xml::Element* el = xml::FindRootElement(res->root.get());
+ if (!el) {
+ diag->Error(DiagMessage(res->file.source) << "no root tag defined");
+ return {};
+ }
+
+ if (el->name != "manifest" && !el->namespace_uri.empty()) {
+ diag->Error(DiagMessage(res->file.source)
+ << "no <manifest> root tag defined");
+ return {};
+ }
+
+ std::unique_ptr<ClassDefinition> permission_class =
+ util::make_unique<ClassDefinition>("permission", ClassQualifier::Static,
+ false);
+ std::unique_ptr<ClassDefinition> permission_group_class =
+ util::make_unique<ClassDefinition>("permission_group",
+ ClassQualifier::Static, false);
+
+ bool error = false;
+ std::vector<xml::Element*> children = el->GetChildElements();
+ for (xml::Element* child_el : children) {
+ if (child_el->namespace_uri.empty()) {
+ if (child_el->name == "permission") {
+ error |= !WriteSymbol(res->file.source, diag, child_el,
+ permission_class.get());
+ } else if (child_el->name == "permission-group") {
+ error |= !WriteSymbol(res->file.source, diag, child_el,
+ permission_group_class.get());
+ }
}
+ }
- if (el->name != "manifest" && !el->namespaceUri.empty()) {
- diag->error(DiagMessage(res->file.source) << "no <manifest> root tag defined");
- return {};
- }
+ if (error) {
+ return {};
+ }
- std::unique_ptr<ClassDefinition> permissionClass =
- util::make_unique<ClassDefinition>("permission", ClassQualifier::Static, false);
- std::unique_ptr<ClassDefinition> permissionGroupClass =
- util::make_unique<ClassDefinition>("permission_group", ClassQualifier::Static, false);
-
- bool error = false;
-
- std::vector<xml::Element*> children = el->getChildElements();
- for (xml::Element* childEl : children) {
- if (childEl->namespaceUri.empty()) {
- if (childEl->name == "permission") {
- error |= !writeSymbol(res->file.source, diag, childEl, permissionClass.get());
- } else if (childEl->name == "permission-group") {
- error |= !writeSymbol(res->file.source, diag, childEl, permissionGroupClass.get());
- }
- }
- }
-
- if (error) {
- return {};
- }
-
- std::unique_ptr<ClassDefinition> manifestClass =
- util::make_unique<ClassDefinition>("Manifest", ClassQualifier::None, false);
- manifestClass->addMember(std::move(permissionClass));
- manifestClass->addMember(std::move(permissionGroupClass));
- return manifestClass;
+ std::unique_ptr<ClassDefinition> manifest_class =
+ util::make_unique<ClassDefinition>("Manifest", ClassQualifier::None,
+ false);
+ manifest_class->AddMember(std::move(permission_class));
+ manifest_class->AddMember(std::move(permission_group_class));
+ return manifest_class;
}
-} // namespace aapt
+} // namespace aapt
diff --git a/tools/aapt2/java/ManifestClassGenerator.h b/tools/aapt2/java/ManifestClassGenerator.h
index 1817648..b12202a 100644
--- a/tools/aapt2/java/ManifestClassGenerator.h
+++ b/tools/aapt2/java/ManifestClassGenerator.h
@@ -19,14 +19,11 @@
#include "Diagnostics.h"
#include "java/ClassDefinition.h"
-#include "util/StringPiece.h"
#include "xml/XmlDom.h"
-#include <iostream>
-
namespace aapt {
-std::unique_ptr<ClassDefinition> generateManifestClass(IDiagnostics* diag,
+std::unique_ptr<ClassDefinition> GenerateManifestClass(IDiagnostics* diag,
xml::XmlResource* res);
} // namespace aapt
diff --git a/tools/aapt2/java/ManifestClassGenerator_test.cpp b/tools/aapt2/java/ManifestClassGenerator_test.cpp
index eecb544..5ebf508 100644
--- a/tools/aapt2/java/ManifestClassGenerator_test.cpp
+++ b/tools/aapt2/java/ManifestClassGenerator_test.cpp
@@ -15,30 +15,33 @@
*/
#include "java/ManifestClassGenerator.h"
+
#include "test/Test.h"
namespace aapt {
-static ::testing::AssertionResult getManifestClassText(IAaptContext* context, xml::XmlResource* res,
- std::string* outStr) {
- std::unique_ptr<ClassDefinition> manifestClass = generateManifestClass(
- context->getDiagnostics(), res);
- if (!manifestClass) {
- return ::testing::AssertionFailure() << "manifestClass == nullptr";
- }
+static ::testing::AssertionResult GetManifestClassText(IAaptContext* context,
+ xml::XmlResource* res,
+ std::string* out_str) {
+ std::unique_ptr<ClassDefinition> manifest_class =
+ GenerateManifestClass(context->GetDiagnostics(), res);
+ if (!manifest_class) {
+ return ::testing::AssertionFailure() << "manifest_class == nullptr";
+ }
- std::stringstream out;
- if (!manifestClass->writeJavaFile(manifestClass.get(), "android", true, &out)) {
- return ::testing::AssertionFailure() << "failed to write java file";
- }
+ std::stringstream out;
+ if (!manifest_class->WriteJavaFile(manifest_class.get(), "android", true,
+ &out)) {
+ return ::testing::AssertionFailure() << "failed to write java file";
+ }
- *outStr = out.str();
- return ::testing::AssertionSuccess();
+ *out_str = out.str();
+ return ::testing::AssertionSuccess();
}
TEST(ManifestClassGeneratorTest, NameIsProperlyGeneratedFromSymbol) {
- std::unique_ptr<IAaptContext> context = test::ContextBuilder().build();
- std::unique_ptr<xml::XmlResource> manifest = test::buildXmlDom(R"EOF(
+ std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+ std::unique_ptr<xml::XmlResource> manifest = test::BuildXmlDom(R"EOF(
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<permission android:name="android.permission.ACCESS_INTERNET" />
<permission android:name="android.DO_DANGEROUS_THINGS" />
@@ -46,46 +49,51 @@
<permission-group android:name="foo.bar.PERMISSION" />
</manifest>)EOF");
- std::string actual;
- ASSERT_TRUE(getManifestClassText(context.get(), manifest.get(), &actual));
+ std::string actual;
+ ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), &actual));
- const size_t permissionClassPos = actual.find("public static final class permission {");
- const size_t permissionGroupClassPos =
- actual.find("public static final class permission_group {");
- ASSERT_NE(std::string::npos, permissionClassPos);
- ASSERT_NE(std::string::npos, permissionGroupClassPos);
+ const size_t permission_class_pos =
+ actual.find("public static final class permission {");
+ const size_t permission_croup_class_pos =
+ actual.find("public static final class permission_group {");
+ ASSERT_NE(std::string::npos, permission_class_pos);
+ ASSERT_NE(std::string::npos, permission_croup_class_pos);
- //
- // Make sure these permissions are in the permission class.
- //
+ //
+ // Make sure these permissions are in the permission class.
+ //
- size_t pos = actual.find("public static final String ACCESS_INTERNET="
- "\"android.permission.ACCESS_INTERNET\";");
- EXPECT_GT(pos, permissionClassPos);
- EXPECT_LT(pos, permissionGroupClassPos);
+ size_t pos = actual.find(
+ "public static final String ACCESS_INTERNET="
+ "\"android.permission.ACCESS_INTERNET\";");
+ EXPECT_GT(pos, permission_class_pos);
+ EXPECT_LT(pos, permission_croup_class_pos);
- pos = actual.find("public static final String DO_DANGEROUS_THINGS="
- "\"android.DO_DANGEROUS_THINGS\";");
- EXPECT_GT(pos, permissionClassPos);
- EXPECT_LT(pos, permissionGroupClassPos);
+ pos = actual.find(
+ "public static final String DO_DANGEROUS_THINGS="
+ "\"android.DO_DANGEROUS_THINGS\";");
+ EXPECT_GT(pos, permission_class_pos);
+ EXPECT_LT(pos, permission_croup_class_pos);
- pos = actual.find("public static final String HUH=\"com.test.sample.permission.HUH\";");
- EXPECT_GT(pos, permissionClassPos);
- EXPECT_LT(pos, permissionGroupClassPos);
+ pos = actual.find(
+ "public static final String HUH=\"com.test.sample.permission.HUH\";");
+ EXPECT_GT(pos, permission_class_pos);
+ EXPECT_LT(pos, permission_croup_class_pos);
- //
- // Make sure these permissions are in the permission_group class
- //
+ //
+ // Make sure these permissions are in the permission_group class
+ //
- pos = actual.find("public static final String PERMISSION="
- "\"foo.bar.PERMISSION\";");
- EXPECT_GT(pos, permissionGroupClassPos);
- EXPECT_LT(pos, std::string::npos);
+ pos = actual.find(
+ "public static final String PERMISSION="
+ "\"foo.bar.PERMISSION\";");
+ EXPECT_GT(pos, permission_croup_class_pos);
+ EXPECT_LT(pos, std::string::npos);
}
TEST(ManifestClassGeneratorTest, CommentsAndAnnotationsArePresent) {
- std::unique_ptr<IAaptContext> context = test::ContextBuilder().build();
- std::unique_ptr<xml::XmlResource> manifest = test::buildXmlDom(R"EOF(
+ std::unique_ptr<IAaptContext> context = test::ContextBuilder().Build();
+ std::unique_ptr<xml::XmlResource> manifest = test::BuildXmlDom(R"EOF(
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Required to access the internet.
Added in API 1. -->
@@ -98,36 +106,36 @@
<permission android:name="android.permission.SECRET" />
</manifest>)EOF");
- std::string actual;
- ASSERT_TRUE(getManifestClassText(context.get(), manifest.get(), &actual));
+ std::string actual;
+ ASSERT_TRUE(GetManifestClassText(context.get(), manifest.get(), &actual));
- const char* expectedAccessInternet =
-R"EOF( /**
+ const char* expected_access_internet =
+ R"EOF( /**
* Required to access the internet.
* Added in API 1.
*/
public static final String ACCESS_INTERNET="android.permission.ACCESS_INTERNET";)EOF";
- EXPECT_NE(std::string::npos, actual.find(expectedAccessInternet));
+ EXPECT_NE(std::string::npos, actual.find(expected_access_internet));
- const char* expectedPlayOutside =
-R"EOF( /**
+ const char* expected_play_outside =
+ R"EOF( /**
* @deprecated This permission is for playing outside.
*/
@Deprecated
public static final String PLAY_OUTSIDE="android.permission.PLAY_OUTSIDE";)EOF";
- EXPECT_NE(std::string::npos, actual.find(expectedPlayOutside));
+ EXPECT_NE(std::string::npos, actual.find(expected_play_outside));
- const char* expectedSecret =
-R"EOF( /**
+ const char* expected_secret =
+ R"EOF( /**
* This is a private permission for system only!
* @hide
*/
@android.annotation.SystemApi
public static final String SECRET="android.permission.SECRET";)EOF";
- EXPECT_NE(std::string::npos, actual.find(expectedSecret));
+ EXPECT_NE(std::string::npos, actual.find(expected_secret));
}
-} // namespace aapt
+} // namespace aapt
diff --git a/tools/aapt2/java/ProguardRules.cpp b/tools/aapt2/java/ProguardRules.cpp
index 902ec4c..624a559 100644
--- a/tools/aapt2/java/ProguardRules.cpp
+++ b/tools/aapt2/java/ProguardRules.cpp
@@ -15,254 +15,281 @@
*/
#include "java/ProguardRules.h"
-#include "util/Util.h"
-#include "xml/XmlDom.h"
#include <memory>
#include <string>
+#include "android-base/macros.h"
+
+#include "util/Util.h"
+#include "xml/XmlDom.h"
+
namespace aapt {
namespace proguard {
class BaseVisitor : public xml::Visitor {
-public:
- BaseVisitor(const Source& source, KeepSet* keepSet) : mSource(source), mKeepSet(keepSet) {
+ public:
+ BaseVisitor(const Source& source, KeepSet* keep_set)
+ : source_(source), keep_set_(keep_set) {}
+
+ virtual void Visit(xml::Text*) override{};
+
+ virtual void Visit(xml::Namespace* node) override {
+ for (const auto& child : node->children) {
+ child->Accept(this);
}
+ }
- virtual void visit(xml::Text*) override {};
-
- virtual void visit(xml::Namespace* node) override {
- for (const auto& child : node->children) {
- child->accept(this);
+ virtual void Visit(xml::Element* node) override {
+ if (!node->namespace_uri.empty()) {
+ Maybe<xml::ExtractedPackage> maybe_package =
+ xml::ExtractPackageFromNamespace(node->namespace_uri);
+ if (maybe_package) {
+ // This is a custom view, let's figure out the class name from this.
+ std::string package = maybe_package.value().package + "." + node->name;
+ if (util::IsJavaClassName(package)) {
+ AddClass(node->line_number, package);
}
+ }
+ } else if (util::IsJavaClassName(node->name)) {
+ AddClass(node->line_number, node->name);
}
- virtual void visit(xml::Element* node) override {
- if (!node->namespaceUri.empty()) {
- Maybe<xml::ExtractedPackage> maybePackage = xml::extractPackageFromNamespace(
- node->namespaceUri);
- if (maybePackage) {
- // This is a custom view, let's figure out the class name from this.
- std::string package = maybePackage.value().package + "." + node->name;
- if (util::isJavaClassName(package)) {
- addClass(node->lineNumber, package);
- }
- }
- } else if (util::isJavaClassName(node->name)) {
- addClass(node->lineNumber, node->name);
- }
-
- for (const auto& child: node->children) {
- child->accept(this);
- }
+ for (const auto& child : node->children) {
+ child->Accept(this);
}
+ }
-protected:
- void addClass(size_t lineNumber, const std::string& className) {
- mKeepSet->addClass(Source(mSource.path, lineNumber), className);
- }
+ protected:
+ void AddClass(size_t line_number, const std::string& class_name) {
+ keep_set_->AddClass(Source(source_.path, line_number), class_name);
+ }
- void addMethod(size_t lineNumber, const std::string& methodName) {
- mKeepSet->addMethod(Source(mSource.path, lineNumber), methodName);
- }
+ void AddMethod(size_t line_number, const std::string& method_name) {
+ keep_set_->AddMethod(Source(source_.path, line_number), method_name);
+ }
-private:
- Source mSource;
- KeepSet* mKeepSet;
+ private:
+ DISALLOW_COPY_AND_ASSIGN(BaseVisitor);
+
+ Source source_;
+ KeepSet* keep_set_;
};
-struct LayoutVisitor : public BaseVisitor {
- LayoutVisitor(const Source& source, KeepSet* keepSet) : BaseVisitor(source, keepSet) {
+class LayoutVisitor : public BaseVisitor {
+ public:
+ LayoutVisitor(const Source& source, KeepSet* keep_set)
+ : BaseVisitor(source, keep_set) {}
+
+ virtual void Visit(xml::Element* node) override {
+ bool check_class = false;
+ bool check_name = false;
+ if (node->namespace_uri.empty()) {
+ check_class = node->name == "view" || node->name == "fragment";
+ } else if (node->namespace_uri == xml::kSchemaAndroid) {
+ check_name = node->name == "fragment";
}
- virtual void visit(xml::Element* node) override {
- bool checkClass = false;
- bool checkName = false;
- if (node->namespaceUri.empty()) {
- checkClass = node->name == "view" || node->name == "fragment";
- } else if (node->namespaceUri == xml::kSchemaAndroid) {
- checkName = node->name == "fragment";
- }
-
- for (const auto& attr : node->attributes) {
- if (checkClass && attr.namespaceUri.empty() && attr.name == "class" &&
- util::isJavaClassName(attr.value)) {
- addClass(node->lineNumber, attr.value);
- } else if (checkName && attr.namespaceUri == xml::kSchemaAndroid &&
- attr.name == "name" && util::isJavaClassName(attr.value)) {
- addClass(node->lineNumber, attr.value);
- } else if (attr.namespaceUri == xml::kSchemaAndroid && attr.name == "onClick") {
- addMethod(node->lineNumber, attr.value);
- }
- }
-
- BaseVisitor::visit(node);
+ for (const auto& attr : node->attributes) {
+ if (check_class && attr.namespace_uri.empty() && attr.name == "class" &&
+ util::IsJavaClassName(attr.value)) {
+ AddClass(node->line_number, attr.value);
+ } else if (check_name && attr.namespace_uri == xml::kSchemaAndroid &&
+ attr.name == "name" && util::IsJavaClassName(attr.value)) {
+ AddClass(node->line_number, attr.value);
+ } else if (attr.namespace_uri == xml::kSchemaAndroid &&
+ attr.name == "onClick") {
+ AddMethod(node->line_number, attr.value);
+ }
}
+
+ BaseVisitor::Visit(node);
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(LayoutVisitor);
};
-struct XmlResourceVisitor : public BaseVisitor {
- XmlResourceVisitor(const Source& source, KeepSet* keepSet) : BaseVisitor(source, keepSet) {
+class XmlResourceVisitor : public BaseVisitor {
+ public:
+ XmlResourceVisitor(const Source& source, KeepSet* keep_set)
+ : BaseVisitor(source, keep_set) {}
+
+ virtual void Visit(xml::Element* node) override {
+ bool check_fragment = false;
+ if (node->namespace_uri.empty()) {
+ check_fragment =
+ node->name == "PreferenceScreen" || node->name == "header";
}
- virtual void visit(xml::Element* node) override {
- bool checkFragment = false;
- if (node->namespaceUri.empty()) {
- checkFragment = node->name == "PreferenceScreen" || node->name == "header";
- }
-
- if (checkFragment) {
- xml::Attribute* attr = node->findAttribute(xml::kSchemaAndroid, "fragment");
- if (attr && util::isJavaClassName(attr->value)) {
- addClass(node->lineNumber, attr->value);
- }
- }
-
- BaseVisitor::visit(node);
+ if (check_fragment) {
+ xml::Attribute* attr =
+ node->FindAttribute(xml::kSchemaAndroid, "fragment");
+ if (attr && util::IsJavaClassName(attr->value)) {
+ AddClass(node->line_number, attr->value);
+ }
}
+
+ BaseVisitor::Visit(node);
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(XmlResourceVisitor);
};
-struct TransitionVisitor : public BaseVisitor {
- TransitionVisitor(const Source& source, KeepSet* keepSet) : BaseVisitor(source, keepSet) {
+class TransitionVisitor : public BaseVisitor {
+ public:
+ TransitionVisitor(const Source& source, KeepSet* keep_set)
+ : BaseVisitor(source, keep_set) {}
+
+ virtual void Visit(xml::Element* node) override {
+ bool check_class =
+ node->namespace_uri.empty() &&
+ (node->name == "transition" || node->name == "pathMotion");
+ if (check_class) {
+ xml::Attribute* attr = node->FindAttribute({}, "class");
+ if (attr && util::IsJavaClassName(attr->value)) {
+ AddClass(node->line_number, attr->value);
+ }
}
- virtual void visit(xml::Element* node) override {
- bool checkClass = node->namespaceUri.empty() &&
- (node->name == "transition" || node->name == "pathMotion");
- if (checkClass) {
- xml::Attribute* attr = node->findAttribute({}, "class");
- if (attr && util::isJavaClassName(attr->value)) {
- addClass(node->lineNumber, attr->value);
- }
- }
+ BaseVisitor::Visit(node);
+ }
- BaseVisitor::visit(node);
- }
+ private:
+ DISALLOW_COPY_AND_ASSIGN(TransitionVisitor);
};
-struct ManifestVisitor : public BaseVisitor {
- ManifestVisitor(const Source& source, KeepSet* keepSet, bool mainDexOnly)
- : BaseVisitor(source, keepSet), mMainDexOnly(mainDexOnly) {
- }
+class ManifestVisitor : public BaseVisitor {
+ public:
+ ManifestVisitor(const Source& source, KeepSet* keep_set, bool main_dex_only)
+ : BaseVisitor(source, keep_set), main_dex_only_(main_dex_only) {}
- virtual void visit(xml::Element* node) override {
- if (node->namespaceUri.empty()) {
- bool getName = false;
- if (node->name == "manifest") {
- xml::Attribute* attr = node->findAttribute({}, "package");
- if (attr) {
- mPackage = attr->value;
- }
- } else if (node->name == "application") {
- getName = true;
- xml::Attribute* attr = node->findAttribute(xml::kSchemaAndroid, "backupAgent");
- if (attr) {
- Maybe<std::string> result = util::getFullyQualifiedClassName(mPackage,
- attr->value);
- if (result) {
- addClass(node->lineNumber, result.value());
- }
- }
- if (mMainDexOnly) {
- xml::Attribute* defaultProcess = node->findAttribute(xml::kSchemaAndroid,
- "process");
- if (defaultProcess) {
- mDefaultProcess = defaultProcess->value;
- }
- }
- } else if (node->name == "activity" || node->name == "service" ||
- node->name == "receiver" || node->name == "provider") {
- getName = true;
-
- if (mMainDexOnly) {
- xml::Attribute* componentProcess = node->findAttribute(xml::kSchemaAndroid,
- "process");
-
- const std::string& process = componentProcess ? componentProcess->value
- : mDefaultProcess;
- getName = !process.empty() && process[0] != ':';
- }
- } else if (node-> name == "instrumentation") {
- getName = true;
- }
-
- if (getName) {
- xml::Attribute* attr = node->findAttribute(xml::kSchemaAndroid, "name");
- getName = attr != nullptr;
-
- if (getName) {
- Maybe<std::string> result = util::getFullyQualifiedClassName(mPackage,
- attr->value);
- if (result) {
- addClass(node->lineNumber, result.value());
- }
- }
- }
+ virtual void Visit(xml::Element* node) override {
+ if (node->namespace_uri.empty()) {
+ bool get_name = false;
+ if (node->name == "manifest") {
+ xml::Attribute* attr = node->FindAttribute({}, "package");
+ if (attr) {
+ package_ = attr->value;
}
- BaseVisitor::visit(node);
- }
+ } else if (node->name == "application") {
+ get_name = true;
+ xml::Attribute* attr =
+ node->FindAttribute(xml::kSchemaAndroid, "backupAgent");
+ if (attr) {
+ Maybe<std::string> result =
+ util::GetFullyQualifiedClassName(package_, attr->value);
+ if (result) {
+ AddClass(node->line_number, result.value());
+ }
+ }
+ if (main_dex_only_) {
+ xml::Attribute* default_process =
+ node->FindAttribute(xml::kSchemaAndroid, "process");
+ if (default_process) {
+ default_process_ = default_process->value;
+ }
+ }
+ } else if (node->name == "activity" || node->name == "service" ||
+ node->name == "receiver" || node->name == "provider") {
+ get_name = true;
-private:
- std::string mPackage;
- const bool mMainDexOnly;
- std::string mDefaultProcess;
+ if (main_dex_only_) {
+ xml::Attribute* component_process =
+ node->FindAttribute(xml::kSchemaAndroid, "process");
+
+ const std::string& process =
+ component_process ? component_process->value : default_process_;
+ get_name = !process.empty() && process[0] != ':';
+ }
+ } else if (node->name == "instrumentation") {
+ get_name = true;
+ }
+
+ if (get_name) {
+ xml::Attribute* attr = node->FindAttribute(xml::kSchemaAndroid, "name");
+ get_name = attr != nullptr;
+
+ if (get_name) {
+ Maybe<std::string> result =
+ util::GetFullyQualifiedClassName(package_, attr->value);
+ if (result) {
+ AddClass(node->line_number, result.value());
+ }
+ }
+ }
+ }
+ BaseVisitor::Visit(node);
+ }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ManifestVisitor);
+
+ std::string package_;
+ const bool main_dex_only_;
+ std::string default_process_;
};
-bool collectProguardRulesForManifest(const Source& source, xml::XmlResource* res,
- KeepSet* keepSet, bool mainDexOnly) {
- ManifestVisitor visitor(source, keepSet, mainDexOnly);
- if (res->root) {
- res->root->accept(&visitor);
- return true;
- }
+bool CollectProguardRulesForManifest(const Source& source,
+ xml::XmlResource* res, KeepSet* keep_set,
+ bool main_dex_only) {
+ ManifestVisitor visitor(source, keep_set, main_dex_only);
+ if (res->root) {
+ res->root->Accept(&visitor);
+ return true;
+ }
+ return false;
+}
+
+bool CollectProguardRules(const Source& source, xml::XmlResource* res,
+ KeepSet* keep_set) {
+ if (!res->root) {
return false;
+ }
+
+ switch (res->file.name.type) {
+ case ResourceType::kLayout: {
+ LayoutVisitor visitor(source, keep_set);
+ res->root->Accept(&visitor);
+ break;
+ }
+
+ case ResourceType::kXml: {
+ XmlResourceVisitor visitor(source, keep_set);
+ res->root->Accept(&visitor);
+ break;
+ }
+
+ case ResourceType::kTransition: {
+ TransitionVisitor visitor(source, keep_set);
+ res->root->Accept(&visitor);
+ break;
+ }
+
+ default:
+ break;
+ }
+ return true;
}
-bool collectProguardRules(const Source& source, xml::XmlResource* res, KeepSet* keepSet) {
- if (!res->root) {
- return false;
+bool WriteKeepSet(std::ostream* out, const KeepSet& keep_set) {
+ for (const auto& entry : keep_set.keep_set_) {
+ for (const Source& source : entry.second) {
+ *out << "# Referenced at " << source << "\n";
}
+ *out << "-keep class " << entry.first << " { <init>(...); }\n" << std::endl;
+ }
- switch (res->file.name.type) {
- case ResourceType::kLayout: {
- LayoutVisitor visitor(source, keepSet);
- res->root->accept(&visitor);
- break;
- }
-
- case ResourceType::kXml: {
- XmlResourceVisitor visitor(source, keepSet);
- res->root->accept(&visitor);
- break;
- }
-
- case ResourceType::kTransition: {
- TransitionVisitor visitor(source, keepSet);
- res->root->accept(&visitor);
- break;
- }
-
- default:
- break;
+ for (const auto& entry : keep_set.keep_method_set_) {
+ for (const Source& source : entry.second) {
+ *out << "# Referenced at " << source << "\n";
}
- return true;
+ *out << "-keepclassmembers class * { *** " << entry.first << "(...); }\n"
+ << std::endl;
+ }
+ return true;
}
-bool writeKeepSet(std::ostream* out, const KeepSet& keepSet) {
- for (const auto& entry : keepSet.mKeepSet) {
- for (const Source& source : entry.second) {
- *out << "# Referenced at " << source << "\n";
- }
- *out << "-keep class " << entry.first << " { <init>(...); }\n" << std::endl;
- }
-
- for (const auto& entry : keepSet.mKeepMethodSet) {
- for (const Source& source : entry.second) {
- *out << "# Referenced at " << source << "\n";
- }
- *out << "-keepclassmembers class * { *** " << entry.first << "(...); }\n" << std::endl;
- }
- return true;
-}
-
-} // namespace proguard
-} // namespace aapt
+} // namespace proguard
+} // namespace aapt
diff --git a/tools/aapt2/java/ProguardRules.h b/tools/aapt2/java/ProguardRules.h
index 7578ec2..3c349ba 100644
--- a/tools/aapt2/java/ProguardRules.h
+++ b/tools/aapt2/java/ProguardRules.h
@@ -17,42 +17,42 @@
#ifndef AAPT_PROGUARD_RULES_H
#define AAPT_PROGUARD_RULES_H
-#include "Resource.h"
-#include "Source.h"
-#include "xml/XmlDom.h"
-
#include <map>
#include <ostream>
#include <set>
#include <string>
+#include "Resource.h"
+#include "Source.h"
+#include "xml/XmlDom.h"
+
namespace aapt {
namespace proguard {
class KeepSet {
public:
- inline void addClass(const Source& source, const std::string& className) {
- mKeepSet[className].insert(source);
+ inline void AddClass(const Source& source, const std::string& class_name) {
+ keep_set_[class_name].insert(source);
}
- inline void addMethod(const Source& source, const std::string& methodName) {
- mKeepMethodSet[methodName].insert(source);
+ inline void AddMethod(const Source& source, const std::string& method_name) {
+ keep_method_set_[method_name].insert(source);
}
private:
- friend bool writeKeepSet(std::ostream* out, const KeepSet& keepSet);
+ friend bool WriteKeepSet(std::ostream* out, const KeepSet& keep_set);
- std::map<std::string, std::set<Source>> mKeepSet;
- std::map<std::string, std::set<Source>> mKeepMethodSet;
+ std::map<std::string, std::set<Source>> keep_set_;
+ std::map<std::string, std::set<Source>> keep_method_set_;
};
-bool collectProguardRulesForManifest(const Source& source,
- xml::XmlResource* res, KeepSet* keepSet,
- bool mainDexOnly = false);
-bool collectProguardRules(const Source& source, xml::XmlResource* res,
- KeepSet* keepSet);
+bool CollectProguardRulesForManifest(const Source& source,
+ xml::XmlResource* res, KeepSet* keep_set,
+ bool main_dex_only = false);
+bool CollectProguardRules(const Source& source, xml::XmlResource* res,
+ KeepSet* keep_set);
-bool writeKeepSet(std::ostream* out, const KeepSet& keepSet);
+bool WriteKeepSet(std::ostream* out, const KeepSet& keep_set);
} // namespace proguard
} // namespace aapt