• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019, 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 #pragma once
18 
19 #include <memory>
20 #include <regex>
21 #include <string>
22 #include <unordered_set>
23 #include <variant>
24 #include <vector>
25 
26 #include <android-base/result.h>
27 #include <android-base/strings.h>
28 
29 #include "aidl_typenames.h"
30 #include "code_writer.h"
31 #include "comments.h"
32 #include "diagnostics.h"
33 #include "io_delegate.h"
34 #include "location.h"
35 #include "logging.h"
36 #include "options.h"
37 #include "permission.h"
38 
39 using android::aidl::AidlTypenames;
40 using android::aidl::CodeWriter;
41 using android::aidl::Comments;
42 using android::aidl::Options;
43 using android::base::Result;
44 using std::shared_ptr;
45 using std::string;
46 using std::unique_ptr;
47 using std::vector;
48 class AidlNode;
49 
50 // helper to see if T is the same to one of Args types.
51 template <typename T, typename... Args>
52 struct is_one_of : std::false_type {};
53 
54 template <typename T, typename S, typename... Args>
55 struct is_one_of<T, S, Args...> {
56   enum { value = std::is_same_v<T, S> || is_one_of<T, Args...>::value };
57 };
58 
59 // helper to see if T is std::vector of something.
60 template <typename>
61 struct is_vector : std::false_type {};
62 
63 template <typename T>
64 struct is_vector<std::vector<T>> : std::true_type {};
65 
66 // helper for static_assert(false)
67 template <typename T>
68 struct unsupported_type : std::false_type {};
69 
70 namespace android {
71 namespace aidl {
72 namespace mappings {
73 std::string dump_location(const AidlNode& method);
74 }  // namespace mappings
75 namespace java {
76 std::string dump_location(const AidlNode& method);
77 }  // namespace java
78 }  // namespace aidl
79 }  // namespace android
80 
81 bool ParseFloating(std::string_view sv, double* parsed);
82 bool ParseFloating(std::string_view sv, float* parsed);
83 
84 class AidlDocument;
85 class AidlInterface;
86 class AidlParcelable;
87 class AidlStructuredParcelable;
88 class AidlEnumDeclaration;
89 class AidlUnionDecl;
90 class AidlVariableDeclaration;
91 class AidlConstantDeclaration;
92 class AidlEnumerator;
93 class AidlMethod;
94 class AidlArgument;
95 class AidlConstantValue;
96 class AidlConstantReference;
97 class AidlUnaryConstExpression;
98 class AidlBinaryConstExpression;
99 class AidlAnnotation;
100 
101 // Interface for visitors that can traverse AidlTraversable nodes.
102 class AidlVisitor {
103  public:
104   virtual ~AidlVisitor() = default;
105   virtual void Visit(const AidlDocument&) {}
106   virtual void Visit(const AidlInterface&) {}
107   virtual void Visit(const AidlParcelable&) {}
108   virtual void Visit(const AidlStructuredParcelable&) {}
109   virtual void Visit(const AidlUnionDecl&) {}
110   virtual void Visit(const AidlEnumDeclaration&) {}
111   virtual void Visit(const AidlEnumerator&) {}
112   virtual void Visit(const AidlMethod&) {}
113   virtual void Visit(const AidlVariableDeclaration&) {}
114   virtual void Visit(const AidlConstantDeclaration&) {}
115   virtual void Visit(const AidlArgument&) {}
116   virtual void Visit(const AidlTypeSpecifier&) {}
117   virtual void Visit(const AidlConstantValue&) {}
118   virtual void Visit(const AidlConstantReference&) {}
119   virtual void Visit(const AidlUnaryConstExpression&) {}
120   virtual void Visit(const AidlBinaryConstExpression&) {}
121   virtual void Visit(const AidlAnnotation&) {}
122 };
123 
124 class AidlScope {
125  public:
126   AidlScope(const AidlNode* self) : self_(self) {}
127   virtual ~AidlScope() = default;
128   virtual std::string ResolveName(const std::string& name) const = 0;
129   void SetEnclosingScope(const AidlScope* enclosing) {
130     AIDL_FATAL_IF(enclosing_, AIDL_LOCATION_HERE) << "SetEnclosingScope can be set only once.";
131     enclosing_ = enclosing;
132   }
133   const AidlScope* GetEnclosingScope() const { return enclosing_; }
134   const AidlNode& GetNode() const { return *self_; }
135 
136  private:
137   const AidlNode* self_;
138   const AidlScope* enclosing_ = nullptr;
139 };
140 
141 // Anything that is locatable in a .aidl file.
142 class AidlNode {
143  public:
144   AidlNode(const AidlLocation& location, const Comments& comments = {});
145 
146   virtual ~AidlNode();
147 
148   AidlNode(AidlNode&) = delete;
149   AidlNode& operator=(AidlNode&) = delete;
150   AidlNode(AidlNode&&) = delete;
151   AidlNode& operator=(AidlNode&&) = delete;
152 
153   // To be able to print AidlLocation
154   friend class AidlErrorLog;
155   friend std::string android::aidl::mappings::dump_location(const AidlNode&);
156   friend std::string android::aidl::java::dump_location(const AidlNode&);
157 
158   const AidlLocation& GetLocation() const { return location_; }
159   virtual void TraverseChildren(std::function<void(const AidlNode&)> traverse) const = 0;
160   virtual void DispatchVisit(AidlVisitor&) const = 0;
161 
162   const Comments& GetComments() const { return comments_; }
163   void SetComments(const Comments& comments) { comments_ = comments; }
164 
165   static void ClearUnvisitedNodes();
166   static const std::vector<AidlLocation>& GetLocationsOfUnvisitedNodes();
167   void MarkVisited() const;
168   bool IsUserDefined() const { return !GetLocation().IsInternal(); }
169 
170  private:
171   std::string PrintLine() const;
172   std::string PrintLocation() const;
173   const AidlLocation location_;
174   Comments comments_;
175 
176   // make sure we are able to abort if types are not visited
177   mutable bool visited_ = false;
178   static std::vector<AidlLocation> unvisited_locations_;
179 };
180 
181 // unique_ptr<AidlTypeSpecifier> for type arugment,
182 // std::string for type parameter(T, U, and so on).
183 template <typename T>
184 class AidlParameterizable {
185  public:
186   AidlParameterizable(std::vector<T>* type_params) : type_params_(type_params) {}
187   virtual ~AidlParameterizable() = default;
188   bool IsGeneric() const { return type_params_ != nullptr; }
189   const std::vector<T>& GetTypeParameters() const { return *type_params_; }
190   bool CheckValid() const;
191 
192   __attribute__((warn_unused_result)) bool SetTypeParameters(std::vector<T>* type_params) {
193     if (type_params_) return false;
194     type_params_.reset(type_params);
195     return true;
196   }
197 
198   virtual const AidlNode& AsAidlNode() const = 0;
199 
200  private:
201   unique_ptr<std::vector<T>> type_params_;
202   static_assert(std::is_same<T, unique_ptr<AidlTypeSpecifier>>::value ||
203                 std::is_same<T, std::string>::value);
204 };
205 template <>
206 bool AidlParameterizable<std::string>::CheckValid() const;
207 
208 class AidlCommentable : public AidlNode {
209  public:
210   AidlCommentable(const AidlLocation& location, const Comments& comments)
211       : AidlNode(location, comments) {}
212   virtual ~AidlCommentable() = default;
213 
214   bool IsHidden() const;
215   bool IsDeprecated() const;
216 };
217 
218 // Transforms a value string into a language specific form. Raw value as produced by
219 // AidlConstantValue.
220 using ConstantValueDecorator = std::function<std::string(
221     const AidlTypeSpecifier& type,
222     const std::variant<std::string, std::vector<std::string>>& raw_value)>;
223 
224 class AidlAnnotation : public AidlNode {
225  public:
226   enum class Type {
227     BACKING = 1,
228     JAVA_STABLE_PARCELABLE,
229     UNSUPPORTED_APP_USAGE,
230     VINTF_STABILITY,
231     NULLABLE,
232     UTF8_IN_CPP,
233     SENSITIVE_DATA,
234     JAVA_PASSTHROUGH,
235     JAVA_DERIVE,
236     JAVA_DEFAULT,
237     JAVA_DELEGATOR,
238     JAVA_ONLY_IMMUTABLE,
239     JAVA_SUPPRESS_LINT,
240     FIXED_SIZE,
241     DESCRIPTOR,
242     RUST_DERIVE,
243     SUPPRESS_WARNINGS,
244     PERMISSION_ENFORCE,
245     PERMISSION_NONE,
246     PERMISSION_MANUAL,
247     PROPAGATE_ALLOW_BLOCKING,
248   };
249 
250   using TargetContext = uint16_t;
251   static constexpr TargetContext CONTEXT_TYPE_INTERFACE = 0x1 << 0;
252   static constexpr TargetContext CONTEXT_TYPE_ENUM = 0x1 << 1;
253   static constexpr TargetContext CONTEXT_TYPE_STRUCTURED_PARCELABLE = 0x1 << 2;
254   static constexpr TargetContext CONTEXT_TYPE_UNION = 0x1 << 3;
255   static constexpr TargetContext CONTEXT_TYPE_UNSTRUCTURED_PARCELABLE = 0x1 << 4;
256   static constexpr TargetContext CONTEXT_TYPE =
257       CONTEXT_TYPE_INTERFACE | CONTEXT_TYPE_ENUM | CONTEXT_TYPE_STRUCTURED_PARCELABLE |
258       CONTEXT_TYPE_UNION | CONTEXT_TYPE_UNSTRUCTURED_PARCELABLE;
259   static constexpr TargetContext CONTEXT_CONST = 0x1 << 5;
260   static constexpr TargetContext CONTEXT_FIELD = 0x1 << 6;
261   static constexpr TargetContext CONTEXT_METHOD = 0x1 << 7;
262   static constexpr TargetContext CONTEXT_MEMBER = CONTEXT_CONST | CONTEXT_FIELD | CONTEXT_METHOD;
263   static constexpr TargetContext CONTEXT_TYPE_SPECIFIER = 0x1 << 8;
264   static constexpr TargetContext CONTEXT_ALL =
265       CONTEXT_TYPE | CONTEXT_MEMBER | CONTEXT_TYPE_SPECIFIER;
266 
267   static std::string TypeToString(Type type);
268 
269   static std::unique_ptr<AidlAnnotation> Parse(
270       const AidlLocation& location, const string& name,
271       std::map<std::string, std::shared_ptr<AidlConstantValue>> parameter_list,
272       const Comments& comments);
273 
274   AidlAnnotation(AidlAnnotation&&) = default;
275   virtual ~AidlAnnotation() = default;
276   bool CheckValid() const;
277   bool CheckContext(TargetContext context) const;
278   const string& GetName() const { return schema_.name; }
279   const Type& GetType() const { return schema_.type; }
280   bool Repeatable() const { return schema_.repeatable; }
281 
282   // ToString is for dumping AIDL.
283   // Returns string representation of this annotation.
284   // e.g) "@RustDerive(Clone=true, Copy=true)"
285   string ToString() const;
286 
287   template <typename T>
288   std::optional<T> ParamValue(const std::string& param_name) const;
289 
290   std::map<std::string, std::string> AnnotationParams(
291       const ConstantValueDecorator& decorator) const;
292   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override;
293   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
294 
295   Result<unique_ptr<android::aidl::perm::Expression>> EnforceExpression() const;
296 
297  private:
298   struct ParamType {
299     std::string name;
300     const AidlTypeSpecifier& type;
301     bool required = false;
302   };
303 
304   struct Schema {
305     AidlAnnotation::Type type;
306     std::string name;
307     TargetContext target_context;
308     std::vector<ParamType> parameters;
309     bool repeatable = false;
310 
311     const ParamType* ParamType(const std::string& name) const {
312       for (const auto& param : parameters) {
313         if (param.name == name) {
314           return &param;
315         }
316       }
317       return nullptr;
318     }
319   };
320 
321   static const std::vector<Schema>& AllSchemas();
322 
323   AidlAnnotation(const AidlLocation& location, const Schema& schema,
324                  std::map<std::string, std::shared_ptr<AidlConstantValue>> parameters,
325                  const Comments& comments);
326 
327   const Schema& schema_;
328   std::map<std::string, std::shared_ptr<AidlConstantValue>> parameters_;
329 };
330 
331 static inline bool operator<(const AidlAnnotation& lhs, const AidlAnnotation& rhs) {
332   return lhs.GetName() < rhs.GetName();
333 }
334 static inline bool operator==(const AidlAnnotation& lhs, const AidlAnnotation& rhs) {
335   return lhs.GetName() == rhs.GetName();
336 }
337 
338 class AidlAnnotatable : public AidlCommentable {
339  public:
340   AidlAnnotatable(const AidlLocation& location, const Comments& comments);
341 
342   virtual ~AidlAnnotatable() = default;
343 
344   void Annotate(vector<std::unique_ptr<AidlAnnotation>>&& annotations) {
345     for (auto& annotation : annotations) {
346       annotations_.emplace_back(std::move(annotation));
347     }
348   }
349   bool IsNullable() const;
350   bool IsHeapNullable() const;
351   bool IsUtf8InCpp() const;
352   bool IsSensitiveData() const;
353   bool IsVintfStability() const;
354   bool IsJavaOnlyImmutable() const;
355   bool IsFixedSize() const;
356   bool IsStableApiParcelable(Options::Language lang) const;
357   bool JavaDerive(const std::string& method) const;
358   bool IsJavaDefault() const;
359   bool IsJavaDelegator() const;
360   std::string GetDescriptor() const;
361 
362   const AidlAnnotation* UnsupportedAppUsage() const;
363   const AidlAnnotation* RustDerive() const;
364   const AidlAnnotation* BackingType() const;
365   std::vector<std::string> SuppressWarnings() const;
366   std::unique_ptr<android::aidl::perm::Expression> EnforceExpression() const;
367   bool IsPermissionManual() const;
368   bool IsPermissionNone() const;
369   bool IsPropagateAllowBlocking() const;
370 
371   // ToString is for dumping AIDL.
372   // Returns string representation of annotations.
373   // e.g) "@JavaDerive(toString=true) @RustDerive(Clone=true, Copy=true)"
374   std::string ToString() const;
375 
376   const vector<std::unique_ptr<AidlAnnotation>>& GetAnnotations() const { return annotations_; }
377   bool CheckValid(const AidlTypenames&) const;
378   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override {
379     for (const auto& annot : GetAnnotations()) {
380       traverse(*annot);
381     }
382   }
383 
384  private:
385   vector<std::unique_ptr<AidlAnnotation>> annotations_;
386 };
387 
388 // Represents `[]`
389 struct DynamicArray {};
390 // Represents `[N][M]..`
391 struct FixedSizeArray {
392   FixedSizeArray(std::unique_ptr<AidlConstantValue> dim) { dimensions.push_back(std::move(dim)); }
393   std::vector<std::unique_ptr<AidlConstantValue>> dimensions;
394 };
395 // Represents `[]` or `[N]` part of type specifier
396 using ArrayType = std::variant<DynamicArray, FixedSizeArray>;
397 
398 // AidlTypeSpecifier represents a reference to either a built-in type,
399 // a defined type, or a variant (e.g., array of generic) of a type.
400 class AidlTypeSpecifier final : public AidlAnnotatable,
401                                 public AidlParameterizable<unique_ptr<AidlTypeSpecifier>> {
402  public:
403   AidlTypeSpecifier(const AidlLocation& location, const string& unresolved_name,
404                     std::optional<ArrayType> array,
405                     vector<unique_ptr<AidlTypeSpecifier>>* type_params, const Comments& comments);
406   virtual ~AidlTypeSpecifier() = default;
407 
408   // View of this type which has one-less dimension(s).
409   // e.g.) T[] => T, T[N][M] => T[M]
410   void ViewAsArrayBase(std::function<void(const AidlTypeSpecifier&)> func) const;
411   // ViewAsArrayBase passes "mutated" type to its callback.
412   bool IsMutated() const { return mutated_; }
413 
414   // Returns the full-qualified name of the base type.
415   // int -> int
416   // int[] -> int
417   // List<String> -> List
418   // IFoo -> foo.bar.IFoo (if IFoo is in package foo.bar)
419   const string& GetName() const {
420     if (IsResolved()) {
421       return fully_qualified_name_;
422     } else {
423       return GetUnresolvedName();
424     }
425   }
426 
427   // ToString is for dumping AIDL.
428   // Returns string representation of this type specifier including annotations.
429   // This is "annotations type_name type_params? array_marker?".
430   // e.g) "@utf8InCpp String[]";
431   std::string ToString() const;
432 
433   // Signature is for comparing AIDL types.
434   // Returns string representation of this type specifier.
435   // This is "type_name type_params? array_marker?".
436   // e.g.) "String[]" (even if it is annotated with @utf8InCpp)
437   std::string Signature() const;
438 
439   const string& GetUnresolvedName() const { return unresolved_name_; }
440 
441   const std::vector<std::string> GetSplitName() const { return split_name_; }
442 
443   bool IsResolved() const { return fully_qualified_name_ != ""; }
444 
445   bool IsArray() const { return array_.has_value(); }
446   bool IsDynamicArray() const {
447     return array_.has_value() && std::get_if<DynamicArray>(&*array_) != nullptr;
448   }
449   bool IsFixedSizeArray() const {
450     return array_.has_value() && std::get_if<FixedSizeArray>(&*array_) != nullptr;
451   }
452   std::vector<int32_t> GetFixedSizeArrayDimensions() const;
453 
454   const ArrayType& GetArray() const {
455     AIDL_FATAL_IF(!array_.has_value(), this) << "GetArray() for non-array type";
456     return array_.value();
457   }
458 
459   // Accept transitions from
460   //    T    to T[]
461   // or T    to T[N]
462   // or T[N] to T[N][M]
463   __attribute__((warn_unused_result)) bool MakeArray(ArrayType array_type);
464 
465   // Resolve the base type name to a fully-qualified name. Return false if the
466   // resolution fails.
467   bool Resolve(const AidlTypenames& typenames, const AidlScope* scope);
468 
469   bool CheckValid(const AidlTypenames& typenames) const;
470   bool LanguageSpecificCheckValid(Options::Language lang) const;
471   const AidlNode& AsAidlNode() const override { return *this; }
472 
473   const AidlDefinedType* GetDefinedType() const;
474   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override;
475   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
476 
477  private:
478   const string unresolved_name_;
479   string fully_qualified_name_;
480   mutable std::optional<ArrayType> array_;
481   mutable bool mutated_ = false;  // ViewAsArrayBase() sets this as true to distinguish mutated one
482                                   // from the original type
483   vector<string> split_name_;
484   const AidlDefinedType* defined_type_ = nullptr;  // set when Resolve() for defined types
485 };
486 
487 // Returns the universal value unaltered.
488 std::string AidlConstantValueDecorator(
489     const AidlTypeSpecifier& type,
490     const std::variant<std::string, std::vector<std::string>>& raw_value);
491 
492 class AidlMember : public AidlAnnotatable {
493  public:
494   AidlMember(const AidlLocation& location, const Comments& comments);
495   virtual ~AidlMember() = default;
496 
497   // non-copyable, non-movable
498   AidlMember(const AidlMember&) = delete;
499   AidlMember(AidlMember&&) = delete;
500   AidlMember& operator=(const AidlMember&) = delete;
501   AidlMember& operator=(AidlMember&&) = delete;
502 };
503 
504 // TODO: This class is used for method arguments and also parcelable fields,
505 // and it should be split up since default values don't apply to method
506 // arguments
507 class AidlVariableDeclaration : public AidlMember {
508  public:
509   AidlVariableDeclaration(const AidlLocation& location, AidlTypeSpecifier* type,
510                           const std::string& name);
511   AidlVariableDeclaration(const AidlLocation& location, AidlTypeSpecifier* type,
512                           const std::string& name, AidlConstantValue* default_value);
513   virtual ~AidlVariableDeclaration() = default;
514 
515   // non-copyable, non-movable
516   AidlVariableDeclaration(const AidlVariableDeclaration&) = delete;
517   AidlVariableDeclaration(AidlVariableDeclaration&&) = delete;
518   AidlVariableDeclaration& operator=(const AidlVariableDeclaration&) = delete;
519   AidlVariableDeclaration& operator=(AidlVariableDeclaration&&) = delete;
520 
521   std::string GetName() const { return name_; }
522   std::string GetCapitalizedName() const;
523   const AidlTypeSpecifier& GetType() const { return *type_; }
524   // if this was constructed explicitly with a default value
525   bool IsDefaultUserSpecified() const { return default_user_specified_; }
526   // will return the default value this is constructed with or a default value
527   // if one is available
528   const AidlConstantValue* GetDefaultValue() const { return default_value_.get(); }
529   bool HasUsefulDefaultValue() const;
530 
531   AidlTypeSpecifier* GetMutableType() { return type_.get(); }
532 
533   bool CheckValid(const AidlTypenames& typenames) const;
534 
535   // ToString is for dumping AIDL.
536   // Returns string representation of this variable decl including default value.
537   // This is "annotations type name default_value?".
538   // e.g) "@utf8InCpp String[] names = {"hello"}"
539   std::string ToString() const;
540 
541   // Signature is for comparing AIDL types.
542   // Returns string representation of this variable decl.
543   // This is "type name".
544   // e.g) "String[] name" (even if it is annotated with @utf8InCpp and has a default value.)
545   std::string Signature() const;
546 
547   std::string ValueString(const ConstantValueDecorator& decorator) const;
548 
549   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override;
550   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
551 
552  private:
553   std::unique_ptr<AidlTypeSpecifier> type_;
554   std::string name_;
555   bool default_user_specified_;
556   std::unique_ptr<AidlConstantValue> default_value_;
557 };
558 
559 class AidlArgument : public AidlVariableDeclaration {
560  public:
561   enum Direction { IN_DIR = 1, OUT_DIR = 2, INOUT_DIR = 3 };
562 
563   AidlArgument(const AidlLocation& location, AidlArgument::Direction direction,
564                AidlTypeSpecifier* type, const std::string& name);
565   AidlArgument(const AidlLocation& location, AidlTypeSpecifier* type, const std::string& name);
566   virtual ~AidlArgument() = default;
567 
568   // non-copyable, non-movable
569   AidlArgument(const AidlArgument&) = delete;
570   AidlArgument(AidlArgument&&) = delete;
571   AidlArgument& operator=(const AidlArgument&) = delete;
572   AidlArgument& operator=(AidlArgument&&) = delete;
573 
574   Direction GetDirection() const { return direction_; }
575   bool IsOut() const { return direction_ & OUT_DIR; }
576   bool IsIn() const { return direction_ & IN_DIR; }
577   bool DirectionWasSpecified() const { return direction_specified_; }
578   string GetDirectionSpecifier() const;
579   bool CheckValid(const AidlTypenames& typenames) const;
580 
581   // ToString is for dumping AIDL.
582   // Returns string representation of this argument including direction
583   // This is "direction annotations type name".
584   // e.g) "in @utf8InCpp String[] names"
585   std::string ToString() const;
586 
587   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
588 
589  private:
590   Direction direction_;
591   bool direction_specified_;
592 };
593 
594 struct ArgumentAspect {
595   std::string name;
596   std::set<AidlArgument::Direction> possible_directions;
597 };
598 
599 class AidlUnaryConstExpression;
600 class AidlBinaryConstExpression;
601 class AidlConstantReference;
602 
603 class AidlConstantValue : public AidlNode {
604  public:
605   enum class Type {
606     // WARNING: Don't change this order! The order is used to determine type
607     // promotion during a binary expression.
608     BOOLEAN,
609     INT8,
610     INT32,
611     INT64,
612     ARRAY,
613     CHARACTER,
614     STRING,
615     REF,
616     FLOATING,
617     UNARY,
618     BINARY,
619     ERROR,
620   };
621 
622   // Returns the evaluated value. T> should match to the actual type.
623   template <typename T>
624   T EvaluatedValue() const {
625     is_evaluated_ || (CheckValid() && evaluate());
626     AIDL_FATAL_IF(!is_valid_, this);
627 
628     if constexpr (is_vector<T>::value) {
629       AIDL_FATAL_IF(final_type_ != Type::ARRAY, this);
630       T result;
631       for (const auto& v : values_) {
632         result.push_back(v->EvaluatedValue<typename T::value_type>());
633       }
634       return result;
635     } else if constexpr (is_one_of<T, float, double>::value) {
636       AIDL_FATAL_IF(final_type_ != Type::FLOATING, this);
637       T result;
638       AIDL_FATAL_IF(!ParseFloating(value_, &result), this);
639       return result;
640     } else if constexpr (std::is_same<T, std::string>::value) {
641       AIDL_FATAL_IF(final_type_ != Type::STRING, this);
642       return final_string_value_.substr(1, final_string_value_.size() - 2);  // unquote "
643     } else if constexpr (is_one_of<T, int8_t, int32_t, int64_t>::value) {
644       AIDL_FATAL_IF(final_type_ < Type::INT8 && final_type_ > Type::INT64, this);
645       return static_cast<T>(final_value_);
646     } else if constexpr (std::is_same<T, char16_t>::value) {
647       AIDL_FATAL_IF(final_type_ != Type::CHARACTER, this);
648       return final_string_value_.at(1);  // unquote '
649     } else if constexpr (std::is_same<T, bool>::value) {
650       static_assert(std::is_same<T, bool>::value, "..");
651       AIDL_FATAL_IF(final_type_ != Type::BOOLEAN, this);
652       return final_value_ != 0;
653     } else {
654       static_assert(unsupported_type<T>::value);
655     }
656   }
657 
658   virtual ~AidlConstantValue() = default;
659 
660   // non-copyable, non-movable
661   AidlConstantValue(const AidlConstantValue&) = delete;
662   AidlConstantValue(AidlConstantValue&&) = delete;
663   AidlConstantValue& operator=(const AidlConstantValue&) = delete;
664   AidlConstantValue& operator=(AidlConstantValue&&) = delete;
665 
666   // creates default value, when one isn't specified
667   // nullptr if no default available
668   static AidlConstantValue* Default(const AidlTypeSpecifier& specifier);
669 
670   static AidlConstantValue* Boolean(const AidlLocation& location, bool value);
671   static AidlConstantValue* Character(const AidlLocation& location, const std::string& value);
672   // example: 123, -5498, maybe any size
673   static AidlConstantValue* Integral(const AidlLocation& location, const std::string& value);
674   static AidlConstantValue* Floating(const AidlLocation& location, const std::string& value);
675   static AidlConstantValue* Array(const AidlLocation& location,
676                                   std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values);
677   // example: "\"asdf\""
678   static AidlConstantValue* String(const AidlLocation& location, const string& value);
679 
680   Type GetType() const { return final_type_; }
681   const std::string& Literal() const { return value_; }
682 
683   bool Evaluate() const;
684   virtual bool CheckValid() const;
685 
686   // Raw value of type (currently valid in C++ and Java). Empty string on error.
687   string ValueString(const AidlTypeSpecifier& type, const ConstantValueDecorator& decorator) const;
688 
689   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const {
690     if (type_ == Type::ARRAY) {
691       for (const auto& v : values_) {
692         traverse(*v);
693       }
694     }
695   }
696   void DispatchVisit(AidlVisitor& visitor) const override { visitor.Visit(*this); }
697 
698  private:
699   AidlConstantValue(const AidlLocation& location, Type parsed_type, int64_t parsed_value,
700                     const string& checked_value);
701   AidlConstantValue(const AidlLocation& location, Type type, const string& checked_value);
702   AidlConstantValue(const AidlLocation& location, Type type,
703                     std::unique_ptr<vector<unique_ptr<AidlConstantValue>>> values,
704                     const std::string& value);
705   static string ToString(Type type);
706   static bool ParseIntegral(const string& value, int64_t* parsed_value, Type* parsed_type);
707   static bool IsHex(const string& value);
708 
709   virtual bool evaluate() const;
710 
711   const Type type_ = Type::ERROR;
712   const vector<unique_ptr<AidlConstantValue>> values_;  // if type_ == ARRAY
713   const string value_;                                  // otherwise
714 
715   // State for tracking evaluation of expressions
716   mutable bool is_valid_ = false;      // cache of CheckValid, but may be marked false in evaluate
717   mutable bool is_evaluated_ = false;  // whether evaluate has been called
718   mutable Type final_type_;
719   mutable int64_t final_value_;
720   mutable string final_string_value_ = "";
721 
722   friend AidlUnaryConstExpression;
723   friend AidlBinaryConstExpression;
724   friend AidlConstantReference;
725 };
726 
727 // Represents "<type>.<field>" which resolves to a constant which is one of
728 // - constant declartion
729 // - enumerator
730 // When a <type> is missing, <field> is of the enclosing type.
731 class AidlConstantReference : public AidlConstantValue {
732  public:
733   AidlConstantReference(const AidlLocation& location, const std::string& value);
734 
735   const std::unique_ptr<AidlTypeSpecifier>& GetRefType() const { return ref_type_; }
736   const std::string& GetFieldName() const { return field_name_; }
737 
738   bool CheckValid() const override;
739   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override {
740     if (ref_type_) {
741       traverse(*ref_type_);
742     }
743   }
744   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
745   const AidlConstantValue* Resolve(const AidlDefinedType* scope) const;
746 
747  private:
748   bool evaluate() const override;
749 
750   std::unique_ptr<AidlTypeSpecifier> ref_type_;
751   std::string field_name_;
752   mutable const AidlConstantValue* resolved_ = nullptr;
753 };
754 
755 class AidlUnaryConstExpression : public AidlConstantValue {
756  public:
757   AidlUnaryConstExpression(const AidlLocation& location, const string& op,
758                            std::unique_ptr<AidlConstantValue> rval);
759 
760   static bool IsCompatibleType(Type type, const string& op);
761   bool CheckValid() const override;
762   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override {
763     traverse(*unary_);
764   }
765   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
766 
767  private:
768   bool evaluate() const override;
769 
770   std::unique_ptr<AidlConstantValue> unary_;
771   const string op_;
772 };
773 
774 class AidlBinaryConstExpression : public AidlConstantValue {
775  public:
776   AidlBinaryConstExpression(const AidlLocation& location, std::unique_ptr<AidlConstantValue> lval,
777                             const string& op, std::unique_ptr<AidlConstantValue> rval);
778 
779   bool CheckValid() const override;
780 
781   static bool AreCompatibleTypes(Type t1, Type t2);
782   // Returns the promoted kind for both operands
783   static Type UsualArithmeticConversion(Type left, Type right);
784   // Returns the promoted integral type where INT32 is the smallest type
785   static Type IntegralPromotion(Type in);
786   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override {
787     traverse(*left_val_);
788     traverse(*right_val_);
789   }
790   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
791 
792  private:
793   bool evaluate() const override;
794 
795   std::unique_ptr<AidlConstantValue> left_val_;
796   std::unique_ptr<AidlConstantValue> right_val_;
797   const string op_;
798 };
799 
800 struct AidlAnnotationParameter {
801   std::string name;
802   std::unique_ptr<AidlConstantValue> value;
803 };
804 
805 class AidlConstantDeclaration : public AidlMember {
806  public:
807   AidlConstantDeclaration(const AidlLocation& location, AidlTypeSpecifier* specifier,
808                           const string& name, AidlConstantValue* value);
809   virtual ~AidlConstantDeclaration() = default;
810 
811   // non-copyable, non-movable
812   AidlConstantDeclaration(const AidlConstantDeclaration&) = delete;
813   AidlConstantDeclaration(AidlConstantDeclaration&&) = delete;
814   AidlConstantDeclaration& operator=(const AidlConstantDeclaration&) = delete;
815   AidlConstantDeclaration& operator=(AidlConstantDeclaration&&) = delete;
816 
817   const AidlTypeSpecifier& GetType() const { return *type_; }
818   AidlTypeSpecifier* GetMutableType() { return type_.get(); }
819   const string& GetName() const { return name_; }
820   const AidlConstantValue& GetValue() const { return *value_; }
821   bool CheckValid(const AidlTypenames& typenames) const;
822 
823   // ToString is for dumping AIDL.
824   // Returns string representation of this const decl including a const value.
825   // This is "`const` annotations type name value".
826   // e.g) "const @utf8InCpp String[] names = { "hello" }"
827   string ToString() const;
828 
829   // Signature is for comparing types.
830   // Returns string representation of this const decl.
831   // This is "direction annotations type name".
832   // e.g) "String[] names"
833   string Signature() const;
834 
835   string ValueString(const ConstantValueDecorator& decorator) const {
836     return value_->ValueString(GetType(), decorator);
837   }
838 
839   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override {
840     traverse(GetType());
841     traverse(GetValue());
842   }
843   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
844 
845  private:
846   const unique_ptr<AidlTypeSpecifier> type_;
847   const string name_;
848   unique_ptr<AidlConstantValue> value_;
849 };
850 
851 class AidlMethod : public AidlMember {
852  public:
853   AidlMethod(const AidlLocation& location, bool oneway, AidlTypeSpecifier* type, const string& name,
854              vector<unique_ptr<AidlArgument>>* args, const Comments& comments);
855   AidlMethod(const AidlLocation& location, bool oneway, AidlTypeSpecifier* type, const string& name,
856              vector<unique_ptr<AidlArgument>>* args, const Comments& comments, int id);
857   virtual ~AidlMethod() = default;
858 
859   // non-copyable, non-movable
860   AidlMethod(const AidlMethod&) = delete;
861   AidlMethod(AidlMethod&&) = delete;
862   AidlMethod& operator=(const AidlMethod&) = delete;
863   AidlMethod& operator=(AidlMethod&&) = delete;
864 
865   bool CheckValid(const AidlTypenames&) const;
866   const AidlTypeSpecifier& GetType() const { return *type_; }
867   AidlTypeSpecifier* GetMutableType() { return type_.get(); }
868 
869   // set if this method is part of an interface that is marked oneway
870   void ApplyInterfaceOneway(bool oneway) { oneway_ = oneway_ || oneway; }
871   bool IsOneway() const { return oneway_; }
872 
873   const std::string& GetName() const { return name_; }
874   bool HasId() const { return has_id_; }
875   int GetId() const { return id_; }
876   void SetId(unsigned id) { id_ = id; }
877 
878   const std::vector<std::unique_ptr<AidlArgument>>& GetArguments() const {
879     return arguments_;
880   }
881   // An inout parameter will appear in both GetInArguments()
882   // and GetOutArguments().  AidlMethod retains ownership of the argument
883   // pointers returned in this way.
884   const std::vector<const AidlArgument*>& GetInArguments() const {
885     return in_arguments_;
886   }
887   const std::vector<const AidlArgument*>& GetOutArguments() const {
888     return out_arguments_;
889   }
890 
891   // ToString is for dumping AIDL.
892   // Returns string representation of this method including everything.
893   // This is "ret_type name ( arg_list ) = id".
894   // e.g) "boolean foo(int, @Nullable String) = 1"
895   std::string ToString() const;
896 
897   // Signature is for comparing AIDL types.
898   // Returns string representation of this method's name & type.
899   // e.g) "foo(int, String)"
900   std::string Signature() const;
901 
902   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override {
903     traverse(GetType());
904     for (const auto& a : GetArguments()) {
905       traverse(*a);
906     }
907   }
908   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
909 
910  private:
911   bool oneway_;
912   std::unique_ptr<AidlTypeSpecifier> type_;
913   std::string name_;
914   const std::vector<std::unique_ptr<AidlArgument>> arguments_;
915   std::vector<const AidlArgument*> in_arguments_;
916   std::vector<const AidlArgument*> out_arguments_;
917   bool has_id_;
918   int id_;
919 };
920 
921 // AidlDefinedType represents either an interface, parcelable, or enum that is
922 // defined in the source file.
923 class AidlDefinedType : public AidlMember, public AidlScope {
924  public:
925   AidlDefinedType(const AidlLocation& location, const std::string& name, const Comments& comments,
926                   const std::string& package, std::vector<std::unique_ptr<AidlMember>>* members);
927   virtual ~AidlDefinedType() = default;
928 
929   // non-copyable, non-movable
930   AidlDefinedType(const AidlDefinedType&) = delete;
931   AidlDefinedType(AidlDefinedType&&) = delete;
932   AidlDefinedType& operator=(const AidlDefinedType&) = delete;
933   AidlDefinedType& operator=(AidlDefinedType&&) = delete;
934 
935   const std::string& GetName() const { return name_; };
936 
937   std::string ResolveName(const std::string& name) const override;
938 
939   /* dot joined package, example: "android.package.foo" */
940   std::string GetPackage() const { return package_; }
941   /* dot joined package and name, example: "android.package.foo.IBar" */
942   std::string GetCanonicalName() const;
943   std::vector<std::string> GetSplitPackage() const {
944     if (package_.empty()) return std::vector<std::string>();
945     return android::base::Split(package_, ".");
946   }
947   const AidlDocument& GetDocument() const;
948 
949   virtual std::string GetPreprocessDeclarationName() const = 0;
950 
951   virtual const AidlStructuredParcelable* AsStructuredParcelable() const { return nullptr; }
952   virtual const AidlParcelable* AsParcelable() const { return nullptr; }
953   virtual const AidlEnumDeclaration* AsEnumDeclaration() const { return nullptr; }
954   virtual const AidlUnionDecl* AsUnionDeclaration() const { return nullptr; }
955   virtual const AidlInterface* AsInterface() const { return nullptr; }
956   virtual const AidlParameterizable<std::string>* AsParameterizable() const { return nullptr; }
957   virtual bool CheckValid(const AidlTypenames& typenames) const;
958   bool LanguageSpecificCheckValid(Options::Language lang) const;
959   AidlStructuredParcelable* AsStructuredParcelable() {
960     return const_cast<AidlStructuredParcelable*>(
961         const_cast<const AidlDefinedType*>(this)->AsStructuredParcelable());
962   }
963   AidlParcelable* AsParcelable() {
964     return const_cast<AidlParcelable*>(const_cast<const AidlDefinedType*>(this)->AsParcelable());
965   }
966   AidlEnumDeclaration* AsEnumDeclaration() {
967     return const_cast<AidlEnumDeclaration*>(
968         const_cast<const AidlDefinedType*>(this)->AsEnumDeclaration());
969   }
970   AidlUnionDecl* AsUnionDeclaration() {
971     return const_cast<AidlUnionDecl*>(
972         const_cast<const AidlDefinedType*>(this)->AsUnionDeclaration());
973   }
974   AidlInterface* AsInterface() {
975     return const_cast<AidlInterface*>(const_cast<const AidlDefinedType*>(this)->AsInterface());
976   }
977 
978   AidlParameterizable<std::string>* AsParameterizable() {
979     return const_cast<AidlParameterizable<std::string>*>(
980         const_cast<const AidlDefinedType*>(this)->AsParameterizable());
981   }
982 
983   const AidlParcelable* AsUnstructuredParcelable() const {
984     if (this->AsStructuredParcelable() != nullptr) return nullptr;
985     if (this->AsUnionDeclaration() != nullptr) return nullptr;
986     return this->AsParcelable();
987   }
988   AidlParcelable* AsUnstructuredParcelable() {
989     return const_cast<AidlParcelable*>(
990         const_cast<const AidlDefinedType*>(this)->AsUnstructuredParcelable());
991   }
992   const AidlDefinedType* GetParentType() const;
993   const AidlDefinedType* GetRootType() const;
994   const std::vector<std::unique_ptr<AidlDefinedType>>& GetNestedTypes() const { return types_; }
995   const std::vector<std::unique_ptr<AidlVariableDeclaration>>& GetFields() const {
996     return variables_;
997   }
998   const std::vector<std::unique_ptr<AidlConstantDeclaration>>& GetConstantDeclarations() const {
999     return constants_;
1000   }
1001   const std::vector<std::unique_ptr<AidlMethod>>& GetMethods() const { return methods_; }
1002   const std::vector<const AidlMember*>& GetMembers() const { return members_; }
1003   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override {
1004     AidlAnnotatable::TraverseChildren(traverse);
1005     for (const auto c : GetMembers()) {
1006       traverse(*c);
1007     }
1008   }
1009 
1010   // Modifiers
1011   void AddMethod(std::unique_ptr<AidlMethod> method) {
1012     members_.push_back(method.get());
1013     methods_.push_back(std::move(method));
1014   }
1015   void AddType(std::unique_ptr<AidlDefinedType> type) {
1016     type->SetEnclosingScope(this);
1017     members_.push_back(type.get());
1018     types_.push_back(std::move(type));
1019   }
1020 
1021  protected:
1022   // utility for subclasses with getter names
1023   bool CheckValidForGetterNames() const;
1024 
1025  private:
1026   bool CheckValidWithMembers(const AidlTypenames& typenames) const;
1027 
1028   std::string name_;
1029   std::string package_;
1030   std::vector<std::unique_ptr<AidlVariableDeclaration>> variables_;
1031   std::vector<std::unique_ptr<AidlConstantDeclaration>> constants_;
1032   std::vector<std::unique_ptr<AidlMethod>> methods_;
1033   std::vector<std::unique_ptr<AidlDefinedType>> types_;
1034   std::vector<const AidlMember*> members_;  // keep members in order of appearance.
1035 };
1036 
1037 class AidlParcelable : public AidlDefinedType, public AidlParameterizable<std::string> {
1038  public:
1039   AidlParcelable(const AidlLocation& location, const std::string& name, const std::string& package,
1040                  const Comments& comments, const std::string& cpp_header = "",
1041                  std::vector<std::string>* type_params = nullptr,
1042                  std::vector<std::unique_ptr<AidlMember>>* members = nullptr);
1043   virtual ~AidlParcelable() = default;
1044 
1045   // non-copyable, non-movable
1046   AidlParcelable(const AidlParcelable&) = delete;
1047   AidlParcelable(AidlParcelable&&) = delete;
1048   AidlParcelable& operator=(const AidlParcelable&) = delete;
1049   AidlParcelable& operator=(AidlParcelable&&) = delete;
1050 
1051   std::string GetCppHeader() const { return cpp_header_; }
1052 
1053   bool CheckValid(const AidlTypenames& typenames) const override;
1054   const AidlParcelable* AsParcelable() const override { return this; }
1055   const AidlParameterizable<std::string>* AsParameterizable() const override { return this; }
1056   const AidlNode& AsAidlNode() const override { return *this; }
1057   std::string GetPreprocessDeclarationName() const override { return "parcelable"; }
1058 
1059   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
1060 
1061  private:
1062   std::string cpp_header_;
1063 };
1064 
1065 class AidlStructuredParcelable : public AidlParcelable {
1066  public:
1067   AidlStructuredParcelable(const AidlLocation& location, const std::string& name,
1068                            const std::string& package, const Comments& comments,
1069                            std::vector<std::string>* type_params,
1070                            std::vector<std::unique_ptr<AidlMember>>* members);
1071   virtual ~AidlStructuredParcelable() = default;
1072 
1073   // non-copyable, non-movable
1074   AidlStructuredParcelable(const AidlStructuredParcelable&) = delete;
1075   AidlStructuredParcelable(AidlStructuredParcelable&&) = delete;
1076   AidlStructuredParcelable& operator=(const AidlStructuredParcelable&) = delete;
1077   AidlStructuredParcelable& operator=(AidlStructuredParcelable&&) = delete;
1078 
1079   const AidlStructuredParcelable* AsStructuredParcelable() const override { return this; }
1080   std::string GetPreprocessDeclarationName() const override { return "structured_parcelable"; }
1081 
1082   bool CheckValid(const AidlTypenames& typenames) const override;
1083   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
1084 };
1085 
1086 class AidlEnumerator : public AidlCommentable {
1087  public:
1088   AidlEnumerator(const AidlLocation& location, const std::string& name, AidlConstantValue* value,
1089                  const Comments& comments);
1090   virtual ~AidlEnumerator() = default;
1091 
1092   // non-copyable, non-movable
1093   AidlEnumerator(const AidlEnumerator&) = delete;
1094   AidlEnumerator(AidlEnumerator&&) = delete;
1095   AidlEnumerator& operator=(const AidlEnumerator&) = delete;
1096   AidlEnumerator& operator=(AidlEnumerator&&) = delete;
1097 
1098   const std::string& GetName() const { return name_; }
1099   AidlConstantValue* GetValue() const { return value_.get(); }
1100   bool CheckValid(const AidlTypeSpecifier& enum_backing_type) const;
1101 
1102   string ValueString(const AidlTypeSpecifier& backing_type,
1103                      const ConstantValueDecorator& decorator) const;
1104 
1105   void SetValue(std::unique_ptr<AidlConstantValue> value) { value_ = std::move(value); }
1106   bool IsValueUserSpecified() const { return value_user_specified_; }
1107 
1108   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override {
1109     traverse(*value_);
1110   }
1111   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
1112 
1113  private:
1114   const std::string name_;
1115   unique_ptr<AidlConstantValue> value_;
1116   const bool value_user_specified_;
1117 };
1118 
1119 class AidlEnumDeclaration : public AidlDefinedType {
1120  public:
1121   AidlEnumDeclaration(const AidlLocation& location, const string& name,
1122                       std::vector<std::unique_ptr<AidlEnumerator>>* enumerators,
1123                       const std::string& package, const Comments& comments);
1124   virtual ~AidlEnumDeclaration() = default;
1125 
1126   // non-copyable, non-movable
1127   AidlEnumDeclaration(const AidlEnumDeclaration&) = delete;
1128   AidlEnumDeclaration(AidlEnumDeclaration&&) = delete;
1129   AidlEnumDeclaration& operator=(const AidlEnumDeclaration&) = delete;
1130   AidlEnumDeclaration& operator=(AidlEnumDeclaration&&) = delete;
1131 
1132   bool Autofill(const AidlTypenames&);
1133   const AidlTypeSpecifier& GetBackingType() const { return *backing_type_; }
1134   const std::vector<std::unique_ptr<AidlEnumerator>>& GetEnumerators() const {
1135     return enumerators_;
1136   }
1137   bool CheckValid(const AidlTypenames& typenames) const override;
1138   std::string GetPreprocessDeclarationName() const override { return "enum"; }
1139 
1140   const AidlEnumDeclaration* AsEnumDeclaration() const override { return this; }
1141 
1142   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override {
1143     AidlDefinedType::TraverseChildren(traverse);
1144     if (backing_type_) {
1145       traverse(*backing_type_);
1146     }
1147     for (const auto& c : GetEnumerators()) {
1148       traverse(*c);
1149     }
1150   }
1151   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
1152 
1153  private:
1154 
1155   const std::string name_;
1156   const std::vector<std::unique_ptr<AidlEnumerator>> enumerators_;
1157   std::unique_ptr<AidlTypeSpecifier> backing_type_;
1158 };
1159 
1160 class AidlUnionDecl : public AidlParcelable {
1161  public:
1162   AidlUnionDecl(const AidlLocation& location, const std::string& name, const std::string& package,
1163                 const Comments& comments, std::vector<std::string>* type_params,
1164                 std::vector<std::unique_ptr<AidlMember>>* members);
1165   virtual ~AidlUnionDecl() = default;
1166 
1167   // non-copyable, non-movable
1168   AidlUnionDecl(const AidlUnionDecl&) = delete;
1169   AidlUnionDecl(AidlUnionDecl&&) = delete;
1170   AidlUnionDecl& operator=(const AidlUnionDecl&) = delete;
1171   AidlUnionDecl& operator=(AidlUnionDecl&&) = delete;
1172 
1173 
1174   const AidlNode& AsAidlNode() const override { return *this; }
1175   bool CheckValid(const AidlTypenames& typenames) const override;
1176   std::string GetPreprocessDeclarationName() const override { return "union"; }
1177 
1178   const AidlUnionDecl* AsUnionDeclaration() const override { return this; }
1179   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
1180 };
1181 
1182 class AidlInterface final : public AidlDefinedType {
1183  public:
1184   AidlInterface(const AidlLocation& location, const std::string& name, const Comments& comments,
1185                 bool oneway, const std::string& package,
1186                 std::vector<std::unique_ptr<AidlMember>>* members);
1187   virtual ~AidlInterface() = default;
1188 
1189   // non-copyable, non-movable
1190   AidlInterface(const AidlInterface&) = delete;
1191   AidlInterface(AidlInterface&&) = delete;
1192   AidlInterface& operator=(const AidlInterface&) = delete;
1193   AidlInterface& operator=(AidlInterface&&) = delete;
1194 
1195   const AidlInterface* AsInterface() const override { return this; }
1196   std::string GetPreprocessDeclarationName() const override { return "interface"; }
1197 
1198   bool CheckValid(const AidlTypenames& typenames) const override;
1199   bool CheckValidPermissionAnnotations(const AidlMethod& m) const;
1200   std::string GetDescriptor() const;
1201   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
1202 };
1203 
1204 inline std::string SimpleName(const std::string& qualified_name) {
1205   return qualified_name.substr(qualified_name.rfind('.') + 1);
1206 }
1207 
1208 // AidlDocument models an AIDL file
1209 class AidlDocument : public AidlCommentable, public AidlScope {
1210  public:
1211   AidlDocument(const AidlLocation& location, const Comments& comments,
1212                std::vector<std::string> imports,
1213                std::vector<std::unique_ptr<AidlDefinedType>> defined_types, bool is_preprocessed);
1214   ~AidlDocument() = default;
1215 
1216   // non-copyable, non-movable
1217   AidlDocument(const AidlDocument&) = delete;
1218   AidlDocument(AidlDocument&&) = delete;
1219   AidlDocument& operator=(const AidlDocument&) = delete;
1220   AidlDocument& operator=(AidlDocument&&) = delete;
1221 
1222   std::string ResolveName(const std::string& name) const override;
1223   const std::vector<std::string>& Imports() const { return imports_; }
1224   const std::vector<std::unique_ptr<AidlDefinedType>>& DefinedTypes() const {
1225     return defined_types_;
1226   }
1227   bool IsPreprocessed() const { return is_preprocessed_; }
1228 
1229   void TraverseChildren(std::function<void(const AidlNode&)> traverse) const override {
1230     for (const auto& t : DefinedTypes()) {
1231       traverse(*t);
1232     }
1233   }
1234   void DispatchVisit(AidlVisitor& v) const override { v.Visit(*this); }
1235 
1236  private:
1237   const std::vector<std::string> imports_;
1238   const std::vector<std::unique_ptr<AidlDefinedType>> defined_types_;
1239   bool is_preprocessed_;
1240 };
1241 
1242 template <typename T>
1243 std::optional<T> AidlAnnotation::ParamValue(const std::string& param_name) const {
1244   auto it = parameters_.find(param_name);
1245   if (it == parameters_.end()) {
1246     return std::nullopt;
1247   }
1248   return it->second->EvaluatedValue<T>();
1249 }
1250 
1251 // Utilities to make a visitor to visit AST tree in top-down order
1252 // Given:       foo
1253 //              / \
1254 //            bar baz
1255 // VisitTopDown(v, foo) makes v visit foo -> bar -> baz.
1256 inline void VisitTopDown(std::function<void(const AidlNode&)> v, const AidlNode& node) {
1257   std::function<void(const AidlNode&)> top_down = [&](const AidlNode& n) {
1258     v(n);
1259     n.TraverseChildren(top_down);
1260   };
1261   top_down(node);
1262 }
1263 inline void VisitTopDown(AidlVisitor& v, const AidlNode& node) {
1264   VisitTopDown([&](const AidlNode& n) { n.DispatchVisit(v); }, node);
1265 }
1266 
1267 // Utility to make a visitor to visit AST tree in bottom-up order
1268 // Given:       foo
1269 //              / \
1270 //            bar baz
1271 // VisitBottomUp(v, foo) makes v visit bar -> baz -> foo.
1272 inline void VisitBottomUp(AidlVisitor& v, const AidlNode& node) {
1273   std::function<void(const AidlNode&)> bottom_up = [&](const AidlNode& n) {
1274     n.TraverseChildren(bottom_up);
1275     n.DispatchVisit(v);
1276   };
1277   bottom_up(node);
1278 }
1279 
1280 template <typename T>
1281 const T* AidlCast(const AidlNode& node) {
1282   struct CastVisitor : AidlVisitor {
1283     const T* cast = nullptr;
1284     void Visit(const T& t) override { cast = &t; }
1285   } visitor;
1286   node.DispatchVisit(visitor);
1287   return visitor.cast;
1288 }
1289 
1290 template <>
1291 const AidlDefinedType* AidlCast<AidlDefinedType>(const AidlNode& node);
1292 
1293 template <typename T>
1294 T* AidlCast(AidlNode& node) {
1295   return const_cast<T*>(AidlCast<T>(const_cast<const AidlNode&>(node)));
1296 }
1297 
1298 template <typename AidlNodeType>
1299 vector<const AidlNodeType*> Collect(const AidlNode& root) {
1300   vector<const AidlNodeType*> result;
1301   std::function<void(const AidlNode&)> top_down = [&](const AidlNode& n) {
1302     if (auto cast = AidlCast<AidlNodeType>(n); cast) {
1303       result.push_back(cast);
1304     }
1305     n.TraverseChildren(top_down);
1306   };
1307   top_down(root);
1308   return result;
1309 }
1310 
1311 template <typename VisitFn>
1312 bool TopologicalVisit(const vector<unique_ptr<AidlDefinedType>>& nested_types, VisitFn visit) {
1313   // 1. Maps deeply nested types to one of nested_types
1314   map<const AidlDefinedType*, const AidlDefinedType*> roots;
1315   for (const auto& nested : nested_types) {
1316     for (const auto& t : Collect<AidlDefinedType>(*nested)) {
1317       roots[t] = nested.get();
1318     }
1319   }
1320   // 2. Collect sibling types referenced within each nested type.
1321   map<const AidlDefinedType*, vector<const AidlDefinedType*>> required_types;
1322   for (const auto& nested : nested_types) {
1323     for (const auto& t : Collect<AidlTypeSpecifier>(*nested)) {
1324       if (auto defined_type = t->GetDefinedType(); defined_type) {
1325         auto sibling = roots[defined_type];
1326         if (sibling && sibling != nested.get()) {
1327           required_types[nested.get()].push_back(sibling);
1328         }
1329       }
1330     }
1331   };
1332   // 3. Run DFS
1333   enum { NOT_STARTED = 0, STARTED = 1, FINISHED = 2 };
1334   map<const AidlDefinedType*, int> visited;
1335   std::function<bool(const AidlDefinedType&)> dfs = [&](const AidlDefinedType& type) {
1336     if (visited[&type] == FINISHED) {
1337       return true;
1338     } else if (visited[&type] == STARTED) {
1339       return false;
1340     } else {
1341       visited[&type] = STARTED;
1342       // Visit every required dep first
1343       for (const auto& dep_type : required_types[&type]) {
1344         if (!dfs(*dep_type)) {
1345           return false;
1346         }
1347       }
1348       visited[&type] = FINISHED;
1349       visit(type);
1350       return true;
1351     }
1352   };
1353 
1354   for (const auto& type : nested_types) {
1355     if (!dfs(*type)) {
1356       return false;
1357     }
1358   }
1359 
1360   return true;
1361 }
1362