blob: bcfb203a7dcfd2beb8edb933d432d47f4dcc1555 [file] [log] [blame]
Andrei Homescub62afd92020-05-11 19:24:59 -07001/*
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
Andrei Homescu71bd1c32020-12-17 18:21:05 -080019#include <android-base/stringprintf.h>
20#include <android-base/strings.h>
Andrei Homescub62afd92020-05-11 19:24:59 -070021#include <stdio.h>
22#include <stdlib.h>
23#include <string.h>
Andrei Homescu71bd1c32020-12-17 18:21:05 -080024
Andrei Homescub62afd92020-05-11 19:24:59 -070025#include <map>
26#include <memory>
27#include <sstream>
28
Andrei Homescub62afd92020-05-11 19:24:59 -070029#include "aidl_to_cpp_common.h"
30#include "aidl_to_rust.h"
31#include "code_writer.h"
Jooyung Hand4fe00e2021-01-11 16:21:53 +090032#include "comments.h"
Andrei Homescub62afd92020-05-11 19:24:59 -070033#include "logging.h"
34
Andrei Homescue61feb52020-08-18 15:44:24 -070035using android::base::Join;
Andrei Homescub62afd92020-05-11 19:24:59 -070036using std::ostringstream;
37using std::shared_ptr;
38using std::string;
39using std::unique_ptr;
40using std::vector;
41
42namespace android {
43namespace aidl {
44namespace rust {
45
46static constexpr const char kArgumentPrefix[] = "_arg_";
47static constexpr const char kGetInterfaceVersion[] = "getInterfaceVersion";
48static constexpr const char kGetInterfaceHash[] = "getInterfaceHash";
49
50void GenerateMangledAlias(CodeWriter& out, const AidlDefinedType* type) {
51 ostringstream alias;
52 for (const auto& component : type->GetSplitPackage()) {
53 alias << "_" << component.size() << "_" << component;
54 }
55 alias << "_" << type->GetName().size() << "_" << type->GetName();
56 out << "pub(crate) mod mangled { pub use super::" << type->GetName() << " as " << alias.str()
57 << "; }\n";
58}
59
60string BuildArg(const AidlArgument& arg, const AidlTypenames& typenames) {
61 // We pass in parameters that are not primitives by const reference.
62 // Arrays get passed in as slices, which is handled in RustNameOf.
63 auto arg_mode = ArgumentStorageMode(arg, typenames);
64 auto arg_type = RustNameOf(arg.GetType(), typenames, arg_mode);
65 return kArgumentPrefix + arg.GetName() + ": " + arg_type;
66}
67
68string BuildMethod(const AidlMethod& method, const AidlTypenames& typenames) {
69 auto method_type = RustNameOf(method.GetType(), typenames, StorageMode::VALUE);
70 auto return_type = string{"binder::public_api::Result<"} + method_type + ">";
71 string parameters = "&self";
72 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
73 parameters += ", ";
74 parameters += BuildArg(*arg, typenames);
75 }
76 return "fn " + method.GetName() + "(" + parameters + ") -> " + return_type;
77}
78
Steven Morelanda7764e52020-10-27 17:29:29 +000079void GenerateClientMethod(CodeWriter& out, const AidlInterface& iface, const AidlMethod& method,
80 const AidlTypenames& typenames, const Options& options,
81 const std::string& trait_name) {
Andrei Homescub62afd92020-05-11 19:24:59 -070082 // Generate the method
83 out << BuildMethod(method, typenames) << " {\n";
84 out.Indent();
85
86 if (!method.IsUserDefined()) {
87 if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
88 // Check if the version is in the cache
89 out << "let _aidl_version = "
90 "self.cached_version.load(std::sync::atomic::Ordering::Relaxed);\n";
91 out << "if _aidl_version != -1 { return Ok(_aidl_version); }\n";
92 }
93
94 if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
95 out << "{\n";
96 out << " let _aidl_hash_lock = self.cached_hash.lock().unwrap();\n";
97 out << " if let Some(ref _aidl_hash) = *_aidl_hash_lock {\n";
98 out << " return Ok(_aidl_hash.clone());\n";
99 out << " }\n";
100 out << "}\n";
101 }
102 }
103
104 // Call transact()
Steven Morelanda7764e52020-10-27 17:29:29 +0000105 vector<string> flags;
Andrew Walbran7a1563f2021-03-09 12:17:13 +0000106 if (method.IsOneway()) flags.push_back("binder::FLAG_ONEWAY");
107 if (iface.IsSensitiveData()) flags.push_back("binder::FLAG_CLEAR_BUF");
Steven Morelanda7764e52020-10-27 17:29:29 +0000108
109 string transact_flags = flags.empty() ? "0" : Join(flags, " | ");
Andrei Homescub62afd92020-05-11 19:24:59 -0700110 out << "let _aidl_reply = self.binder.transact("
111 << "transactions::" << method.GetName() << ", " << transact_flags << ", |_aidl_data| {\n";
112 out.Indent();
113
Steven Morelanda7764e52020-10-27 17:29:29 +0000114 if (iface.IsSensitiveData()) {
115 out << "_aidl_data.mark_sensitive();\n";
116 }
117
Andrei Homescub62afd92020-05-11 19:24:59 -0700118 // Arguments
119 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
120 auto arg_name = kArgumentPrefix + arg->GetName();
121 if (arg->IsIn()) {
122 // If the argument is already a reference, don't reference it again
123 // (unless we turned it into an Option<&T>)
124 auto ref_mode = ArgumentReferenceMode(*arg, typenames);
125 if (IsReference(ref_mode)) {
126 out << "_aidl_data.write(" << arg_name << ")?;\n";
127 } else {
128 out << "_aidl_data.write(&" << arg_name << ")?;\n";
129 }
130 } else if (arg->GetType().IsArray()) {
131 // For out-only arrays, send the array size
132 if (arg->GetType().IsNullable()) {
133 out << "_aidl_data.write_slice_size(" << arg_name << ".as_deref())?;\n";
134 } else {
135 out << "_aidl_data.write_slice_size(Some(" << arg_name << "))?;\n";
136 }
137 }
138 }
139
140 // Return Ok(()) if all the `_aidl_data.write(...)?;` calls pass
141 out << "Ok(())\n";
142 out.Dedent();
143 out << "});\n";
144
145 // Check for UNKNOWN_TRANSACTION and call the default impl
Andrei Homescu71bd1c32020-12-17 18:21:05 -0800146 if (method.IsUserDefined()) {
147 string default_args;
148 for (const std::unique_ptr<AidlArgument>& arg : method.GetArguments()) {
149 if (!default_args.empty()) {
150 default_args += ", ";
151 }
152 default_args += kArgumentPrefix;
153 default_args += arg->GetName();
Andrei Homescub62afd92020-05-11 19:24:59 -0700154 }
Andrei Homescu71bd1c32020-12-17 18:21:05 -0800155 out << "if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {\n";
156 out << " if let Some(_aidl_default_impl) = <Self as " << trait_name
157 << ">::getDefaultImpl() {\n";
158 out << " return _aidl_default_impl." << method.GetName() << "(" << default_args << ");\n";
159 out << " }\n";
160 out << "}\n";
Andrei Homescub62afd92020-05-11 19:24:59 -0700161 }
Andrei Homescub62afd92020-05-11 19:24:59 -0700162
163 // Return all other errors
164 out << "let _aidl_reply = _aidl_reply?;\n";
165
166 string return_val = "()";
167 if (!method.IsOneway()) {
168 // Check for errors
169 out << "let _aidl_status: binder::Status = _aidl_reply.read()?;\n";
170 out << "if !_aidl_status.is_ok() { return Err(_aidl_status); }\n";
171
172 // Return reply value
173 if (method.GetType().GetName() != "void") {
174 auto return_type = RustNameOf(method.GetType(), typenames, StorageMode::VALUE);
175 out << "let _aidl_return: " << return_type << " = _aidl_reply.read()?;\n";
176 return_val = "_aidl_return";
177
178 if (!method.IsUserDefined()) {
179 if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
180 out << "self.cached_version.store(_aidl_return, std::sync::atomic::Ordering::Relaxed);\n";
181 }
182 if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
183 out << "*self.cached_hash.lock().unwrap() = Some(_aidl_return.clone());\n";
184 }
185 }
186 }
187
188 for (const AidlArgument* arg : method.GetOutArguments()) {
189 out << "*" << kArgumentPrefix << arg->GetName() << " = _aidl_reply.read()?;\n";
190 }
191 }
192
193 // Return the result
194 out << "Ok(" << return_val << ")\n";
195 out.Dedent();
196 out << "}\n";
197}
198
199void GenerateServerTransaction(CodeWriter& out, const AidlMethod& method,
200 const AidlTypenames& typenames) {
201 out << "transactions::" << method.GetName() << " => {\n";
202 out.Indent();
203
204 string args;
205 for (const auto& arg : method.GetArguments()) {
206 string arg_name = kArgumentPrefix + arg->GetName();
207 StorageMode arg_mode;
208 if (arg->IsIn()) {
209 arg_mode = StorageMode::VALUE;
210 } else {
211 // We need a value we can call Default::default() on
212 arg_mode = StorageMode::DEFAULT_VALUE;
213 }
214 auto arg_type = RustNameOf(arg->GetType(), typenames, arg_mode);
215
216 string arg_mut = arg->IsOut() ? "mut " : "";
217 string arg_init = arg->IsIn() ? "_aidl_data.read()?" : "Default::default()";
218 out << "let " << arg_mut << arg_name << ": " << arg_type << " = " << arg_init << ";\n";
219 if (!arg->IsIn() && arg->GetType().IsArray()) {
220 // _aidl_data.resize_[nullable_]out_vec(&mut _arg_foo)?;
221 auto resize_name = arg->GetType().IsNullable() ? "resize_nullable_out_vec" : "resize_out_vec";
222 out << "_aidl_data." << resize_name << "(&mut " << arg_name << ")?;\n";
223 }
224
225 auto ref_mode = ArgumentReferenceMode(*arg, typenames);
226 if (!args.empty()) {
227 args += ", ";
228 }
229 args += TakeReference(ref_mode, arg_name);
230 }
231 out << "let _aidl_return = _aidl_service." << method.GetName() << "(" << args << ");\n";
232
233 if (!method.IsOneway()) {
234 out << "match &_aidl_return {\n";
235 out.Indent();
236 out << "Ok(_aidl_return) => {\n";
237 out.Indent();
238 out << "_aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;\n";
239 if (method.GetType().GetName() != "void") {
240 out << "_aidl_reply.write(_aidl_return)?;\n";
241 }
242
243 // Serialize out arguments
244 for (const AidlArgument* arg : method.GetOutArguments()) {
245 string arg_name = kArgumentPrefix + arg->GetName();
246
247 auto& arg_type = arg->GetType();
248 if (!arg->IsIn() && arg_type.IsArray() && arg_type.GetName() == "ParcelFileDescriptor") {
249 // We represent arrays of ParcelFileDescriptor as
250 // Vec<Option<ParcelFileDescriptor>> when they're out-arguments,
251 // but we need all of them to be initialized to Some; if there's
252 // any None, return UNEXPECTED_NULL (this is what libbinder_ndk does)
253 out << "if " << arg_name << ".iter().any(Option::is_none) { "
254 << "return Err(binder::StatusCode::UNEXPECTED_NULL); }\n";
255 } else if (!arg->IsIn() && !TypeHasDefault(arg_type, typenames)) {
256 // Unwrap out-only arguments that we wrapped in Option<T>
257 out << "let " << arg_name << " = " << arg_name
258 << ".ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
259 }
260
261 out << "_aidl_reply.write(&" << arg_name << ")?;\n";
262 }
263 out.Dedent();
264 out << "}\n";
265 out << "Err(_aidl_status) => _aidl_reply.write(_aidl_status)?\n";
266 out.Dedent();
267 out << "}\n";
268 }
269 out << "Ok(())\n";
270 out.Dedent();
271 out << "}\n";
272}
273
274void GenerateServerItems(CodeWriter& out, const AidlInterface* iface,
275 const AidlTypenames& typenames) {
276 auto trait_name = ClassName(*iface, cpp::ClassNames::INTERFACE);
277 auto server_name = ClassName(*iface, cpp::ClassNames::SERVER);
278
279 // Forward all IFoo functions from Binder to the inner object
280 out << "impl " << trait_name << " for binder::Binder<" << server_name << "> {\n";
281 out.Indent();
282 for (const auto& method : iface->GetMethods()) {
283 string args;
284 for (const std::unique_ptr<AidlArgument>& arg : method->GetArguments()) {
285 if (!args.empty()) {
286 args += ", ";
287 }
288 args += kArgumentPrefix;
289 args += arg->GetName();
290 }
291 out << BuildMethod(*method, typenames) << " { "
292 << "self.0." << method->GetName() << "(" << args << ") }\n";
293 }
294 out.Dedent();
295 out << "}\n";
296
297 out << "fn on_transact("
298 "_aidl_service: &dyn "
299 << trait_name
300 << ", "
301 "_aidl_code: binder::TransactionCode, "
302 "_aidl_data: &binder::parcel::Parcel, "
303 "_aidl_reply: &mut binder::parcel::Parcel) -> binder::Result<()> {\n";
304 out.Indent();
305 out << "match _aidl_code {\n";
306 out.Indent();
307 for (const auto& method : iface->GetMethods()) {
308 GenerateServerTransaction(out, *method, typenames);
309 }
310 out << "_ => Err(binder::StatusCode::UNKNOWN_TRANSACTION)\n";
311 out.Dedent();
312 out << "}\n";
313 out.Dedent();
314 out << "}\n";
315}
316
Jooyung Hand4fe00e2021-01-11 16:21:53 +0900317void GenerateDeprecated(CodeWriter& out, const AidlCommentable& type) {
318 if (auto deprecated = FindDeprecated(type.GetComments()); deprecated.has_value()) {
319 if (deprecated->note.empty()) {
320 out << "#[deprecated]\n";
321 } else {
322 out << "#[deprecated = " << QuotedEscape(deprecated->note) << "]\n";
323 }
Jooyung Han720253d2021-01-05 19:13:17 +0900324 }
325}
326
Jooyung Han3f347ca2020-12-01 12:41:50 +0900327template <typename TypeWithConstants>
328void GenerateConstantDeclarations(CodeWriter& out, const TypeWithConstants& type,
329 const AidlTypenames& typenames) {
330 for (const auto& constant : type.GetConstantDeclarations()) {
331 const AidlTypeSpecifier& type = constant->GetType();
332 const AidlConstantValue& value = constant->GetValue();
333
334 string const_type;
335 if (type.Signature() == "String") {
336 const_type = "&str";
337 } else if (type.Signature() == "byte" || type.Signature() == "int" ||
338 type.Signature() == "long") {
339 const_type = RustNameOf(type, typenames, StorageMode::VALUE);
340 } else {
341 AIDL_FATAL(value) << "Unrecognized constant type: " << type.Signature();
342 }
343
Jooyung Han720253d2021-01-05 19:13:17 +0900344 GenerateDeprecated(out, *constant);
Jooyung Han3f347ca2020-12-01 12:41:50 +0900345 out << "pub const " << constant->GetName() << ": " << const_type << " = "
346 << constant->ValueString(ConstantValueDecoratorRef) << ";\n";
347 }
348}
349
Andrei Homescub62afd92020-05-11 19:24:59 -0700350bool GenerateRustInterface(const string& filename, const AidlInterface* iface,
351 const AidlTypenames& typenames, const IoDelegate& io_delegate,
352 const Options& options) {
353 CodeWriterPtr code_writer = io_delegate.GetCodeWriter(filename);
354
355 *code_writer << "#![allow(non_upper_case_globals)]\n";
356 *code_writer << "#![allow(non_snake_case)]\n";
Andrew Walbran7a1563f2021-03-09 12:17:13 +0000357 // Import IBinderInternal for transact()
358 *code_writer << "#[allow(unused_imports)] use binder::IBinderInternal;\n";
Andrei Homescub62afd92020-05-11 19:24:59 -0700359
360 auto trait_name = ClassName(*iface, cpp::ClassNames::INTERFACE);
361 auto client_name = ClassName(*iface, cpp::ClassNames::CLIENT);
362 auto server_name = ClassName(*iface, cpp::ClassNames::SERVER);
363 *code_writer << "use binder::declare_binder_interface;\n";
364 *code_writer << "declare_binder_interface! {\n";
365 code_writer->Indent();
366 *code_writer << trait_name << "[\"" << iface->GetDescriptor() << "\"] {\n";
367 code_writer->Indent();
368 *code_writer << "native: " << server_name << "(on_transact),\n";
369 *code_writer << "proxy: " << client_name << " {\n";
370 code_writer->Indent();
371 if (options.Version() > 0) {
372 string comma = options.Hash().empty() ? "" : ",";
373 *code_writer << "cached_version: "
374 "std::sync::atomic::AtomicI32 = "
375 "std::sync::atomic::AtomicI32::new(-1)"
376 << comma << "\n";
377 }
378 if (!options.Hash().empty()) {
379 *code_writer << "cached_hash: "
380 "std::sync::Mutex<Option<String>> = "
381 "std::sync::Mutex::new(None)\n";
382 }
383 code_writer->Dedent();
384 *code_writer << "},\n";
385 code_writer->Dedent();
386 *code_writer << "}\n";
387 code_writer->Dedent();
388 *code_writer << "}\n";
389
Jooyung Han720253d2021-01-05 19:13:17 +0900390 GenerateDeprecated(*code_writer, *iface);
Andrei Homescub62afd92020-05-11 19:24:59 -0700391 *code_writer << "pub trait " << trait_name << ": binder::Interface + Send {\n";
392 code_writer->Indent();
393 *code_writer << "fn get_descriptor() -> &'static str where Self: Sized { \""
394 << iface->GetDescriptor() << "\" }\n";
395
396 for (const auto& method : iface->GetMethods()) {
397 // Generate the method
Jooyung Han720253d2021-01-05 19:13:17 +0900398 GenerateDeprecated(*code_writer, *method);
Andrei Homescub62afd92020-05-11 19:24:59 -0700399 if (method->IsUserDefined()) {
Andrei Homescu71bd1c32020-12-17 18:21:05 -0800400 *code_writer << BuildMethod(*method, typenames) << ";\n";
Andrei Homescub62afd92020-05-11 19:24:59 -0700401 } else {
402 // Generate default implementations for meta methods
Andrei Homescu71bd1c32020-12-17 18:21:05 -0800403 *code_writer << BuildMethod(*method, typenames) << " {\n";
404 code_writer->Indent();
Andrei Homescub62afd92020-05-11 19:24:59 -0700405 if (method->GetName() == kGetInterfaceVersion && options.Version() > 0) {
406 *code_writer << "Ok(VERSION)\n";
407 } else if (method->GetName() == kGetInterfaceHash && !options.Hash().empty()) {
408 *code_writer << "Ok(HASH.into())\n";
409 }
Andrei Homescu71bd1c32020-12-17 18:21:05 -0800410 code_writer->Dedent();
411 *code_writer << "}\n";
Andrei Homescub62afd92020-05-11 19:24:59 -0700412 }
Andrei Homescub62afd92020-05-11 19:24:59 -0700413 }
414
415 // Emit the default implementation code inside the trait
Andrei Homescu71bd1c32020-12-17 18:21:05 -0800416 auto default_trait_name = ClassName(*iface, cpp::ClassNames::DEFAULT_IMPL);
417 auto default_ref_name = default_trait_name + "Ref";
Andrei Homescub62afd92020-05-11 19:24:59 -0700418 *code_writer << "fn getDefaultImpl()"
Andrei Homescu71bd1c32020-12-17 18:21:05 -0800419 << " -> " << default_ref_name << " where Self: Sized {\n";
Andrei Homescub62afd92020-05-11 19:24:59 -0700420 *code_writer << " DEFAULT_IMPL.lock().unwrap().clone()\n";
421 *code_writer << "}\n";
Andrei Homescu71bd1c32020-12-17 18:21:05 -0800422 *code_writer << "fn setDefaultImpl(d: " << default_ref_name << ")"
423 << " -> " << default_ref_name << " where Self: Sized {\n";
Andrei Homescub62afd92020-05-11 19:24:59 -0700424 *code_writer << " std::mem::replace(&mut *DEFAULT_IMPL.lock().unwrap(), d)\n";
425 *code_writer << "}\n";
426 code_writer->Dedent();
427 *code_writer << "}\n";
428
Andrei Homescu71bd1c32020-12-17 18:21:05 -0800429 // Emit the default trait
430 *code_writer << "pub trait " << default_trait_name << ": Send + Sync {\n";
431 code_writer->Indent();
432 for (const auto& method : iface->GetMethods()) {
433 if (!method->IsUserDefined()) {
434 continue;
435 }
436
437 // Generate the default method
438 *code_writer << BuildMethod(*method, typenames) << " {\n";
439 code_writer->Indent();
440 *code_writer << "Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())\n";
441 code_writer->Dedent();
442 *code_writer << "}\n";
443 }
444 code_writer->Dedent();
445 *code_writer << "}\n";
446
Andrei Homescub62afd92020-05-11 19:24:59 -0700447 // Generate the transaction code constants
448 // The constants get their own sub-module to avoid conflicts
449 *code_writer << "pub mod transactions {\n";
450 code_writer->Indent();
Andrei Homescub62afd92020-05-11 19:24:59 -0700451 for (const auto& method : iface->GetMethods()) {
452 // Generate the transaction code constant
453 *code_writer << "pub const " << method->GetName()
454 << ": binder::TransactionCode = "
Andrew Walbran7a1563f2021-03-09 12:17:13 +0000455 "binder::FIRST_CALL_TRANSACTION + " +
Andrei Homescub62afd92020-05-11 19:24:59 -0700456 std::to_string(method->GetId()) + ";\n";
457 }
458 code_writer->Dedent();
459 *code_writer << "}\n";
460
461 // Emit the default implementation code outside the trait
Andrei Homescu71bd1c32020-12-17 18:21:05 -0800462 *code_writer << "pub type " << default_ref_name << " = Option<std::sync::Arc<dyn "
463 << default_trait_name << ">>;\n";
Andrei Homescub62afd92020-05-11 19:24:59 -0700464 *code_writer << "use lazy_static::lazy_static;\n";
465 *code_writer << "lazy_static! {\n";
Andrei Homescu71bd1c32020-12-17 18:21:05 -0800466 *code_writer << " static ref DEFAULT_IMPL: std::sync::Mutex<" << default_ref_name
Andrei Homescub62afd92020-05-11 19:24:59 -0700467 << "> = std::sync::Mutex::new(None);\n";
468 *code_writer << "}\n";
469
470 // Emit the interface constants
Jooyung Han3f347ca2020-12-01 12:41:50 +0900471 GenerateConstantDeclarations(*code_writer, *iface, typenames);
Andrei Homescub62afd92020-05-11 19:24:59 -0700472
473 GenerateMangledAlias(*code_writer, iface);
474
475 // Emit VERSION and HASH
476 // These need to be top-level item constants instead of associated consts
477 // because the latter are incompatible with trait objects, see
478 // https://doc.rust-lang.org/reference/items/traits.html#object-safety
479 if (options.Version() > 0) {
480 *code_writer << "pub const VERSION: i32 = " << std::to_string(options.Version()) << ";\n";
481 }
482 if (!options.Hash().empty()) {
483 *code_writer << "pub const HASH: &str = \"" << options.Hash() << "\";\n";
484 }
485
486 // Generate the client-side methods
487 *code_writer << "impl " << trait_name << " for " << client_name << " {\n";
488 code_writer->Indent();
489 for (const auto& method : iface->GetMethods()) {
Steven Morelanda7764e52020-10-27 17:29:29 +0000490 GenerateClientMethod(*code_writer, *iface, *method, typenames, options, trait_name);
Andrei Homescub62afd92020-05-11 19:24:59 -0700491 }
492 code_writer->Dedent();
493 *code_writer << "}\n";
494
495 // Generate the server-side methods
496 GenerateServerItems(*code_writer, iface, typenames);
497
498 return true;
499}
500
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900501void GenerateParcelBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
502 const AidlTypenames& typenames) {
Jooyung Han720253d2021-01-05 19:13:17 +0900503 GenerateDeprecated(out, *parcel);
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900504 out << "pub struct " << parcel->GetName() << " {\n";
505 out.Indent();
506 for (const auto& variable : parcel->GetFields()) {
Jooyung Han720253d2021-01-05 19:13:17 +0900507 GenerateDeprecated(out, *variable);
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900508 auto field_type = RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD);
509 out << "pub " << variable->GetName() << ": " << field_type << ",\n";
510 }
511 out.Dedent();
512 out << "}\n";
513}
514
Andrei Homescub62afd92020-05-11 19:24:59 -0700515void GenerateParcelDefault(CodeWriter& out, const AidlStructuredParcelable* parcel) {
516 out << "impl Default for " << parcel->GetName() << " {\n";
517 out.Indent();
518 out << "fn default() -> Self {\n";
519 out.Indent();
520 out << "Self {\n";
521 out.Indent();
522 for (const auto& variable : parcel->GetFields()) {
523 if (variable->GetDefaultValue()) {
524 out << variable->GetName() << ": " << variable->ValueString(ConstantValueDecorator) << ",\n";
525 } else {
526 out << variable->GetName() << ": Default::default(),\n";
527 }
528 }
529 out.Dedent();
530 out << "}\n";
531 out.Dedent();
532 out << "}\n";
533 out.Dedent();
534 out << "}\n";
535}
536
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900537void GenerateParcelSerializeBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
538 const AidlTypenames& typenames) {
539 out << "parcel.sized_write(|subparcel| {\n";
540 out.Indent();
541 for (const auto& variable : parcel->GetFields()) {
542 if (!TypeHasDefault(variable->GetType(), typenames)) {
543 out << "let __field_ref = this." << variable->GetName()
544 << ".as_ref().ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
545 out << "subparcel.write(__field_ref)?;\n";
546 } else {
547 out << "subparcel.write(&this." << variable->GetName() << ")?;\n";
548 }
549 }
550 out << "Ok(())\n";
551 out.Dedent();
552 out << "})\n";
553}
554
555void GenerateParcelDeserializeBody(CodeWriter& out, const AidlStructuredParcelable* parcel,
556 const AidlTypenames& typenames) {
557 out << "let start_pos = parcel.get_data_position();\n";
558 out << "let parcelable_size: i32 = parcel.read()?;\n";
559 out << "if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }\n";
560
561 // Pre-emit the common field epilogue code, shared between all fields:
562 ostringstream epilogue;
563 epilogue << "if (parcel.get_data_position() - start_pos) == parcelable_size {\n";
564 // We assume the lhs can never be > parcelable_size, because then the read
565 // immediately preceding this check would have returned NOT_ENOUGH_DATA
566 epilogue << " return Ok(Some(result));\n";
567 epilogue << "}\n";
568 string epilogue_str = epilogue.str();
569
570 out << "let mut result = Self::default();\n";
571 for (const auto& variable : parcel->GetFields()) {
572 if (!TypeHasDefault(variable->GetType(), typenames)) {
573 out << "result." << variable->GetName() << " = Some(parcel.read()?);\n";
574 } else {
575 out << "result." << variable->GetName() << " = parcel.read()?;\n";
576 }
577 out << epilogue_str;
578 }
579
580 out << "Ok(Some(result))\n";
581}
582
583void GenerateParcelBody(CodeWriter& out, const AidlUnionDecl* parcel,
584 const AidlTypenames& typenames) {
Jooyung Han720253d2021-01-05 19:13:17 +0900585 GenerateDeprecated(out, *parcel);
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900586 out << "pub enum " << parcel->GetName() << " {\n";
587 out.Indent();
588 for (const auto& variable : parcel->GetFields()) {
Jooyung Han720253d2021-01-05 19:13:17 +0900589 GenerateDeprecated(out, *variable);
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900590 auto field_type = RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD);
591 out << variable->GetCapitalizedName() << "(" << field_type << "),\n";
592 }
593 out.Dedent();
594 out << "}\n";
595}
596
597void GenerateParcelDefault(CodeWriter& out, const AidlUnionDecl* parcel) {
598 out << "impl Default for " << parcel->GetName() << " {\n";
599 out.Indent();
600 out << "fn default() -> Self {\n";
601 out.Indent();
602
603 AIDL_FATAL_IF(parcel->GetFields().empty(), *parcel)
604 << "Union '" << parcel->GetName() << "' is empty.";
605 const auto& first_field = parcel->GetFields()[0];
606 const auto& first_value = first_field->ValueString(ConstantValueDecorator);
607
608 out << "Self::";
609 if (first_field->GetDefaultValue()) {
610 out << first_field->GetCapitalizedName() << "(" << first_value << ")\n";
611 } else {
612 out << first_field->GetCapitalizedName() << "(Default::default())\n";
613 }
614
615 out.Dedent();
616 out << "}\n";
617 out.Dedent();
618 out << "}\n";
619}
620
621void GenerateParcelSerializeBody(CodeWriter& out, const AidlUnionDecl* parcel,
622 const AidlTypenames& typenames) {
623 out << "match this {\n";
624 out.Indent();
625 int tag = 0;
626 for (const auto& variable : parcel->GetFields()) {
627 out << "Self::" << variable->GetCapitalizedName() << "(v) => {\n";
628 out.Indent();
629 out << "parcel.write(&" << std::to_string(tag++) << "i32)?;\n";
630 if (!TypeHasDefault(variable->GetType(), typenames)) {
631 out << "let __field_ref = v.as_ref().ok_or(binder::StatusCode::UNEXPECTED_NULL)?;\n";
632 out << "parcel.write(__field_ref)\n";
633 } else {
634 out << "parcel.write(v)\n";
635 }
636 out.Dedent();
637 out << "}\n";
638 }
639 out.Dedent();
640 out << "}\n";
641}
642
643void GenerateParcelDeserializeBody(CodeWriter& out, const AidlUnionDecl* parcel,
644 const AidlTypenames& typenames) {
645 out << "let tag: i32 = parcel.read()?;\n";
646 out << "match tag {\n";
647 out.Indent();
648 int tag = 0;
649 for (const auto& variable : parcel->GetFields()) {
650 auto field_type = RustNameOf(variable->GetType(), typenames, StorageMode::PARCELABLE_FIELD);
651
652 out << std::to_string(tag++) << " => {\n";
653 out.Indent();
654 out << "let value: " << field_type << " = ";
655 if (!TypeHasDefault(variable->GetType(), typenames)) {
656 out << "Some(parcel.read()?);\n";
657 } else {
658 out << "parcel.read()?;\n";
659 }
660 out << "Ok(Some(Self::" << variable->GetCapitalizedName() << "(value)))\n";
661 out.Dedent();
662 out << "}\n";
663 }
664 out << "_ => {\n";
665 out << " Err(binder::StatusCode::BAD_VALUE)\n";
666 out << "}\n";
667 out.Dedent();
668 out << "}\n";
669}
670
671template <typename ParcelableType>
672void GenerateParcelSerialize(CodeWriter& out, const ParcelableType* parcel,
Andrei Homescub62afd92020-05-11 19:24:59 -0700673 const AidlTypenames& typenames) {
674 out << "impl binder::parcel::Serialize for " << parcel->GetName() << " {\n";
675 out << " fn serialize(&self, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {\n";
676 out << " <Self as binder::parcel::SerializeOption>::serialize_option(Some(self), parcel)\n";
677 out << " }\n";
678 out << "}\n";
679
680 out << "impl binder::parcel::SerializeArray for " << parcel->GetName() << " {}\n";
681
682 out << "impl binder::parcel::SerializeOption for " << parcel->GetName() << " {\n";
683 out.Indent();
684 out << "fn serialize_option(this: Option<&Self>, parcel: &mut binder::parcel::Parcel) -> "
685 "binder::Result<()> {\n";
686 out.Indent();
687 out << "let this = if let Some(this) = this {\n";
688 out << " parcel.write(&1i32)?;\n";
689 out << " this\n";
690 out << "} else {\n";
691 out << " return parcel.write(&0i32);\n";
692 out << "};\n";
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900693
694 GenerateParcelSerializeBody(out, parcel, typenames);
695
Andrei Homescuad9d0da2020-08-06 18:43:40 -0700696 out.Dedent();
Andrei Homescub62afd92020-05-11 19:24:59 -0700697 out << "}\n";
698 out.Dedent();
699 out << "}\n";
700}
701
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900702template <typename ParcelableType>
703void GenerateParcelDeserialize(CodeWriter& out, const ParcelableType* parcel,
Andrei Homescub62afd92020-05-11 19:24:59 -0700704 const AidlTypenames& typenames) {
705 out << "impl binder::parcel::Deserialize for " << parcel->GetName() << " {\n";
706 out << " fn deserialize(parcel: &binder::parcel::Parcel) -> binder::Result<Self> {\n";
707 out << " <Self as binder::parcel::DeserializeOption>::deserialize_option(parcel)\n";
708 out << " .transpose()\n";
709 out << " .unwrap_or(Err(binder::StatusCode::UNEXPECTED_NULL))\n";
710 out << " }\n";
711 out << "}\n";
712
713 out << "impl binder::parcel::DeserializeArray for " << parcel->GetName() << " {}\n";
714
715 out << "impl binder::parcel::DeserializeOption for " << parcel->GetName() << " {\n";
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900716 out.Indent();
717 out << "fn deserialize_option(parcel: &binder::parcel::Parcel) -> binder::Result<Option<Self>> "
Andrei Homescub62afd92020-05-11 19:24:59 -0700718 "{\n";
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900719 out.Indent();
720 out << "let status: i32 = parcel.read()?;\n";
721 out << "if status == 0 { return Ok(None); }\n";
Andrei Homescub62afd92020-05-11 19:24:59 -0700722
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900723 GenerateParcelDeserializeBody(out, parcel, typenames);
Andrei Homescub62afd92020-05-11 19:24:59 -0700724
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900725 out.Dedent();
726 out << "}\n";
727 out.Dedent();
Andrei Homescub62afd92020-05-11 19:24:59 -0700728 out << "}\n";
729}
730
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900731template <typename ParcelableType>
732bool GenerateRustParcel(const string& filename, const ParcelableType* parcel,
Andrei Homescub62afd92020-05-11 19:24:59 -0700733 const AidlTypenames& typenames, const IoDelegate& io_delegate) {
734 CodeWriterPtr code_writer = io_delegate.GetCodeWriter(filename);
735
Andrei Homescue61feb52020-08-18 15:44:24 -0700736 // Debug is always derived because all Rust AIDL types implement it
737 // ParcelFileDescriptor doesn't support any of the others because
738 // it's a newtype over std::fs::File which only implements Debug
739 vector<string> derives{"Debug"};
740 const AidlAnnotation* derive_annotation = parcel->RustDerive();
741 if (derive_annotation != nullptr) {
742 for (const auto& name_and_param : derive_annotation->AnnotationParams(ConstantValueDecorator)) {
743 if (name_and_param.second == "true") {
744 derives.push_back(name_and_param.first);
745 }
746 }
747 }
748
749 *code_writer << "#[derive(" << Join(derives, ", ") << ")]\n";
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900750 GenerateParcelBody(*code_writer, parcel, typenames);
Jooyung Han3f347ca2020-12-01 12:41:50 +0900751 GenerateConstantDeclarations(*code_writer, *parcel, typenames);
Andrei Homescub62afd92020-05-11 19:24:59 -0700752 GenerateMangledAlias(*code_writer, parcel);
753 GenerateParcelDefault(*code_writer, parcel);
754 GenerateParcelSerialize(*code_writer, parcel, typenames);
755 GenerateParcelDeserialize(*code_writer, parcel, typenames);
Andrei Homescub62afd92020-05-11 19:24:59 -0700756 return true;
757}
758
759bool GenerateRustEnumDeclaration(const string& filename, const AidlEnumDeclaration* enum_decl,
760 const AidlTypenames& typenames, const IoDelegate& io_delegate) {
761 CodeWriterPtr code_writer = io_delegate.GetCodeWriter(filename);
762
763 const auto& aidl_backing_type = enum_decl->GetBackingType();
764 auto backing_type = RustNameOf(aidl_backing_type, typenames, StorageMode::VALUE);
765
Jooyung Hanb7a60ec2021-01-21 13:47:59 +0900766 // TODO(b/177860423) support "deprecated" for enum types
Andrei Homescub62afd92020-05-11 19:24:59 -0700767 *code_writer << "#![allow(non_upper_case_globals)]\n";
Andrei Homescu0717c432020-09-04 17:41:00 -0700768 *code_writer << "use binder::declare_binder_enum;\n";
769 *code_writer << "declare_binder_enum! { " << enum_decl->GetName() << " : " << backing_type
770 << " {\n";
771 code_writer->Indent();
Andrei Homescub62afd92020-05-11 19:24:59 -0700772 for (const auto& enumerator : enum_decl->GetEnumerators()) {
773 auto value = enumerator->GetValue()->ValueString(aidl_backing_type, ConstantValueDecorator);
Andrei Homescu0717c432020-09-04 17:41:00 -0700774 *code_writer << enumerator->GetName() << " = " << value << ",\n";
Andrei Homescub62afd92020-05-11 19:24:59 -0700775 }
Andrei Homescu0717c432020-09-04 17:41:00 -0700776 code_writer->Dedent();
777 *code_writer << "} }\n";
Andrei Homescub62afd92020-05-11 19:24:59 -0700778
779 GenerateMangledAlias(*code_writer, enum_decl);
780
781 return true;
782}
783
784bool GenerateRust(const string& filename, const AidlDefinedType* defined_type,
785 const AidlTypenames& typenames, const IoDelegate& io_delegate,
786 const Options& options) {
787 if (const AidlStructuredParcelable* parcelable = defined_type->AsStructuredParcelable();
788 parcelable != nullptr) {
789 return GenerateRustParcel(filename, parcelable, typenames, io_delegate);
790 }
791
Jooyung Hanf93b5bd2020-10-28 15:12:08 +0900792 if (const AidlUnionDecl* parcelable = defined_type->AsUnionDeclaration(); parcelable != nullptr) {
793 return GenerateRustParcel(filename, parcelable, typenames, io_delegate);
794 }
795
Andrei Homescub62afd92020-05-11 19:24:59 -0700796 if (const AidlEnumDeclaration* enum_decl = defined_type->AsEnumDeclaration();
797 enum_decl != nullptr) {
798 return GenerateRustEnumDeclaration(filename, enum_decl, typenames, io_delegate);
799 }
800
801 if (const AidlInterface* interface = defined_type->AsInterface(); interface != nullptr) {
802 return GenerateRustInterface(filename, interface, typenames, io_delegate, options);
803 }
804
Steven Moreland21780812020-09-11 01:29:45 +0000805 AIDL_FATAL(filename) << "Unrecognized type sent for Rust generation.";
Andrei Homescub62afd92020-05-11 19:24:59 -0700806 return false;
807}
808
809} // namespace rust
810} // namespace aidl
811} // namespace android