diff options
Diffstat (limited to 'tools/aapt2/java/JavaClassGenerator.cpp')
-rw-r--r-- | tools/aapt2/java/JavaClassGenerator.cpp | 390 |
1 files changed, 274 insertions, 116 deletions
diff --git a/tools/aapt2/java/JavaClassGenerator.cpp b/tools/aapt2/java/JavaClassGenerator.cpp index 6e340a2a2742..2d076c2d5a66 100644 --- a/tools/aapt2/java/JavaClassGenerator.cpp +++ b/tools/aapt2/java/JavaClassGenerator.cpp @@ -21,8 +21,9 @@ #include "ValueVisitor.h" #include "java/AnnotationProcessor.h" -#include "java/ClassDefinitionWriter.h" +#include "java/ClassDefinition.h" #include "java/JavaClassGenerator.h" +#include "process/SymbolTable.h" #include "util/StringPiece.h" #include <algorithm> @@ -33,18 +34,9 @@ namespace aapt { -JavaClassGenerator::JavaClassGenerator(ResourceTable* table, JavaClassGeneratorOptions options) : - mTable(table), mOptions(options) { -} - -static void generateHeader(const StringPiece16& packageNameToGenerate, std::ostream* out) { - *out << "/* 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" - "package " << packageNameToGenerate << ";\n\n"; +JavaClassGenerator::JavaClassGenerator(IAaptContext* context, ResourceTable* table, + const JavaClassGeneratorOptions& options) : + mContext(context), mTable(table), mOptions(options) { } static const std::set<StringPiece16> sJavaIdentifiers = { @@ -68,71 +60,39 @@ static bool isValidSymbol(const StringPiece16& symbol) { * Java symbols can not contain . or -, but those are valid in a resource name. * Replace those with '_'. */ -static std::u16string transform(const StringPiece16& symbol) { - std::u16string output = symbol.toString(); - for (char16_t& c : output) { - if (c == u'.' || c == u'-') { - c = u'_'; +static std::string transform(const StringPiece16& symbol) { + std::string output = util::utf16ToUtf8(symbol); + for (char& c : output) { + if (c == '.' || c == '-') { + c = '_'; } } return output; } -bool JavaClassGenerator::skipSymbol(SymbolState state) { - switch (mOptions.types) { - case JavaClassGeneratorOptions::SymbolTypes::kAll: - return false; - case JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate: - return state == SymbolState::kUndefined; - case JavaClassGeneratorOptions::SymbolTypes::kPublic: - return state != SymbolState::kPublic; - } - return true; -} - -void JavaClassGenerator::writeStyleableEntryForClass(ClassDefinitionWriter* outClassDef, - AnnotationProcessor* processor, - const StringPiece16& packageNameToGenerate, - const std::u16string& entryName, - const Styleable* styleable) { - // This must be sorted by resource ID. - std::vector<std::pair<ResourceId, ResourceNameRef>> 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"); - sortedAttributes.emplace_back(attr.id ? attr.id.value() : ResourceId(0), attr.name.value()); - } - std::sort(sortedAttributes.begin(), sortedAttributes.end()); - - auto accessorFunc = [](const std::pair<ResourceId, ResourceNameRef>& a) -> ResourceId { - return a.first; - }; - - // First we emit the array containing the IDs of each attribute. - outClassDef->addArrayMember(transform(entryName), processor, - sortedAttributes.begin(), - sortedAttributes.end(), - accessorFunc); - - // Now we emit the indices into the array. - size_t attrCount = sortedAttributes.size(); - for (size_t i = 0; i < attrCount; i++) { - std::stringstream name; - name << transform(entryName); - - // We may reference IDs from other packages, so prefix the entry name with - // the package. - const ResourceNameRef& itemName = sortedAttributes[i].second; - if (!itemName.package.empty() && packageNameToGenerate != itemName.package) { - name << "_" << transform(itemName.package); - } - name << "_" << transform(itemName.entry); - - outClassDef->addIntMember(name.str(), nullptr, i); +/** + * Transforms an attribute in a styleable to the Java field name: + * + * <declare-styleable name="Foo"> + * <attr name="android:bar" /> + * <attr name="bar" /> + * </declare-styleable> + * + * Foo_android_bar + * Foo_bar + */ +static std::string transformNestedAttr(const ResourceNameRef& attrName, + const std::string& styleableClassName, + const StringPiece16& packageNameToGenerate) { + std::string output = styleableClassName; + + // 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; } static void addAttributeFormatDoc(AnnotationProcessor* processor, Attribute* attr) { @@ -206,25 +166,209 @@ static void addAttributeFormatDoc(AnnotationProcessor* processor, Attribute* att 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>"; + << "<td>" << std::hex << symbol.value << std::dec << "</td>" + << "<td>" << util::trimWhitespace(symbol.symbol.getComment()) << "</td></tr>"; processor->appendComment(line.str()); } processor->appendComment("</table>"); } } -bool JavaClassGenerator::writeEntriesForClass(ClassDefinitionWriter* outClassDef, - const StringPiece16& packageNameToGenerate, - const ResourceTablePackage* package, - const ResourceTableType* type) { +bool JavaClassGenerator::skipSymbol(SymbolState state) { + switch (mOptions.types) { + case JavaClassGeneratorOptions::SymbolTypes::kAll: + return false; + case JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate: + return state == SymbolState::kUndefined; + case JavaClassGeneratorOptions::SymbolTypes::kPublic: + return state != SymbolState::kPublic; + } + return true; +} + +struct StyleableAttr { + const Reference* attrRef; + std::shared_ptr<Attribute> attribute; + std::string fieldName; +}; + +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; + } else { + return lhs.attrRef->name.value() < rhs.attrRef->name.value(); + } +} + +void JavaClassGenerator::addMembersToStyleableClass(const StringPiece16& packageNameToGenerate, + const std::u16string& 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) { + styleableAttr.attribute = symbol->attribute; + } + sortedAttributes.push_back(std::move(styleableAttr)); + } + + // 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) { + 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>"; + if (entry.attribute) { + styleableComment << entry.attribute->getComment(); + } + styleableComment << "</td></tr>\n"; + } + styleableComment << "</table>\n"; + + for (const StyleableAttr& entry : sortedAttributes) { + styleableComment << "@see #" << entry.fieldName << "\n"; + } + + styleableArrayDef->getCommentBuilder()->appendComment(styleableComment.str()); + } + + // Add the ResourceIds to the array member. + for (const StyleableAttr& styleableAttr : sortedAttributes) { + styleableArrayDef->addElement( + styleableAttr.attrRef->id ? styleableAttr.attrRef->id.value() : ResourceId(0)); + } + + // 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]; + const ResourceName& attrName = styleableAttr.attrRef->name.value(); + + StringPiece16 packageName = attrName.package; + if (packageName.empty()) { + packageName = mContext->getCompilationPackage(); + } + + std::unique_ptr<IntMember> indexMember = util::make_unique<IntMember>( + sortedAttributes[i].fieldName, i); + + AnnotationProcessor* attrProcessor = indexMember->getCommentBuilder(); + + StringPiece16 comment = styleableAttr.attrRef->getComment(); + if (styleableAttr.attribute && comment.empty()) { + comment = styleableAttr.attribute->getComment(); + } + + 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(); + + if (styleableAttr.attribute) { + addAttributeFormatDoc(attrProcessor, styleableAttr.attribute.get()); + attrProcessor->appendNewLine(); + } + + std::stringstream doclavaName; + doclavaName << "@attr name " << packageName << ":" << attrName.entry;; + attrProcessor->appendComment(doclavaName.str()); + + outStyleableClassDef->addMember(std::move(indexMember)); + } +} + +bool JavaClassGenerator::addMembersToTypeClass(const StringPiece16& packageNameToGenerate, + const ResourceTablePackage* package, + const ResourceTableType* type, + ClassDefinition* outTypeClassDef) { + for (const auto& entry : type->entries) { if (skipSymbol(entry->symbolStatus.state)) { continue; } - ResourceId id(package->id.value(), type->id.value(), entry->id.value()); - assert(id.isValid()); + ResourceId id; + if (package->id && type->id && entry->id) { + id = ResourceId(package->id.value(), type->id.value(), entry->id.value()); + } std::u16string unmangledPackage; std::u16string unmangledName = entry->name; @@ -249,33 +393,41 @@ bool JavaClassGenerator::writeEntriesForClass(ClassDefinitionWriter* outClassDef return false; } - // Build the comments and annotations for this entry. - - AnnotationProcessor processor; - if (entry->symbolStatus.state != SymbolState::kUndefined) { - processor.appendComment(entry->symbolStatus.comment); - } - - 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); - } - } - if (type->type == ResourceType::kStyleable) { assert(!entry->values.empty()); + const Styleable* styleable = static_cast<const Styleable*>( entry->values.front()->value.get()); - writeStyleableEntryForClass(outClassDef, &processor, packageNameToGenerate, - unmangledName, styleable); + + // Comments are handled within this method. + addMembersToStyleableClass(packageNameToGenerate, unmangledName, styleable, + outTypeClassDef); } else { - outClassDef->addResourceMember(transform(unmangledName), &processor, id); + 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; @@ -287,9 +439,8 @@ bool JavaClassGenerator::generate(const StringPiece16& packageNameToGenerate, st bool JavaClassGenerator::generate(const StringPiece16& packageNameToGenerate, const StringPiece16& outPackageName, std::ostream* out) { - generateHeader(outPackageName, out); - *out << "public final class R {\n"; + ClassDefinition rClass("R", ClassQualifier::None, true); for (const auto& package : mTable->packages) { for (const auto& type : package->types) { @@ -297,13 +448,15 @@ bool JavaClassGenerator::generate(const StringPiece16& packageNameToGenerate, continue; } - ClassDefinitionWriterOptions classOptions; - classOptions.useFinalQualifier = mOptions.useFinal; - classOptions.forceCreationIfEmpty = + const bool forceCreationIfEmpty = (mOptions.types == JavaClassGeneratorOptions::SymbolTypes::kPublic); - ClassDefinitionWriter classDef(toString(type->type), classOptions); - bool result = writeEntriesForClass(&classDef, packageNameToGenerate, - package.get(), type.get()); + + std::unique_ptr<ClassDefinition> classDef = util::make_unique<ClassDefinition>( + util::utf16ToUtf8(toString(type->type)), ClassQualifier::Static, + forceCreationIfEmpty); + + bool result = addMembersToTypeClass(packageNameToGenerate, package.get(), type.get(), + classDef.get()); if (!result) { return false; } @@ -312,26 +465,31 @@ bool JavaClassGenerator::generate(const StringPiece16& packageNameToGenerate, // Also include private attributes in this same class. ResourceTableType* privType = package->findType(ResourceType::kAttrPrivate); if (privType) { - result = writeEntriesForClass(&classDef, packageNameToGenerate, - package.get(), privType); + result = addMembersToTypeClass(packageNameToGenerate, package.get(), privType, + classDef.get()); if (!result) { return false; } } } - AnnotationProcessor processor; 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. - processor.appendComment("@doconly"); + AnnotationProcessor* processor = classDef->getCommentBuilder(); + processor->appendComment("@doconly"); } - classDef.writeToStream(out, " ", &processor); + + rClass.addMember(std::move(classDef)); } } - *out << "}\n"; + if (!ClassDefinition::writeJavaFile(&rClass, util::utf16ToUtf8(outPackageName), + mOptions.useFinal, out)) { + return false; + } + out->flush(); return true; } |