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