1 //===--- ASTDumper.cpp - Dumping implementation for ASTs ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AST dump methods, which dump out the
11 // AST in a form that exposes type details and other fields.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CommentVisitor.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclLookups.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclVisitor.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/AST/TypeVisitor.h"
24 #include "clang/Basic/Module.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
28 using namespace clang::comments;
29 
30 //===----------------------------------------------------------------------===//
31 // ASTDumper Visitor
32 //===----------------------------------------------------------------------===//
33 
34 namespace  {
35   // Colors used for various parts of the AST dump
36   // Do not use bold yellow for any text.  It is hard to read on white screens.
37 
38   struct TerminalColor {
39     raw_ostream::Colors Color;
40     bool Bold;
41   };
42 
43   // Red           - CastColor
44   // Green         - TypeColor
45   // Bold Green    - DeclKindNameColor, UndeserializedColor
46   // Yellow        - AddressColor, LocationColor
47   // Blue          - CommentColor, NullColor, IndentColor
48   // Bold Blue     - AttrColor
49   // Bold Magenta  - StmtColor
50   // Cyan          - ValueKindColor, ObjectKindColor
51   // Bold Cyan     - ValueColor, DeclNameColor
52 
53   // Decl kind names (VarDecl, FunctionDecl, etc)
54   static const TerminalColor DeclKindNameColor = { raw_ostream::GREEN, true };
55   // Attr names (CleanupAttr, GuardedByAttr, etc)
56   static const TerminalColor AttrColor = { raw_ostream::BLUE, true };
57   // Statement names (DeclStmt, ImplicitCastExpr, etc)
58   static const TerminalColor StmtColor = { raw_ostream::MAGENTA, true };
59   // Comment names (FullComment, ParagraphComment, TextComment, etc)
60   static const TerminalColor CommentColor = { raw_ostream::BLUE, false };
61 
62   // Type names (int, float, etc, plus user defined types)
63   static const TerminalColor TypeColor = { raw_ostream::GREEN, false };
64 
65   // Pointer address
66   static const TerminalColor AddressColor = { raw_ostream::YELLOW, false };
67   // Source locations
68   static const TerminalColor LocationColor = { raw_ostream::YELLOW, false };
69 
70   // lvalue/xvalue
71   static const TerminalColor ValueKindColor = { raw_ostream::CYAN, false };
72   // bitfield/objcproperty/objcsubscript/vectorcomponent
73   static const TerminalColor ObjectKindColor = { raw_ostream::CYAN, false };
74 
75   // Null statements
76   static const TerminalColor NullColor = { raw_ostream::BLUE, false };
77 
78   // Undeserialized entities
79   static const TerminalColor UndeserializedColor = { raw_ostream::GREEN, true };
80 
81   // CastKind from CastExpr's
82   static const TerminalColor CastColor = { raw_ostream::RED, false };
83 
84   // Value of the statement
85   static const TerminalColor ValueColor = { raw_ostream::CYAN, true };
86   // Decl names
87   static const TerminalColor DeclNameColor = { raw_ostream::CYAN, true };
88 
89   // Indents ( `, -. | )
90   static const TerminalColor IndentColor = { raw_ostream::BLUE, false };
91 
92   class ASTDumper
93       : public ConstDeclVisitor<ASTDumper>, public ConstStmtVisitor<ASTDumper>,
94         public ConstCommentVisitor<ASTDumper>, public TypeVisitor<ASTDumper> {
95     raw_ostream &OS;
96     const CommandTraits *Traits;
97     const SourceManager *SM;
98 
99     /// Pending[i] is an action to dump an entity at level i.
100     llvm::SmallVector<std::function<void(bool isLastChild)>, 32> Pending;
101 
102     /// Indicates whether we're at the top level.
103     bool TopLevel;
104 
105     /// Indicates if we're handling the first child after entering a new depth.
106     bool FirstChild;
107 
108     /// Prefix for currently-being-dumped entity.
109     std::string Prefix;
110 
111     /// Keep track of the last location we print out so that we can
112     /// print out deltas from then on out.
113     const char *LastLocFilename;
114     unsigned LastLocLine;
115 
116     /// The \c FullComment parent of the comment being dumped.
117     const FullComment *FC;
118 
119     bool ShowColors;
120 
121     /// Dump a child of the current node.
122     template<typename Fn> void dumpChild(Fn doDumpChild) {
123       // If we're at the top level, there's nothing interesting to do; just
124       // run the dumper.
125       if (TopLevel) {
126         TopLevel = false;
127         doDumpChild();
128         while (!Pending.empty()) {
129           Pending.back()(true);
130           Pending.pop_back();
131         }
132         Prefix.clear();
133         OS << "\n";
134         TopLevel = true;
135         return;
136       }
137 
138       const FullComment *OrigFC = FC;
139       auto dumpWithIndent = [this, doDumpChild, OrigFC](bool isLastChild) {
140         // Print out the appropriate tree structure and work out the prefix for
141         // children of this node. For instance:
142         //
143         //   A        Prefix = ""
144         //   |-B      Prefix = "| "
145         //   | `-C    Prefix = "|   "
146         //   `-D      Prefix = "  "
147         //     |-E    Prefix = "  | "
148         //     `-F    Prefix = "    "
149         //   G        Prefix = ""
150         //
151         // Note that the first level gets no prefix.
152         {
153           OS << '\n';
154           ColorScope Color(*this, IndentColor);
155           OS << Prefix << (isLastChild ? '`' : '|') << '-';
156           this->Prefix.push_back(isLastChild ? ' ' : '|');
157           this->Prefix.push_back(' ');
158         }
159 
160         FirstChild = true;
161         unsigned Depth = Pending.size();
162 
163         FC = OrigFC;
164         doDumpChild();
165 
166         // If any children are left, they're the last at their nesting level.
167         // Dump those ones out now.
168         while (Depth < Pending.size()) {
169           Pending.back()(true);
170           this->Pending.pop_back();
171         }
172 
173         // Restore the old prefix.
174         this->Prefix.resize(Prefix.size() - 2);
175       };
176 
177       if (FirstChild) {
178         Pending.push_back(std::move(dumpWithIndent));
179       } else {
180         Pending.back()(false);
181         Pending.back() = std::move(dumpWithIndent);
182       }
183       FirstChild = false;
184     }
185 
186     class ColorScope {
187       ASTDumper &Dumper;
188     public:
189       ColorScope(ASTDumper &Dumper, TerminalColor Color)
190         : Dumper(Dumper) {
191         if (Dumper.ShowColors)
192           Dumper.OS.changeColor(Color.Color, Color.Bold);
193       }
194       ~ColorScope() {
195         if (Dumper.ShowColors)
196           Dumper.OS.resetColor();
197       }
198     };
199 
200   public:
201     ASTDumper(raw_ostream &OS, const CommandTraits *Traits,
202               const SourceManager *SM)
203       : OS(OS), Traits(Traits), SM(SM), TopLevel(true), FirstChild(true),
204         LastLocFilename(""), LastLocLine(~0U), FC(nullptr),
205         ShowColors(SM && SM->getDiagnostics().getShowColors()) { }
206 
207     ASTDumper(raw_ostream &OS, const CommandTraits *Traits,
208               const SourceManager *SM, bool ShowColors)
209       : OS(OS), Traits(Traits), SM(SM), TopLevel(true), FirstChild(true),
210         LastLocFilename(""), LastLocLine(~0U),
211         ShowColors(ShowColors) { }
212 
213     void dumpDecl(const Decl *D);
214     void dumpStmt(const Stmt *S);
215     void dumpFullComment(const FullComment *C);
216 
217     // Utilities
218     void dumpPointer(const void *Ptr);
219     void dumpSourceRange(SourceRange R);
220     void dumpLocation(SourceLocation Loc);
221     void dumpBareType(QualType T, bool Desugar = true);
222     void dumpType(QualType T);
223     void dumpTypeAsChild(QualType T);
224     void dumpTypeAsChild(const Type *T);
225     void dumpBareDeclRef(const Decl *Node);
226     void dumpDeclRef(const Decl *Node, const char *Label = nullptr);
227     void dumpName(const NamedDecl *D);
228     bool hasNodes(const DeclContext *DC);
229     void dumpDeclContext(const DeclContext *DC);
230     void dumpLookups(const DeclContext *DC, bool DumpDecls);
231     void dumpAttr(const Attr *A);
232 
233     // C++ Utilities
234     void dumpAccessSpecifier(AccessSpecifier AS);
235     void dumpCXXCtorInitializer(const CXXCtorInitializer *Init);
236     void dumpTemplateParameters(const TemplateParameterList *TPL);
237     void dumpTemplateArgumentListInfo(const TemplateArgumentListInfo &TALI);
238     void dumpTemplateArgumentLoc(const TemplateArgumentLoc &A);
239     void dumpTemplateArgumentList(const TemplateArgumentList &TAL);
240     void dumpTemplateArgument(const TemplateArgument &A,
241                               SourceRange R = SourceRange());
242 
243     // Types
244     void VisitComplexType(const ComplexType *T) {
245       dumpTypeAsChild(T->getElementType());
246     }
247     void VisitPointerType(const PointerType *T) {
248       dumpTypeAsChild(T->getPointeeType());
249     }
250     void VisitBlockPointerType(const BlockPointerType *T) {
251       dumpTypeAsChild(T->getPointeeType());
252     }
253     void VisitReferenceType(const ReferenceType *T) {
254       dumpTypeAsChild(T->getPointeeType());
255     }
256     void VisitRValueReferenceType(const ReferenceType *T) {
257       if (T->isSpelledAsLValue())
258         OS << " written as lvalue reference";
259       VisitReferenceType(T);
260     }
261     void VisitMemberPointerType(const MemberPointerType *T) {
262       dumpTypeAsChild(T->getClass());
263       dumpTypeAsChild(T->getPointeeType());
264     }
265     void VisitArrayType(const ArrayType *T) {
266       switch (T->getSizeModifier()) {
267         case ArrayType::Normal: break;
268         case ArrayType::Static: OS << " static"; break;
269         case ArrayType::Star: OS << " *"; break;
270       }
271       OS << " " << T->getIndexTypeQualifiers().getAsString();
272       dumpTypeAsChild(T->getElementType());
273     }
274     void VisitConstantArrayType(const ConstantArrayType *T) {
275       OS << " " << T->getSize();
276       VisitArrayType(T);
277     }
278     void VisitVariableArrayType(const VariableArrayType *T) {
279       OS << " ";
280       dumpSourceRange(T->getBracketsRange());
281       VisitArrayType(T);
282       dumpStmt(T->getSizeExpr());
283     }
284     void VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
285       VisitArrayType(T);
286       OS << " ";
287       dumpSourceRange(T->getBracketsRange());
288       dumpStmt(T->getSizeExpr());
289     }
290     void VisitDependentSizedExtVectorType(
291         const DependentSizedExtVectorType *T) {
292       OS << " ";
293       dumpLocation(T->getAttributeLoc());
294       dumpTypeAsChild(T->getElementType());
295       dumpStmt(T->getSizeExpr());
296     }
297     void VisitVectorType(const VectorType *T) {
298       switch (T->getVectorKind()) {
299         case VectorType::GenericVector: break;
300         case VectorType::AltiVecVector: OS << " altivec"; break;
301         case VectorType::AltiVecPixel: OS << " altivec pixel"; break;
302         case VectorType::AltiVecBool: OS << " altivec bool"; break;
303         case VectorType::NeonVector: OS << " neon"; break;
304         case VectorType::NeonPolyVector: OS << " neon poly"; break;
305       }
306       OS << " " << T->getNumElements();
307       dumpTypeAsChild(T->getElementType());
308     }
309     void VisitFunctionType(const FunctionType *T) {
310       auto EI = T->getExtInfo();
311       if (EI.getNoReturn()) OS << " noreturn";
312       if (EI.getProducesResult()) OS << " produces_result";
313       if (EI.getHasRegParm()) OS << " regparm " << EI.getRegParm();
314       OS << " " << FunctionType::getNameForCallConv(EI.getCC());
315       dumpTypeAsChild(T->getReturnType());
316     }
317     void VisitFunctionProtoType(const FunctionProtoType *T) {
318       auto EPI = T->getExtProtoInfo();
319       if (EPI.HasTrailingReturn) OS << " trailing_return";
320       if (T->isConst()) OS << " const";
321       if (T->isVolatile()) OS << " volatile";
322       if (T->isRestrict()) OS << " restrict";
323       switch (EPI.RefQualifier) {
324         case RQ_None: break;
325         case RQ_LValue: OS << " &"; break;
326         case RQ_RValue: OS << " &&"; break;
327       }
328       // FIXME: Exception specification.
329       // FIXME: Consumed parameters.
330       VisitFunctionType(T);
331       for (QualType PT : T->getParamTypes())
332         dumpTypeAsChild(PT);
333       if (EPI.Variadic)
334         dumpChild([=] { OS << "..."; });
335     }
336     void VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
337       dumpDeclRef(T->getDecl());
338     }
339     void VisitTypedefType(const TypedefType *T) {
340       dumpDeclRef(T->getDecl());
341     }
342     void VisitTypeOfExprType(const TypeOfExprType *T) {
343       dumpStmt(T->getUnderlyingExpr());
344     }
345     void VisitDecltypeType(const DecltypeType *T) {
346       dumpStmt(T->getUnderlyingExpr());
347     }
348     void VisitUnaryTransformType(const UnaryTransformType *T) {
349       switch (T->getUTTKind()) {
350       case UnaryTransformType::EnumUnderlyingType:
351         OS << " underlying_type";
352         break;
353       }
354       dumpTypeAsChild(T->getBaseType());
355     }
356     void VisitTagType(const TagType *T) {
357       dumpDeclRef(T->getDecl());
358     }
359     void VisitAttributedType(const AttributedType *T) {
360       // FIXME: AttrKind
361       dumpTypeAsChild(T->getModifiedType());
362     }
363     void VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
364       OS << " depth " << T->getDepth() << " index " << T->getIndex();
365       if (T->isParameterPack()) OS << " pack";
366       dumpDeclRef(T->getDecl());
367     }
368     void VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
369       dumpTypeAsChild(T->getReplacedParameter());
370     }
371     void VisitSubstTemplateTypeParmPackType(
372         const SubstTemplateTypeParmPackType *T) {
373       dumpTypeAsChild(T->getReplacedParameter());
374       dumpTemplateArgument(T->getArgumentPack());
375     }
376     void VisitAutoType(const AutoType *T) {
377       if (T->isDecltypeAuto()) OS << " decltype(auto)";
378       if (!T->isDeduced())
379         OS << " undeduced";
380     }
381     void VisitTemplateSpecializationType(const TemplateSpecializationType *T) {
382       if (T->isTypeAlias()) OS << " alias";
383       OS << " "; T->getTemplateName().dump(OS);
384       for (auto &Arg : *T)
385         dumpTemplateArgument(Arg);
386       if (T->isTypeAlias())
387         dumpTypeAsChild(T->getAliasedType());
388     }
389     void VisitInjectedClassNameType(const InjectedClassNameType *T) {
390       dumpDeclRef(T->getDecl());
391     }
392     void VisitObjCInterfaceType(const ObjCInterfaceType *T) {
393       dumpDeclRef(T->getDecl());
394     }
395     void VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
396       dumpTypeAsChild(T->getPointeeType());
397     }
398     void VisitAtomicType(const AtomicType *T) {
399       dumpTypeAsChild(T->getValueType());
400     }
401     void VisitAdjustedType(const AdjustedType *T) {
402       dumpTypeAsChild(T->getOriginalType());
403     }
404     void VisitPackExpansionType(const PackExpansionType *T) {
405       if (auto N = T->getNumExpansions()) OS << " expansions " << *N;
406       if (!T->isSugared())
407         dumpTypeAsChild(T->getPattern());
408     }
409     // FIXME: ElaboratedType, DependentNameType,
410     // DependentTemplateSpecializationType, ObjCObjectType
411 
412     // Decls
413     void VisitLabelDecl(const LabelDecl *D);
414     void VisitTypedefDecl(const TypedefDecl *D);
415     void VisitEnumDecl(const EnumDecl *D);
416     void VisitRecordDecl(const RecordDecl *D);
417     void VisitEnumConstantDecl(const EnumConstantDecl *D);
418     void VisitIndirectFieldDecl(const IndirectFieldDecl *D);
419     void VisitFunctionDecl(const FunctionDecl *D);
420     void VisitFieldDecl(const FieldDecl *D);
421     void VisitVarDecl(const VarDecl *D);
422     void VisitFileScopeAsmDecl(const FileScopeAsmDecl *D);
423     void VisitImportDecl(const ImportDecl *D);
424 
425     // C++ Decls
426     void VisitNamespaceDecl(const NamespaceDecl *D);
427     void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D);
428     void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D);
429     void VisitTypeAliasDecl(const TypeAliasDecl *D);
430     void VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl *D);
431     void VisitCXXRecordDecl(const CXXRecordDecl *D);
432     void VisitStaticAssertDecl(const StaticAssertDecl *D);
433     template<typename SpecializationDecl>
434     void VisitTemplateDeclSpecialization(const SpecializationDecl *D,
435                                          bool DumpExplicitInst,
436                                          bool DumpRefOnly);
437     template<typename TemplateDecl>
438     void VisitTemplateDecl(const TemplateDecl *D, bool DumpExplicitInst);
439     void VisitFunctionTemplateDecl(const FunctionTemplateDecl *D);
440     void VisitClassTemplateDecl(const ClassTemplateDecl *D);
441     void VisitClassTemplateSpecializationDecl(
442         const ClassTemplateSpecializationDecl *D);
443     void VisitClassTemplatePartialSpecializationDecl(
444         const ClassTemplatePartialSpecializationDecl *D);
445     void VisitClassScopeFunctionSpecializationDecl(
446         const ClassScopeFunctionSpecializationDecl *D);
447     void VisitVarTemplateDecl(const VarTemplateDecl *D);
448     void VisitVarTemplateSpecializationDecl(
449         const VarTemplateSpecializationDecl *D);
450     void VisitVarTemplatePartialSpecializationDecl(
451         const VarTemplatePartialSpecializationDecl *D);
452     void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
453     void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
454     void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
455     void VisitUsingDecl(const UsingDecl *D);
456     void VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D);
457     void VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D);
458     void VisitUsingShadowDecl(const UsingShadowDecl *D);
459     void VisitLinkageSpecDecl(const LinkageSpecDecl *D);
460     void VisitAccessSpecDecl(const AccessSpecDecl *D);
461     void VisitFriendDecl(const FriendDecl *D);
462 
463     // ObjC Decls
464     void VisitObjCIvarDecl(const ObjCIvarDecl *D);
465     void VisitObjCMethodDecl(const ObjCMethodDecl *D);
466     void VisitObjCCategoryDecl(const ObjCCategoryDecl *D);
467     void VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D);
468     void VisitObjCProtocolDecl(const ObjCProtocolDecl *D);
469     void VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D);
470     void VisitObjCImplementationDecl(const ObjCImplementationDecl *D);
471     void VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *D);
472     void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
473     void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
474     void VisitBlockDecl(const BlockDecl *D);
475 
476     // Stmts.
477     void VisitStmt(const Stmt *Node);
478     void VisitDeclStmt(const DeclStmt *Node);
479     void VisitAttributedStmt(const AttributedStmt *Node);
480     void VisitLabelStmt(const LabelStmt *Node);
481     void VisitGotoStmt(const GotoStmt *Node);
482     void VisitCXXCatchStmt(const CXXCatchStmt *Node);
483 
484     // Exprs
485     void VisitExpr(const Expr *Node);
486     void VisitCastExpr(const CastExpr *Node);
487     void VisitDeclRefExpr(const DeclRefExpr *Node);
488     void VisitPredefinedExpr(const PredefinedExpr *Node);
489     void VisitCharacterLiteral(const CharacterLiteral *Node);
490     void VisitIntegerLiteral(const IntegerLiteral *Node);
491     void VisitFloatingLiteral(const FloatingLiteral *Node);
492     void VisitStringLiteral(const StringLiteral *Str);
493     void VisitInitListExpr(const InitListExpr *ILE);
494     void VisitUnaryOperator(const UnaryOperator *Node);
495     void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Node);
496     void VisitMemberExpr(const MemberExpr *Node);
497     void VisitExtVectorElementExpr(const ExtVectorElementExpr *Node);
498     void VisitBinaryOperator(const BinaryOperator *Node);
499     void VisitCompoundAssignOperator(const CompoundAssignOperator *Node);
500     void VisitAddrLabelExpr(const AddrLabelExpr *Node);
501     void VisitBlockExpr(const BlockExpr *Node);
502     void VisitOpaqueValueExpr(const OpaqueValueExpr *Node);
503 
504     // C++
505     void VisitCXXNamedCastExpr(const CXXNamedCastExpr *Node);
506     void VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *Node);
507     void VisitCXXThisExpr(const CXXThisExpr *Node);
508     void VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *Node);
509     void VisitCXXConstructExpr(const CXXConstructExpr *Node);
510     void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Node);
511     void VisitCXXNewExpr(const CXXNewExpr *Node);
512     void VisitCXXDeleteExpr(const CXXDeleteExpr *Node);
513     void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Node);
514     void VisitExprWithCleanups(const ExprWithCleanups *Node);
515     void VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *Node);
516     void dumpCXXTemporary(const CXXTemporary *Temporary);
517     void VisitLambdaExpr(const LambdaExpr *Node) {
518       VisitExpr(Node);
519       dumpDecl(Node->getLambdaClass());
520     }
521     void VisitSizeOfPackExpr(const SizeOfPackExpr *Node);
522 
523     // ObjC
524     void VisitObjCAtCatchStmt(const ObjCAtCatchStmt *Node);
525     void VisitObjCEncodeExpr(const ObjCEncodeExpr *Node);
526     void VisitObjCMessageExpr(const ObjCMessageExpr *Node);
527     void VisitObjCBoxedExpr(const ObjCBoxedExpr *Node);
528     void VisitObjCSelectorExpr(const ObjCSelectorExpr *Node);
529     void VisitObjCProtocolExpr(const ObjCProtocolExpr *Node);
530     void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Node);
531     void VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *Node);
532     void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *Node);
533     void VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *Node);
534 
535     // Comments.
536     const char *getCommandName(unsigned CommandID);
537     void dumpComment(const Comment *C);
538 
539     // Inline comments.
540     void visitTextComment(const TextComment *C);
541     void visitInlineCommandComment(const InlineCommandComment *C);
542     void visitHTMLStartTagComment(const HTMLStartTagComment *C);
543     void visitHTMLEndTagComment(const HTMLEndTagComment *C);
544 
545     // Block comments.
546     void visitBlockCommandComment(const BlockCommandComment *C);
547     void visitParamCommandComment(const ParamCommandComment *C);
548     void visitTParamCommandComment(const TParamCommandComment *C);
549     void visitVerbatimBlockComment(const VerbatimBlockComment *C);
550     void visitVerbatimBlockLineComment(const VerbatimBlockLineComment *C);
551     void visitVerbatimLineComment(const VerbatimLineComment *C);
552   };
553 }
554 
555 //===----------------------------------------------------------------------===//
556 //  Utilities
557 //===----------------------------------------------------------------------===//
558 
559 void ASTDumper::dumpPointer(const void *Ptr) {
560   ColorScope Color(*this, AddressColor);
561   OS << ' ' << Ptr;
562 }
563 
564 void ASTDumper::dumpLocation(SourceLocation Loc) {
565   if (!SM)
566     return;
567 
568   ColorScope Color(*this, LocationColor);
569   SourceLocation SpellingLoc = SM->getSpellingLoc(Loc);
570 
571   // The general format we print out is filename:line:col, but we drop pieces
572   // that haven't changed since the last loc printed.
573   PresumedLoc PLoc = SM->getPresumedLoc(SpellingLoc);
574 
575   if (PLoc.isInvalid()) {
576     OS << "<invalid sloc>";
577     return;
578   }
579 
580   if (strcmp(PLoc.getFilename(), LastLocFilename) != 0) {
581     OS << PLoc.getFilename() << ':' << PLoc.getLine()
582        << ':' << PLoc.getColumn();
583     LastLocFilename = PLoc.getFilename();
584     LastLocLine = PLoc.getLine();
585   } else if (PLoc.getLine() != LastLocLine) {
586     OS << "line" << ':' << PLoc.getLine()
587        << ':' << PLoc.getColumn();
588     LastLocLine = PLoc.getLine();
589   } else {
590     OS << "col" << ':' << PLoc.getColumn();
591   }
592 }
593 
594 void ASTDumper::dumpSourceRange(SourceRange R) {
595   // Can't translate locations if a SourceManager isn't available.
596   if (!SM)
597     return;
598 
599   OS << " <";
600   dumpLocation(R.getBegin());
601   if (R.getBegin() != R.getEnd()) {
602     OS << ", ";
603     dumpLocation(R.getEnd());
604   }
605   OS << ">";
606 
607   // <t2.c:123:421[blah], t2.c:412:321>
608 
609 }
610 
611 void ASTDumper::dumpBareType(QualType T, bool Desugar) {
612   ColorScope Color(*this, TypeColor);
613 
614   SplitQualType T_split = T.split();
615   OS << "'" << QualType::getAsString(T_split) << "'";
616 
617   if (Desugar && !T.isNull()) {
618     // If the type is sugared, also dump a (shallow) desugared type.
619     SplitQualType D_split = T.getSplitDesugaredType();
620     if (T_split != D_split)
621       OS << ":'" << QualType::getAsString(D_split) << "'";
622   }
623 }
624 
625 void ASTDumper::dumpType(QualType T) {
626   OS << ' ';
627   dumpBareType(T);
628 }
629 
630 void ASTDumper::dumpTypeAsChild(QualType T) {
631   SplitQualType SQT = T.split();
632   if (!SQT.Quals.hasQualifiers())
633     return dumpTypeAsChild(SQT.Ty);
634 
635   dumpChild([=] {
636     OS << "QualType";
637     dumpPointer(T.getAsOpaquePtr());
638     OS << " ";
639     dumpBareType(T, false);
640     OS << " " << T.split().Quals.getAsString();
641     dumpTypeAsChild(T.split().Ty);
642   });
643 }
644 
645 void ASTDumper::dumpTypeAsChild(const Type *T) {
646   dumpChild([=] {
647     if (!T) {
648       ColorScope Color(*this, NullColor);
649       OS << "<<<NULL>>>";
650       return;
651     }
652 
653     {
654       ColorScope Color(*this, TypeColor);
655       OS << T->getTypeClassName() << "Type";
656     }
657     dumpPointer(T);
658     OS << " ";
659     dumpBareType(QualType(T, 0), false);
660 
661     QualType SingleStepDesugar =
662         T->getLocallyUnqualifiedSingleStepDesugaredType();
663     if (SingleStepDesugar != QualType(T, 0))
664       OS << " sugar";
665     if (T->isDependentType())
666       OS << " dependent";
667     else if (T->isInstantiationDependentType())
668       OS << " instantiation_dependent";
669     if (T->isVariablyModifiedType())
670       OS << " variably_modified";
671     if (T->containsUnexpandedParameterPack())
672       OS << " contains_unexpanded_pack";
673     if (T->isFromAST())
674       OS << " imported";
675 
676     TypeVisitor<ASTDumper>::Visit(T);
677 
678     if (SingleStepDesugar != QualType(T, 0))
679       dumpTypeAsChild(SingleStepDesugar);
680   });
681 }
682 
683 void ASTDumper::dumpBareDeclRef(const Decl *D) {
684   {
685     ColorScope Color(*this, DeclKindNameColor);
686     OS << D->getDeclKindName();
687   }
688   dumpPointer(D);
689 
690   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
691     ColorScope Color(*this, DeclNameColor);
692     OS << " '" << ND->getDeclName() << '\'';
693   }
694 
695   if (const ValueDecl *VD = dyn_cast<ValueDecl>(D))
696     dumpType(VD->getType());
697 }
698 
699 void ASTDumper::dumpDeclRef(const Decl *D, const char *Label) {
700   if (!D)
701     return;
702 
703   dumpChild([=]{
704     if (Label)
705       OS << Label << ' ';
706     dumpBareDeclRef(D);
707   });
708 }
709 
710 void ASTDumper::dumpName(const NamedDecl *ND) {
711   if (ND->getDeclName()) {
712     ColorScope Color(*this, DeclNameColor);
713     OS << ' ' << ND->getNameAsString();
714   }
715 }
716 
717 bool ASTDumper::hasNodes(const DeclContext *DC) {
718   if (!DC)
719     return false;
720 
721   return DC->hasExternalLexicalStorage() ||
722          DC->noload_decls_begin() != DC->noload_decls_end();
723 }
724 
725 void ASTDumper::dumpDeclContext(const DeclContext *DC) {
726   if (!DC)
727     return;
728 
729   for (auto *D : DC->noload_decls())
730     dumpDecl(D);
731 
732   if (DC->hasExternalLexicalStorage()) {
733     dumpChild([=]{
734       ColorScope Color(*this, UndeserializedColor);
735       OS << "<undeserialized declarations>";
736     });
737   }
738 }
739 
740 void ASTDumper::dumpLookups(const DeclContext *DC, bool DumpDecls) {
741   dumpChild([=] {
742     OS << "StoredDeclsMap ";
743     dumpBareDeclRef(cast<Decl>(DC));
744 
745     const DeclContext *Primary = DC->getPrimaryContext();
746     if (Primary != DC) {
747       OS << " primary";
748       dumpPointer(cast<Decl>(Primary));
749     }
750 
751     bool HasUndeserializedLookups = Primary->hasExternalVisibleStorage();
752 
753     DeclContext::all_lookups_iterator I = Primary->noload_lookups_begin(),
754                                       E = Primary->noload_lookups_end();
755     while (I != E) {
756       DeclarationName Name = I.getLookupName();
757       DeclContextLookupResult R = *I++;
758 
759       dumpChild([=] {
760         OS << "DeclarationName ";
761         {
762           ColorScope Color(*this, DeclNameColor);
763           OS << '\'' << Name << '\'';
764         }
765 
766         for (DeclContextLookupResult::iterator RI = R.begin(), RE = R.end();
767              RI != RE; ++RI) {
768           dumpChild([=] {
769             dumpBareDeclRef(*RI);
770 
771             if ((*RI)->isHidden())
772               OS << " hidden";
773 
774             // If requested, dump the redecl chain for this lookup.
775             if (DumpDecls) {
776               // Dump earliest decl first.
777               std::function<void(Decl *)> DumpWithPrev = [&](Decl *D) {
778                 if (Decl *Prev = D->getPreviousDecl())
779                   DumpWithPrev(Prev);
780                 dumpDecl(D);
781               };
782               DumpWithPrev(*RI);
783             }
784           });
785         }
786       });
787     }
788 
789     if (HasUndeserializedLookups) {
790       dumpChild([=] {
791         ColorScope Color(*this, UndeserializedColor);
792         OS << "<undeserialized lookups>";
793       });
794     }
795   });
796 }
797 
798 void ASTDumper::dumpAttr(const Attr *A) {
799   dumpChild([=] {
800     {
801       ColorScope Color(*this, AttrColor);
802 
803       switch (A->getKind()) {
804 #define ATTR(X) case attr::X: OS << #X; break;
805 #include "clang/Basic/AttrList.inc"
806       default:
807         llvm_unreachable("unexpected attribute kind");
808       }
809       OS << "Attr";
810     }
811     dumpPointer(A);
812     dumpSourceRange(A->getRange());
813     if (A->isInherited())
814       OS << " Inherited";
815     if (A->isImplicit())
816       OS << " Implicit";
817 #include "clang/AST/AttrDump.inc"
818   });
819 }
820 
821 static void dumpPreviousDeclImpl(raw_ostream &OS, ...) {}
822 
823 template<typename T>
824 static void dumpPreviousDeclImpl(raw_ostream &OS, const Mergeable<T> *D) {
825   const T *First = D->getFirstDecl();
826   if (First != D)
827     OS << " first " << First;
828 }
829 
830 template<typename T>
831 static void dumpPreviousDeclImpl(raw_ostream &OS, const Redeclarable<T> *D) {
832   const T *Prev = D->getPreviousDecl();
833   if (Prev)
834     OS << " prev " << Prev;
835 }
836 
837 /// Dump the previous declaration in the redeclaration chain for a declaration,
838 /// if any.
839 static void dumpPreviousDecl(raw_ostream &OS, const Decl *D) {
840   switch (D->getKind()) {
841 #define DECL(DERIVED, BASE) \
842   case Decl::DERIVED: \
843     return dumpPreviousDeclImpl(OS, cast<DERIVED##Decl>(D));
844 #define ABSTRACT_DECL(DECL)
845 #include "clang/AST/DeclNodes.inc"
846   }
847   llvm_unreachable("Decl that isn't part of DeclNodes.inc!");
848 }
849 
850 //===----------------------------------------------------------------------===//
851 //  C++ Utilities
852 //===----------------------------------------------------------------------===//
853 
854 void ASTDumper::dumpAccessSpecifier(AccessSpecifier AS) {
855   switch (AS) {
856   case AS_none:
857     break;
858   case AS_public:
859     OS << "public";
860     break;
861   case AS_protected:
862     OS << "protected";
863     break;
864   case AS_private:
865     OS << "private";
866     break;
867   }
868 }
869 
870 void ASTDumper::dumpCXXCtorInitializer(const CXXCtorInitializer *Init) {
871   dumpChild([=] {
872     OS << "CXXCtorInitializer";
873     if (Init->isAnyMemberInitializer()) {
874       OS << ' ';
875       dumpBareDeclRef(Init->getAnyMember());
876     } else if (Init->isBaseInitializer()) {
877       dumpType(QualType(Init->getBaseClass(), 0));
878     } else if (Init->isDelegatingInitializer()) {
879       dumpType(Init->getTypeSourceInfo()->getType());
880     } else {
881       llvm_unreachable("Unknown initializer type");
882     }
883     dumpStmt(Init->getInit());
884   });
885 }
886 
887 void ASTDumper::dumpTemplateParameters(const TemplateParameterList *TPL) {
888   if (!TPL)
889     return;
890 
891   for (TemplateParameterList::const_iterator I = TPL->begin(), E = TPL->end();
892        I != E; ++I)
893     dumpDecl(*I);
894 }
895 
896 void ASTDumper::dumpTemplateArgumentListInfo(
897     const TemplateArgumentListInfo &TALI) {
898   for (unsigned i = 0, e = TALI.size(); i < e; ++i)
899     dumpTemplateArgumentLoc(TALI[i]);
900 }
901 
902 void ASTDumper::dumpTemplateArgumentLoc(const TemplateArgumentLoc &A) {
903   dumpTemplateArgument(A.getArgument(), A.getSourceRange());
904 }
905 
906 void ASTDumper::dumpTemplateArgumentList(const TemplateArgumentList &TAL) {
907   for (unsigned i = 0, e = TAL.size(); i < e; ++i)
908     dumpTemplateArgument(TAL[i]);
909 }
910 
911 void ASTDumper::dumpTemplateArgument(const TemplateArgument &A, SourceRange R) {
912   dumpChild([=] {
913     OS << "TemplateArgument";
914     if (R.isValid())
915       dumpSourceRange(R);
916 
917     switch (A.getKind()) {
918     case TemplateArgument::Null:
919       OS << " null";
920       break;
921     case TemplateArgument::Type:
922       OS << " type";
923       dumpType(A.getAsType());
924       break;
925     case TemplateArgument::Declaration:
926       OS << " decl";
927       dumpDeclRef(A.getAsDecl());
928       break;
929     case TemplateArgument::NullPtr:
930       OS << " nullptr";
931       break;
932     case TemplateArgument::Integral:
933       OS << " integral " << A.getAsIntegral();
934       break;
935     case TemplateArgument::Template:
936       OS << " template ";
937       A.getAsTemplate().dump(OS);
938       break;
939     case TemplateArgument::TemplateExpansion:
940       OS << " template expansion";
941       A.getAsTemplateOrTemplatePattern().dump(OS);
942       break;
943     case TemplateArgument::Expression:
944       OS << " expr";
945       dumpStmt(A.getAsExpr());
946       break;
947     case TemplateArgument::Pack:
948       OS << " pack";
949       for (TemplateArgument::pack_iterator I = A.pack_begin(), E = A.pack_end();
950            I != E; ++I)
951         dumpTemplateArgument(*I);
952       break;
953     }
954   });
955 }
956 
957 //===----------------------------------------------------------------------===//
958 //  Decl dumping methods.
959 //===----------------------------------------------------------------------===//
960 
961 void ASTDumper::dumpDecl(const Decl *D) {
962   dumpChild([=] {
963     if (!D) {
964       ColorScope Color(*this, NullColor);
965       OS << "<<<NULL>>>";
966       return;
967     }
968 
969     {
970       ColorScope Color(*this, DeclKindNameColor);
971       OS << D->getDeclKindName() << "Decl";
972     }
973     dumpPointer(D);
974     if (D->getLexicalDeclContext() != D->getDeclContext())
975       OS << " parent " << cast<Decl>(D->getDeclContext());
976     dumpPreviousDecl(OS, D);
977     dumpSourceRange(D->getSourceRange());
978     OS << ' ';
979     dumpLocation(D->getLocation());
980     if (Module *M = D->getOwningModule())
981       OS << " in " << M->getFullModuleName();
982     if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
983       if (ND->isHidden())
984         OS << " hidden";
985     if (D->isImplicit())
986       OS << " implicit";
987     if (D->isUsed())
988       OS << " used";
989     else if (D->isThisDeclarationReferenced())
990       OS << " referenced";
991     if (D->isInvalidDecl())
992       OS << " invalid";
993     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
994       if (FD->isConstexpr())
995         OS << " constexpr";
996 
997 
998     ConstDeclVisitor<ASTDumper>::Visit(D);
999 
1000     for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); I != E;
1001          ++I)
1002       dumpAttr(*I);
1003 
1004     if (const FullComment *Comment =
1005             D->getASTContext().getLocalCommentForDeclUncached(D))
1006       dumpFullComment(Comment);
1007 
1008     // Decls within functions are visited by the body.
1009     if (!isa<FunctionDecl>(*D) && !isa<ObjCMethodDecl>(*D) &&
1010         hasNodes(dyn_cast<DeclContext>(D)))
1011       dumpDeclContext(cast<DeclContext>(D));
1012   });
1013 }
1014 
1015 void ASTDumper::VisitLabelDecl(const LabelDecl *D) {
1016   dumpName(D);
1017 }
1018 
1019 void ASTDumper::VisitTypedefDecl(const TypedefDecl *D) {
1020   dumpName(D);
1021   dumpType(D->getUnderlyingType());
1022   if (D->isModulePrivate())
1023     OS << " __module_private__";
1024 }
1025 
1026 void ASTDumper::VisitEnumDecl(const EnumDecl *D) {
1027   if (D->isScoped()) {
1028     if (D->isScopedUsingClassTag())
1029       OS << " class";
1030     else
1031       OS << " struct";
1032   }
1033   dumpName(D);
1034   if (D->isModulePrivate())
1035     OS << " __module_private__";
1036   if (D->isFixed())
1037     dumpType(D->getIntegerType());
1038 }
1039 
1040 void ASTDumper::VisitRecordDecl(const RecordDecl *D) {
1041   OS << ' ' << D->getKindName();
1042   dumpName(D);
1043   if (D->isModulePrivate())
1044     OS << " __module_private__";
1045   if (D->isCompleteDefinition())
1046     OS << " definition";
1047 }
1048 
1049 void ASTDumper::VisitEnumConstantDecl(const EnumConstantDecl *D) {
1050   dumpName(D);
1051   dumpType(D->getType());
1052   if (const Expr *Init = D->getInitExpr())
1053     dumpStmt(Init);
1054 }
1055 
1056 void ASTDumper::VisitIndirectFieldDecl(const IndirectFieldDecl *D) {
1057   dumpName(D);
1058   dumpType(D->getType());
1059 
1060   for (auto *Child : D->chain())
1061     dumpDeclRef(Child);
1062 }
1063 
1064 void ASTDumper::VisitFunctionDecl(const FunctionDecl *D) {
1065   dumpName(D);
1066   dumpType(D->getType());
1067 
1068   StorageClass SC = D->getStorageClass();
1069   if (SC != SC_None)
1070     OS << ' ' << VarDecl::getStorageClassSpecifierString(SC);
1071   if (D->isInlineSpecified())
1072     OS << " inline";
1073   if (D->isVirtualAsWritten())
1074     OS << " virtual";
1075   if (D->isModulePrivate())
1076     OS << " __module_private__";
1077 
1078   if (D->isPure())
1079     OS << " pure";
1080   else if (D->isDeletedAsWritten())
1081     OS << " delete";
1082 
1083   if (const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>()) {
1084     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1085     switch (EPI.ExceptionSpec.Type) {
1086     default: break;
1087     case EST_Unevaluated:
1088       OS << " noexcept-unevaluated " << EPI.ExceptionSpec.SourceDecl;
1089       break;
1090     case EST_Uninstantiated:
1091       OS << " noexcept-uninstantiated " << EPI.ExceptionSpec.SourceTemplate;
1092       break;
1093     }
1094   }
1095 
1096   if (const FunctionTemplateSpecializationInfo *FTSI =
1097           D->getTemplateSpecializationInfo())
1098     dumpTemplateArgumentList(*FTSI->TemplateArguments);
1099 
1100   for (ArrayRef<NamedDecl *>::iterator
1101        I = D->getDeclsInPrototypeScope().begin(),
1102        E = D->getDeclsInPrototypeScope().end(); I != E; ++I)
1103     dumpDecl(*I);
1104 
1105   if (!D->param_begin() && D->getNumParams())
1106     dumpChild([=] { OS << "<<NULL params x " << D->getNumParams() << ">>"; });
1107   else
1108     for (FunctionDecl::param_const_iterator I = D->param_begin(),
1109                                             E = D->param_end();
1110          I != E; ++I)
1111       dumpDecl(*I);
1112 
1113   if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(D))
1114     for (CXXConstructorDecl::init_const_iterator I = C->init_begin(),
1115                                                  E = C->init_end();
1116          I != E; ++I)
1117       dumpCXXCtorInitializer(*I);
1118 
1119   if (D->doesThisDeclarationHaveABody())
1120     dumpStmt(D->getBody());
1121 }
1122 
1123 void ASTDumper::VisitFieldDecl(const FieldDecl *D) {
1124   dumpName(D);
1125   dumpType(D->getType());
1126   if (D->isMutable())
1127     OS << " mutable";
1128   if (D->isModulePrivate())
1129     OS << " __module_private__";
1130 
1131   if (D->isBitField())
1132     dumpStmt(D->getBitWidth());
1133   if (Expr *Init = D->getInClassInitializer())
1134     dumpStmt(Init);
1135 }
1136 
1137 void ASTDumper::VisitVarDecl(const VarDecl *D) {
1138   dumpName(D);
1139   dumpType(D->getType());
1140   StorageClass SC = D->getStorageClass();
1141   if (SC != SC_None)
1142     OS << ' ' << VarDecl::getStorageClassSpecifierString(SC);
1143   switch (D->getTLSKind()) {
1144   case VarDecl::TLS_None: break;
1145   case VarDecl::TLS_Static: OS << " tls"; break;
1146   case VarDecl::TLS_Dynamic: OS << " tls_dynamic"; break;
1147   }
1148   if (D->isModulePrivate())
1149     OS << " __module_private__";
1150   if (D->isNRVOVariable())
1151     OS << " nrvo";
1152   if (D->hasInit()) {
1153     switch (D->getInitStyle()) {
1154     case VarDecl::CInit: OS << " cinit"; break;
1155     case VarDecl::CallInit: OS << " callinit"; break;
1156     case VarDecl::ListInit: OS << " listinit"; break;
1157     }
1158     dumpStmt(D->getInit());
1159   }
1160 }
1161 
1162 void ASTDumper::VisitFileScopeAsmDecl(const FileScopeAsmDecl *D) {
1163   dumpStmt(D->getAsmString());
1164 }
1165 
1166 void ASTDumper::VisitImportDecl(const ImportDecl *D) {
1167   OS << ' ' << D->getImportedModule()->getFullModuleName();
1168 }
1169 
1170 //===----------------------------------------------------------------------===//
1171 // C++ Declarations
1172 //===----------------------------------------------------------------------===//
1173 
1174 void ASTDumper::VisitNamespaceDecl(const NamespaceDecl *D) {
1175   dumpName(D);
1176   if (D->isInline())
1177     OS << " inline";
1178   if (!D->isOriginalNamespace())
1179     dumpDeclRef(D->getOriginalNamespace(), "original");
1180 }
1181 
1182 void ASTDumper::VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
1183   OS << ' ';
1184   dumpBareDeclRef(D->getNominatedNamespace());
1185 }
1186 
1187 void ASTDumper::VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
1188   dumpName(D);
1189   dumpDeclRef(D->getAliasedNamespace());
1190 }
1191 
1192 void ASTDumper::VisitTypeAliasDecl(const TypeAliasDecl *D) {
1193   dumpName(D);
1194   dumpType(D->getUnderlyingType());
1195 }
1196 
1197 void ASTDumper::VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl *D) {
1198   dumpName(D);
1199   dumpTemplateParameters(D->getTemplateParameters());
1200   dumpDecl(D->getTemplatedDecl());
1201 }
1202 
1203 void ASTDumper::VisitCXXRecordDecl(const CXXRecordDecl *D) {
1204   VisitRecordDecl(D);
1205   if (!D->isCompleteDefinition())
1206     return;
1207 
1208   for (const auto &I : D->bases()) {
1209     dumpChild([=] {
1210       if (I.isVirtual())
1211         OS << "virtual ";
1212       dumpAccessSpecifier(I.getAccessSpecifier());
1213       dumpType(I.getType());
1214       if (I.isPackExpansion())
1215         OS << "...";
1216     });
1217   }
1218 }
1219 
1220 void ASTDumper::VisitStaticAssertDecl(const StaticAssertDecl *D) {
1221   dumpStmt(D->getAssertExpr());
1222   dumpStmt(D->getMessage());
1223 }
1224 
1225 template<typename SpecializationDecl>
1226 void ASTDumper::VisitTemplateDeclSpecialization(const SpecializationDecl *D,
1227                                                 bool DumpExplicitInst,
1228                                                 bool DumpRefOnly) {
1229   bool DumpedAny = false;
1230   for (auto *RedeclWithBadType : D->redecls()) {
1231     // FIXME: The redecls() range sometimes has elements of a less-specific
1232     // type. (In particular, ClassTemplateSpecializationDecl::redecls() gives
1233     // us TagDecls, and should give CXXRecordDecls).
1234     auto *Redecl = dyn_cast<SpecializationDecl>(RedeclWithBadType);
1235     if (!Redecl) {
1236       // Found the injected-class-name for a class template. This will be dumped
1237       // as part of its surrounding class so we don't need to dump it here.
1238       assert(isa<CXXRecordDecl>(RedeclWithBadType) &&
1239              "expected an injected-class-name");
1240       continue;
1241     }
1242 
1243     switch (Redecl->getTemplateSpecializationKind()) {
1244     case TSK_ExplicitInstantiationDeclaration:
1245     case TSK_ExplicitInstantiationDefinition:
1246       if (!DumpExplicitInst)
1247         break;
1248       // Fall through.
1249     case TSK_Undeclared:
1250     case TSK_ImplicitInstantiation:
1251       if (DumpRefOnly)
1252         dumpDeclRef(Redecl);
1253       else
1254         dumpDecl(Redecl);
1255       DumpedAny = true;
1256       break;
1257     case TSK_ExplicitSpecialization:
1258       break;
1259     }
1260   }
1261 
1262   // Ensure we dump at least one decl for each specialization.
1263   if (!DumpedAny)
1264     dumpDeclRef(D);
1265 }
1266 
1267 template<typename TemplateDecl>
1268 void ASTDumper::VisitTemplateDecl(const TemplateDecl *D,
1269                                   bool DumpExplicitInst) {
1270   dumpName(D);
1271   dumpTemplateParameters(D->getTemplateParameters());
1272 
1273   dumpDecl(D->getTemplatedDecl());
1274 
1275   for (auto *Child : D->specializations())
1276     VisitTemplateDeclSpecialization(Child, DumpExplicitInst,
1277                                     !D->isCanonicalDecl());
1278 }
1279 
1280 void ASTDumper::VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {
1281   // FIXME: We don't add a declaration of a function template specialization
1282   // to its context when it's explicitly instantiated, so dump explicit
1283   // instantiations when we dump the template itself.
1284   VisitTemplateDecl(D, true);
1285 }
1286 
1287 void ASTDumper::VisitClassTemplateDecl(const ClassTemplateDecl *D) {
1288   VisitTemplateDecl(D, false);
1289 }
1290 
1291 void ASTDumper::VisitClassTemplateSpecializationDecl(
1292     const ClassTemplateSpecializationDecl *D) {
1293   VisitCXXRecordDecl(D);
1294   dumpTemplateArgumentList(D->getTemplateArgs());
1295 }
1296 
1297 void ASTDumper::VisitClassTemplatePartialSpecializationDecl(
1298     const ClassTemplatePartialSpecializationDecl *D) {
1299   VisitClassTemplateSpecializationDecl(D);
1300   dumpTemplateParameters(D->getTemplateParameters());
1301 }
1302 
1303 void ASTDumper::VisitClassScopeFunctionSpecializationDecl(
1304     const ClassScopeFunctionSpecializationDecl *D) {
1305   dumpDeclRef(D->getSpecialization());
1306   if (D->hasExplicitTemplateArgs())
1307     dumpTemplateArgumentListInfo(D->templateArgs());
1308 }
1309 
1310 void ASTDumper::VisitVarTemplateDecl(const VarTemplateDecl *D) {
1311   VisitTemplateDecl(D, false);
1312 }
1313 
1314 void ASTDumper::VisitVarTemplateSpecializationDecl(
1315     const VarTemplateSpecializationDecl *D) {
1316   dumpTemplateArgumentList(D->getTemplateArgs());
1317   VisitVarDecl(D);
1318 }
1319 
1320 void ASTDumper::VisitVarTemplatePartialSpecializationDecl(
1321     const VarTemplatePartialSpecializationDecl *D) {
1322   dumpTemplateParameters(D->getTemplateParameters());
1323   VisitVarTemplateSpecializationDecl(D);
1324 }
1325 
1326 void ASTDumper::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
1327   if (D->wasDeclaredWithTypename())
1328     OS << " typename";
1329   else
1330     OS << " class";
1331   if (D->isParameterPack())
1332     OS << " ...";
1333   dumpName(D);
1334   if (D->hasDefaultArgument())
1335     dumpTemplateArgument(D->getDefaultArgument());
1336 }
1337 
1338 void ASTDumper::VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1339   dumpType(D->getType());
1340   if (D->isParameterPack())
1341     OS << " ...";
1342   dumpName(D);
1343   if (D->hasDefaultArgument())
1344     dumpTemplateArgument(D->getDefaultArgument());
1345 }
1346 
1347 void ASTDumper::VisitTemplateTemplateParmDecl(
1348     const TemplateTemplateParmDecl *D) {
1349   if (D->isParameterPack())
1350     OS << " ...";
1351   dumpName(D);
1352   dumpTemplateParameters(D->getTemplateParameters());
1353   if (D->hasDefaultArgument())
1354     dumpTemplateArgumentLoc(D->getDefaultArgument());
1355 }
1356 
1357 void ASTDumper::VisitUsingDecl(const UsingDecl *D) {
1358   OS << ' ';
1359   D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
1360   OS << D->getNameAsString();
1361 }
1362 
1363 void ASTDumper::VisitUnresolvedUsingTypenameDecl(
1364     const UnresolvedUsingTypenameDecl *D) {
1365   OS << ' ';
1366   D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
1367   OS << D->getNameAsString();
1368 }
1369 
1370 void ASTDumper::VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D) {
1371   OS << ' ';
1372   D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
1373   OS << D->getNameAsString();
1374   dumpType(D->getType());
1375 }
1376 
1377 void ASTDumper::VisitUsingShadowDecl(const UsingShadowDecl *D) {
1378   OS << ' ';
1379   dumpBareDeclRef(D->getTargetDecl());
1380 }
1381 
1382 void ASTDumper::VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
1383   switch (D->getLanguage()) {
1384   case LinkageSpecDecl::lang_c: OS << " C"; break;
1385   case LinkageSpecDecl::lang_cxx: OS << " C++"; break;
1386   }
1387 }
1388 
1389 void ASTDumper::VisitAccessSpecDecl(const AccessSpecDecl *D) {
1390   OS << ' ';
1391   dumpAccessSpecifier(D->getAccess());
1392 }
1393 
1394 void ASTDumper::VisitFriendDecl(const FriendDecl *D) {
1395   if (TypeSourceInfo *T = D->getFriendType())
1396     dumpType(T->getType());
1397   else
1398     dumpDecl(D->getFriendDecl());
1399 }
1400 
1401 //===----------------------------------------------------------------------===//
1402 // Obj-C Declarations
1403 //===----------------------------------------------------------------------===//
1404 
1405 void ASTDumper::VisitObjCIvarDecl(const ObjCIvarDecl *D) {
1406   dumpName(D);
1407   dumpType(D->getType());
1408   if (D->getSynthesize())
1409     OS << " synthesize";
1410 
1411   switch (D->getAccessControl()) {
1412   case ObjCIvarDecl::None:
1413     OS << " none";
1414     break;
1415   case ObjCIvarDecl::Private:
1416     OS << " private";
1417     break;
1418   case ObjCIvarDecl::Protected:
1419     OS << " protected";
1420     break;
1421   case ObjCIvarDecl::Public:
1422     OS << " public";
1423     break;
1424   case ObjCIvarDecl::Package:
1425     OS << " package";
1426     break;
1427   }
1428 }
1429 
1430 void ASTDumper::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
1431   if (D->isInstanceMethod())
1432     OS << " -";
1433   else
1434     OS << " +";
1435   dumpName(D);
1436   dumpType(D->getReturnType());
1437 
1438   if (D->isThisDeclarationADefinition()) {
1439     dumpDeclContext(D);
1440   } else {
1441     for (ObjCMethodDecl::param_const_iterator I = D->param_begin(),
1442                                               E = D->param_end();
1443          I != E; ++I)
1444       dumpDecl(*I);
1445   }
1446 
1447   if (D->isVariadic())
1448     dumpChild([=] { OS << "..."; });
1449 
1450   if (D->hasBody())
1451     dumpStmt(D->getBody());
1452 }
1453 
1454 void ASTDumper::VisitObjCCategoryDecl(const ObjCCategoryDecl *D) {
1455   dumpName(D);
1456   dumpDeclRef(D->getClassInterface());
1457   dumpDeclRef(D->getImplementation());
1458   for (ObjCCategoryDecl::protocol_iterator I = D->protocol_begin(),
1459                                            E = D->protocol_end();
1460        I != E; ++I)
1461     dumpDeclRef(*I);
1462 }
1463 
1464 void ASTDumper::VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D) {
1465   dumpName(D);
1466   dumpDeclRef(D->getClassInterface());
1467   dumpDeclRef(D->getCategoryDecl());
1468 }
1469 
1470 void ASTDumper::VisitObjCProtocolDecl(const ObjCProtocolDecl *D) {
1471   dumpName(D);
1472 
1473   for (auto *Child : D->protocols())
1474     dumpDeclRef(Child);
1475 }
1476 
1477 void ASTDumper::VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D) {
1478   dumpName(D);
1479   dumpDeclRef(D->getSuperClass(), "super");
1480 
1481   dumpDeclRef(D->getImplementation());
1482   for (auto *Child : D->protocols())
1483     dumpDeclRef(Child);
1484 }
1485 
1486 void ASTDumper::VisitObjCImplementationDecl(const ObjCImplementationDecl *D) {
1487   dumpName(D);
1488   dumpDeclRef(D->getSuperClass(), "super");
1489   dumpDeclRef(D->getClassInterface());
1490   for (ObjCImplementationDecl::init_const_iterator I = D->init_begin(),
1491                                                    E = D->init_end();
1492        I != E; ++I)
1493     dumpCXXCtorInitializer(*I);
1494 }
1495 
1496 void ASTDumper::VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *D) {
1497   dumpName(D);
1498   dumpDeclRef(D->getClassInterface());
1499 }
1500 
1501 void ASTDumper::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
1502   dumpName(D);
1503   dumpType(D->getType());
1504 
1505   if (D->getPropertyImplementation() == ObjCPropertyDecl::Required)
1506     OS << " required";
1507   else if (D->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1508     OS << " optional";
1509 
1510   ObjCPropertyDecl::PropertyAttributeKind Attrs = D->getPropertyAttributes();
1511   if (Attrs != ObjCPropertyDecl::OBJC_PR_noattr) {
1512     if (Attrs & ObjCPropertyDecl::OBJC_PR_readonly)
1513       OS << " readonly";
1514     if (Attrs & ObjCPropertyDecl::OBJC_PR_assign)
1515       OS << " assign";
1516     if (Attrs & ObjCPropertyDecl::OBJC_PR_readwrite)
1517       OS << " readwrite";
1518     if (Attrs & ObjCPropertyDecl::OBJC_PR_retain)
1519       OS << " retain";
1520     if (Attrs & ObjCPropertyDecl::OBJC_PR_copy)
1521       OS << " copy";
1522     if (Attrs & ObjCPropertyDecl::OBJC_PR_nonatomic)
1523       OS << " nonatomic";
1524     if (Attrs & ObjCPropertyDecl::OBJC_PR_atomic)
1525       OS << " atomic";
1526     if (Attrs & ObjCPropertyDecl::OBJC_PR_weak)
1527       OS << " weak";
1528     if (Attrs & ObjCPropertyDecl::OBJC_PR_strong)
1529       OS << " strong";
1530     if (Attrs & ObjCPropertyDecl::OBJC_PR_unsafe_unretained)
1531       OS << " unsafe_unretained";
1532     if (Attrs & ObjCPropertyDecl::OBJC_PR_getter)
1533       dumpDeclRef(D->getGetterMethodDecl(), "getter");
1534     if (Attrs & ObjCPropertyDecl::OBJC_PR_setter)
1535       dumpDeclRef(D->getSetterMethodDecl(), "setter");
1536   }
1537 }
1538 
1539 void ASTDumper::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
1540   dumpName(D->getPropertyDecl());
1541   if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1542     OS << " synthesize";
1543   else
1544     OS << " dynamic";
1545   dumpDeclRef(D->getPropertyDecl());
1546   dumpDeclRef(D->getPropertyIvarDecl());
1547 }
1548 
1549 void ASTDumper::VisitBlockDecl(const BlockDecl *D) {
1550   for (auto I : D->params())
1551     dumpDecl(I);
1552 
1553   if (D->isVariadic())
1554     dumpChild([=]{ OS << "..."; });
1555 
1556   if (D->capturesCXXThis())
1557     dumpChild([=]{ OS << "capture this"; });
1558 
1559   for (const auto &I : D->captures()) {
1560     dumpChild([=] {
1561       OS << "capture";
1562       if (I.isByRef())
1563         OS << " byref";
1564       if (I.isNested())
1565         OS << " nested";
1566       if (I.getVariable()) {
1567         OS << ' ';
1568         dumpBareDeclRef(I.getVariable());
1569       }
1570       if (I.hasCopyExpr())
1571         dumpStmt(I.getCopyExpr());
1572     });
1573   }
1574   dumpStmt(D->getBody());
1575 }
1576 
1577 //===----------------------------------------------------------------------===//
1578 //  Stmt dumping methods.
1579 //===----------------------------------------------------------------------===//
1580 
1581 void ASTDumper::dumpStmt(const Stmt *S) {
1582   dumpChild([=] {
1583     if (!S) {
1584       ColorScope Color(*this, NullColor);
1585       OS << "<<<NULL>>>";
1586       return;
1587     }
1588 
1589     if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
1590       VisitDeclStmt(DS);
1591       return;
1592     }
1593 
1594     ConstStmtVisitor<ASTDumper>::Visit(S);
1595 
1596     for (Stmt::const_child_range CI = S->children(); CI; ++CI)
1597       dumpStmt(*CI);
1598   });
1599 }
1600 
1601 void ASTDumper::VisitStmt(const Stmt *Node) {
1602   {
1603     ColorScope Color(*this, StmtColor);
1604     OS << Node->getStmtClassName();
1605   }
1606   dumpPointer(Node);
1607   dumpSourceRange(Node->getSourceRange());
1608 }
1609 
1610 void ASTDumper::VisitDeclStmt(const DeclStmt *Node) {
1611   VisitStmt(Node);
1612   for (DeclStmt::const_decl_iterator I = Node->decl_begin(),
1613                                      E = Node->decl_end();
1614        I != E; ++I)
1615     dumpDecl(*I);
1616 }
1617 
1618 void ASTDumper::VisitAttributedStmt(const AttributedStmt *Node) {
1619   VisitStmt(Node);
1620   for (ArrayRef<const Attr *>::iterator I = Node->getAttrs().begin(),
1621                                         E = Node->getAttrs().end();
1622        I != E; ++I)
1623     dumpAttr(*I);
1624 }
1625 
1626 void ASTDumper::VisitLabelStmt(const LabelStmt *Node) {
1627   VisitStmt(Node);
1628   OS << " '" << Node->getName() << "'";
1629 }
1630 
1631 void ASTDumper::VisitGotoStmt(const GotoStmt *Node) {
1632   VisitStmt(Node);
1633   OS << " '" << Node->getLabel()->getName() << "'";
1634   dumpPointer(Node->getLabel());
1635 }
1636 
1637 void ASTDumper::VisitCXXCatchStmt(const CXXCatchStmt *Node) {
1638   VisitStmt(Node);
1639   dumpDecl(Node->getExceptionDecl());
1640 }
1641 
1642 //===----------------------------------------------------------------------===//
1643 //  Expr dumping methods.
1644 //===----------------------------------------------------------------------===//
1645 
1646 void ASTDumper::VisitExpr(const Expr *Node) {
1647   VisitStmt(Node);
1648   dumpType(Node->getType());
1649 
1650   {
1651     ColorScope Color(*this, ValueKindColor);
1652     switch (Node->getValueKind()) {
1653     case VK_RValue:
1654       break;
1655     case VK_LValue:
1656       OS << " lvalue";
1657       break;
1658     case VK_XValue:
1659       OS << " xvalue";
1660       break;
1661     }
1662   }
1663 
1664   {
1665     ColorScope Color(*this, ObjectKindColor);
1666     switch (Node->getObjectKind()) {
1667     case OK_Ordinary:
1668       break;
1669     case OK_BitField:
1670       OS << " bitfield";
1671       break;
1672     case OK_ObjCProperty:
1673       OS << " objcproperty";
1674       break;
1675     case OK_ObjCSubscript:
1676       OS << " objcsubscript";
1677       break;
1678     case OK_VectorComponent:
1679       OS << " vectorcomponent";
1680       break;
1681     }
1682   }
1683 }
1684 
1685 static void dumpBasePath(raw_ostream &OS, const CastExpr *Node) {
1686   if (Node->path_empty())
1687     return;
1688 
1689   OS << " (";
1690   bool First = true;
1691   for (CastExpr::path_const_iterator I = Node->path_begin(),
1692                                      E = Node->path_end();
1693        I != E; ++I) {
1694     const CXXBaseSpecifier *Base = *I;
1695     if (!First)
1696       OS << " -> ";
1697 
1698     const CXXRecordDecl *RD =
1699     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1700 
1701     if (Base->isVirtual())
1702       OS << "virtual ";
1703     OS << RD->getName();
1704     First = false;
1705   }
1706 
1707   OS << ')';
1708 }
1709 
1710 void ASTDumper::VisitCastExpr(const CastExpr *Node) {
1711   VisitExpr(Node);
1712   OS << " <";
1713   {
1714     ColorScope Color(*this, CastColor);
1715     OS << Node->getCastKindName();
1716   }
1717   dumpBasePath(OS, Node);
1718   OS << ">";
1719 }
1720 
1721 void ASTDumper::VisitDeclRefExpr(const DeclRefExpr *Node) {
1722   VisitExpr(Node);
1723 
1724   OS << " ";
1725   dumpBareDeclRef(Node->getDecl());
1726   if (Node->getDecl() != Node->getFoundDecl()) {
1727     OS << " (";
1728     dumpBareDeclRef(Node->getFoundDecl());
1729     OS << ")";
1730   }
1731 }
1732 
1733 void ASTDumper::VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *Node) {
1734   VisitExpr(Node);
1735   OS << " (";
1736   if (!Node->requiresADL())
1737     OS << "no ";
1738   OS << "ADL) = '" << Node->getName() << '\'';
1739 
1740   UnresolvedLookupExpr::decls_iterator
1741     I = Node->decls_begin(), E = Node->decls_end();
1742   if (I == E)
1743     OS << " empty";
1744   for (; I != E; ++I)
1745     dumpPointer(*I);
1746 }
1747 
1748 void ASTDumper::VisitObjCIvarRefExpr(const ObjCIvarRefExpr *Node) {
1749   VisitExpr(Node);
1750 
1751   {
1752     ColorScope Color(*this, DeclKindNameColor);
1753     OS << " " << Node->getDecl()->getDeclKindName() << "Decl";
1754   }
1755   OS << "='" << *Node->getDecl() << "'";
1756   dumpPointer(Node->getDecl());
1757   if (Node->isFreeIvar())
1758     OS << " isFreeIvar";
1759 }
1760 
1761 void ASTDumper::VisitPredefinedExpr(const PredefinedExpr *Node) {
1762   VisitExpr(Node);
1763   OS << " " << PredefinedExpr::getIdentTypeName(Node->getIdentType());
1764 }
1765 
1766 void ASTDumper::VisitCharacterLiteral(const CharacterLiteral *Node) {
1767   VisitExpr(Node);
1768   ColorScope Color(*this, ValueColor);
1769   OS << " " << Node->getValue();
1770 }
1771 
1772 void ASTDumper::VisitIntegerLiteral(const IntegerLiteral *Node) {
1773   VisitExpr(Node);
1774 
1775   bool isSigned = Node->getType()->isSignedIntegerType();
1776   ColorScope Color(*this, ValueColor);
1777   OS << " " << Node->getValue().toString(10, isSigned);
1778 }
1779 
1780 void ASTDumper::VisitFloatingLiteral(const FloatingLiteral *Node) {
1781   VisitExpr(Node);
1782   ColorScope Color(*this, ValueColor);
1783   OS << " " << Node->getValueAsApproximateDouble();
1784 }
1785 
1786 void ASTDumper::VisitStringLiteral(const StringLiteral *Str) {
1787   VisitExpr(Str);
1788   ColorScope Color(*this, ValueColor);
1789   OS << " ";
1790   Str->outputString(OS);
1791 }
1792 
1793 void ASTDumper::VisitInitListExpr(const InitListExpr *ILE) {
1794   VisitExpr(ILE);
1795   if (auto *Filler = ILE->getArrayFiller()) {
1796     dumpChild([=] {
1797       OS << "array filler";
1798       dumpStmt(Filler);
1799     });
1800   }
1801   if (auto *Field = ILE->getInitializedFieldInUnion()) {
1802     OS << " field ";
1803     dumpBareDeclRef(Field);
1804   }
1805 }
1806 
1807 void ASTDumper::VisitUnaryOperator(const UnaryOperator *Node) {
1808   VisitExpr(Node);
1809   OS << " " << (Node->isPostfix() ? "postfix" : "prefix")
1810      << " '" << UnaryOperator::getOpcodeStr(Node->getOpcode()) << "'";
1811 }
1812 
1813 void ASTDumper::VisitUnaryExprOrTypeTraitExpr(
1814     const UnaryExprOrTypeTraitExpr *Node) {
1815   VisitExpr(Node);
1816   switch(Node->getKind()) {
1817   case UETT_SizeOf:
1818     OS << " sizeof";
1819     break;
1820   case UETT_AlignOf:
1821     OS << " alignof";
1822     break;
1823   case UETT_VecStep:
1824     OS << " vec_step";
1825     break;
1826   }
1827   if (Node->isArgumentType())
1828     dumpType(Node->getArgumentType());
1829 }
1830 
1831 void ASTDumper::VisitMemberExpr(const MemberExpr *Node) {
1832   VisitExpr(Node);
1833   OS << " " << (Node->isArrow() ? "->" : ".") << *Node->getMemberDecl();
1834   dumpPointer(Node->getMemberDecl());
1835 }
1836 
1837 void ASTDumper::VisitExtVectorElementExpr(const ExtVectorElementExpr *Node) {
1838   VisitExpr(Node);
1839   OS << " " << Node->getAccessor().getNameStart();
1840 }
1841 
1842 void ASTDumper::VisitBinaryOperator(const BinaryOperator *Node) {
1843   VisitExpr(Node);
1844   OS << " '" << BinaryOperator::getOpcodeStr(Node->getOpcode()) << "'";
1845 }
1846 
1847 void ASTDumper::VisitCompoundAssignOperator(
1848     const CompoundAssignOperator *Node) {
1849   VisitExpr(Node);
1850   OS << " '" << BinaryOperator::getOpcodeStr(Node->getOpcode())
1851      << "' ComputeLHSTy=";
1852   dumpBareType(Node->getComputationLHSType());
1853   OS << " ComputeResultTy=";
1854   dumpBareType(Node->getComputationResultType());
1855 }
1856 
1857 void ASTDumper::VisitBlockExpr(const BlockExpr *Node) {
1858   VisitExpr(Node);
1859   dumpDecl(Node->getBlockDecl());
1860 }
1861 
1862 void ASTDumper::VisitOpaqueValueExpr(const OpaqueValueExpr *Node) {
1863   VisitExpr(Node);
1864 
1865   if (Expr *Source = Node->getSourceExpr())
1866     dumpStmt(Source);
1867 }
1868 
1869 // GNU extensions.
1870 
1871 void ASTDumper::VisitAddrLabelExpr(const AddrLabelExpr *Node) {
1872   VisitExpr(Node);
1873   OS << " " << Node->getLabel()->getName();
1874   dumpPointer(Node->getLabel());
1875 }
1876 
1877 //===----------------------------------------------------------------------===//
1878 // C++ Expressions
1879 //===----------------------------------------------------------------------===//
1880 
1881 void ASTDumper::VisitCXXNamedCastExpr(const CXXNamedCastExpr *Node) {
1882   VisitExpr(Node);
1883   OS << " " << Node->getCastName()
1884      << "<" << Node->getTypeAsWritten().getAsString() << ">"
1885      << " <" << Node->getCastKindName();
1886   dumpBasePath(OS, Node);
1887   OS << ">";
1888 }
1889 
1890 void ASTDumper::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *Node) {
1891   VisitExpr(Node);
1892   OS << " " << (Node->getValue() ? "true" : "false");
1893 }
1894 
1895 void ASTDumper::VisitCXXThisExpr(const CXXThisExpr *Node) {
1896   VisitExpr(Node);
1897   OS << " this";
1898 }
1899 
1900 void ASTDumper::VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *Node) {
1901   VisitExpr(Node);
1902   OS << " functional cast to " << Node->getTypeAsWritten().getAsString()
1903      << " <" << Node->getCastKindName() << ">";
1904 }
1905 
1906 void ASTDumper::VisitCXXConstructExpr(const CXXConstructExpr *Node) {
1907   VisitExpr(Node);
1908   CXXConstructorDecl *Ctor = Node->getConstructor();
1909   dumpType(Ctor->getType());
1910   if (Node->isElidable())
1911     OS << " elidable";
1912   if (Node->requiresZeroInitialization())
1913     OS << " zeroing";
1914 }
1915 
1916 void ASTDumper::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Node) {
1917   VisitExpr(Node);
1918   OS << " ";
1919   dumpCXXTemporary(Node->getTemporary());
1920 }
1921 
1922 void ASTDumper::VisitCXXNewExpr(const CXXNewExpr *Node) {
1923   VisitExpr(Node);
1924   if (Node->isGlobalNew())
1925     OS << " global";
1926   if (Node->isArray())
1927     OS << " array";
1928   if (Node->getOperatorNew()) {
1929     OS << ' ';
1930     dumpBareDeclRef(Node->getOperatorNew());
1931   }
1932   // We could dump the deallocation function used in case of error, but it's
1933   // usually not that interesting.
1934 }
1935 
1936 void ASTDumper::VisitCXXDeleteExpr(const CXXDeleteExpr *Node) {
1937   VisitExpr(Node);
1938   if (Node->isGlobalDelete())
1939     OS << " global";
1940   if (Node->isArrayForm())
1941     OS << " array";
1942   if (Node->getOperatorDelete()) {
1943     OS << ' ';
1944     dumpBareDeclRef(Node->getOperatorDelete());
1945   }
1946 }
1947 
1948 void
1949 ASTDumper::VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Node) {
1950   VisitExpr(Node);
1951   if (const ValueDecl *VD = Node->getExtendingDecl()) {
1952     OS << " extended by ";
1953     dumpBareDeclRef(VD);
1954   }
1955 }
1956 
1957 void ASTDumper::VisitExprWithCleanups(const ExprWithCleanups *Node) {
1958   VisitExpr(Node);
1959   for (unsigned i = 0, e = Node->getNumObjects(); i != e; ++i)
1960     dumpDeclRef(Node->getObject(i), "cleanup");
1961 }
1962 
1963 void ASTDumper::dumpCXXTemporary(const CXXTemporary *Temporary) {
1964   OS << "(CXXTemporary";
1965   dumpPointer(Temporary);
1966   OS << ")";
1967 }
1968 
1969 void ASTDumper::VisitSizeOfPackExpr(const SizeOfPackExpr *Node) {
1970   VisitExpr(Node);
1971   dumpPointer(Node->getPack());
1972   dumpName(Node->getPack());
1973 }
1974 
1975 
1976 //===----------------------------------------------------------------------===//
1977 // Obj-C Expressions
1978 //===----------------------------------------------------------------------===//
1979 
1980 void ASTDumper::VisitObjCMessageExpr(const ObjCMessageExpr *Node) {
1981   VisitExpr(Node);
1982   OS << " selector=";
1983   Node->getSelector().print(OS);
1984   switch (Node->getReceiverKind()) {
1985   case ObjCMessageExpr::Instance:
1986     break;
1987 
1988   case ObjCMessageExpr::Class:
1989     OS << " class=";
1990     dumpBareType(Node->getClassReceiver());
1991     break;
1992 
1993   case ObjCMessageExpr::SuperInstance:
1994     OS << " super (instance)";
1995     break;
1996 
1997   case ObjCMessageExpr::SuperClass:
1998     OS << " super (class)";
1999     break;
2000   }
2001 }
2002 
2003 void ASTDumper::VisitObjCBoxedExpr(const ObjCBoxedExpr *Node) {
2004   VisitExpr(Node);
2005   OS << " selector=";
2006   Node->getBoxingMethod()->getSelector().print(OS);
2007 }
2008 
2009 void ASTDumper::VisitObjCAtCatchStmt(const ObjCAtCatchStmt *Node) {
2010   VisitStmt(Node);
2011   if (const VarDecl *CatchParam = Node->getCatchParamDecl())
2012     dumpDecl(CatchParam);
2013   else
2014     OS << " catch all";
2015 }
2016 
2017 void ASTDumper::VisitObjCEncodeExpr(const ObjCEncodeExpr *Node) {
2018   VisitExpr(Node);
2019   dumpType(Node->getEncodedType());
2020 }
2021 
2022 void ASTDumper::VisitObjCSelectorExpr(const ObjCSelectorExpr *Node) {
2023   VisitExpr(Node);
2024 
2025   OS << " ";
2026   Node->getSelector().print(OS);
2027 }
2028 
2029 void ASTDumper::VisitObjCProtocolExpr(const ObjCProtocolExpr *Node) {
2030   VisitExpr(Node);
2031 
2032   OS << ' ' << *Node->getProtocol();
2033 }
2034 
2035 void ASTDumper::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Node) {
2036   VisitExpr(Node);
2037   if (Node->isImplicitProperty()) {
2038     OS << " Kind=MethodRef Getter=\"";
2039     if (Node->getImplicitPropertyGetter())
2040       Node->getImplicitPropertyGetter()->getSelector().print(OS);
2041     else
2042       OS << "(null)";
2043 
2044     OS << "\" Setter=\"";
2045     if (ObjCMethodDecl *Setter = Node->getImplicitPropertySetter())
2046       Setter->getSelector().print(OS);
2047     else
2048       OS << "(null)";
2049     OS << "\"";
2050   } else {
2051     OS << " Kind=PropertyRef Property=\"" << *Node->getExplicitProperty() <<'"';
2052   }
2053 
2054   if (Node->isSuperReceiver())
2055     OS << " super";
2056 
2057   OS << " Messaging=";
2058   if (Node->isMessagingGetter() && Node->isMessagingSetter())
2059     OS << "Getter&Setter";
2060   else if (Node->isMessagingGetter())
2061     OS << "Getter";
2062   else if (Node->isMessagingSetter())
2063     OS << "Setter";
2064 }
2065 
2066 void ASTDumper::VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *Node) {
2067   VisitExpr(Node);
2068   if (Node->isArraySubscriptRefExpr())
2069     OS << " Kind=ArraySubscript GetterForArray=\"";
2070   else
2071     OS << " Kind=DictionarySubscript GetterForDictionary=\"";
2072   if (Node->getAtIndexMethodDecl())
2073     Node->getAtIndexMethodDecl()->getSelector().print(OS);
2074   else
2075     OS << "(null)";
2076 
2077   if (Node->isArraySubscriptRefExpr())
2078     OS << "\" SetterForArray=\"";
2079   else
2080     OS << "\" SetterForDictionary=\"";
2081   if (Node->setAtIndexMethodDecl())
2082     Node->setAtIndexMethodDecl()->getSelector().print(OS);
2083   else
2084     OS << "(null)";
2085 }
2086 
2087 void ASTDumper::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *Node) {
2088   VisitExpr(Node);
2089   OS << " " << (Node->getValue() ? "__objc_yes" : "__objc_no");
2090 }
2091 
2092 //===----------------------------------------------------------------------===//
2093 // Comments
2094 //===----------------------------------------------------------------------===//
2095 
2096 const char *ASTDumper::getCommandName(unsigned CommandID) {
2097   if (Traits)
2098     return Traits->getCommandInfo(CommandID)->Name;
2099   const CommandInfo *Info = CommandTraits::getBuiltinCommandInfo(CommandID);
2100   if (Info)
2101     return Info->Name;
2102   return "<not a builtin command>";
2103 }
2104 
2105 void ASTDumper::dumpFullComment(const FullComment *C) {
2106   if (!C)
2107     return;
2108 
2109   FC = C;
2110   dumpComment(C);
2111   FC = nullptr;
2112 }
2113 
2114 void ASTDumper::dumpComment(const Comment *C) {
2115   dumpChild([=] {
2116     if (!C) {
2117       ColorScope Color(*this, NullColor);
2118       OS << "<<<NULL>>>";
2119       return;
2120     }
2121 
2122     {
2123       ColorScope Color(*this, CommentColor);
2124       OS << C->getCommentKindName();
2125     }
2126     dumpPointer(C);
2127     dumpSourceRange(C->getSourceRange());
2128     ConstCommentVisitor<ASTDumper>::visit(C);
2129     for (Comment::child_iterator I = C->child_begin(), E = C->child_end();
2130          I != E; ++I)
2131       dumpComment(*I);
2132   });
2133 }
2134 
2135 void ASTDumper::visitTextComment(const TextComment *C) {
2136   OS << " Text=\"" << C->getText() << "\"";
2137 }
2138 
2139 void ASTDumper::visitInlineCommandComment(const InlineCommandComment *C) {
2140   OS << " Name=\"" << getCommandName(C->getCommandID()) << "\"";
2141   switch (C->getRenderKind()) {
2142   case InlineCommandComment::RenderNormal:
2143     OS << " RenderNormal";
2144     break;
2145   case InlineCommandComment::RenderBold:
2146     OS << " RenderBold";
2147     break;
2148   case InlineCommandComment::RenderMonospaced:
2149     OS << " RenderMonospaced";
2150     break;
2151   case InlineCommandComment::RenderEmphasized:
2152     OS << " RenderEmphasized";
2153     break;
2154   }
2155 
2156   for (unsigned i = 0, e = C->getNumArgs(); i != e; ++i)
2157     OS << " Arg[" << i << "]=\"" << C->getArgText(i) << "\"";
2158 }
2159 
2160 void ASTDumper::visitHTMLStartTagComment(const HTMLStartTagComment *C) {
2161   OS << " Name=\"" << C->getTagName() << "\"";
2162   if (C->getNumAttrs() != 0) {
2163     OS << " Attrs: ";
2164     for (unsigned i = 0, e = C->getNumAttrs(); i != e; ++i) {
2165       const HTMLStartTagComment::Attribute &Attr = C->getAttr(i);
2166       OS << " \"" << Attr.Name << "=\"" << Attr.Value << "\"";
2167     }
2168   }
2169   if (C->isSelfClosing())
2170     OS << " SelfClosing";
2171 }
2172 
2173 void ASTDumper::visitHTMLEndTagComment(const HTMLEndTagComment *C) {
2174   OS << " Name=\"" << C->getTagName() << "\"";
2175 }
2176 
2177 void ASTDumper::visitBlockCommandComment(const BlockCommandComment *C) {
2178   OS << " Name=\"" << getCommandName(C->getCommandID()) << "\"";
2179   for (unsigned i = 0, e = C->getNumArgs(); i != e; ++i)
2180     OS << " Arg[" << i << "]=\"" << C->getArgText(i) << "\"";
2181 }
2182 
2183 void ASTDumper::visitParamCommandComment(const ParamCommandComment *C) {
2184   OS << " " << ParamCommandComment::getDirectionAsString(C->getDirection());
2185 
2186   if (C->isDirectionExplicit())
2187     OS << " explicitly";
2188   else
2189     OS << " implicitly";
2190 
2191   if (C->hasParamName()) {
2192     if (C->isParamIndexValid())
2193       OS << " Param=\"" << C->getParamName(FC) << "\"";
2194     else
2195       OS << " Param=\"" << C->getParamNameAsWritten() << "\"";
2196   }
2197 
2198   if (C->isParamIndexValid() && !C->isVarArgParam())
2199     OS << " ParamIndex=" << C->getParamIndex();
2200 }
2201 
2202 void ASTDumper::visitTParamCommandComment(const TParamCommandComment *C) {
2203   if (C->hasParamName()) {
2204     if (C->isPositionValid())
2205       OS << " Param=\"" << C->getParamName(FC) << "\"";
2206     else
2207       OS << " Param=\"" << C->getParamNameAsWritten() << "\"";
2208   }
2209 
2210   if (C->isPositionValid()) {
2211     OS << " Position=<";
2212     for (unsigned i = 0, e = C->getDepth(); i != e; ++i) {
2213       OS << C->getIndex(i);
2214       if (i != e - 1)
2215         OS << ", ";
2216     }
2217     OS << ">";
2218   }
2219 }
2220 
2221 void ASTDumper::visitVerbatimBlockComment(const VerbatimBlockComment *C) {
2222   OS << " Name=\"" << getCommandName(C->getCommandID()) << "\""
2223         " CloseName=\"" << C->getCloseName() << "\"";
2224 }
2225 
2226 void ASTDumper::visitVerbatimBlockLineComment(
2227     const VerbatimBlockLineComment *C) {
2228   OS << " Text=\"" << C->getText() << "\"";
2229 }
2230 
2231 void ASTDumper::visitVerbatimLineComment(const VerbatimLineComment *C) {
2232   OS << " Text=\"" << C->getText() << "\"";
2233 }
2234 
2235 //===----------------------------------------------------------------------===//
2236 // Type method implementations
2237 //===----------------------------------------------------------------------===//
2238 
2239 void QualType::dump(const char *msg) const {
2240   if (msg)
2241     llvm::errs() << msg << ": ";
2242   dump();
2243 }
2244 
2245 LLVM_DUMP_METHOD void QualType::dump() const {
2246   ASTDumper Dumper(llvm::errs(), nullptr, nullptr);
2247   Dumper.dumpTypeAsChild(*this);
2248 }
2249 
2250 LLVM_DUMP_METHOD void Type::dump() const { QualType(this, 0).dump(); }
2251 
2252 //===----------------------------------------------------------------------===//
2253 // Decl method implementations
2254 //===----------------------------------------------------------------------===//
2255 
2256 LLVM_DUMP_METHOD void Decl::dump() const { dump(llvm::errs()); }
2257 
2258 LLVM_DUMP_METHOD void Decl::dump(raw_ostream &OS) const {
2259   ASTDumper P(OS, &getASTContext().getCommentCommandTraits(),
2260               &getASTContext().getSourceManager());
2261   P.dumpDecl(this);
2262 }
2263 
2264 LLVM_DUMP_METHOD void Decl::dumpColor() const {
2265   ASTDumper P(llvm::errs(), &getASTContext().getCommentCommandTraits(),
2266               &getASTContext().getSourceManager(), /*ShowColors*/true);
2267   P.dumpDecl(this);
2268 }
2269 
2270 LLVM_DUMP_METHOD void DeclContext::dumpLookups() const {
2271   dumpLookups(llvm::errs());
2272 }
2273 
2274 LLVM_DUMP_METHOD void DeclContext::dumpLookups(raw_ostream &OS,
2275                                                bool DumpDecls) const {
2276   const DeclContext *DC = this;
2277   while (!DC->isTranslationUnit())
2278     DC = DC->getParent();
2279   ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();
2280   ASTDumper P(OS, &Ctx.getCommentCommandTraits(), &Ctx.getSourceManager());
2281   P.dumpLookups(this, DumpDecls);
2282 }
2283 
2284 //===----------------------------------------------------------------------===//
2285 // Stmt method implementations
2286 //===----------------------------------------------------------------------===//
2287 
2288 LLVM_DUMP_METHOD void Stmt::dump(SourceManager &SM) const {
2289   dump(llvm::errs(), SM);
2290 }
2291 
2292 LLVM_DUMP_METHOD void Stmt::dump(raw_ostream &OS, SourceManager &SM) const {
2293   ASTDumper P(OS, nullptr, &SM);
2294   P.dumpStmt(this);
2295 }
2296 
2297 LLVM_DUMP_METHOD void Stmt::dump(raw_ostream &OS) const {
2298   ASTDumper P(OS, nullptr, nullptr);
2299   P.dumpStmt(this);
2300 }
2301 
2302 LLVM_DUMP_METHOD void Stmt::dump() const {
2303   ASTDumper P(llvm::errs(), nullptr, nullptr);
2304   P.dumpStmt(this);
2305 }
2306 
2307 LLVM_DUMP_METHOD void Stmt::dumpColor() const {
2308   ASTDumper P(llvm::errs(), nullptr, nullptr, /*ShowColors*/true);
2309   P.dumpStmt(this);
2310 }
2311 
2312 //===----------------------------------------------------------------------===//
2313 // Comment method implementations
2314 //===----------------------------------------------------------------------===//
2315 
2316 LLVM_DUMP_METHOD void Comment::dump() const {
2317   dump(llvm::errs(), nullptr, nullptr);
2318 }
2319 
2320 LLVM_DUMP_METHOD void Comment::dump(const ASTContext &Context) const {
2321   dump(llvm::errs(), &Context.getCommentCommandTraits(),
2322        &Context.getSourceManager());
2323 }
2324 
2325 void Comment::dump(raw_ostream &OS, const CommandTraits *Traits,
2326                    const SourceManager *SM) const {
2327   const FullComment *FC = dyn_cast<FullComment>(this);
2328   ASTDumper D(OS, Traits, SM);
2329   D.dumpFullComment(FC);
2330 }
2331 
2332 LLVM_DUMP_METHOD void Comment::dumpColor() const {
2333   const FullComment *FC = dyn_cast<FullComment>(this);
2334   ASTDumper D(llvm::errs(), nullptr, nullptr, /*ShowColors*/true);
2335   D.dumpFullComment(FC);
2336 }
2337