1#!/usr/bin/python3 2 3# Copyright (C) 2023 The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16# 17"""A script to generate ENUM_NAME.java file and test files using ENUM_NAME.aidl file. 18 19 Need ANDROID_BUILD_TOP environmental variable to be set. This script will update ENUM_NAME.java 20 under packages/services/Car/car-lib/src/android/car/hardware/property, as well as the 21 ENUM_NAMETest.java files in cts/tests/tests/car/src/android/car/cts and 22 packages/services/Car/tests/android_car_api_test/src/android/car/apitest 23 24 Usage: 25 $ python translate_aidl_enums.py ENUM_NAME.aidl 26""" 27import os 28import sys 29 30LICENSE = """/* 31 * Copyright (C) 2023 The Android Open Source Project 32 * 33 * Licensed under the Apache License, Version 2.0 (the "License"); 34 * you may not use this file except in compliance with the License. 35 * You may obtain a copy of the License at 36 * 37 * http://www.apache.org/licenses/LICENSE-2.0 38 * 39 * Unless required by applicable law or agreed to in writing, software 40 * distributed under the License is distributed on an "AS IS" BASIS, 41 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 42 * See the License for the specific language governing permissions and 43 * limitations under the License. 44 */ 45""" 46 47class EnumParser: 48 def __init__(self, file_path, file_name): 49 self.filePath = file_path 50 self.fileName = file_name 51 self.lowerFileName = self.fileName[0].lower() + self.fileName[1:] 52 self.enums = [] 53 self.outputMsg = [] 54 self.outputMsg.append(LICENSE) 55 self.outputMsg.append("\npackage android.car.hardware.property;\n") 56 self.outputMsg.append(""" 57import android.annotation.IntDef; 58import android.annotation.NonNull; 59 60import com.android.car.internal.util.ConstantDebugUtils; 61 62import java.lang.annotation.Retention; 63import java.lang.annotation.RetentionPolicy; 64""") 65 66 with open(self.filePath, 'r') as f: 67 for line in f.readlines()[16:]: 68 if line in ["package android.hardware.automotive.vehicle;\n", 69 "@VintfStability\n", 70 '@Backing(type="int")\n']: 71 continue 72 73 msg = line 74 msgSplit = msg.strip().split() 75 if len(msgSplit) > 0 and msgSplit[0] == "enum": 76 msgSplit[0] = "public final class" 77 msg = " ".join(msgSplit) + "\n" 78 elif len(msgSplit) > 1 and msgSplit[1] == '=': 79 msgSplit.insert(0, " public static final int") 80 self.enums.append(msgSplit[1]) 81 msgSplit[-1] = msgSplit[-1][:-1] + ";\n" 82 msg = " ".join(msgSplit) 83 elif msg == "}\n": 84 self.outputMsg.append(""" 85 private {2}() {{}} 86 87 /** 88 * Returns a user-friendly representation of {{@code {2}}}. 89 */ 90 @NonNull 91 public static String toString(@{2}Int int {0}) {{ 92 String {0}String = ConstantDebugUtils.toName( 93 {2}.class, {0}); 94 return ({0}String != null) 95 ? {0}String 96 : "0x" + Integer.toHexString({0}); 97 }} 98 99 /** @hide */ 100 @IntDef({1}) 101 @Retention(RetentionPolicy.SOURCE) 102 public @interface {2}Int {{}}\n""".format(self.lowerFileName, "{" + ", ".join(self.enums) + "}", 103 self.fileName)) 104 self.outputMsg.append(msg) 105 self.outputMsg.append("TODO: delete this line and manually update this file with app-facing documentation and necessary tags.\n") 106 107 self.outputMsgApiTest = [] 108 self.outputMsgApiTest.append(LICENSE) 109 self.outputMsgApiTest.append("""package android.car.apitest; 110 111import static com.google.common.truth.Truth.assertWithMessage; 112 113import androidx.test.filters.SmallTest; 114 115import org.junit.Test; 116import org.junit.runner.RunWith; 117import org.junit.runners.Parameterized; 118 119import java.util.Arrays; 120import java.util.Collection; 121 122@SmallTest 123@RunWith(Parameterized.class) 124public class {0}Test {{ 125 private final int mJavaConstantValue; 126 private final int mHalConstantValue; 127 128 public {0}Test(int javaConstantValue, int halConstantValue) {{ 129 mJavaConstantValue = javaConstantValue; 130 mHalConstantValue = halConstantValue; 131 }} 132 133 @Parameterized.Parameters 134 public static Collection constantValues() {{ 135 return Arrays.asList( 136 new Object[][] {{""".format(self.fileName)) 137 for enum in self.enums: 138 self.outputMsgApiTest.append(""" 139 {{ 140 android.car.hardware.property.{0}.{1}, 141 android.hardware.automotive.vehicle.{0}.{1} 142 }},""".format(self.fileName, enum)) 143 self.outputMsgApiTest.append(""" 144 }); 145 } 146 147 @Test 148 public void testMatchWithVehicleHal() { 149 assertWithMessage("Java constant") 150 .that(mJavaConstantValue) 151 .isEqualTo(mHalConstantValue); 152 } 153} 154""") 155 156 self.outputMsgCtsTest = [] 157 self.outputMsgCtsTest.append(LICENSE) 158 self.outputMsgCtsTest.append(""" 159package android.car.cts; 160 161import static com.google.common.truth.Truth.assertThat; 162import static com.google.common.truth.Truth.assertWithMessage; 163 164import android.car.cts.utils.VehiclePropertyUtils; 165import android.car.hardware.property.{0}; 166 167import org.junit.Test; 168 169import java.util.List; 170 171public class {0}Test {{ 172 173 @Test 174 public void testToString() {{""".format(self.fileName)) 175 for enum in self.enums: 176 self.outputMsgCtsTest.append(""" 177 assertThat({0}.toString( 178 {0}.{1})) 179 .isEqualTo("{1}");""".format(self.fileName, enum)) 180 self.outputMsgCtsTest.append(""" 181 assertThat({0}.toString({1})).isEqualTo("{2}"); 182 assertThat({0}.toString(12)).isEqualTo("0xc"); 183 }} 184 185 @Test 186 public void testAll{0}sAreMappedInToString() {{ 187 List<Integer> {3}s = 188 VehiclePropertyUtils.getIntegersFromDataEnums({0}.class); 189 for (Integer {3} : {3}s) {{ 190 String {3}String = {0}.toString( 191 {3}); 192 assertWithMessage("%s starts with 0x", {3}String).that( 193 {3}String.startsWith("0x")).isFalse(); 194 }} 195 }} 196}} 197""".format(self.fileName, len(self.enums), hex(len(self.enums)), self.lowerFileName)) 198 199def main(): 200 if len(sys.argv) != 2: 201 print("Usage: {} enum_aidl_file".format(sys.argv[0])) 202 sys.exit(1) 203 print("WARNING: This file only generates the base enum values in the framework layer. The " 204 + "generated files must be reviewed by you and edited if any additional changes are " 205 + "required. The java enum file should be updated with app-developer facing " 206 + "documentation, the @FlaggedApi tag for the new API, and with the @SystemApi tag if " 207 + "the new property is system API") 208 file_path = sys.argv[1] 209 file_name = file_path.split('/')[-1][:-5] 210 parser = EnumParser(file_path, file_name) 211 212 android_top = os.environ['ANDROID_BUILD_TOP'] 213 if not android_top: 214 print('ANDROID_BUILD_TOP is not in environmental variable, please run source and lunch ' 215 + 'at the android root') 216 217 with open(android_top + "/packages/services/Car/car-lib/src/android/car/hardware/property/" 218 + file_name + ".java", 'w') as f: 219 f.write("".join(parser.outputMsg)) 220 221 with open(android_top 222 + "/packages/services/Car/tests/android_car_api_test/src/android/car/apitest/" 223 + file_name + "Test.java", 'w') as f: 224 f.write("".join(parser.outputMsgApiTest)) 225 226 with open(android_top + "/cts/tests/tests/car/src/android/car/cts/" + file_name + "Test.java", 227 'w') as f: 228 f.write("".join(parser.outputMsgCtsTest)) 229 230if __name__ == "__main__": 231 main() 232