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