1 /*
2 * Copyright (C) 2018 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
17 #define LOG_TAG "sysprop_java_gen"
18
19 #include "JavaGen.h"
20
21 #include <android-base/file.h>
22 #include <android-base/logging.h>
23 #include <android-base/stringprintf.h>
24 #include <android-base/strings.h>
25 #include <cerrno>
26 #include <filesystem>
27 #include <regex>
28 #include <string>
29
30 #include "CodeWriter.h"
31 #include "Common.h"
32 #include "sysprop.pb.h"
33
34 using android::base::Result;
35
36 namespace {
37
38 constexpr const char* kIndent = " ";
39
40 constexpr const char* kJavaFileImports =
41 R"(import android.os.SystemProperties;
42 import android.util.Log;
43
44 import java.lang.StringBuilder;
45 import java.util.ArrayList;
46 import java.util.function.Function;
47 import java.util.List;
48 import java.util.Locale;
49 import java.util.Optional;
50 import java.util.StringJoiner;
51 import java.util.stream.Collectors;
52
53 )";
54
55 constexpr const char* kJavaParsersAndFormatters =
56 R"s(private static Boolean tryParseBoolean(String str) {
57 switch (str.toLowerCase(Locale.US)) {
58 case "1":
59 case "true":
60 return Boolean.TRUE;
61 case "0":
62 case "false":
63 return Boolean.FALSE;
64 default:
65 return null;
66 }
67 }
68
69 private static Integer tryParseInteger(String str) {
70 try {
71 return Integer.valueOf(str);
72 } catch (NumberFormatException e) {
73 return null;
74 }
75 }
76
77 private static Integer tryParseUInt(String str) {
78 try {
79 return Integer.parseUnsignedInt(str);
80 } catch (NumberFormatException e) {
81 return null;
82 }
83 }
84
85 private static Long tryParseLong(String str) {
86 try {
87 return Long.valueOf(str);
88 } catch (NumberFormatException e) {
89 return null;
90 }
91 }
92
93 private static Long tryParseULong(String str) {
94 try {
95 return Long.parseUnsignedLong(str);
96 } catch (NumberFormatException e) {
97 return null;
98 }
99 }
100
101 private static Double tryParseDouble(String str) {
102 try {
103 return Double.valueOf(str);
104 } catch (NumberFormatException e) {
105 return null;
106 }
107 }
108
109 private static String tryParseString(String str) {
110 return "".equals(str) ? null : str;
111 }
112
113 private static <T extends Enum<T>> T tryParseEnum(Class<T> enumType, String str) {
114 try {
115 return Enum.valueOf(enumType, str.toUpperCase(Locale.US));
116 } catch (IllegalArgumentException e) {
117 return null;
118 }
119 }
120
121 private static <T> List<T> tryParseList(Function<String, T> elementParser, String str) {
122 if ("".equals(str)) return new ArrayList<>();
123
124 List<T> ret = new ArrayList<>();
125
126 int p = 0;
127 for (;;) {
128 StringBuilder sb = new StringBuilder();
129 while (p < str.length() && str.charAt(p) != ',') {
130 if (str.charAt(p) == '\\') ++p;
131 if (p == str.length()) break;
132 sb.append(str.charAt(p++));
133 }
134 ret.add(elementParser.apply(sb.toString()));
135 if (p == str.length()) break;
136 ++p;
137 }
138
139 return ret;
140 }
141
142 private static <T extends Enum<T>> List<T> tryParseEnumList(Class<T> enumType, String str) {
143 if ("".equals(str)) return new ArrayList<>();
144
145 List<T> ret = new ArrayList<>();
146
147 for (String element : str.split(",")) {
148 ret.add(tryParseEnum(enumType, element));
149 }
150
151 return ret;
152 }
153
154 private static String escape(String str) {
155 return str.replaceAll("([\\\\,])", "\\\\$1");
156 }
157
158 private static <T> String formatList(List<T> list) {
159 StringJoiner joiner = new StringJoiner(",");
160
161 for (T element : list) {
162 joiner.add(element == null ? "" : escape(element.toString()));
163 }
164
165 return joiner.toString();
166 }
167
168 private static String formatUIntList(List<Integer> list) {
169 StringJoiner joiner = new StringJoiner(",");
170
171 for (Integer element : list) {
172 joiner.add(element == null ? "" : escape(Integer.toUnsignedString(element)));
173 }
174
175 return joiner.toString();
176 }
177
178 private static String formatULongList(List<Long> list) {
179 StringJoiner joiner = new StringJoiner(",");
180
181 for (Long element : list) {
182 joiner.add(element == null ? "" : escape(Long.toUnsignedString(element)));
183 }
184
185 return joiner.toString();
186 }
187
188 private static <T extends Enum<T>> String formatEnumList(List<T> list, Function<T, String> elementFormatter) {
189 StringJoiner joiner = new StringJoiner(",");
190
191 for (T element : list) {
192 joiner.add(element == null ? "" : elementFormatter.apply(element));
193 }
194
195 return joiner.toString();
196 }
197 )s";
198
199 const std::regex kRegexDot{"\\."};
200 const std::regex kRegexUnderscore{"_"};
201
202 std::string GetJavaTypeName(const sysprop::Property& prop);
203 std::string GetJavaEnumTypeName(const sysprop::Property& prop);
204 std::string GetJavaPackageName(const sysprop::Properties& props);
205 std::string GetJavaClassName(const sysprop::Properties& props);
206 std::string GetParsingExpression(const sysprop::Property& prop);
207 std::string GetFormattingExpression(const sysprop::Property& prop);
208 std::string GenerateJavaClass(const sysprop::Properties& props,
209 sysprop::Scope scope);
210
GetJavaEnumTypeName(const sysprop::Property & prop)211 std::string GetJavaEnumTypeName(const sysprop::Property& prop) {
212 return ApiNameToIdentifier(prop.api_name()) + "_values";
213 }
214
GetJavaTypeName(const sysprop::Property & prop)215 std::string GetJavaTypeName(const sysprop::Property& prop) {
216 switch (prop.type()) {
217 case sysprop::Boolean:
218 return "Boolean";
219 case sysprop::Integer:
220 case sysprop::UInt:
221 return "Integer";
222 case sysprop::Long:
223 case sysprop::ULong:
224 return "Long";
225 case sysprop::Double:
226 return "Double";
227 case sysprop::String:
228 return "String";
229 case sysprop::Enum:
230 return GetJavaEnumTypeName(prop);
231 case sysprop::BooleanList:
232 return "List<Boolean>";
233 case sysprop::IntegerList:
234 case sysprop::UIntList:
235 return "List<Integer>";
236 case sysprop::LongList:
237 case sysprop::ULongList:
238 return "List<Long>";
239 case sysprop::DoubleList:
240 return "List<Double>";
241 case sysprop::StringList:
242 return "List<String>";
243 case sysprop::EnumList:
244 return "List<" + GetJavaEnumTypeName(prop) + ">";
245 default:
246 __builtin_unreachable();
247 }
248 }
249
GetParsingExpression(const sysprop::Property & prop)250 std::string GetParsingExpression(const sysprop::Property& prop) {
251 switch (prop.type()) {
252 case sysprop::Boolean:
253 return "Optional.ofNullable(tryParseBoolean(value))";
254 case sysprop::Integer:
255 return "Optional.ofNullable(tryParseInteger(value))";
256 case sysprop::UInt:
257 return "Optional.ofNullable(tryParseUInt(value))";
258 case sysprop::Long:
259 return "Optional.ofNullable(tryParseLong(value))";
260 case sysprop::ULong:
261 return "Optional.ofNullable(tryParseULong(value))";
262 case sysprop::Double:
263 return "Optional.ofNullable(tryParseDouble(value))";
264 case sysprop::String:
265 return "Optional.ofNullable(tryParseString(value))";
266 case sysprop::Enum:
267 return "Optional.ofNullable(tryParseEnum(" + GetJavaEnumTypeName(prop) +
268 ".class, value))";
269 case sysprop::EnumList:
270 return "tryParseEnumList(" + GetJavaEnumTypeName(prop) +
271 ".class, "
272 "value)";
273 default:
274 break;
275 }
276
277 // The remaining cases are lists for types other than Enum which share the
278 // same parsing function "tryParseList"
279 std::string element_parser;
280
281 switch (prop.type()) {
282 case sysprop::BooleanList:
283 element_parser = "v -> tryParseBoolean(v)";
284 break;
285 case sysprop::IntegerList:
286 element_parser = "v -> tryParseInteger(v)";
287 break;
288 case sysprop::LongList:
289 element_parser = "v -> tryParseLong(v)";
290 break;
291 case sysprop::DoubleList:
292 element_parser = "v -> tryParseDouble(v)";
293 break;
294 case sysprop::StringList:
295 element_parser = "v -> tryParseString(v)";
296 break;
297 case sysprop::UIntList:
298 element_parser = "v -> tryParseUInt(v)";
299 break;
300 case sysprop::ULongList:
301 element_parser = "v -> tryParseULong(v)";
302 break;
303 default:
304 __builtin_unreachable();
305 }
306
307 return "tryParseList(" + element_parser + ", value)";
308 }
309
GetFormattingExpression(const sysprop::Property & prop)310 std::string GetFormattingExpression(const sysprop::Property& prop) {
311 if (prop.integer_as_bool()) {
312 if (prop.type() == sysprop::Boolean) {
313 // Boolean -> Integer String
314 return "(value ? \"1\" : \"0\")";
315 } else {
316 // List<Boolean> -> String directly
317 return "value.stream().map("
318 "x -> x == null ? \"\" : (x ? \"1\" : \"0\"))"
319 ".collect(Collectors.joining(\",\"))";
320 }
321 }
322
323 switch (prop.type()) {
324 case sysprop::Enum:
325 return "value.getPropValue()";
326 case sysprop::EnumList:
327 return "formatEnumList(value, " + GetJavaEnumTypeName(prop) +
328 "::getPropValue)";
329 case sysprop::UInt:
330 return "Integer.toUnsignedString(value)";
331 case sysprop::ULong:
332 return "Long.toUnsignedString(value)";
333 case sysprop::UIntList:
334 return "formatUIntList(value)";
335 case sysprop::ULongList:
336 return "formatULongList(value)";
337 default:
338 break;
339 }
340
341 return IsListProp(prop) ? "formatList(value)" : "value.toString()";
342 }
343
GetJavaPackageName(const sysprop::Properties & props)344 std::string GetJavaPackageName(const sysprop::Properties& props) {
345 const std::string& module = props.module();
346 return module.substr(0, module.rfind('.'));
347 }
348
GetJavaClassName(const sysprop::Properties & props)349 std::string GetJavaClassName(const sysprop::Properties& props) {
350 const std::string& module = props.module();
351 return module.substr(module.rfind('.') + 1);
352 }
353
GenerateJavaClass(const sysprop::Properties & props,sysprop::Scope scope)354 std::string GenerateJavaClass(const sysprop::Properties& props,
355 sysprop::Scope scope) {
356 std::string package_name = GetJavaPackageName(props);
357 std::string class_name = GetJavaClassName(props);
358
359 CodeWriter writer(kIndent);
360 writer.Write("%s", kGeneratedFileFooterComments);
361 writer.Write("package %s;\n\n", package_name.c_str());
362 writer.Write("%s", kJavaFileImports);
363 writer.Write("public final class %s {\n", class_name.c_str());
364 writer.Indent();
365 writer.Write("private %s () {}\n\n", class_name.c_str());
366 writer.Write("%s", kJavaParsersAndFormatters);
367
368 for (int i = 0; i < props.prop_size(); ++i) {
369 const sysprop::Property& prop = props.prop(i);
370
371 // skip if scope is internal and we are generating public class
372 if (prop.scope() > scope) continue;
373
374 writer.Write("\n");
375
376 std::string prop_id = ApiNameToIdentifier(prop.api_name()).c_str();
377 std::string prop_type = GetJavaTypeName(prop);
378
379 if (prop.type() == sysprop::Enum || prop.type() == sysprop::EnumList) {
380 writer.Write("public static enum %s {\n",
381 GetJavaEnumTypeName(prop).c_str());
382 writer.Indent();
383 std::vector<std::string> values = ParseEnumValues(prop.enum_values());
384 for (std::size_t i = 0; i < values.size(); ++i) {
385 const std::string& name = values[i];
386 writer.Write("%s(\"%s\")", ToUpper(name).c_str(), name.c_str());
387 if (i + 1 < values.size()) {
388 writer.Write(",\n");
389 } else {
390 writer.Write(";\n");
391 }
392 }
393 writer.Write(
394 "private final String propValue;\n"
395 "private %s(String propValue) {\n",
396 GetJavaEnumTypeName(prop).c_str());
397 writer.Indent();
398 writer.Write("this.propValue = propValue;\n");
399 writer.Dedent();
400 writer.Write(
401 "}\n"
402 "public String getPropValue() {\n");
403 writer.Indent();
404 writer.Write("return propValue;\n");
405 writer.Dedent();
406 writer.Write("}\n");
407 writer.Dedent();
408 writer.Write("}\n\n");
409 }
410
411 if (prop.deprecated()) {
412 writer.Write("@Deprecated\n");
413 }
414
415 if (IsListProp(prop)) {
416 writer.Write("public static %s %s() {\n", prop_type.c_str(),
417 prop_id.c_str());
418 } else {
419 writer.Write("public static Optional<%s> %s() {\n", prop_type.c_str(),
420 prop_id.c_str());
421 }
422 writer.Indent();
423 writer.Write("String value = SystemProperties.get(\"%s\");\n",
424 prop.prop_name().c_str());
425 if (!prop.legacy_prop_name().empty()) {
426 // SystemProperties.get() returns "" (empty string) when the property
427 // doesn't exist
428 writer.Write("if (\"\".equals(value)) {\n");
429 writer.Indent();
430 writer.Write(
431 "Log.v(\"%s\", \"prop %s doesn't exist; fallback to legacy prop "
432 "%s\");\n",
433 class_name.c_str(), prop.prop_name().c_str(),
434 prop.legacy_prop_name().c_str());
435 writer.Write("value = SystemProperties.get(\"%s\");\n",
436 prop.legacy_prop_name().c_str());
437 writer.Dedent();
438 writer.Write("}\n");
439 }
440 writer.Write("return %s;\n", GetParsingExpression(prop).c_str());
441 writer.Dedent();
442 writer.Write("}\n");
443
444 if (prop.access() != sysprop::Readonly) {
445 writer.Write("\n");
446 if (prop.deprecated()) {
447 writer.Write("@Deprecated\n");
448 }
449 writer.Write("public static void %s(%s value) {\n", prop_id.c_str(),
450 prop_type.c_str());
451 writer.Indent();
452 writer.Write("SystemProperties.set(\"%s\", value == null ? \"\" : %s);\n",
453 prop.prop_name().c_str(),
454 GetFormattingExpression(prop).c_str());
455 writer.Dedent();
456 writer.Write("}\n");
457 }
458 }
459
460 writer.Dedent();
461 writer.Write("}\n");
462
463 return writer.Code();
464 }
465
466 } // namespace
467
GenerateJavaLibrary(const std::string & input_file_path,sysprop::Scope scope,const std::string & java_output_dir)468 Result<void> GenerateJavaLibrary(const std::string& input_file_path,
469 sysprop::Scope scope,
470 const std::string& java_output_dir) {
471 sysprop::Properties props;
472
473 if (auto res = ParseProps(input_file_path); res.ok()) {
474 props = std::move(*res);
475 } else {
476 return res.error();
477 }
478
479 std::string java_result = GenerateJavaClass(props, scope);
480 std::string package_name = GetJavaPackageName(props);
481 std::string java_package_dir =
482 java_output_dir + "/" + std::regex_replace(package_name, kRegexDot, "/");
483
484 std::error_code ec;
485 std::filesystem::create_directories(java_package_dir, ec);
486 if (ec) {
487 return Errorf("Creating directory to {} failed: {}", java_package_dir,
488 ec.message());
489 }
490
491 std::string class_name = GetJavaClassName(props);
492 std::string java_output_file = java_package_dir + "/" + class_name + ".java";
493 if (!android::base::WriteStringToFile(java_result, java_output_file)) {
494 return ErrnoErrorf("Writing generated java class to {} failed",
495 java_output_file);
496 }
497
498 return {};
499 }
500