• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018, The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include "aidl_to_cpp_common.h"
17 
18 #include <android-base/format.h>
19 #include <android-base/stringprintf.h>
20 #include <android-base/strings.h>
21 
22 #include <limits>
23 #include <set>
24 #include <unordered_map>
25 
26 #include "comments.h"
27 #include "logging.h"
28 #include "os.h"
29 
30 using ::android::base::Join;
31 using ::android::base::Split;
32 
33 namespace android {
34 namespace aidl {
35 namespace cpp {
36 
37 char kTransactionLogStruct[] = R"(struct TransactionLog {
38   double duration_ms;
39   std::string interface_name;
40   std::string method_name;
41   const void* proxy_address;
42   const void* stub_address;
43   std::vector<std::pair<std::string, std::string>> input_args;
44   std::vector<std::pair<std::string, std::string>> output_args;
45   std::string result;
46   std::string exception_message;
47   int32_t exception_code;
48   int32_t transaction_error;
49   int32_t service_specific_error_code;
50 };
51 )";
52 
HasDeprecatedField(const AidlParcelable & parcelable)53 bool HasDeprecatedField(const AidlParcelable& parcelable) {
54   return std::any_of(parcelable.GetFields().begin(), parcelable.GetFields().end(),
55                      [](const auto& field) { return field->IsDeprecated(); });
56 }
57 
ClassName(const AidlDefinedType & defined_type,ClassNames type)58 string ClassName(const AidlDefinedType& defined_type, ClassNames type) {
59   string base_name = defined_type.GetName();
60   if (base_name.length() >= 2 && base_name[0] == 'I' && isupper(base_name[1])) {
61     base_name = base_name.substr(1);
62   }
63 
64   switch (type) {
65     case ClassNames::CLIENT:
66       return "Bp" + base_name;
67     case ClassNames::SERVER:
68       return "Bn" + base_name;
69     case ClassNames::INTERFACE:
70       return "I" + base_name;
71     case ClassNames::DEFAULT_IMPL:
72       return "I" + base_name + "Default";
73     case ClassNames::BASE:
74       return base_name;
75     case ClassNames::DELEGATOR_IMPL:
76       return "I" + base_name + "Delegator";
77     case ClassNames::RAW:
78       [[fallthrough]];
79     default:
80       return defined_type.GetName();
81   }
82 }
83 
HeaderFile(const AidlDefinedType & defined_type,ClassNames class_type,bool use_os_sep)84 std::string HeaderFile(const AidlDefinedType& defined_type, ClassNames class_type,
85                        bool use_os_sep) {
86   // For a nested type, we need to include its top-most parent type's header.
87   const AidlDefinedType* toplevel = &defined_type;
88   for (auto parent = toplevel->GetParentType(); parent;) {
89     // When including the parent's header, it should be always RAW
90     class_type = ClassNames::RAW;
91     toplevel = parent;
92     parent = toplevel->GetParentType();
93   }
94   AIDL_FATAL_IF(toplevel->GetParentType() != nullptr, defined_type)
95       << "Can't find a top-level decl";
96 
97   char separator = (use_os_sep) ? OS_PATH_SEPARATOR : '/';
98   vector<string> paths = toplevel->GetSplitPackage();
99   paths.push_back(ClassName(*toplevel, class_type));
100   return Join(paths, separator) + ".h";
101 }
102 
103 // Ensures that output_file is  <out_dir>/<packagename>/<typename>.cpp
ValidateOutputFilePath(const string & output_file,const Options & options,const AidlDefinedType & defined_type)104 bool ValidateOutputFilePath(const string& output_file, const Options& options,
105                             const AidlDefinedType& defined_type) {
106   const auto& out_dir =
107       !options.OutputDir().empty() ? options.OutputDir() : options.OutputHeaderDir();
108   if (output_file.empty() || !android::base::StartsWith(output_file, out_dir)) {
109     // If output_file is not set (which happens in the unit tests) or is outside of out_dir, we can
110     // help but accepting it, because the path is what the user has requested.
111     return true;
112   }
113 
114   string canonical_name = defined_type.GetCanonicalName();
115   std::replace(canonical_name.begin(), canonical_name.end(), '.', OS_PATH_SEPARATOR);
116   const string expected = out_dir + canonical_name + ".cpp";
117   if (expected != output_file) {
118     AIDL_ERROR(defined_type) << "Output file is expected to be at " << expected << ", but is "
119                              << output_file << ".\n If this is an Android platform "
120                              << "build, consider providing the input AIDL files using a filegroup "
121                              << "with `path:\"<base>\"` so that the AIDL files are located at "
122                              << "<base>/<packagename>/<typename>.aidl.";
123     return false;
124   }
125   return true;
126 }
127 
EnterNamespace(CodeWriter & out,const AidlDefinedType & defined_type)128 void EnterNamespace(CodeWriter& out, const AidlDefinedType& defined_type) {
129   const std::vector<std::string> packages = defined_type.GetSplitPackage();
130   for (const std::string& package : packages) {
131     out << "namespace " << package << " {\n";
132   }
133 }
LeaveNamespace(CodeWriter & out,const AidlDefinedType & defined_type)134 void LeaveNamespace(CodeWriter& out, const AidlDefinedType& defined_type) {
135   const std::vector<std::string> packages = defined_type.GetSplitPackage();
136   for (auto it = packages.rbegin(); it != packages.rend(); ++it) {
137     out << "}  // namespace " << *it << "\n";
138   }
139 }
140 
BuildVarName(const AidlArgument & a)141 string BuildVarName(const AidlArgument& a) {
142   string prefix = "out_";
143   if (a.GetDirection() & AidlArgument::IN_DIR) {
144     prefix = "in_";
145   }
146   return prefix + a.GetName();
147 }
148 
WriteLogForArgument(CodeWriter & w,const AidlArgument & a,bool is_server,const string & log_var,bool is_ndk)149 void WriteLogForArgument(CodeWriter& w, const AidlArgument& a, bool is_server,
150                          const string& log_var, bool is_ndk) {
151   const string var_name = is_server || is_ndk ? BuildVarName(a) : a.GetName();
152   const bool is_pointer = a.IsOut() && !is_server;
153   const string value_expr = (is_pointer ? "*" : "") + var_name;
154   w << log_var
155     << ".emplace_back(\"" + var_name + "\", ::android::internal::ToString(" + value_expr + "));\n";
156 }
157 
GenLogBeforeExecute(const string className,const AidlMethod & method,bool isServer,bool isNdk)158 const string GenLogBeforeExecute(const string className, const AidlMethod& method, bool isServer,
159                                  bool isNdk) {
160   string code;
161   CodeWriterPtr writer = CodeWriter::ForString(&code);
162   (*writer) << className << "::TransactionLog _transaction_log;\n";
163 
164   (*writer) << "if (" << className << "::logFunc != nullptr) {\n";
165   (*writer).Indent();
166 
167   for (const auto& a : method.GetInArguments()) {
168     WriteLogForArgument(*writer, *a, isServer, "_transaction_log.input_args", isNdk);
169   }
170 
171   (*writer).Dedent();
172   (*writer) << "}\n";
173 
174   (*writer) << "auto _log_start = std::chrono::steady_clock::now();\n";
175   writer->Close();
176   return code;
177 }
178 
GenLogAfterExecute(const string className,const AidlInterface & interface,const AidlMethod & method,const string & statusVarName,const string & returnVarName,bool isServer,bool isNdk)179 const string GenLogAfterExecute(const string className, const AidlInterface& interface,
180                                 const AidlMethod& method, const string& statusVarName,
181                                 const string& returnVarName, bool isServer, bool isNdk) {
182   string code;
183   CodeWriterPtr writer = CodeWriter::ForString(&code);
184 
185   (*writer) << "if (" << className << "::logFunc != nullptr) {\n";
186   (*writer).Indent();
187   const auto address = (isNdk && isServer) ? "_aidl_impl.get()" : "static_cast<const void*>(this)";
188   (*writer) << "auto _log_end = std::chrono::steady_clock::now();\n";
189   (*writer) << "_transaction_log.duration_ms = std::chrono::duration<double, std::milli>(_log_end "
190                "- _log_start).count();\n";
191   (*writer) << "_transaction_log.interface_name = \"" << interface.GetCanonicalName() << "\";\n";
192   (*writer) << "_transaction_log.method_name = \"" << method.GetName() << "\";\n";
193   (*writer) << "_transaction_log.stub_address = " << (isServer ? address : "nullptr") << ";\n";
194   (*writer) << "_transaction_log.proxy_address = " << (isServer ? "nullptr" : address) << ";\n";
195 
196   if (isNdk) {
197     (*writer) << "_transaction_log.exception_code = AStatus_getExceptionCode(" << statusVarName
198               << ".get());\n";
199     (*writer) << "_transaction_log.exception_message = AStatus_getMessage(" << statusVarName
200               << ".get());\n";
201     (*writer) << "_transaction_log.transaction_error = AStatus_getStatus(" << statusVarName
202               << ".get());\n";
203     (*writer) << "_transaction_log.service_specific_error_code = AStatus_getServiceSpecificError("
204               << statusVarName << ".get());\n";
205   } else {
206     (*writer) << "_transaction_log.exception_code = " << statusVarName << ".exceptionCode();\n";
207     (*writer) << "_transaction_log.exception_message = " << statusVarName
208               << ".exceptionMessage();\n";
209     (*writer) << "_transaction_log.transaction_error = " << statusVarName
210               << ".transactionError();\n";
211     (*writer) << "_transaction_log.service_specific_error_code = " << statusVarName
212               << ".serviceSpecificErrorCode();\n";
213   }
214 
215   for (const auto& a : method.GetOutArguments()) {
216     WriteLogForArgument(*writer, *a, isServer, "_transaction_log.output_args", isNdk);
217   }
218 
219   if (method.GetType().GetName() != "void") {
220     const string expr = (isServer ? "" : "*") + returnVarName;
221     (*writer) << "_transaction_log.result = ::android::internal::ToString(" << expr << ");\n";
222   }
223 
224   // call the user-provided function with the transaction log object
225   (*writer) << className << "::logFunc(_transaction_log);\n";
226 
227   (*writer).Dedent();
228   (*writer) << "}\n";
229 
230   writer->Close();
231   return code;
232 }
233 
234 // Returns Parent1::Parent2::Self. Namespaces are not included.
GetQualifiedName(const AidlDefinedType & type,ClassNames class_names)235 string GetQualifiedName(const AidlDefinedType& type, ClassNames class_names) {
236   string q_name = ClassName(type, class_names);
237   for (auto parent = type.GetParentType(); parent; parent = parent->GetParentType()) {
238     q_name = parent->GetName() + "::" + q_name;
239   }
240   return q_name;
241 }
242 
243 // Generates enum's class declaration. This should be called in a proper scope. For example, in its
244 // namespace or parent type.
GenerateEnumClassDecl(CodeWriter & out,const AidlEnumDeclaration & enum_decl,const std::string & backing_type,ConstantValueDecorator decorator)245 void GenerateEnumClassDecl(CodeWriter& out, const AidlEnumDeclaration& enum_decl,
246                            const std::string& backing_type, ConstantValueDecorator decorator) {
247   out << "enum class";
248   GenerateDeprecated(out, enum_decl);
249   out << " " << enum_decl.GetName() << " : " << backing_type << " {\n";
250   out.Indent();
251   for (const auto& enumerator : enum_decl.GetEnumerators()) {
252     out << enumerator->GetName();
253     GenerateDeprecated(out, *enumerator);
254     out << " = " << enumerator->ValueString(enum_decl.GetBackingType(), decorator) << ",\n";
255   }
256   out.Dedent();
257   out << "};\n";
258 }
259 
IsEnumDeprecated(const AidlEnumDeclaration & enum_decl)260 static bool IsEnumDeprecated(const AidlEnumDeclaration& enum_decl) {
261   if (enum_decl.IsDeprecated()) {
262     return true;
263   }
264   for (const auto& e : enum_decl.GetEnumerators()) {
265     if (e->IsDeprecated()) {
266       return true;
267     }
268   }
269   return false;
270 }
271 
272 // enum_values template value is defined in its own namespace (android::internal or ndk::internal),
273 // so the enum_decl type should be fully qualified.
GenerateEnumValues(const AidlEnumDeclaration & enum_decl,const std::vector<std::string> & enclosing_namespaces_of_enum_decl)274 std::string GenerateEnumValues(const AidlEnumDeclaration& enum_decl,
275                                const std::vector<std::string>& enclosing_namespaces_of_enum_decl) {
276   const auto fq_name =
277       Join(Append(enclosing_namespaces_of_enum_decl, enum_decl.GetSplitPackage()), "::") +
278       "::" + GetQualifiedName(enum_decl);
279   const auto size = enum_decl.GetEnumerators().size();
280   std::ostringstream code;
281   code << "#pragma clang diagnostic push\n";
282   code << "#pragma clang diagnostic ignored \"-Wc++17-extensions\"\n";
283   if (IsEnumDeprecated(enum_decl)) {
284     code << "#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"\n";
285   }
286   code << "template <>\n";
287   code << "constexpr inline std::array<" << fq_name << ", " << size << ">";
288   code << " enum_values<" << fq_name << "> = {\n";
289   for (const auto& enumerator : enum_decl.GetEnumerators()) {
290     code << "  " << fq_name << "::" << enumerator->GetName() << ",\n";
291   }
292   code << "};\n";
293   code << "#pragma clang diagnostic pop\n";
294   return code.str();
295 }
296 
297 // toString(enum_type) is defined in the same namespace of the type.
298 // So, if enum_decl is nested in parent type(s), it should be qualified with parent type(s).
GenerateEnumToString(const AidlEnumDeclaration & enum_decl,const std::string & backing_type)299 std::string GenerateEnumToString(const AidlEnumDeclaration& enum_decl,
300                                  const std::string& backing_type) {
301   const auto q_name = GetQualifiedName(enum_decl);
302   std::ostringstream code;
303   bool is_enum_deprecated = IsEnumDeprecated(enum_decl);
304   if (is_enum_deprecated) {
305     code << "#pragma clang diagnostic push\n";
306     code << "#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"\n";
307   }
308   code << "[[nodiscard]] static inline std::string toString(" + q_name + " val) {\n";
309   code << "  switch(val) {\n";
310   std::set<std::string> unique_cases;
311   for (const auto& enumerator : enum_decl.GetEnumerators()) {
312     std::string c = enumerator->ValueString(enum_decl.GetBackingType(), AidlConstantValueDecorator);
313     // Only add a case if its value has not yet been used in the switch
314     // statement. C++ does not allow multiple cases with the same value, but
315     // enums does allow this. In this scenario, the first declared
316     // enumerator with the given value is printed.
317     if (unique_cases.count(c) == 0) {
318       unique_cases.insert(c);
319       code << "  case " << q_name << "::" << enumerator->GetName() << ":\n";
320       code << "    return \"" << enumerator->GetName() << "\";\n";
321     }
322   }
323   code << "  default:\n";
324   code << "    return std::to_string(static_cast<" << backing_type << ">(val));\n";
325   code << "  }\n";
326   code << "}\n";
327   if (is_enum_deprecated) {
328     code << "#pragma clang diagnostic pop\n";
329   }
330   return code.str();
331 }
332 
TemplateDecl(const AidlParcelable & defined_type)333 std::string TemplateDecl(const AidlParcelable& defined_type) {
334   std::string decl = "";
335   if (defined_type.IsGeneric()) {
336     std::vector<std::string> template_params;
337     for (const auto& parameter : defined_type.GetTypeParameters()) {
338       template_params.push_back(parameter);
339     }
340     decl = base::StringPrintf("template <typename %s>\n",
341                               base::Join(template_params, ", typename ").c_str());
342   }
343   return decl;
344 }
345 
GenerateParcelableComparisonOperators(CodeWriter & out,const AidlParcelable & parcelable)346 void GenerateParcelableComparisonOperators(CodeWriter& out, const AidlParcelable& parcelable) {
347   std::set<string> operators{"<", ">", "==", ">=", "<=", "!="};
348 
349   if (parcelable.AsUnionDeclaration() && parcelable.IsFixedSize()) {
350     auto name = parcelable.GetName();
351     auto max_tag = parcelable.GetFields().back()->GetName();
352     auto min_tag = parcelable.GetFields().front()->GetName();
353     auto tmpl = R"--(static int _cmp(const {name}& _lhs, const {name}& _rhs) {{
354   return _cmp_value(_lhs.getTag(), _rhs.getTag()) || _cmp_value_at<{max_tag}>(_lhs, _rhs);
355 }}
356 template <Tag _Tag>
357 static int _cmp_value_at(const {name}& _lhs, const {name}& _rhs) {{
358   if constexpr (_Tag == {min_tag}) {{
359     return _cmp_value(_lhs.get<_Tag>(), _rhs.get<_Tag>());
360   }} else {{
361     return (_lhs.getTag() == _Tag)
362       ? _cmp_value(_lhs.get<_Tag>(), _rhs.get<_Tag>())
363       : _cmp_value_at<static_cast<Tag>(static_cast<size_t>(_Tag)-1)>(_lhs, _rhs);
364   }}
365 }}
366 template <typename _Type>
367 static int _cmp_value(const _Type& _lhs, const _Type& _rhs) {{
368   return (_lhs == _rhs) ? 0 : (_lhs < _rhs) ? -1 : 1;
369 }}
370 )--";
371     out << fmt::format(tmpl, fmt::arg("name", name), fmt::arg("min_tag", min_tag),
372                        fmt::arg("max_tag", max_tag));
373     for (const auto& op : operators) {
374       out << "inline bool operator" << op << "(const " << name << "&_rhs) const {\n";
375       out << "  return _cmp(*this, _rhs) " << op << " 0;\n";
376       out << "}\n";
377     }
378     return;
379   }
380 
381   bool is_empty = false;
382 
383   auto comparable = [&](const string& prefix) {
384     vector<string> fields;
385     if (auto p = parcelable.AsStructuredParcelable(); p != nullptr) {
386       is_empty = p->GetFields().empty();
387       for (const auto& f : p->GetFields()) {
388         fields.push_back(prefix + f->GetName());
389       }
390       return "std::tie(" + Join(fields, ", ") + ")";
391     } else if (auto p = parcelable.AsUnionDeclaration(); p != nullptr) {
392       return prefix + "_value";
393     } else {
394       AIDL_FATAL(parcelable) << "Unknown paracelable type";
395     }
396   };
397 
398   string lhs = comparable("");
399   string rhs = comparable("rhs.");
400   for (const auto& op : operators) {
401     out << "inline bool operator" << op << "(const " << parcelable.GetName() << "&"
402         << (is_empty ? "" : " rhs") << ") const {\n"
403         << "  return " << lhs << " " << op << " " << rhs << ";\n"
404         << "}\n";
405   }
406   out << "\n";
407 }
408 
409 // Output may look like:
410 // inline std::string toString() const {
411 //   std::ostringstream os;
412 //   os << "MyData{";
413 //   os << "field1: " << field1;
414 //   os << ", field2: " << v.field2;
415 //   ...
416 //   os << "}";
417 //   return os.str();
418 // }
GenerateToString(CodeWriter & out,const AidlStructuredParcelable & parcelable)419 void GenerateToString(CodeWriter& out, const AidlStructuredParcelable& parcelable) {
420   out << "inline std::string toString() const {\n";
421   out.Indent();
422   out << "std::ostringstream os;\n";
423   out << "os << \"" << parcelable.GetName() << "{\";\n";
424   bool first = true;
425   for (const auto& f : parcelable.GetFields()) {
426     if (first) {
427       out << "os << \"";
428       first = false;
429     } else {
430       out << "os << \", ";
431     }
432     out << f->GetName() << ": \" << ::android::internal::ToString(" << f->GetName() << ");\n";
433   }
434   out << "os << \"}\";\n";
435   out << "return os.str();\n";
436   out.Dedent();
437   out << "}\n";
438 }
439 
440 // Output may look like:
441 // inline std::string toString() const {
442 //   std::ostringstream os;
443 //   os << "MyData{";
444 //   switch (v.getTag()) {
445 //   case MyData::field: os << "field: " << v.get<MyData::field>(); break;
446 //   ...
447 //   }
448 //   os << "}";
449 //   return os.str();
450 // }
GenerateToString(CodeWriter & out,const AidlUnionDecl & parcelable)451 void GenerateToString(CodeWriter& out, const AidlUnionDecl& parcelable) {
452   out << "inline std::string toString() const {\n";
453   out.Indent();
454   out << "std::ostringstream os;\n";
455   out << "os << \"" + parcelable.GetName() + "{\";\n";
456   out << "switch (getTag()) {\n";
457   for (const auto& f : parcelable.GetFields()) {
458     const string tag = f->GetName();
459     out << "case " << tag << ": os << \"" << tag << ": \" << "
460         << "::android::internal::ToString(get<" + tag + ">()); break;\n";
461   }
462   out << "}\n";
463   out << "os << \"}\";\n";
464   out << "return os.str();\n";
465   out.Dedent();
466   out << "}\n";
467 }
468 
GetDeprecatedAttribute(const AidlCommentable & type)469 std::string GetDeprecatedAttribute(const AidlCommentable& type) {
470   if (auto deprecated = FindDeprecated(type.GetComments()); deprecated.has_value()) {
471     if (deprecated->note.empty()) {
472       return "__attribute__((deprecated))";
473     }
474     return "__attribute__((deprecated(" + QuotedEscape(deprecated->note) + ")))";
475   }
476   return "";
477 }
478 
AlignmentOf(const AidlTypeSpecifier & type,const AidlTypenames & typenames)479 size_t AlignmentOf(const AidlTypeSpecifier& type, const AidlTypenames& typenames) {
480   static map<string, size_t> alignment = {
481       {"boolean", 1}, {"byte", 1}, {"char", 2}, {"double", 8},
482       {"float", 4},   {"int", 4},  {"long", 8},
483   };
484 
485   string name = type.GetName();
486   if (auto enum_decl = typenames.GetEnumDeclaration(type); enum_decl) {
487     name = enum_decl->GetBackingType().GetName();
488   }
489   // default to 0 for parcelable types
490   return alignment[name];
491 }
492 
GetHeaders(const AidlUnionDecl & decl)493 std::set<std::string> UnionWriter::GetHeaders(const AidlUnionDecl& decl) {
494   std::set<std::string> union_headers = {
495       "cassert",      // __assert for logging
496       "type_traits",  // std::is_same_v
497       "utility",      // std::mode/forward for value
498       "variant",      // union's impl
499   };
500   if (decl.IsFixedSize()) {
501     union_headers.insert("tuple");  // fixed-sized union's typelist
502   }
503   return union_headers;
504 }
505 
506 // fixed-sized union class looks like:
507 // class Union {
508 // public:
509 //   enum Tag : uint8_t {
510 //     field1 = 0,
511 //     field2,
512 //   };
513 //  ... methods ...
514 // private:
515 //   Tag _tag;
516 //   union {
517 //     type1 field1;
518 //     type2 field2;
519 //   } _value;
520 // };
521 
PrivateFields(CodeWriter & out) const522 void UnionWriter::PrivateFields(CodeWriter& out) const {
523   if (decl.IsFixedSize()) {
524     AIDL_FATAL_IF(decl.GetFields().empty(), decl) << "Union '" << decl.GetName() << "' is empty.";
525     const auto& first_field = decl.GetFields()[0];
526     const auto& default_name = first_field->GetName();
527     const auto& default_value = name_of(first_field->GetType(), typenames) + "(" +
528                                 first_field->ValueString(decorator) + ")";
529 
530     out << "Tag _tag = " << default_name << ";\n";
531     out << "union _value_t {\n";
532     out.Indent();
533     out << "_value_t() {}\n";
534     out << "~_value_t() {}\n";
535     for (const auto& f : decl.GetFields()) {
536       const auto& fn = f->GetName();
537       out << name_of(f->GetType(), typenames) << " " << fn;
538       if (decl.IsFixedSize()) {
539         int alignment = AlignmentOf(f->GetType(), typenames);
540         if (alignment > 0) {
541           out << " __attribute__((aligned (" << std::to_string(alignment) << ")))";
542         }
543       }
544       if (fn == default_name) {
545         out << " = " << default_value;
546       }
547       out << ";\n";
548     }
549     out.Dedent();
550     out << "} _value;\n";
551   } else {
552     vector<string> field_types;
553     for (const auto& f : decl.GetFields()) {
554       field_types.push_back(name_of(f->GetType(), typenames));
555     }
556     out << "std::variant<" + Join(field_types, ", ") + "> _value;\n";
557   }
558 }
559 
PublicFields(CodeWriter & out) const560 void UnionWriter::PublicFields(CodeWriter& out) const {
561   out << "// Expose tag symbols for legacy code\n";
562   for (const auto& f : decl.GetFields()) {
563     out << "static const inline Tag";
564     GenerateDeprecated(out, *f);
565     out << " " << f->GetName() << " = Tag::" << f->GetName() << ";\n";
566   }
567 
568   const auto& name = decl.GetName();
569 
570   if (decl.IsFixedSize()) {
571     vector<string> field_types;
572     for (const auto& f : decl.GetFields()) {
573       field_types.push_back(name_of(f->GetType(), typenames));
574     }
575     auto typelist = Join(field_types, ", ");
576     auto tmpl = R"--(
577 template <Tag _Tag>
578 using _at = typename std::tuple_element<static_cast<size_t>(_Tag), std::tuple<{typelist}>>::type;
579 template <Tag _Tag, typename _Type>
580 static {name} make(_Type&& _arg) {{
581   {name} _inst;
582   _inst.set<_Tag>(std::forward<_Type>(_arg));
583   return _inst;
584 }}
585 constexpr Tag getTag() const {{
586   return _tag;
587 }}
588 template <Tag _Tag>
589 const _at<_Tag>& get() const {{
590   if (_Tag != _tag) {{ __assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, "bad access: a wrong tag"); }}
591   return *(_at<_Tag>*)(&_value);
592 }}
593 template <Tag _Tag>
594 _at<_Tag>& get() {{
595   if (_Tag != _tag) {{ __assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, "bad access: a wrong tag"); }}
596   return *(_at<_Tag>*)(&_value);
597 }}
598 template <Tag _Tag, typename _Type>
599 void set(_Type&& _arg) {{
600   _tag = _Tag;
601   get<_Tag>() = std::forward<_Type>(_arg);
602 }}
603 )--";
604     out << fmt::format(tmpl, fmt::arg("name", name), fmt::arg("typelist", typelist));
605   } else {
606     AIDL_FATAL_IF(decl.GetFields().empty(), decl) << "Union '" << name << "' is empty.";
607     const auto& first_field = decl.GetFields()[0];
608     const auto& default_name = first_field->GetName();
609     const auto& default_value = name_of(first_field->GetType(), typenames) + "(" +
610                                 first_field->ValueString(decorator) + ")";
611 
612     auto tmpl = R"--(
613 template<typename _Tp>
614 static constexpr bool _not_self = !std::is_same_v<std::remove_cv_t<std::remove_reference_t<_Tp>>, {name}>;
615 
616 {name}() : _value(std::in_place_index<static_cast<size_t>({default_name})>, {default_value}) {{ }}
617 
618 template <typename _Tp, typename = std::enable_if_t<_not_self<_Tp>>>
619 // NOLINTNEXTLINE(google-explicit-constructor)
620 constexpr {name}(_Tp&& _arg)
621     : _value(std::forward<_Tp>(_arg)) {{}}
622 
623 template <size_t _Np, typename... _Tp>
624 constexpr explicit {name}(std::in_place_index_t<_Np>, _Tp&&... _args)
625     : _value(std::in_place_index<_Np>, std::forward<_Tp>(_args)...) {{}}
626 
627 template <Tag _tag, typename... _Tp>
628 static {name} make(_Tp&&... _args) {{
629   return {name}(std::in_place_index<static_cast<size_t>(_tag)>, std::forward<_Tp>(_args)...);
630 }}
631 
632 template <Tag _tag, typename _Tp, typename... _Up>
633 static {name} make(std::initializer_list<_Tp> _il, _Up&&... _args) {{
634   return {name}(std::in_place_index<static_cast<size_t>(_tag)>, std::move(_il), std::forward<_Up>(_args)...);
635 }}
636 
637 Tag getTag() const {{
638   return static_cast<Tag>(_value.index());
639 }}
640 
641 template <Tag _tag>
642 const auto& get() const {{
643   if (getTag() != _tag) {{ __assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, "bad access: a wrong tag"); }}
644   return std::get<static_cast<size_t>(_tag)>(_value);
645 }}
646 
647 template <Tag _tag>
648 auto& get() {{
649   if (getTag() != _tag) {{ __assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, "bad access: a wrong tag"); }}
650   return std::get<static_cast<size_t>(_tag)>(_value);
651 }}
652 
653 template <Tag _tag, typename... _Tp>
654 void set(_Tp&&... _args) {{
655   _value.emplace<static_cast<size_t>(_tag)>(std::forward<_Tp>(_args)...);
656 }}
657 
658 )--";
659     out << fmt::format(tmpl, fmt::arg("name", name), fmt::arg("default_name", default_name),
660                        fmt::arg("default_value", default_value));
661   }
662 }
663 
ReadFromParcel(CodeWriter & out,const ParcelWriterContext & ctx) const664 void UnionWriter::ReadFromParcel(CodeWriter& out, const ParcelWriterContext& ctx) const {
665   // Even though @FixedSize union may use a smaller type than int32_t, we need to read/write it
666   // as if it is int32_t for compatibility with other bckends.
667   auto tag_type = typenames.MakeResolvedType(AIDL_LOCATION_HERE, "int", /* is_array= */ false);
668 
669   const string tag = "_aidl_tag";
670   const string value = "_aidl_value";
671   const string status = "_aidl_ret_status";
672 
673   auto read_var = [&](const string& var, const AidlTypeSpecifier& type) {
674     out << fmt::format("{} {};\n", name_of(type, typenames), var);
675     out << fmt::format("if (({} = ", status);
676     ctx.read_func(out, var, type);
677     out << fmt::format(") != {}) return {};\n", ctx.status_ok, status);
678   };
679 
680   out << fmt::format("{} {};\n", ctx.status_type, status);
681   read_var(tag, *tag_type);
682   out << fmt::format("switch (static_cast<Tag>({})) {{\n", tag);
683   for (const auto& variable : decl.GetFields()) {
684     out << fmt::format("case {}: {{\n", variable->GetName());
685     out.Indent();
686     const auto& type = variable->GetType();
687     read_var(value, type);
688     out << fmt::format("if constexpr (std::is_trivially_copyable_v<{}>) {{\n",
689                        name_of(type, typenames));
690     out.Indent();
691     out << fmt::format("set<{}>({});\n", variable->GetName(), value);
692     out.Dedent();
693     out << "} else {\n";
694     out.Indent();
695     // Even when the `if constexpr` is false, the compiler runs the tidy check for the
696     // next line, which doesn't make sense. Silence the check for the unreachable code.
697     out << "// NOLINTNEXTLINE(performance-move-const-arg)\n";
698     out << fmt::format("set<{}>(std::move({}));\n", variable->GetName(), value);
699     out.Dedent();
700     out << "}\n";
701     out << fmt::format("return {}; }}\n", ctx.status_ok);
702     out.Dedent();
703   }
704   out << "}\n";
705   out << fmt::format("return {};\n", ctx.status_bad);
706 }
707 
WriteToParcel(CodeWriter & out,const ParcelWriterContext & ctx) const708 void UnionWriter::WriteToParcel(CodeWriter& out, const ParcelWriterContext& ctx) const {
709   // Even though @FixedSize union may use a smaller type than int32_t, we need to read/write it
710   // as if it is int32_t for compatibility with other bckends.
711   auto tag_type = typenames.MakeResolvedType(AIDL_LOCATION_HERE, "int", /* is_array= */ false);
712 
713   const string tag = "_aidl_tag";
714   const string value = "_aidl_value";
715   const string status = "_aidl_ret_status";
716 
717   out << fmt::format("{} {} = ", ctx.status_type, status);
718   ctx.write_func(out, "static_cast<int32_t>(getTag())", *tag_type);
719   out << ";\n";
720   out << fmt::format("if ({} != {}) return {};\n", status, ctx.status_ok, status);
721   out << "switch (getTag()) {\n";
722   for (const auto& variable : decl.GetFields()) {
723     if (variable->IsDeprecated()) {
724       out << "#pragma clang diagnostic push\n";
725       out << "#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"\n";
726     }
727     out << fmt::format("case {}: return ", variable->GetName());
728     ctx.write_func(out, "get<" + variable->GetName() + ">()", variable->GetType());
729     out << ";\n";
730     if (variable->IsDeprecated()) {
731       out << "#pragma clang diagnostic pop\n";
732     }
733   }
734   out << "}\n";
735   out << "__assert2(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"can't reach here\");\n";
736 }
737 
CppConstantValueDecorator(const AidlTypeSpecifier & type,const std::variant<std::string,std::vector<std::string>> & raw_value,bool is_ndk)738 std::string CppConstantValueDecorator(
739     const AidlTypeSpecifier& type,
740     const std::variant<std::string, std::vector<std::string>>& raw_value, bool is_ndk) {
741   if (type.IsArray()) {
742     auto values = std::get<std::vector<std::string>>(raw_value);
743     // Hexadecimal literals for byte arrays should be casted to uint8_t
744     if (type.GetName() == "byte" &&
745         std::any_of(values.begin(), values.end(),
746                     [](const auto& value) { return !value.empty() && value[0] == '-'; })) {
747       for (auto& value : values) {
748         // cast only if necessary
749         if (value[0] == '-') {
750           value = "uint8_t(" + value + ")";
751         }
752       }
753     }
754     std::string value = "{" + Join(values, ", ") + "}";
755 
756     if (type.IsFixedSizeArray()) {
757       // For arrays, use double braces because arrays can be nested.
758       //  e.g.) array<array<int, 2>, 3> ints = {{ {{1,2}}, {{3,4}}, {{5,6}} }};
759       // Vectors might need double braces, but since we don't have nested vectors (yet)
760       // single brace would work even for optional vectors.
761       value = "{" + value + "}";
762     }
763 
764     if (!type.IsMutated() && type.IsNullable()) {
765       // For outermost std::optional<>, we need an additional brace pair to initialize its value.
766       value = "{" + value + "}";
767     }
768     return value;
769   }
770 
771   const std::string& value = std::get<std::string>(raw_value);
772   if (AidlTypenames::IsBuiltinTypename(type.GetName())) {
773     if (type.GetName() == "boolean") {
774       return value;
775     } else if (type.GetName() == "byte") {
776       return value;
777     } else if (type.GetName() == "char") {
778       // TODO: consider 'L'-prefix for wide char literal
779       return value;
780     } else if (type.GetName() == "double") {
781       return value;
782     } else if (type.GetName() == "float") {
783       return value;  // value has 'f' suffix
784     } else if (type.GetName() == "int") {
785       return value;
786     } else if (type.GetName() == "long") {
787       return value + "L";
788     } else if (type.GetName() == "String") {
789       if (is_ndk || type.IsUtf8InCpp()) {
790         return value;
791       } else {
792         return "::android::String16(" + value + ")";
793       }
794     }
795     AIDL_FATAL(type) << "Unknown built-in type: " << type.GetName();
796   }
797 
798   auto defined_type = type.GetDefinedType();
799   AIDL_FATAL_IF(!defined_type, type) << "Invalid type for \"" << value << "\"";
800   auto enum_type = defined_type->AsEnumDeclaration();
801   AIDL_FATAL_IF(!enum_type, type) << "Invalid type for \"" << value << "\"";
802 
803   auto cpp_type_name = "::" + Join(Split(enum_type->GetCanonicalName(), "."), "::");
804   if (is_ndk) {
805     cpp_type_name = "::aidl" + cpp_type_name;
806   }
807   return cpp_type_name + "::" + value.substr(value.find_last_of('.') + 1);
808 }
809 
810 // Collect all forward declarations for the type's interface header.
811 // Nested types are visited as well via VisitTopDown.
GenerateForwardDecls(CodeWriter & out,const AidlDefinedType & root_type,bool is_ndk)812 void GenerateForwardDecls(CodeWriter& out, const AidlDefinedType& root_type, bool is_ndk) {
813   struct Visitor : AidlVisitor {
814     using PackagePath = std::vector<std::string>;
815     struct ClassDeclInfo {
816       std::string template_decl;
817     };
818     std::map<PackagePath, std::map<std::string, ClassDeclInfo>> classes;
819     // Collect class names for each interface or parcelable type
820     void Visit(const AidlTypeSpecifier& type) override {
821       const auto defined_type = type.GetDefinedType();
822       if (defined_type && !defined_type->GetParentType()) {
823         // Forward declarations are not supported for nested types
824         auto package = defined_type->GetSplitPackage();
825         if (defined_type->AsInterface() != nullptr) {
826           auto name = ClassName(*defined_type, ClassNames::INTERFACE);
827           classes[package][std::move(name)] = ClassDeclInfo();
828         } else if (auto* p = defined_type->AsStructuredParcelable(); p != nullptr) {
829           auto name = defined_type->GetName();
830           ClassDeclInfo info;
831           info.template_decl = TemplateDecl(*p);
832           classes[package][std::move(name)] = std::move(info);
833         }
834       }
835     }
836   } v;
837   VisitTopDown(v, root_type);
838 
839   if (v.classes.empty()) {
840     return;
841   }
842 
843   for (const auto& it : v.classes) {
844     auto package = it.first;
845     auto& classes = it.second;
846 
847     if (is_ndk) {
848       package.insert(package.begin(), "aidl");
849     }
850 
851     std::string namespace_name = Join(package, "::");
852     if (!namespace_name.empty()) {
853       out << "namespace " << namespace_name << " {\n";
854     }
855     for (const auto& [name, info] : classes) {
856       out << info.template_decl << "class " << name << ";\n";
857     }
858     if (!namespace_name.empty()) {
859       out << "}  // namespace " << namespace_name << "\n";
860     }
861   }
862 }
863 }  // namespace cpp
864 }  // namespace aidl
865 }  // namespace android
866