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 "generate_rust.h"
18
19 #include <android-base/stringprintf.h>
20 #include <android-base/strings.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include <map>
26 #include <memory>
27 #include <sstream>
28
29 #include "aidl_to_cpp_common.h"
30 #include "aidl_to_rust.h"
31 #include "code_writer.h"
32 #include "comments.h"
33 #include "logging.h"
34
35 using android::base::Join;
36 using android::base::Split;
37 using std::ostringstream;
38 using std::shared_ptr;
39 using std::string;
40 using std::unique_ptr;
41 using std::vector;
42
43 namespace android {
44 namespace aidl {
45 namespace rust {
46
47 static constexpr const char kArgumentPrefix[] = "_arg_";
48 static constexpr const char kGetInterfaceVersion[] = "getInterfaceVersion";
49 static constexpr const char kGetInterfaceHash[] = "getInterfaceHash";
50
51 struct MangledAliasVisitor : AidlVisitor {
52 CodeWriter& out;
MangledAliasVisitorandroid::aidl::rust::MangledAliasVisitor53 MangledAliasVisitor(CodeWriter& out) : out(out) {}
Visitandroid::aidl::rust::MangledAliasVisitor54 void Visit(const AidlStructuredParcelable& type) override { VisitType(type); }
Visitandroid::aidl::rust::MangledAliasVisitor55 void Visit(const AidlInterface& type) override { VisitType(type); }
Visitandroid::aidl::rust::MangledAliasVisitor56 void Visit(const AidlEnumDeclaration& type) override { VisitType(type); }
Visitandroid::aidl::rust::MangledAliasVisitor57 void Visit(const AidlUnionDecl& type) override { VisitType(type); }
58 template <typename T>
VisitTypeandroid::aidl::rust::MangledAliasVisitor59 void VisitType(const T& type) {
60 out << " pub use " << Qname(type) << " as " << Mangled(type) << ";\n";
61 }
62 // Return a mangled name for a type (including AIDL package)
63 template <typename T>
Mangledandroid::aidl::rust::MangledAliasVisitor64 string Mangled(const T& type) const {
65 ostringstream alias;
66 for (const auto& component : Split(type.GetCanonicalName(), ".")) {
67 alias << "_" << component.size() << "_" << component;
68 }
69 return alias.str();
70 }
71 template <typename T>
Typenameandroid::aidl::rust::MangledAliasVisitor72 string Typename(const T& type) const {
73 if constexpr (std::is_same_v<T, AidlInterface>) {
74 return ClassName(type, cpp::ClassNames::INTERFACE);
75 } else {
76 return type.GetName();
77 }
78 }
79 // Return a fully qualified name for a type in the current file (excluding AIDL package)
80 template <typename T>
Qnameandroid::aidl::rust::MangledAliasVisitor81 string Qname(const T& type) const {
82 return Module(type) + "::r#" + Typename(type);
83 }
84 // Return a module name for a type (relative to the file)
85 template <typename T>
Moduleandroid::aidl::rust::MangledAliasVisitor86 string Module(const T& type) const {
87 if (type.GetParentType()) {
88 return Module(*type.GetParentType()) + "::r#" + type.GetName();
89 } else {
90 return "super";
91 }
92 }
93 };
94
GenerateMangledAliases(CodeWriter & out,const AidlDefinedType & type)95 void GenerateMangledAliases(CodeWriter& out, const AidlDefinedType& type) {
96 MangledAliasVisitor v(out);
97 out << "pub(crate) mod mangled {\n";
98 VisitTopDown(v, type);
99 out << "}\n";
100 }
101
BuildArg(const AidlArgument & arg,const AidlTypenames & typenames,Lifetime lifetime)102 string BuildArg(const AidlArgument& arg, const AidlTypenames& typenames, Lifetime lifetime) {
103 // We pass in parameters that are not primitives by const reference.
104 // Arrays get passed in as slices, which is handled in RustNameOf.
105 auto arg_mode = ArgumentStorageMode(arg, typenames);
106 auto arg_type = RustNameOf(arg.GetType(), typenames, arg_mode, lifetime);
107 return kArgumentPrefix + arg.GetName() + ": " + arg_type;
108 }
109
110 enum class MethodKind {
111 // This is a normal non-async method.
112 NORMAL,
113 // This is an async method. Identical to NORMAL except that async is added
114 // in front of `fn`.
115 ASYNC,
116 // This is an async function, but using a boxed future instead of the async
117 // keyword.
118 BOXED_FUTURE,
119 // This could have been a non-async method, but it returns a Future so that
120 // it would not be breaking to make the function do async stuff in the future.
121 READY_FUTURE,
122 };
123
BuildMethod(const AidlMethod & method,const AidlTypenames & typenames,const MethodKind kind=MethodKind::NORMAL)124 string BuildMethod(const AidlMethod& method, const AidlTypenames& typenames,
125 const MethodKind kind = MethodKind::NORMAL) {
126 // We need to mark the arguments with a lifetime only when returning a future that
127 // actually captures the arguments.
128 Lifetime lifetime;
129 switch (kind) {
130 case MethodKind::NORMAL:
131 case MethodKind::ASYNC:
132 case MethodKind::READY_FUTURE:
133 lifetime = Lifetime::NONE;
134 break;
135 case MethodKind::BOXED_FUTURE:
136 lifetime = Lifetime::A;
137 break;
138 }
139
140 auto method_type = RustNameOf(method.GetType(), typenames, StorageMode::VALUE, lifetime);
141 auto return_type = string{"binder::Result<"} + method_type + ">";
142 auto fn_prefix = string{""};
143
144 switch (kind) {
145 case MethodKind::NORMAL:
146 // Don't wrap the return type in anything.
147 break;
148 case MethodKind::ASYNC:
149 fn_prefix = "async ";
150 break;
151 case MethodKind::BOXED_FUTURE:
152 return_type = "binder::BoxFuture<'a, " + return_type + ">";
153 break;
154 case MethodKind::READY_FUTURE:
155 return_type = "std::future::Ready<" + return_type + ">";
156 break;
157 }
158
159 string parameters = "&" + RustLifetimeName(lifetime) + "self";
160 string lifetime_str = RustLifetimeGeneric(lifetime);
161
162 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
163 parameters += ", ";
164 parameters += BuildArg(*arg, typenames, lifetime);
165 }
166
167 return fn_prefix + "fn r#" + method.GetName() + lifetime_str + "(" + parameters + ") -> " +
168 return_type;
169 }
170
GenerateClientMethodHelpers(CodeWriter & out,const AidlInterface & iface,const AidlMethod & method,const AidlTypenames & typenames,const Options & options,const std::string & default_trait_name)171 void GenerateClientMethodHelpers(CodeWriter& out, const AidlInterface& iface,
172 const AidlMethod& method, const AidlTypenames& typenames,
173 const Options& options, const std::string& default_trait_name) {
174 string parameters = "&self";
175 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
176 parameters += ", ";
177 parameters += BuildArg(*arg, typenames, Lifetime::NONE);
178 }
179
180 // Generate build_parcel helper.
181 out << "fn build_parcel_" + method.GetName() + "(" + parameters +
182 ") -> binder::Result<binder::binder_impl::Parcel> {\n";
183 out.Indent();
184
185 out << "let mut aidl_data = self.binder.prepare_transact()?;\n";
186
187 if (iface.IsSensitiveData()) {
188 out << "aidl_data.mark_sensitive();\n";
189 }
190
191 // Arguments
192 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
193 auto arg_name = kArgumentPrefix + arg->GetName();
194 if (arg->IsIn()) {
195 // If the argument is already a reference, don't reference it again
196 // (unless we turned it into an Option<&T>)
197 auto ref_mode = ArgumentReferenceMode(*arg, typenames);
198 if (IsReference(ref_mode)) {
199 out << "aidl_data.write(" << arg_name << ")?;\n";
200 } else {
201 out << "aidl_data.write(&" << arg_name << ")?;\n";
202 }
203 } else if (arg->GetType().IsDynamicArray()) {
204 // For out-only arrays, send the array size
205 if (arg->GetType().IsNullable()) {
206 out << "aidl_data.write_slice_size(" << arg_name << ".as_deref())?;\n";
207 } else {
208 out << "aidl_data.write_slice_size(Some(" << arg_name << "))?;\n";
209 }
210 }
211 }
212
213 out << "Ok(aidl_data)\n";
214 out.Dedent();
215 out << "}\n";
216
217 // Generate read_response helper.
218 auto return_type = RustNameOf(method.GetType(), typenames, StorageMode::VALUE, Lifetime::NONE);
219 out << "fn read_response_" + method.GetName() + "(" + parameters +
220 ", _aidl_reply: std::result::Result<binder::binder_impl::Parcel, "
221 "binder::StatusCode>) -> binder::Result<" +
222 return_type + "> {\n";
223 out.Indent();
224
225 // Check for UNKNOWN_TRANSACTION and call the default impl
226 if (method.IsUserDefined()) {
227 string default_args;
228 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
229 if (!default_args.empty()) {
230 default_args += ", ";
231 }
232 default_args += kArgumentPrefix;
233 default_args += arg->GetName();
234 }
235 out << "if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {\n";
236 out << " if let Some(_aidl_default_impl) = <Self as " << default_trait_name
237 << ">::getDefaultImpl() {\n";
238 out << " return _aidl_default_impl.r#" << method.GetName() << "(" << default_args << ");\n";
239 out << " }\n";
240 out << "}\n";
241 }
242
243 // Return all other errors
244 out << "let _aidl_reply = _aidl_reply?;\n";
245
246 string return_val = "()";
247 if (!method.IsOneway()) {
248 // Check for errors
249 out << "let _aidl_status: binder::Status = _aidl_reply.read()?;\n";
250 out << "if !_aidl_status.is_ok() { return Err(_aidl_status); }\n";
251
252 // Return reply value
253 if (method.GetType().GetName() != "void") {
254 auto return_type =
255 RustNameOf(method.GetType(), typenames, StorageMode::VALUE, Lifetime::NONE);
256 out << "let _aidl_return: " << return_type << " = _aidl_reply.read()?;\n";
257 return_val = "_aidl_return";
258
259 if (!method.IsUserDefined()) {
260 if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
261 out << "self.cached_version.store(_aidl_return, std::sync::atomic::Ordering::Relaxed);\n";
262 }
263 if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
264 out << "*self.cached_hash.lock().unwrap() = Some(_aidl_return.clone());\n";
265 }
266 }
267 }
268
269 for (const AidlArgument* arg : method.GetOutArguments()) {
270 out << "_aidl_reply.read_onto(" << kArgumentPrefix << arg->GetName() << ")?;\n";
271 }
272 }
273
274 // Return the result
275 out << "Ok(" << return_val << ")\n";
276
277 out.Dedent();
278 out << "}\n";
279 }
280
GenerateClientMethod(CodeWriter & out,const AidlInterface & iface,const AidlMethod & method,const AidlTypenames & typenames,const Options & options,const MethodKind kind)281 void GenerateClientMethod(CodeWriter& out, const AidlInterface& iface, const AidlMethod& method,
282 const AidlTypenames& typenames, const Options& options,
283 const MethodKind kind) {
284 // Generate the method
285 out << BuildMethod(method, typenames, kind) << " {\n";
286 out.Indent();
287
288 if (!method.IsUserDefined()) {
289 if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
290 // Check if the version is in the cache
291 out << "let _aidl_version = "
292 "self.cached_version.load(std::sync::atomic::Ordering::Relaxed);\n";
293 switch (kind) {
294 case MethodKind::NORMAL:
295 case MethodKind::ASYNC:
296 out << "if _aidl_version != -1 { return Ok(_aidl_version); }\n";
297 break;
298 case MethodKind::BOXED_FUTURE:
299 out << "if _aidl_version != -1 { return Box::pin(std::future::ready(Ok(_aidl_version))); "
300 "}\n";
301 break;
302 case MethodKind::READY_FUTURE:
303 out << "if _aidl_version != -1 { return std::future::ready(Ok(_aidl_version)); }\n";
304 break;
305 }
306 }
307
308 if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
309 out << "{\n";
310 out << " let _aidl_hash_lock = self.cached_hash.lock().unwrap();\n";
311 out << " if let Some(ref _aidl_hash) = *_aidl_hash_lock {\n";
312 switch (kind) {
313 case MethodKind::NORMAL:
314 case MethodKind::ASYNC:
315 out << " return Ok(_aidl_hash.clone());\n";
316 break;
317 case MethodKind::BOXED_FUTURE:
318 out << " return Box::pin(std::future::ready(Ok(_aidl_hash.clone())));\n";
319 break;
320 case MethodKind::READY_FUTURE:
321 out << " return std::future::ready(Ok(_aidl_hash.clone()));\n";
322 break;
323 }
324 out << " }\n";
325 out << "}\n";
326 }
327 }
328
329 string build_parcel_args;
330 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
331 if (!build_parcel_args.empty()) {
332 build_parcel_args += ", ";
333 }
334 build_parcel_args += kArgumentPrefix;
335 build_parcel_args += arg->GetName();
336 }
337
338 string read_response_args =
339 build_parcel_args.empty() ? "_aidl_reply" : build_parcel_args + ", _aidl_reply";
340
341 vector<string> flags;
342 if (method.IsOneway()) flags.push_back("binder::binder_impl::FLAG_ONEWAY");
343 if (iface.IsSensitiveData()) flags.push_back("binder::binder_impl::FLAG_CLEAR_BUF");
344 flags.push_back("binder::binder_impl::FLAG_PRIVATE_LOCAL");
345
346 string transact_flags = flags.empty() ? "0" : Join(flags, " | ");
347
348 switch (kind) {
349 case MethodKind::NORMAL:
350 case MethodKind::ASYNC:
351 // Prepare transaction.
352 out << "let _aidl_data = self.build_parcel_" + method.GetName() + "(" + build_parcel_args +
353 ")?;\n";
354 // Submit transaction.
355 out << "let _aidl_reply = self.binder.submit_transact(transactions::r#" << method.GetName()
356 << ", _aidl_data, " << transact_flags << ");\n";
357 // Deserialize response.
358 out << "self.read_response_" + method.GetName() + "(" + read_response_args + ")\n";
359 break;
360 case MethodKind::READY_FUTURE:
361 // Prepare transaction.
362 out << "let _aidl_data = match self.build_parcel_" + method.GetName() + "(" +
363 build_parcel_args + ") {\n";
364 out.Indent();
365 out << "Ok(_aidl_data) => _aidl_data,\n";
366 out << "Err(err) => return std::future::ready(Err(err)),\n";
367 out.Dedent();
368 out << "};\n";
369 // Submit transaction.
370 out << "let _aidl_reply = self.binder.submit_transact(transactions::r#" << method.GetName()
371 << ", _aidl_data, " << transact_flags << ");\n";
372 // Deserialize response.
373 out << "std::future::ready(self.read_response_" + method.GetName() + "(" +
374 read_response_args + "))\n";
375 break;
376 case MethodKind::BOXED_FUTURE:
377 // Prepare transaction.
378 out << "let _aidl_data = match self.build_parcel_" + method.GetName() + "(" +
379 build_parcel_args + ") {\n";
380 out.Indent();
381 out << "Ok(_aidl_data) => _aidl_data,\n";
382 out << "Err(err) => return Box::pin(std::future::ready(Err(err))),\n";
383 out.Dedent();
384 out << "};\n";
385 // Submit transaction.
386 out << "let binder = self.binder.clone();\n";
387 out << "P::spawn(\n";
388 out.Indent();
389 out << "move || binder.submit_transact(transactions::r#" << method.GetName()
390 << ", _aidl_data, " << transact_flags << "),\n";
391 out << "move |_aidl_reply| async move {\n";
392 out.Indent();
393 // Deserialize response.
394 out << "self.read_response_" + method.GetName() + "(" + read_response_args + ")\n";
395 out.Dedent();
396 out << "}\n";
397 out.Dedent();
398 out << ")\n";
399 break;
400 }
401
402 out.Dedent();
403 out << "}\n";
404 }
405
GenerateServerTransaction(CodeWriter & out,const AidlInterface & interface,const AidlMethod & method,const AidlTypenames & typenames)406 void GenerateServerTransaction(CodeWriter& out, const AidlInterface& interface,
407 const AidlMethod& method, const AidlTypenames& typenames) {
408 out << "transactions::r#" << method.GetName() << " => {\n";
409 out.Indent();
410
411 if (interface.EnforceExpression() || method.GetType().EnforceExpression()) {
412 out << "compile_error!(\"Permission checks not support for the Rust backend\");\n";
413 }
414
415 string args;
416 for (const auto& arg : method.GetArguments()) {
417 string arg_name = kArgumentPrefix + arg->GetName();
418 StorageMode arg_mode;
419 if (arg->IsIn()) {
420 arg_mode = StorageMode::VALUE;
421 } else {
422 // We need a value we can call Default::default() on
423 arg_mode = StorageMode::DEFAULT_VALUE;
424 }
425 auto arg_type = RustNameOf(arg->GetType(), typenames, arg_mode, Lifetime::NONE);
426
427 string arg_mut = arg->IsOut() ? "mut " : "";
428 string arg_init = arg->IsIn() ? "_aidl_data.read()?" : "Default::default()";
429 out << "let " << arg_mut << arg_name << ": " << arg_type << " = " << arg_init << ";\n";
430 if (!arg->IsIn() && arg->GetType().IsDynamicArray()) {
431 // _aidl_data.resize_[nullable_]out_vec(&mut _arg_foo)?;
432 auto resize_name = arg->GetType().IsNullable() ? "resize_nullable_out_vec" : "resize_out_vec";
433 out << "_aidl_data." << resize_name << "(&mut " << arg_name << ")?;\n";
434 }
435
436 auto ref_mode = ArgumentReferenceMode(*arg, typenames);
437 if (!args.empty()) {
438 args += ", ";
439 }
440 args += TakeReference(ref_mode, arg_name);
441 }
442 out << "let _aidl_return = _aidl_service.r#" << method.GetName() << "(" << args << ");\n";
443
444 if (!method.IsOneway()) {
445 out << "match &_aidl_return {\n";
446 out.Indent();
447 out << "Ok(_aidl_return) => {\n";
448 out.Indent();
449 out << "_aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;\n";
450 if (method.GetType().GetName() != "void") {
451 out << "_aidl_reply.write(_aidl_return)?;\n";
452 }
453
454 // Serialize out arguments
455 for (const AidlArgument* arg : method.GetOutArguments()) {
456 string arg_name = kArgumentPrefix + arg->GetName();
457
458 auto& arg_type = arg->GetType();
459 if (!arg->IsIn() && arg_type.IsArray() && arg_type.GetName() == "ParcelFileDescriptor") {
460 // We represent arrays of ParcelFileDescriptor as
461 // Vec<Option<ParcelFileDescriptor>> when they're out-arguments,
462 // but we need all of them to be initialized to Some; if there's
463 // any None, return UNEXPECTED_NULL (this is what libbinder_ndk does)
464 out << "if " << arg_name << ".iter().any(Option::is_none) { "
465 << "return Err(binder::StatusCode::UNEXPECTED_NULL); }\n";
466 } else if (!arg->IsIn() && TypeNeedsOption(arg_type, typenames)) {
467 // Unwrap out-only arguments that we wrapped in Option<T>
468 out << "let " << arg_name << " = " << arg_name
469 << ".ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
470 }
471
472 out << "_aidl_reply.write(&" << arg_name << ")?;\n";
473 }
474 out.Dedent();
475 out << "}\n";
476 out << "Err(_aidl_status) => _aidl_reply.write(_aidl_status)?\n";
477 out.Dedent();
478 out << "}\n";
479 }
480 out << "Ok(())\n";
481 out.Dedent();
482 out << "}\n";
483 }
484
GenerateServerItems(CodeWriter & out,const AidlInterface * iface,const AidlTypenames & typenames)485 void GenerateServerItems(CodeWriter& out, const AidlInterface* iface,
486 const AidlTypenames& typenames) {
487 auto trait_name = ClassName(*iface, cpp::ClassNames::INTERFACE);
488 auto server_name = ClassName(*iface, cpp::ClassNames::SERVER);
489
490 // Forward all IFoo functions from Binder to the inner object
491 out << "impl " << trait_name << " for binder::binder_impl::Binder<" << server_name << "> {\n";
492 out.Indent();
493 for (const auto& method : iface->GetMethods()) {
494 string args;
495 for (const std::unique_ptr<AidlArgument>& arg : method->GetArguments()) {
496 if (!args.empty()) {
497 args += ", ";
498 }
499 args += kArgumentPrefix;
500 args += arg->GetName();
501 }
502 out << BuildMethod(*method, typenames) << " { "
503 << "self.0.r#" << method->GetName() << "(" << args << ") }\n";
504 }
505 out.Dedent();
506 out << "}\n";
507
508 out << "fn on_transact("
509 "_aidl_service: &dyn "
510 << trait_name
511 << ", "
512 "_aidl_code: binder::binder_impl::TransactionCode, "
513 "_aidl_data: &binder::binder_impl::BorrowedParcel<'_>, "
514 "_aidl_reply: &mut binder::binder_impl::BorrowedParcel<'_>) -> std::result::Result<(), "
515 "binder::StatusCode> "
516 "{\n";
517 out.Indent();
518 out << "match _aidl_code {\n";
519 out.Indent();
520 for (const auto& method : iface->GetMethods()) {
521 GenerateServerTransaction(out, *iface, *method, typenames);
522 }
523 out << "_ => Err(binder::StatusCode::UNKNOWN_TRANSACTION)\n";
524 out.Dedent();
525 out << "}\n";
526 out.Dedent();
527 out << "}\n";
528 }
529
GenerateDeprecated(CodeWriter & out,const AidlCommentable & type)530 void GenerateDeprecated(CodeWriter& out, const AidlCommentable& type) {
531 if (auto deprecated = FindDeprecated(type.GetComments()); deprecated.has_value()) {
532 if (deprecated->note.empty()) {
533 out << "#[deprecated]\n";
534 } else {
535 out << "#[deprecated = " << QuotedEscape(deprecated->note) << "]\n";
536 }
537 }
538 }
539
540 template <typename TypeWithConstants>
GenerateConstantDeclarations(CodeWriter & out,const TypeWithConstants & type,const AidlTypenames & typenames)541 void GenerateConstantDeclarations(CodeWriter& out, const TypeWithConstants& type,
542 const AidlTypenames& typenames) {
543 for (const auto& constant : type.GetConstantDeclarations()) {
544 const AidlTypeSpecifier& type = constant->GetType();
545 const AidlConstantValue& value = constant->GetValue();
546
547 string const_type;
548 if (type.Signature() == "String") {
549 const_type = "&str";
550 } else if (type.Signature() == "byte" || type.Signature() == "int" ||
551 type.Signature() == "long" || type.Signature() == "float" ||
552 type.Signature() == "double") {
553 const_type = RustNameOf(type, typenames, StorageMode::VALUE, Lifetime::NONE);
554 } else {
555 AIDL_FATAL(value) << "Unrecognized constant type: " << type.Signature();
556 }
557
558 GenerateDeprecated(out, *constant);
559 out << "pub const r#" << constant->GetName() << ": " << const_type << " = "
560 << constant->ValueString(ConstantValueDecoratorRef) << ";\n";
561 }
562 }
563
GenerateRustInterface(CodeWriter * code_writer,const AidlInterface * iface,const AidlTypenames & typenames,const Options & options)564 void GenerateRustInterface(CodeWriter* code_writer, const AidlInterface* iface,
565 const AidlTypenames& typenames, const Options& options) {
566 *code_writer << "#![allow(non_upper_case_globals)]\n";
567 *code_writer << "#![allow(non_snake_case)]\n";
568 // Import IBinderInternal for transact()
569 *code_writer << "#[allow(unused_imports)] use binder::binder_impl::IBinderInternal;\n";
570
571 auto trait_name = ClassName(*iface, cpp::ClassNames::INTERFACE);
572 auto trait_name_async = trait_name + "Async";
573 auto trait_name_async_server = trait_name + "AsyncServer";
574 auto client_name = ClassName(*iface, cpp::ClassNames::CLIENT);
575 auto server_name = ClassName(*iface, cpp::ClassNames::SERVER);
576 *code_writer << "use binder::declare_binder_interface;\n";
577 *code_writer << "declare_binder_interface! {\n";
578 code_writer->Indent();
579 *code_writer << trait_name << "[\"" << iface->GetDescriptor() << "\"] {\n";
580 code_writer->Indent();
581 *code_writer << "native: " << server_name << "(on_transact),\n";
582 *code_writer << "proxy: " << client_name << " {\n";
583 code_writer->Indent();
584 if (options.Version() > 0) {
585 string comma = options.Hash().empty() ? "" : ",";
586 *code_writer << "cached_version: "
587 "std::sync::atomic::AtomicI32 = "
588 "std::sync::atomic::AtomicI32::new(-1)"
589 << comma << "\n";
590 }
591 if (!options.Hash().empty()) {
592 *code_writer << "cached_hash: "
593 "std::sync::Mutex<Option<String>> = "
594 "std::sync::Mutex::new(None)\n";
595 }
596 code_writer->Dedent();
597 *code_writer << "},\n";
598 *code_writer << "async: " << trait_name_async << ",\n";
599 if (iface->IsVintfStability()) {
600 *code_writer << "stability: binder::binder_impl::Stability::Vintf,\n";
601 }
602 code_writer->Dedent();
603 *code_writer << "}\n";
604 code_writer->Dedent();
605 *code_writer << "}\n";
606
607 // Emit the trait.
608 GenerateDeprecated(*code_writer, *iface);
609 *code_writer << "pub trait " << trait_name << ": binder::Interface + Send {\n";
610 code_writer->Indent();
611 *code_writer << "fn get_descriptor() -> &'static str where Self: Sized { \""
612 << iface->GetDescriptor() << "\" }\n";
613
614 for (const auto& method : iface->GetMethods()) {
615 // Generate the method
616 GenerateDeprecated(*code_writer, *method);
617 if (method->IsUserDefined()) {
618 *code_writer << BuildMethod(*method, typenames) << ";\n";
619 } else {
620 // Generate default implementations for meta methods
621 *code_writer << BuildMethod(*method, typenames) << " {\n";
622 code_writer->Indent();
623 if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
624 *code_writer << "Ok(VERSION)\n";
625 } else if (method->GetName() == kGetInterfaceHash && !options.Hash().empty()) {
626 *code_writer << "Ok(HASH.into())\n";
627 }
628 code_writer->Dedent();
629 *code_writer << "}\n";
630 }
631 }
632
633 // Emit the default implementation code inside the trait
634 auto default_trait_name = ClassName(*iface, cpp::ClassNames::DEFAULT_IMPL);
635 auto default_ref_name = default_trait_name + "Ref";
636 *code_writer << "fn getDefaultImpl()"
637 << " -> " << default_ref_name << " where Self: Sized {\n";
638 *code_writer << " DEFAULT_IMPL.lock().unwrap().clone()\n";
639 *code_writer << "}\n";
640 *code_writer << "fn setDefaultImpl(d: " << default_ref_name << ")"
641 << " -> " << default_ref_name << " where Self: Sized {\n";
642 *code_writer << " std::mem::replace(&mut *DEFAULT_IMPL.lock().unwrap(), d)\n";
643 *code_writer << "}\n";
644 code_writer->Dedent();
645 *code_writer << "}\n";
646
647 // Emit the async trait.
648 GenerateDeprecated(*code_writer, *iface);
649 *code_writer << "pub trait " << trait_name_async << "<P>: binder::Interface + Send {\n";
650 code_writer->Indent();
651 *code_writer << "fn get_descriptor() -> &'static str where Self: Sized { \""
652 << iface->GetDescriptor() << "\" }\n";
653
654 for (const auto& method : iface->GetMethods()) {
655 // Generate the method
656 GenerateDeprecated(*code_writer, *method);
657
658 MethodKind kind = method->IsOneway() ? MethodKind::READY_FUTURE : MethodKind::BOXED_FUTURE;
659
660 if (method->IsUserDefined()) {
661 *code_writer << BuildMethod(*method, typenames, kind) << ";\n";
662 } else {
663 // Generate default implementations for meta methods
664 *code_writer << BuildMethod(*method, typenames, kind) << " {\n";
665 code_writer->Indent();
666 if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
667 *code_writer << "Box::pin(async move { Ok(VERSION) })\n";
668 } else if (method->GetName() == kGetInterfaceHash && !options.Hash().empty()) {
669 *code_writer << "Box::pin(async move { Ok(HASH.into()) })\n";
670 }
671 code_writer->Dedent();
672 *code_writer << "}\n";
673 }
674 }
675 code_writer->Dedent();
676 *code_writer << "}\n";
677
678 // Emit the async server trait.
679 GenerateDeprecated(*code_writer, *iface);
680 *code_writer << "#[::async_trait::async_trait]\n";
681 *code_writer << "pub trait " << trait_name_async_server << ": binder::Interface + Send {\n";
682 code_writer->Indent();
683 *code_writer << "fn get_descriptor() -> &'static str where Self: Sized { \""
684 << iface->GetDescriptor() << "\" }\n";
685
686 for (const auto& method : iface->GetMethods()) {
687 // Generate the method
688 if (method->IsUserDefined()) {
689 GenerateDeprecated(*code_writer, *method);
690 *code_writer << BuildMethod(*method, typenames, MethodKind::ASYNC) << ";\n";
691 }
692 }
693 code_writer->Dedent();
694 *code_writer << "}\n";
695
696 // Emit a new_async_binder method for binding an async server.
697 *code_writer << "impl " << server_name << " {\n";
698 code_writer->Indent();
699 *code_writer << "/// Create a new async binder service.\n";
700 *code_writer << "pub fn new_async_binder<T, R>(inner: T, rt: R, features: "
701 "binder::BinderFeatures) -> binder::Strong<dyn "
702 << trait_name << ">\n";
703 *code_writer << "where\n";
704 code_writer->Indent();
705 *code_writer << "T: " << trait_name_async_server
706 << " + binder::Interface + Send + Sync + 'static,\n";
707 *code_writer << "R: binder::binder_impl::BinderAsyncRuntime + Send + Sync + 'static,\n";
708 code_writer->Dedent();
709 *code_writer << "{\n";
710 code_writer->Indent();
711 // Define a wrapper struct that implements the non-async trait by calling block_on.
712 *code_writer << "struct Wrapper<T, R> {\n";
713 code_writer->Indent();
714 *code_writer << "_inner: T,\n";
715 *code_writer << "_rt: R,\n";
716 code_writer->Dedent();
717 *code_writer << "}\n";
718 *code_writer << "impl<T, R> binder::Interface for Wrapper<T, R> where T: binder::Interface, R: "
719 "Send + Sync {\n";
720 code_writer->Indent();
721 *code_writer << "fn as_binder(&self) -> binder::SpIBinder { self._inner.as_binder() }\n";
722 *code_writer
723 << "fn dump(&self, _file: &std::fs::File, _args: &[&std::ffi::CStr]) -> "
724 "std::result::Result<(), binder::StatusCode> { self._inner.dump(_file, _args) }\n";
725 code_writer->Dedent();
726 *code_writer << "}\n";
727 *code_writer << "impl<T, R> " << trait_name << " for Wrapper<T, R>\n";
728 *code_writer << "where\n";
729 code_writer->Indent();
730 *code_writer << "T: " << trait_name_async_server << " + Send + Sync + 'static,\n";
731 *code_writer << "R: binder::binder_impl::BinderAsyncRuntime + Send + Sync + 'static,\n";
732 code_writer->Dedent();
733 *code_writer << "{\n";
734 code_writer->Indent();
735 for (const auto& method : iface->GetMethods()) {
736 // Generate the method
737 if (method->IsUserDefined()) {
738 string args = "";
739 for (const std::unique_ptr<AidlArgument>& arg : method->GetArguments()) {
740 if (!args.empty()) {
741 args += ", ";
742 }
743 args += kArgumentPrefix;
744 args += arg->GetName();
745 }
746
747 *code_writer << BuildMethod(*method, typenames) << " {\n";
748 code_writer->Indent();
749 *code_writer << "self._rt.block_on(self._inner.r#" << method->GetName() << "(" << args
750 << "))\n";
751 code_writer->Dedent();
752 *code_writer << "}\n";
753 }
754 }
755 code_writer->Dedent();
756 *code_writer << "}\n";
757
758 *code_writer << "let wrapped = Wrapper { _inner: inner, _rt: rt };\n";
759 *code_writer << "Self::new_binder(wrapped, features)\n";
760
761 code_writer->Dedent();
762 *code_writer << "}\n";
763 code_writer->Dedent();
764 *code_writer << "}\n";
765
766 // Emit the default trait
767 *code_writer << "pub trait " << default_trait_name << ": Send + Sync {\n";
768 code_writer->Indent();
769 for (const auto& method : iface->GetMethods()) {
770 if (!method->IsUserDefined()) {
771 continue;
772 }
773
774 // Generate the default method
775 *code_writer << BuildMethod(*method, typenames) << " {\n";
776 code_writer->Indent();
777 *code_writer << "Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())\n";
778 code_writer->Dedent();
779 *code_writer << "}\n";
780 }
781 code_writer->Dedent();
782 *code_writer << "}\n";
783
784 // Generate the transaction code constants
785 // The constants get their own sub-module to avoid conflicts
786 *code_writer << "pub mod transactions {\n";
787 code_writer->Indent();
788 for (const auto& method : iface->GetMethods()) {
789 // Generate the transaction code constant
790 *code_writer << "pub const r#" << method->GetName()
791 << ": binder::binder_impl::TransactionCode = "
792 "binder::binder_impl::FIRST_CALL_TRANSACTION + " +
793 std::to_string(method->GetId()) + ";\n";
794 }
795 code_writer->Dedent();
796 *code_writer << "}\n";
797
798 // Emit the default implementation code outside the trait
799 *code_writer << "pub type " << default_ref_name << " = Option<std::sync::Arc<dyn "
800 << default_trait_name << ">>;\n";
801 *code_writer << "use lazy_static::lazy_static;\n";
802 *code_writer << "lazy_static! {\n";
803 *code_writer << " static ref DEFAULT_IMPL: std::sync::Mutex<" << default_ref_name
804 << "> = std::sync::Mutex::new(None);\n";
805 *code_writer << "}\n";
806
807 // Emit the interface constants
808 GenerateConstantDeclarations(*code_writer, *iface, typenames);
809
810 // Emit VERSION and HASH
811 // These need to be top-level item constants instead of associated consts
812 // because the latter are incompatible with trait objects, see
813 // https://doc.rust-lang.org/reference/items/traits.html#object-safety
814 if (options.Version() > 0) {
815 *code_writer << "pub const VERSION: i32 = " << std::to_string(options.Version()) << ";\n";
816 }
817 if (!options.Hash().empty()) {
818 *code_writer << "pub const HASH: &str = \"" << options.Hash() << "\";\n";
819 }
820
821 // Generate the client-side method helpers
822 //
823 // The methods in this block are not marked pub, so they are not accessible from outside the
824 // AIDL generated code.
825 *code_writer << "impl " << client_name << " {\n";
826 code_writer->Indent();
827 for (const auto& method : iface->GetMethods()) {
828 GenerateClientMethodHelpers(*code_writer, *iface, *method, typenames, options, trait_name);
829 }
830 code_writer->Dedent();
831 *code_writer << "}\n";
832
833 // Generate the client-side methods
834 *code_writer << "impl " << trait_name << " for " << client_name << " {\n";
835 code_writer->Indent();
836 for (const auto& method : iface->GetMethods()) {
837 GenerateClientMethod(*code_writer, *iface, *method, typenames, options, MethodKind::NORMAL);
838 }
839 code_writer->Dedent();
840 *code_writer << "}\n";
841
842 // Generate the async client-side methods
843 *code_writer << "impl<P: binder::BinderAsyncPool> " << trait_name_async << "<P> for "
844 << client_name << " {\n";
845 code_writer->Indent();
846 for (const auto& method : iface->GetMethods()) {
847 MethodKind kind = method->IsOneway() ? MethodKind::READY_FUTURE : MethodKind::BOXED_FUTURE;
848 GenerateClientMethod(*code_writer, *iface, *method, typenames, options, kind);
849 }
850 code_writer->Dedent();
851 *code_writer << "}\n";
852
853 // Generate the server-side methods
854 GenerateServerItems(*code_writer, iface, typenames);
855 }
856
RemoveUsed(std::set<std::string> * params,const AidlTypeSpecifier & type)857 void RemoveUsed(std::set<std::string>* params, const AidlTypeSpecifier& type) {
858 if (!type.IsResolved()) {
859 params->erase(type.GetName());
860 }
861 if (type.IsGeneric()) {
862 for (const auto& param : type.GetTypeParameters()) {
863 RemoveUsed(params, *param);
864 }
865 }
866 }
867
FreeParams(const AidlStructuredParcelable * parcel)868 std::set<std::string> FreeParams(const AidlStructuredParcelable* parcel) {
869 if (!parcel->IsGeneric()) {
870 return std::set<std::string>();
871 }
872 auto typeParams = parcel->GetTypeParameters();
873 std::set<std::string> unusedParams(typeParams.begin(), typeParams.end());
874 for (const auto& variable : parcel->GetFields()) {
875 RemoveUsed(&unusedParams, variable->GetType());
876 }
877 return unusedParams;
878 }
879
WriteParams(CodeWriter & out,const AidlParameterizable<std::string> * parcel,std::string extra)880 void WriteParams(CodeWriter& out, const AidlParameterizable<std::string>* parcel,
881 std::string extra) {
882 if (parcel->IsGeneric()) {
883 out << "<";
884 for (const auto& param : parcel->GetTypeParameters()) {
885 out << param << extra << ",";
886 }
887 out << ">";
888 }
889 }
890
WriteParams(CodeWriter & out,const AidlParameterizable<std::string> * parcel)891 void WriteParams(CodeWriter& out, const AidlParameterizable<std::string>* parcel) {
892 WriteParams(out, parcel, "");
893 }
894
GenerateParcelBody(CodeWriter & out,const AidlStructuredParcelable * parcel,const AidlTypenames & typenames)895 void GenerateParcelBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
896 const AidlTypenames& typenames) {
897 GenerateDeprecated(out, *parcel);
898 out << "pub struct r#" << parcel->GetName();
899 WriteParams(out, parcel);
900 out << " {\n";
901 out.Indent();
902 for (const auto& variable : parcel->GetFields()) {
903 GenerateDeprecated(out, *variable);
904 auto field_type =
905 RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD, Lifetime::NONE);
906 out << "pub r#" << variable->GetName() << ": " << field_type << ",\n";
907 }
908 for (const auto& unused_param : FreeParams(parcel)) {
909 out << "_phantom_" << unused_param << ": std::marker::PhantomData<" << unused_param << ">,\n";
910 }
911 out.Dedent();
912 out << "}\n";
913 }
914
GenerateParcelDefault(CodeWriter & out,const AidlStructuredParcelable * parcel)915 void GenerateParcelDefault(CodeWriter& out, const AidlStructuredParcelable* parcel) {
916 out << "impl";
917 WriteParams(out, parcel, ": Default");
918 out << " Default for r#" << parcel->GetName();
919 WriteParams(out, parcel);
920 out << " {\n";
921 out.Indent();
922 out << "fn default() -> Self {\n";
923 out.Indent();
924 out << "Self {\n";
925 out.Indent();
926 for (const auto& variable : parcel->GetFields()) {
927 out << "r#" << variable->GetName() << ": ";
928 if (variable->GetDefaultValue()) {
929 out << variable->ValueString(ConstantValueDecorator);
930 } else {
931 // Some types don't implement "Default".
932 // - ParcelableHolder
933 // - Arrays
934 if (variable->GetType().GetName() == "ParcelableHolder") {
935 out << "binder::ParcelableHolder::new(";
936 if (parcel->IsVintfStability()) {
937 out << "binder::binder_impl::Stability::Vintf";
938 } else {
939 out << "binder::binder_impl::Stability::Local";
940 }
941 out << ")";
942 } else if (variable->GetType().IsFixedSizeArray() && !variable->GetType().IsNullable()) {
943 out << ArrayDefaultValue(variable->GetType());
944 } else {
945 out << "Default::default()";
946 }
947 }
948 out << ",\n";
949 }
950 for (const auto& unused_param : FreeParams(parcel)) {
951 out << "r#_phantom_" << unused_param << ": Default::default(),\n";
952 }
953 out.Dedent();
954 out << "}\n";
955 out.Dedent();
956 out << "}\n";
957 out.Dedent();
958 out << "}\n";
959 }
960
GenerateParcelSerializeBody(CodeWriter & out,const AidlStructuredParcelable * parcel,const AidlTypenames & typenames)961 void GenerateParcelSerializeBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
962 const AidlTypenames& typenames) {
963 out << "parcel.sized_write(|subparcel| {\n";
964 out.Indent();
965 for (const auto& variable : parcel->GetFields()) {
966 if (TypeNeedsOption(variable->GetType(), typenames)) {
967 out << "let __field_ref = self.r#" << variable->GetName()
968 << ".as_ref().ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
969 out << "subparcel.write(__field_ref)?;\n";
970 } else {
971 out << "subparcel.write(&self.r#" << variable->GetName() << ")?;\n";
972 }
973 }
974 out << "Ok(())\n";
975 out.Dedent();
976 out << "})\n";
977 }
978
GenerateParcelDeserializeBody(CodeWriter & out,const AidlStructuredParcelable * parcel,const AidlTypenames & typenames)979 void GenerateParcelDeserializeBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
980 const AidlTypenames& typenames) {
981 out << "parcel.sized_read(|subparcel| {\n";
982 out.Indent();
983
984 for (const auto& variable : parcel->GetFields()) {
985 out << "if subparcel.has_more_data() {\n";
986 out.Indent();
987 if (TypeNeedsOption(variable->GetType(), typenames)) {
988 out << "self.r#" << variable->GetName() << " = Some(subparcel.read()?);\n";
989 } else {
990 out << "self.r#" << variable->GetName() << " = subparcel.read()?;\n";
991 }
992 out.Dedent();
993 out << "}\n";
994 }
995 out << "Ok(())\n";
996 out.Dedent();
997 out << "})\n";
998 }
999
GenerateParcelBody(CodeWriter & out,const AidlUnionDecl * parcel,const AidlTypenames & typenames)1000 void GenerateParcelBody(CodeWriter& out, const AidlUnionDecl* parcel,
1001 const AidlTypenames& typenames) {
1002 GenerateDeprecated(out, *parcel);
1003 out << "pub enum r#" << parcel->GetName() << " {\n";
1004 out.Indent();
1005 for (const auto& variable : parcel->GetFields()) {
1006 GenerateDeprecated(out, *variable);
1007 auto field_type =
1008 RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD, Lifetime::NONE);
1009 out << variable->GetCapitalizedName() << "(" << field_type << "),\n";
1010 }
1011 out.Dedent();
1012 out << "}\n";
1013 }
1014
GenerateParcelDefault(CodeWriter & out,const AidlUnionDecl * parcel)1015 void GenerateParcelDefault(CodeWriter& out, const AidlUnionDecl* parcel) {
1016 out << "impl";
1017 WriteParams(out, parcel, ": Default");
1018 out << " Default for r#" << parcel->GetName();
1019 WriteParams(out, parcel);
1020 out << " {\n";
1021 out.Indent();
1022 out << "fn default() -> Self {\n";
1023 out.Indent();
1024
1025 AIDL_FATAL_IF(parcel->GetFields().empty(), *parcel)
1026 << "Union '" << parcel->GetName() << "' is empty.";
1027 const auto& first_field = parcel->GetFields()[0];
1028 const auto& first_value = first_field->ValueString(ConstantValueDecorator);
1029
1030 out << "Self::";
1031 if (first_field->GetDefaultValue()) {
1032 out << first_field->GetCapitalizedName() << "(" << first_value << ")\n";
1033 } else {
1034 out << first_field->GetCapitalizedName() << "(Default::default())\n";
1035 }
1036
1037 out.Dedent();
1038 out << "}\n";
1039 out.Dedent();
1040 out << "}\n";
1041 }
1042
GenerateParcelSerializeBody(CodeWriter & out,const AidlUnionDecl * parcel,const AidlTypenames & typenames)1043 void GenerateParcelSerializeBody(CodeWriter& out, const AidlUnionDecl* parcel,
1044 const AidlTypenames& typenames) {
1045 out << "match self {\n";
1046 out.Indent();
1047 int tag = 0;
1048 for (const auto& variable : parcel->GetFields()) {
1049 out << "Self::" << variable->GetCapitalizedName() << "(v) => {\n";
1050 out.Indent();
1051 out << "parcel.write(&" << std::to_string(tag++) << "i32)?;\n";
1052 if (TypeNeedsOption(variable->GetType(), typenames)) {
1053 out << "let __field_ref = v.as_ref().ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
1054 out << "parcel.write(__field_ref)\n";
1055 } else {
1056 out << "parcel.write(v)\n";
1057 }
1058 out.Dedent();
1059 out << "}\n";
1060 }
1061 out.Dedent();
1062 out << "}\n";
1063 }
1064
GenerateParcelDeserializeBody(CodeWriter & out,const AidlUnionDecl * parcel,const AidlTypenames & typenames)1065 void GenerateParcelDeserializeBody(CodeWriter& out, const AidlUnionDecl* parcel,
1066 const AidlTypenames& typenames) {
1067 out << "let tag: i32 = parcel.read()?;\n";
1068 out << "match tag {\n";
1069 out.Indent();
1070 int tag = 0;
1071 for (const auto& variable : parcel->GetFields()) {
1072 auto field_type =
1073 RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD, Lifetime::NONE);
1074
1075 out << std::to_string(tag++) << " => {\n";
1076 out.Indent();
1077 out << "let value: " << field_type << " = ";
1078 if (TypeNeedsOption(variable->GetType(), typenames)) {
1079 out << "Some(parcel.read()?);\n";
1080 } else {
1081 out << "parcel.read()?;\n";
1082 }
1083 out << "*self = Self::" << variable->GetCapitalizedName() << "(value);\n";
1084 out << "Ok(())\n";
1085 out.Dedent();
1086 out << "}\n";
1087 }
1088 out << "_ => {\n";
1089 out << " Err(binder::StatusCode::BAD_VALUE)\n";
1090 out << "}\n";
1091 out.Dedent();
1092 out << "}\n";
1093 }
1094
1095 template <typename ParcelableType>
GenerateParcelableTrait(CodeWriter & out,const ParcelableType * parcel,const AidlTypenames & typenames)1096 void GenerateParcelableTrait(CodeWriter& out, const ParcelableType* parcel,
1097 const AidlTypenames& typenames) {
1098 out << "impl";
1099 WriteParams(out, parcel);
1100 out << " binder::Parcelable for r#" << parcel->GetName();
1101 WriteParams(out, parcel);
1102 out << " {\n";
1103 out.Indent();
1104
1105 out << "fn write_to_parcel(&self, "
1106 "parcel: &mut binder::binder_impl::BorrowedParcel) -> std::result::Result<(), "
1107 "binder::StatusCode> "
1108 "{\n";
1109 out.Indent();
1110 GenerateParcelSerializeBody(out, parcel, typenames);
1111 out.Dedent();
1112 out << "}\n";
1113
1114 out << "fn read_from_parcel(&mut self, "
1115 "parcel: &binder::binder_impl::BorrowedParcel) -> std::result::Result<(), "
1116 "binder::StatusCode> {\n";
1117 out.Indent();
1118 GenerateParcelDeserializeBody(out, parcel, typenames);
1119 out.Dedent();
1120 out << "}\n";
1121
1122 out.Dedent();
1123 out << "}\n";
1124
1125 // Emit the outer (de)serialization traits
1126 out << "binder::impl_serialize_for_parcelable!(r#" << parcel->GetName();
1127 WriteParams(out, parcel);
1128 out << ");\n";
1129 out << "binder::impl_deserialize_for_parcelable!(r#" << parcel->GetName();
1130 WriteParams(out, parcel);
1131 out << ");\n";
1132 }
1133
1134 template <typename ParcelableType>
GenerateMetadataTrait(CodeWriter & out,const ParcelableType * parcel)1135 void GenerateMetadataTrait(CodeWriter& out, const ParcelableType* parcel) {
1136 out << "impl";
1137 WriteParams(out, parcel);
1138 out << " binder::binder_impl::ParcelableMetadata for r#" << parcel->GetName();
1139 WriteParams(out, parcel);
1140 out << " {\n";
1141 out.Indent();
1142
1143 out << "fn get_descriptor() -> &'static str { \"" << parcel->GetCanonicalName() << "\" }\n";
1144
1145 if (parcel->IsVintfStability()) {
1146 out << "fn get_stability(&self) -> binder::binder_impl::Stability { "
1147 "binder::binder_impl::Stability::Vintf }\n";
1148 }
1149
1150 out.Dedent();
1151 out << "}\n";
1152 }
1153
1154 template <typename ParcelableType>
GenerateRustParcel(CodeWriter * code_writer,const ParcelableType * parcel,const AidlTypenames & typenames)1155 void GenerateRustParcel(CodeWriter* code_writer, const ParcelableType* parcel,
1156 const AidlTypenames& typenames) {
1157 vector<string> derives = parcel->RustDerive();
1158
1159 // Debug is always derived because all Rust AIDL types implement it
1160 // ParcelFileDescriptor doesn't support any of the others because
1161 // it's a newtype over std::fs::File which only implements Debug
1162 derives.insert(derives.begin(), "Debug");
1163
1164 *code_writer << "#[derive(" << Join(derives, ", ") << ")]\n";
1165 GenerateParcelBody(*code_writer, parcel, typenames);
1166 GenerateConstantDeclarations(*code_writer, *parcel, typenames);
1167 GenerateParcelDefault(*code_writer, parcel);
1168 GenerateParcelableTrait(*code_writer, parcel, typenames);
1169 GenerateMetadataTrait(*code_writer, parcel);
1170 }
1171
GenerateRustEnumDeclaration(CodeWriter * code_writer,const AidlEnumDeclaration * enum_decl,const AidlTypenames & typenames)1172 void GenerateRustEnumDeclaration(CodeWriter* code_writer, const AidlEnumDeclaration* enum_decl,
1173 const AidlTypenames& typenames) {
1174 const auto& aidl_backing_type = enum_decl->GetBackingType();
1175 auto backing_type = RustNameOf(aidl_backing_type, typenames, StorageMode::VALUE, Lifetime::NONE);
1176
1177 *code_writer << "#![allow(non_upper_case_globals)]\n";
1178 *code_writer << "use binder::declare_binder_enum;\n";
1179 *code_writer << "declare_binder_enum! {\n";
1180 code_writer->Indent();
1181
1182 GenerateDeprecated(*code_writer, *enum_decl);
1183 *code_writer << "r#" << enum_decl->GetName() << " : [" << backing_type << "; "
1184 << std::to_string(enum_decl->GetEnumerators().size()) << "] {\n";
1185 code_writer->Indent();
1186 for (const auto& enumerator : enum_decl->GetEnumerators()) {
1187 auto value = enumerator->GetValue()->ValueString(aidl_backing_type, ConstantValueDecorator);
1188 GenerateDeprecated(*code_writer, *enumerator);
1189 *code_writer << "r#" << enumerator->GetName() << " = " << value << ",\n";
1190 }
1191 code_writer->Dedent();
1192 *code_writer << "}\n";
1193
1194 code_writer->Dedent();
1195 *code_writer << "}\n";
1196 }
1197
GenerateClass(CodeWriter * code_writer,const AidlDefinedType & defined_type,const AidlTypenames & types,const Options & options)1198 void GenerateClass(CodeWriter* code_writer, const AidlDefinedType& defined_type,
1199 const AidlTypenames& types, const Options& options) {
1200 if (const AidlStructuredParcelable* parcelable = defined_type.AsStructuredParcelable();
1201 parcelable != nullptr) {
1202 GenerateRustParcel(code_writer, parcelable, types);
1203 } else if (const AidlEnumDeclaration* enum_decl = defined_type.AsEnumDeclaration();
1204 enum_decl != nullptr) {
1205 GenerateRustEnumDeclaration(code_writer, enum_decl, types);
1206 } else if (const AidlInterface* interface = defined_type.AsInterface(); interface != nullptr) {
1207 GenerateRustInterface(code_writer, interface, types, options);
1208 } else if (const AidlUnionDecl* union_decl = defined_type.AsUnionDeclaration();
1209 union_decl != nullptr) {
1210 GenerateRustParcel(code_writer, union_decl, types);
1211 } else {
1212 AIDL_FATAL(defined_type) << "Unrecognized type sent for Rust generation.";
1213 }
1214
1215 for (const auto& nested : defined_type.GetNestedTypes()) {
1216 (*code_writer) << "pub mod r#" << nested->GetName() << " {\n";
1217 code_writer->Indent();
1218 GenerateClass(code_writer, *nested, types, options);
1219 code_writer->Dedent();
1220 (*code_writer) << "}\n";
1221 }
1222 }
1223
GenerateRust(const string & filename,const Options & options,const AidlTypenames & types,const AidlDefinedType & defined_type,const IoDelegate & io_delegate)1224 void GenerateRust(const string& filename, const Options& options, const AidlTypenames& types,
1225 const AidlDefinedType& defined_type, const IoDelegate& io_delegate) {
1226 CodeWriterPtr code_writer = io_delegate.GetCodeWriter(filename);
1227
1228 // Forbid the use of unsafe in auto-generated code.
1229 // Unsafe code should only be allowed in libbinder_rs.
1230 *code_writer << "#![forbid(unsafe_code)]\n";
1231 // Disable rustfmt on auto-generated files, including the golden outputs
1232 *code_writer << "#![rustfmt::skip]\n";
1233 GenerateClass(code_writer.get(), defined_type, types, options);
1234 GenerateMangledAliases(*code_writer, defined_type);
1235
1236 AIDL_FATAL_IF(!code_writer->Close(), defined_type) << "I/O Error!";
1237 }
1238
1239 } // namespace rust
1240 } // namespace aidl
1241 } // namespace android
1242