blob: 6e340a2a27427542422d197f69d0d61792f9576e [file] [log] [blame]
Adam Lesinski6f6ceb72014-11-14 14:48:12 -08001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Adam Lesinski769de982015-04-10 19:43:55 -070017#include "NameMangler.h"
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080018#include "Resource.h"
19#include "ResourceTable.h"
20#include "ResourceValues.h"
Adam Lesinski3b4cd942015-10-30 16:31:42 -070021#include "ValueVisitor.h"
22
Adam Lesinskica5638f2015-10-21 14:42:43 -070023#include "java/AnnotationProcessor.h"
Adam Lesinskib274e352015-11-06 15:14:35 -080024#include "java/ClassDefinitionWriter.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070025#include "java/JavaClassGenerator.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070026#include "util/StringPiece.h"
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080027
Adam Lesinskica2fc352015-04-03 12:08:26 -070028#include <algorithm>
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080029#include <ostream>
30#include <set>
31#include <sstream>
32#include <tuple>
33
34namespace aapt {
35
Adam Lesinski1ab598f2015-08-14 14:26:04 -070036JavaClassGenerator::JavaClassGenerator(ResourceTable* table, JavaClassGeneratorOptions options) :
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080037 mTable(table), mOptions(options) {
38}
39
Adam Lesinski1ab598f2015-08-14 14:26:04 -070040static void generateHeader(const StringPiece16& packageNameToGenerate, std::ostream* out) {
41 *out << "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
42 " *\n"
43 " * This class was automatically generated by the\n"
44 " * aapt tool from the resource data it found. It\n"
45 " * should not be modified by hand.\n"
46 " */\n\n"
47 "package " << packageNameToGenerate << ";\n\n";
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080048}
49
50static const std::set<StringPiece16> sJavaIdentifiers = {
51 u"abstract", u"assert", u"boolean", u"break", u"byte",
52 u"case", u"catch", u"char", u"class", u"const", u"continue",
53 u"default", u"do", u"double", u"else", u"enum", u"extends",
54 u"final", u"finally", u"float", u"for", u"goto", u"if",
55 u"implements", u"import", u"instanceof", u"int", u"interface",
56 u"long", u"native", u"new", u"package", u"private", u"protected",
57 u"public", u"return", u"short", u"static", u"strictfp", u"super",
58 u"switch", u"synchronized", u"this", u"throw", u"throws",
59 u"transient", u"try", u"void", u"volatile", u"while", u"true",
60 u"false", u"null"
61};
62
63static bool isValidSymbol(const StringPiece16& symbol) {
64 return sJavaIdentifiers.find(symbol) == sJavaIdentifiers.end();
65}
66
67/*
68 * Java symbols can not contain . or -, but those are valid in a resource name.
69 * Replace those with '_'.
70 */
71static std::u16string transform(const StringPiece16& symbol) {
72 std::u16string output = symbol.toString();
73 for (char16_t& c : output) {
74 if (c == u'.' || c == u'-') {
75 c = u'_';
76 }
77 }
78 return output;
79}
80
Adam Lesinski9e10ac72015-10-16 14:37:48 -070081bool JavaClassGenerator::skipSymbol(SymbolState state) {
82 switch (mOptions.types) {
83 case JavaClassGeneratorOptions::SymbolTypes::kAll:
84 return false;
85 case JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate:
86 return state == SymbolState::kUndefined;
87 case JavaClassGeneratorOptions::SymbolTypes::kPublic:
88 return state != SymbolState::kPublic;
89 }
90 return true;
91}
92
Adam Lesinskib274e352015-11-06 15:14:35 -080093void JavaClassGenerator::writeStyleableEntryForClass(ClassDefinitionWriter* outClassDef,
94 AnnotationProcessor* processor,
95 const StringPiece16& packageNameToGenerate,
96 const std::u16string& entryName,
97 const Styleable* styleable) {
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080098 // This must be sorted by resource ID.
Adam Lesinski838a6872015-05-01 13:14:05 -070099 std::vector<std::pair<ResourceId, ResourceNameRef>> sortedAttributes;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700100 sortedAttributes.reserve(styleable->entries.size());
101 for (const auto& attr : styleable->entries) {
Adam Lesinski330edcd2015-05-04 17:40:56 -0700102 // If we are not encoding final attributes, the styleable entry may have no ID
103 // if we are building a static library.
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700104 assert((!mOptions.useFinal || attr.id) && "no ID set for Styleable entry");
105 assert(attr.name && "no name set for Styleable entry");
106 sortedAttributes.emplace_back(attr.id ? attr.id.value() : ResourceId(0), attr.name.value());
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800107 }
108 std::sort(sortedAttributes.begin(), sortedAttributes.end());
109
Adam Lesinskib274e352015-11-06 15:14:35 -0800110 auto accessorFunc = [](const std::pair<ResourceId, ResourceNameRef>& a) -> ResourceId {
111 return a.first;
112 };
113
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800114 // First we emit the array containing the IDs of each attribute.
Adam Lesinskib274e352015-11-06 15:14:35 -0800115 outClassDef->addArrayMember(transform(entryName), processor,
116 sortedAttributes.begin(),
117 sortedAttributes.end(),
118 accessorFunc);
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800119
120 // Now we emit the indices into the array.
Adam Lesinskib274e352015-11-06 15:14:35 -0800121 size_t attrCount = sortedAttributes.size();
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800122 for (size_t i = 0; i < attrCount; i++) {
Adam Lesinskib274e352015-11-06 15:14:35 -0800123 std::stringstream name;
124 name << transform(entryName);
Adam Lesinski838a6872015-05-01 13:14:05 -0700125
126 // We may reference IDs from other packages, so prefix the entry name with
127 // the package.
128 const ResourceNameRef& itemName = sortedAttributes[i].second;
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700129 if (!itemName.package.empty() && packageNameToGenerate != itemName.package) {
Adam Lesinskib274e352015-11-06 15:14:35 -0800130 name << "_" << transform(itemName.package);
Adam Lesinski838a6872015-05-01 13:14:05 -0700131 }
Adam Lesinskib274e352015-11-06 15:14:35 -0800132 name << "_" << transform(itemName.entry);
133
134 outClassDef->addIntMember(name.str(), nullptr, i);
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800135 }
136}
137
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700138static void addAttributeFormatDoc(AnnotationProcessor* processor, Attribute* attr) {
139 const uint32_t typeMask = attr->typeMask;
140 if (typeMask & android::ResTable_map::TYPE_REFERENCE) {
141 processor->appendComment(
142 "<p>May be a reference to another resource, in the form\n"
143 "\"<code>@[+][<i>package</i>:]<i>type</i>/<i>name</i></code>\" or a theme\n"
144 "attribute in the form\n"
145 "\"<code>?[<i>package</i>:]<i>type</i>/<i>name</i></code>\".");
146 }
147
148 if (typeMask & android::ResTable_map::TYPE_STRING) {
149 processor->appendComment(
Adam Lesinskib274e352015-11-06 15:14:35 -0800150 "<p>May be a string value, using '\\\\;' to escape characters such as\n"
151 "'\\\\n' or '\\\\uxxxx' for a unicode character;");
Adam Lesinski3b4cd942015-10-30 16:31:42 -0700152 }
153
154 if (typeMask & android::ResTable_map::TYPE_INTEGER) {
155 processor->appendComment("<p>May be an integer value, such as \"<code>100</code>\".");
156 }
157
158 if (typeMask & android::ResTable_map::TYPE_BOOLEAN) {
159 processor->appendComment(
160 "<p>May be a boolean value, such as \"<code>true</code>\" or\n"
161 "\"<code>false</code>\".");
162 }
163
164 if (typeMask & android::ResTable_map::TYPE_COLOR) {
165 processor->appendComment(
166 "<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\",\n"
167 "\"<code>#<i>argb</i></code>\", \"<code>#<i>rrggbb</i></code\", or \n"
168 "\"<code>#<i>aarrggbb</i></code>\".");
169 }
170
171 if (typeMask & android::ResTable_map::TYPE_FLOAT) {
172 processor->appendComment(
173 "<p>May be a floating point value, such as \"<code>1.2</code>\".");
174 }
175
176 if (typeMask & android::ResTable_map::TYPE_DIMENSION) {
177 processor->appendComment(
178 "<p>May be a dimension value, which is a floating point number appended with a\n"
179 "unit such as \"<code>14.5sp</code>\".\n"
180 "Available units are: px (pixels), dp (density-independent pixels),\n"
181 "sp (scaled pixels based on preferred font size), in (inches), and\n"
182 "mm (millimeters).");
183 }
184
185 if (typeMask & android::ResTable_map::TYPE_FRACTION) {
186 processor->appendComment(
187 "<p>May be a fractional value, which is a floating point number appended with\n"
188 "either % or %p, such as \"<code>14.5%</code>\".\n"
189 "The % suffix always means a percentage of the base size;\n"
190 "the optional %p suffix provides a size relative to some parent container.");
191 }
192
193 if (typeMask & (android::ResTable_map::TYPE_FLAGS | android::ResTable_map::TYPE_ENUM)) {
194 if (typeMask & android::ResTable_map::TYPE_FLAGS) {
195 processor->appendComment(
196 "<p>Must be one or more (separated by '|') of the following "
197 "constant values.</p>");
198 } else {
199 processor->appendComment("<p>Must be one of the following constant values.</p>");
200 }
201
202 processor->appendComment("<table>\n<colgroup align=\"left\" />\n"
203 "<colgroup align=\"left\" />\n"
204 "<colgroup align=\"left\" />\n"
205 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n");
206 for (const Attribute::Symbol& symbol : attr->symbols) {
207 std::stringstream line;
208 line << "<tr><td>" << symbol.symbol.name.value().entry << "</td>"
209 << "<td>" << std::hex << symbol.value << std::dec << "</td>"
210 << "<td>" << util::trimWhitespace(symbol.symbol.getComment()) << "</td></tr>";
211 processor->appendComment(line.str());
212 }
213 processor->appendComment("</table>");
214 }
215}
216
Adam Lesinskib274e352015-11-06 15:14:35 -0800217bool JavaClassGenerator::writeEntriesForClass(ClassDefinitionWriter* outClassDef,
218 const StringPiece16& packageNameToGenerate,
219 const ResourceTablePackage* package,
220 const ResourceTableType* type) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700221 for (const auto& entry : type->entries) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700222 if (skipSymbol(entry->symbolStatus.state)) {
223 continue;
224 }
225
226 ResourceId id(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinski769de982015-04-10 19:43:55 -0700227 assert(id.isValid());
228
Adam Lesinskib274e352015-11-06 15:14:35 -0800229 std::u16string unmangledPackage;
230 std::u16string unmangledName = entry->name;
Adam Lesinski769de982015-04-10 19:43:55 -0700231 if (NameMangler::unmangle(&unmangledName, &unmangledPackage)) {
232 // The entry name was mangled, and we successfully unmangled it.
233 // Check that we want to emit this symbol.
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700234 if (package->name != unmangledPackage) {
Adam Lesinski769de982015-04-10 19:43:55 -0700235 // Skip the entry if it doesn't belong to the package we're writing.
236 continue;
237 }
Adam Lesinskib274e352015-11-06 15:14:35 -0800238 } else if (packageNameToGenerate != package->name) {
239 // We are processing a mangled package name,
240 // but this is a non-mangled resource.
241 continue;
Adam Lesinski769de982015-04-10 19:43:55 -0700242 }
243
244 if (!isValidSymbol(unmangledName)) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700245 ResourceNameRef resourceName(packageNameToGenerate, type->type, unmangledName);
Adam Lesinski769de982015-04-10 19:43:55 -0700246 std::stringstream err;
247 err << "invalid symbol name '" << resourceName << "'";
248 mError = err.str();
249 return false;
250 }
251
Adam Lesinskib274e352015-11-06 15:14:35 -0800252 // Build the comments and annotations for this entry.
253
254 AnnotationProcessor processor;
255 if (entry->symbolStatus.state != SymbolState::kUndefined) {
256 processor.appendComment(entry->symbolStatus.comment);
257 }
258
259 for (const auto& configValue : entry->values) {
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -0800260 processor.appendComment(configValue->value->getComment());
Adam Lesinskib274e352015-11-06 15:14:35 -0800261 }
262
263 // If this is an Attribute, append the format Javadoc.
264 if (!entry->values.empty()) {
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -0800265 if (Attribute* attr = valueCast<Attribute>(entry->values.front()->value.get())) {
Adam Lesinskib274e352015-11-06 15:14:35 -0800266 // We list out the available values for the given attribute.
267 addAttributeFormatDoc(&processor, attr);
268 }
269 }
270
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700271 if (type->type == ResourceType::kStyleable) {
Adam Lesinski769de982015-04-10 19:43:55 -0700272 assert(!entry->values.empty());
Adam Lesinskib274e352015-11-06 15:14:35 -0800273 const Styleable* styleable = static_cast<const Styleable*>(
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -0800274 entry->values.front()->value.get());
Adam Lesinskib274e352015-11-06 15:14:35 -0800275 writeStyleableEntryForClass(outClassDef, &processor, packageNameToGenerate,
276 unmangledName, styleable);
Adam Lesinski769de982015-04-10 19:43:55 -0700277 } else {
Adam Lesinskib274e352015-11-06 15:14:35 -0800278 outClassDef->addResourceMember(transform(unmangledName), &processor, id);
Adam Lesinski769de982015-04-10 19:43:55 -0700279 }
280 }
281 return true;
282}
283
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700284bool JavaClassGenerator::generate(const StringPiece16& packageNameToGenerate, std::ostream* out) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700285 return generate(packageNameToGenerate, packageNameToGenerate, out);
286}
287
288bool JavaClassGenerator::generate(const StringPiece16& packageNameToGenerate,
289 const StringPiece16& outPackageName, std::ostream* out) {
290 generateHeader(outPackageName, out);
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800291
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700292 *out << "public final class R {\n";
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800293
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700294 for (const auto& package : mTable->packages) {
295 for (const auto& type : package->types) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700296 if (type->type == ResourceType::kAttrPrivate) {
Adam Lesinskib274e352015-11-06 15:14:35 -0800297 continue;
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700298 }
Adam Lesinskib274e352015-11-06 15:14:35 -0800299
300 ClassDefinitionWriterOptions classOptions;
301 classOptions.useFinalQualifier = mOptions.useFinal;
302 classOptions.forceCreationIfEmpty =
303 (mOptions.types == JavaClassGeneratorOptions::SymbolTypes::kPublic);
304 ClassDefinitionWriter classDef(toString(type->type), classOptions);
305 bool result = writeEntriesForClass(&classDef, packageNameToGenerate,
306 package.get(), type.get());
307 if (!result) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700308 return false;
309 }
Adam Lesinskib274e352015-11-06 15:14:35 -0800310
311 if (type->type == ResourceType::kAttr) {
312 // Also include private attributes in this same class.
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -0800313 ResourceTableType* privType = package->findType(ResourceType::kAttrPrivate);
314 if (privType) {
Adam Lesinskib274e352015-11-06 15:14:35 -0800315 result = writeEntriesForClass(&classDef, packageNameToGenerate,
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -0800316 package.get(), privType);
Adam Lesinskib274e352015-11-06 15:14:35 -0800317 if (!result) {
318 return false;
319 }
320 }
321 }
322
323 AnnotationProcessor processor;
324 if (type->type == ResourceType::kStyleable &&
325 mOptions.types == JavaClassGeneratorOptions::SymbolTypes::kPublic) {
326 // When generating a public R class, we don't want Styleable to be part of the API.
327 // It is only emitted for documentation purposes.
328 processor.appendComment("@doconly");
329 }
330 classDef.writeToStream(out, " ", &processor);
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800331 }
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800332 }
333
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700334 *out << "}\n";
335 out->flush();
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800336 return true;
337}
338
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700339
340
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800341} // namespace aapt