1 /*
2 * Copyright (C) 2020, 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 #include "aidl_to_rust.h"
18 #include "aidl_language.h"
19 #include "aidl_typenames.h"
20 #include "logging.h"
21
22 #include <android-base/stringprintf.h>
23 #include <android-base/strings.h>
24
25 #include <functional>
26 #include <iostream>
27 #include <map>
28 #include <string>
29 #include <vector>
30
31 using android::base::Join;
32 using android::base::Split;
33 using android::base::StringPrintf;
34
35 namespace android {
36 namespace aidl {
37 namespace rust {
38
39 namespace {
40 std::string GetRawRustName(const AidlTypeSpecifier& type);
41
ConstantValueDecoratorInternal(const AidlTypeSpecifier & type,const std::variant<std::string,std::vector<std::string>> & raw_value,bool by_ref)42 std::string ConstantValueDecoratorInternal(
43 const AidlTypeSpecifier& type,
44 const std::variant<std::string, std::vector<std::string>>& raw_value, bool by_ref) {
45 if (type.IsArray()) {
46 const auto& values = std::get<std::vector<std::string>>(raw_value);
47 std::string value = "[" + Join(values, ", ") + "]";
48 if (type.IsDynamicArray()) {
49 value = "vec!" + value;
50 }
51 if (!type.IsMutated() && type.IsNullable()) {
52 value = "Some(" + value + ")";
53 }
54 return value;
55 }
56
57 std::string value = std::get<std::string>(raw_value);
58
59 const auto& aidl_name = type.GetName();
60 if (aidl_name == "char") {
61 return value + " as u16";
62 }
63
64 if (aidl_name == "float") {
65 // value already ends in `f`, so just add `32`
66 return value + "32";
67 }
68
69 if (aidl_name == "double") {
70 return value + "f64";
71 }
72
73 if (auto defined_type = type.GetDefinedType(); defined_type) {
74 auto enum_type = defined_type->AsEnumDeclaration();
75 AIDL_FATAL_IF(!enum_type, type) << "Invalid type for \"" << value << "\"";
76 return GetRawRustName(type) + "::" + value.substr(value.find_last_of('.') + 1);
77 }
78
79 if (aidl_name == "String" && !by_ref) {
80 // The actual type might be String or &str,
81 // and .into() transparently converts into either one
82 value = value + ".into()";
83 }
84
85 if (type.IsNullable()) {
86 value = "Some(" + value + ")";
87 }
88
89 return value;
90 }
91
GetRawRustName(const AidlTypeSpecifier & type)92 std::string GetRawRustName(const AidlTypeSpecifier& type) {
93 // Each Rust type is defined in a file with the same name,
94 // e.g., IFoo is in IFoo.rs
95 auto split_name = type.GetSplitName();
96 std::string rust_name{"crate::mangled::"};
97 for (const auto& component : split_name) {
98 rust_name += StringPrintf("_%zd_%s", component.size(), component.c_str());
99 }
100 return rust_name;
101 }
102
103 // Usually, this means that the type implements `Default`, however `ParcelableHolder` is also
104 // included in this list because the code generator knows how to call `::new(stability)`.
AutoConstructor(const AidlTypeSpecifier & type,const AidlTypenames & typenames)105 bool AutoConstructor(const AidlTypeSpecifier& type, const AidlTypenames& typenames) {
106 return !(type.GetName() == "ParcelFileDescriptor" || type.GetName() == "IBinder" ||
107 TypeIsInterface(type, typenames));
108 }
109
GetRustName(const AidlTypeSpecifier & type,const AidlTypenames & typenames,StorageMode mode)110 std::string GetRustName(const AidlTypeSpecifier& type, const AidlTypenames& typenames,
111 StorageMode mode) {
112 // map from AIDL built-in type name to the corresponding Rust type name
113 static map<string, string> m = {
114 {"void", "()"},
115 {"boolean", "bool"},
116 {"byte", "i8"},
117 {"char", "u16"},
118 {"int", "i32"},
119 {"long", "i64"},
120 {"float", "f32"},
121 {"double", "f64"},
122 {"String", "String"},
123 {"IBinder", "binder::SpIBinder"},
124 {"ParcelFileDescriptor", "binder::ParcelFileDescriptor"},
125 {"ParcelableHolder", "binder::ParcelableHolder"},
126 };
127 const string& type_name = type.GetName();
128 if (m.find(type_name) != m.end()) {
129 AIDL_FATAL_IF(!AidlTypenames::IsBuiltinTypename(type_name), type);
130 if (type_name == "String" && mode == StorageMode::UNSIZED_ARGUMENT) {
131 return "str";
132 } else {
133 return m[type_name];
134 }
135 }
136 auto name = GetRawRustName(type);
137 if (TypeIsInterface(type, typenames)) {
138 name = "binder::Strong<dyn " + name + ">";
139 }
140 if (type.IsGeneric()) {
141 name += "<";
142 for (const auto& param : type.GetTypeParameters()) {
143 name += GetRustName(*param, typenames, mode);
144 name += ",";
145 }
146 name += ">";
147 }
148 return name;
149 }
150 } // namespace
151
ConstantValueDecorator(const AidlTypeSpecifier & type,const std::variant<std::string,std::vector<std::string>> & raw_value)152 std::string ConstantValueDecorator(
153 const AidlTypeSpecifier& type,
154 const std::variant<std::string, std::vector<std::string>>& raw_value) {
155 return ConstantValueDecoratorInternal(type, raw_value, false);
156 }
157
ConstantValueDecoratorRef(const AidlTypeSpecifier & type,const std::variant<std::string,std::vector<std::string>> & raw_value)158 std::string ConstantValueDecoratorRef(
159 const AidlTypeSpecifier& type,
160 const std::variant<std::string, std::vector<std::string>>& raw_value) {
161 return ConstantValueDecoratorInternal(type, raw_value, true);
162 }
163
164 // Returns default value for array.
ArrayDefaultValue(const AidlTypeSpecifier & type)165 std::string ArrayDefaultValue(const AidlTypeSpecifier& type) {
166 AIDL_FATAL_IF(!type.IsFixedSizeArray(), type) << "not a fixed-size array";
167 auto dimensions = type.GetFixedSizeArrayDimensions();
168 std::string value = "Default::default()";
169 for (auto it = rbegin(dimensions), end = rend(dimensions); it != end; it++) {
170 value = "[" + Join(std::vector<std::string>(*it, value), ", ") + "]";
171 }
172 return value;
173 }
174
175 // Returns true if @nullable T[] should be mapped Option<Vec<Option<T>>
UsesOptionInNullableVector(const AidlTypeSpecifier & type,const AidlTypenames & typenames)176 bool UsesOptionInNullableVector(const AidlTypeSpecifier& type, const AidlTypenames& typenames) {
177 AIDL_FATAL_IF(!type.IsArray() && !typenames.IsList(type), type) << "not a vector";
178 AIDL_FATAL_IF(typenames.IsList(type) && type.GetTypeParameters().size() != 1, type)
179 << "List should have a single type arg.";
180
181 const auto& element_type = type.IsArray() ? type : *type.GetTypeParameters().at(0);
182 if (typenames.IsPrimitiveTypename(element_type.GetName())) {
183 return false;
184 }
185 if (typenames.GetEnumDeclaration(element_type)) {
186 return false;
187 }
188 return true;
189 }
190
RustLifetimeName(Lifetime lifetime)191 std::string RustLifetimeName(Lifetime lifetime) {
192 switch (lifetime) {
193 case Lifetime::NONE:
194 return "";
195 case Lifetime::A:
196 return "'a ";
197 }
198 }
199
RustLifetimeGeneric(Lifetime lifetime)200 std::string RustLifetimeGeneric(Lifetime lifetime) {
201 switch (lifetime) {
202 case Lifetime::NONE:
203 return "";
204 case Lifetime::A:
205 return "<'a>";
206 }
207 }
208
RustNameOf(const AidlTypeSpecifier & type,const AidlTypenames & typenames,StorageMode mode,Lifetime lifetime)209 std::string RustNameOf(const AidlTypeSpecifier& type, const AidlTypenames& typenames,
210 StorageMode mode, Lifetime lifetime) {
211 std::string rust_name;
212 if (type.IsArray() || typenames.IsList(type)) {
213 const auto& element_type = type.IsGeneric() ? (*type.GetTypeParameters().at(0)) : type;
214 StorageMode element_mode;
215 if (type.IsFixedSizeArray() && mode == StorageMode::PARCELABLE_FIELD) {
216 // Elements of fixed-size array field need to have Default.
217 element_mode = StorageMode::DEFAULT_VALUE;
218 } else if (mode == StorageMode::OUT_ARGUMENT || mode == StorageMode::DEFAULT_VALUE) {
219 // Elements need to have Default for resize_out_vec()
220 element_mode = StorageMode::DEFAULT_VALUE;
221 } else {
222 element_mode = StorageMode::VALUE;
223 }
224 if (type.IsArray() && element_type.GetName() == "byte") {
225 rust_name = "u8";
226 } else {
227 rust_name = GetRustName(element_type, typenames, element_mode);
228 }
229
230 // Needs `Option` wrapping because type is not default constructible
231 const bool default_option =
232 element_mode == StorageMode::DEFAULT_VALUE && !AutoConstructor(element_type, typenames);
233 // Needs `Option` wrapping due to being a nullable, non-primitive, non-enum type in a vector.
234 const bool nullable_option = type.IsNullable() && UsesOptionInNullableVector(type, typenames);
235 if (default_option || nullable_option) {
236 rust_name = "Option<" + rust_name + ">";
237 }
238
239 if (mode == StorageMode::UNSIZED_ARGUMENT) {
240 rust_name = "[" + rust_name + "]";
241 } else if (type.IsFixedSizeArray()) {
242 auto dimensions = type.GetFixedSizeArrayDimensions();
243 // T[N][M] => [[T; M]; N]
244 for (auto it = rbegin(dimensions), end = rend(dimensions); it != end; it++) {
245 rust_name = "[" + rust_name + "; " + std::to_string(*it) + "]";
246 }
247 } else {
248 rust_name = "Vec<" + rust_name + ">";
249 }
250 } else {
251 rust_name = GetRustName(type, typenames, mode);
252 }
253
254 if (mode == StorageMode::IN_ARGUMENT || mode == StorageMode::UNSIZED_ARGUMENT) {
255 // If this is a nullable input argument, put the reference inside the option,
256 // e.g., `Option<&str>` instead of `&Option<str>`
257 rust_name = "&" + RustLifetimeName(lifetime) + rust_name;
258 }
259
260 if (type.IsNullable() ||
261 // Some types don't implement Default, so we wrap them
262 // in Option, which defaults to None
263 (TypeNeedsOption(type, typenames) &&
264 (mode == StorageMode::DEFAULT_VALUE || mode == StorageMode::OUT_ARGUMENT ||
265 mode == StorageMode::PARCELABLE_FIELD))) {
266 if (type.IsHeapNullable()) {
267 rust_name = "Option<Box<" + rust_name + ">>";
268 } else {
269 rust_name = "Option<" + rust_name + ">";
270 }
271 }
272
273 if (mode == StorageMode::OUT_ARGUMENT || mode == StorageMode::INOUT_ARGUMENT) {
274 rust_name = "&" + RustLifetimeName(lifetime) + "mut " + rust_name;
275 }
276
277 return rust_name;
278 }
279
ArgumentStorageMode(const AidlArgument & arg,const AidlTypenames & typenames)280 StorageMode ArgumentStorageMode(const AidlArgument& arg, const AidlTypenames& typenames) {
281 if (arg.IsOut()) {
282 return arg.IsIn() ? StorageMode::INOUT_ARGUMENT : StorageMode::OUT_ARGUMENT;
283 }
284
285 const auto typeName = arg.GetType().GetName();
286 const auto definedType = typenames.TryGetDefinedType(typeName);
287
288 const bool isEnum = definedType && definedType->AsEnumDeclaration() != nullptr;
289 const bool isPrimitive = AidlTypenames::IsPrimitiveTypename(typeName);
290 if (typeName == "String" || arg.GetType().IsDynamicArray() || typenames.IsList(arg.GetType())) {
291 return StorageMode::UNSIZED_ARGUMENT;
292 } else if (!(isPrimitive || isEnum) || arg.GetType().IsFixedSizeArray()) {
293 return StorageMode::IN_ARGUMENT;
294 } else {
295 return StorageMode::VALUE;
296 }
297 }
298
ArgumentReferenceMode(const AidlArgument & arg,const AidlTypenames & typenames)299 ReferenceMode ArgumentReferenceMode(const AidlArgument& arg, const AidlTypenames& typenames) {
300 auto arg_mode = ArgumentStorageMode(arg, typenames);
301 switch (arg_mode) {
302 case StorageMode::IN_ARGUMENT:
303 if (arg.GetType().IsNullable()) {
304 // &Option<T> => Option<&T>
305 return ReferenceMode::AS_REF;
306 } else {
307 return ReferenceMode::REF;
308 }
309
310 case StorageMode::OUT_ARGUMENT:
311 case StorageMode::INOUT_ARGUMENT:
312 return ReferenceMode::MUT_REF;
313
314 case StorageMode::UNSIZED_ARGUMENT:
315 if (arg.GetType().IsNullable()) {
316 // &Option<String> => Option<&str>
317 // &Option<Vec<T>> => Option<&[T]>
318 return ReferenceMode::AS_DEREF;
319 } else {
320 return ReferenceMode::REF;
321 }
322
323 default:
324 return ReferenceMode::VALUE;
325 }
326 }
327
TakeReference(ReferenceMode ref_mode,const std::string & name)328 std::string TakeReference(ReferenceMode ref_mode, const std::string& name) {
329 switch (ref_mode) {
330 case ReferenceMode::REF:
331 return "&" + name;
332
333 case ReferenceMode::MUT_REF:
334 return "&mut " + name;
335
336 case ReferenceMode::AS_REF:
337 return name + ".as_ref()";
338
339 case ReferenceMode::AS_DEREF:
340 return name + ".as_deref()";
341
342 default:
343 return name;
344 }
345 }
346
TypeIsInterface(const AidlTypeSpecifier & type,const AidlTypenames & typenames)347 bool TypeIsInterface(const AidlTypeSpecifier& type, const AidlTypenames& typenames) {
348 const auto definedType = typenames.TryGetDefinedType(type.GetName());
349 return definedType != nullptr && definedType->AsInterface() != nullptr;
350 }
351
TypeNeedsOption(const AidlTypeSpecifier & type,const AidlTypenames & typenames)352 bool TypeNeedsOption(const AidlTypeSpecifier& type, const AidlTypenames& typenames) {
353 if (type.IsArray() || typenames.IsList(type)) {
354 return false;
355 }
356
357 // Already an Option<T>
358 if (type.IsNullable()) {
359 return false;
360 }
361
362 const string& aidl_name = type.GetName();
363 if (aidl_name == "IBinder") {
364 return true;
365 }
366 if (aidl_name == "ParcelFileDescriptor") {
367 return true;
368 }
369 if (aidl_name == "ParcelableHolder") {
370 // ParcelableHolder never needs an Option because we always
371 // call its new() constructor directly instead of default()
372 return false;
373 }
374
375 // Strong<dyn IFoo> values don't implement Default
376 if (TypeIsInterface(type, typenames)) {
377 return true;
378 }
379
380 return false;
381 }
382
383 } // namespace rust
384 } // namespace aidl
385 } // namespace android
386